//This javascript functions are used in share quote for validating the email id's and avoiding the repetition of mail id's

var first_value=null;
message = 0;
var j=0;
function assign(inn)
{	
  document.getElementById('errors').style.display="none";
  document.getElementById(inn).style.color="red";
  document.getElementById('emailto').value = inn;
  first_value = document.getElementById('emailto').value;
  document.getElementById('cancel').style.display="block";
}

//On mouse over of the mail id change the background color
function mover(val)
{

	val.style.background ="#69B0FF";

}
//On move out of the mail id change the background color to default
function mout(val)
{
	val.style.background ="none";
}

//On click of  textarea add all mail id's to to field and close the mail id division
function show()
{	
	message = 1;
	var pre_value= " ";
  	var final_value =" ";
  	var divid = document.getElementById('email');
   	var theChildren = divid.childNodes;	
   	var i = 0;
 	if (divid.hasChildNodes()){
		
		while (i < theChildren.length){
			
  				document.getElementById(theChildren[i].firstChild.id).style.color="";
  				var selText = theChildren[i].firstChild.innerHTML;
  				pre_value=selText+","+pre_value
						   
			++i;
			}
			final_value = pre_value.substring(0,pre_value.length-2);
			document.getElementById('emailto').value = final_value;
		}
		first_value=null;
		document.getElementById('cancel').style.display="none";
		
}

//On click of cancel image remove the select id from 'To' field
function cancel()
{	
	first_value=null;
	document.getElementById('emailto').value="";
	var divid = document.getElementById('email');
   	var theChildren = divid.childNodes;
   	var i = 0;
	if(divid.hasChildNodes())
						{
							
							while (i < theChildren.length)
							{
								
								document.getElementById(theChildren[i].firstChild.id).style.color="";
	  							if (theChildren[i].firstChild.innerHTML.length>35)
				  					{	
					  					document.getElementById(theChildren[i].firstChild.id).style.color="";
					  					theChildren[i].firstChild.innerHTML=document.getElementById('emailto').value.substring(0,35);
				  					}
	  							++i;
  							}
  							   
						document.getElementById('cancel').style.display="none";
						}
							
}

//On click of save image this function check whether the mail id has already been added 
//If already exsists then display the error if not add to the mail id division
//If mail id's are too big then truncates the mail id and adds to the div
function email()
 {	
 	//Editing the exsisting mail id
	if(first_value!=null)
	{	
		var divid = document.getElementById('email');
   		var theChildren = divid.childNodes;
   		var str = document.getElementById('emailto');
   		
		str_value=Trim(str.value);
		
	   	var i = 0;
	   	var k = 0;
	    r=0;
	 	if (divid.hasChildNodes())
	 	{	
 		while (i < theChildren.length)
 		{	
 			while (k < theChildren.length)
 			{	
 				if(str_value == theChildren[k].firstChild.id)
 				{	
 					if (first_value==theChildren[k].firstChild.id)
 					{	
 					}
 					else
 					{ 
 						r=1; 
 					}	
 					
 				}
 				++k;
 			}
 			if(r==0)
 			{	
	  		if(first_value == theChildren[i].firstChild.id)
	  		{			
	  				
	  				if (emailCheck(str_value)==false)
	  				{
							
							str.focus();
							document.getElementById('errors').style.display="";
							document.getElementById('emailto').value=str_value;
							document.getElementById('errors').innerHTML = "Please correct the following errors before proceeding:"+"<br><ul><li>"+"Enter valid To email address"+"</li><ul>"
							
							return false
					}
					else
					{
		  					document.getElementById(theChildren[i].firstChild.id).style.color="";
		  					document.getElementById('cancel').style.display="none";
		  					theChildren[i].firstChild.innerHTML =str_value;
		  					theChildren[i].firstChild.id =str_value;	
		  					if (theChildren[i].firstChild.innerHTML.length>35)
		  					{	
		  					document.getElementById(theChildren[i].firstChild.id).style.color="";
		  					theChildren[i].firstChild.innerHTML=str_value.substring(0,35);
		  					}
		  					document.getElementById('emailto').value = "";
		  					document.getElementById('errors').innerHTML = ""
		  			}
	  			
	  		}
	  		}				   
			++i;
		}
			
		}
		
		if(r==1)
  		{	
  			document.getElementById('errors').style.display="";
  			document.getElementById('errors').innerHTML = "Please correct the following errors before proceeding:"+"<br><ul><li>"+"Email address already exists"+"</li><ul>"
  			return false
  		}
  		first_value=null;
	}
		else
		{	
			//Adding an email id
			var str = document.getElementById('emailto');
			var fir = document.getElementById('emailto').value;
			
		 	var trim = Trim(fir);	//trim last char if it is comma	
		 	invalid =new Array();
		 	remails = new Array();
		 	var multimails = new Array();
		 	multimails = trim.split(",");
		 	var arrlength= multimails.length;
		 	j=0;flag=0;
		 	notvalid=0;
		 	while(arrlength!=0)
		 	{	
		 		trim=multimails[arrlength-1];
		 			
			 	if (emailCheck(trim)==false)
			 	{	
			 		invalid[notvalid]=trim;	
			 		notvalid=notvalid+1;
			 					
				}
				
				else
				{	//code added to avoid duplicate email id's
					var divid = document.getElementById('email');
   					var theChildren = divid.childNodes;
   					var str = document.getElementById('emailto');
   					var i = 0;
   					
   					var length=theChildren.length;
   					if(theChildren.length==0)
   					{	
   						document.getElementById('errors').innerHTML = ""
							 if(fir.length!="" && trim!="")
							 {		
								if(trim.length>35)
								{	
									multimails[arrlength-1]=trim.substring(0,35);
									
								}			
							 		document.getElementById('cancel').style.display="none";
							 		
							 		var val ="<div>"+"<div  id="+trim+" onclick='assign(this.id);'  onmouseover='mover(this);' onmouseout='mout(this);' STYLE='float: left;width:221px;'>"+multimails[arrlength-1]+"</div>"+"<div onClick='this.parentNode.parentNode.removeChild(this.parentNode);' STYLE='float: left;width:15px;'><a  style='text-decoration:none' ><img id='delete' title='Remove' src='/books/images/remove-mailid.gif'></a></div>"+"</div>";
							 		var valu =val+document.getElementById('email').innerHTML;
								    document.getElementById('email').innerHTML = valu;
								    document.getElementById('emailto').value = "";
								  	document.getElementById('emailto').focus();
								  	Effect.Appear('email',{duration:0.0});
								 
		  		 			 }
   					}
   					
   					while(i<length)
	   				{	
	   					// check whether the email address already exists or not	   					
	   					if(multimails[arrlength-1] == theChildren[i].firstChild.id)	
	   					{	
	   						remails[flag]=multimails[arrlength-1];
	   						flag=flag+1;
	   						j=1;	
	   					}
	   					++i
		  		 	}
	   				
		  		 	
   					if((j!=1 && length !=0))
				  	{		 document.getElementById('errors').innerHTML = ""
							
							 if(fir.length!="" && trim!="")
							 {		
								if(trim.length>35)
								{	multimails[arrlength-1]=trim.substring(0,35);
									//document.getElementById('emailto').value=trim.substring(0,35);
									
								}			
							 		document.getElementById('cancel').style.display="none";
							 		var val ="<div>"+"<div  id="+trim+" onclick='assign(this.id);'  onmouseover='mover(this);' onmouseout='mout(this);' STYLE='float: left;width:221px;'>"+multimails[arrlength-1]+"</div>"+"<div onClick='this.parentNode.parentNode.removeChild(this.parentNode);' STYLE='float: left;width:15px;'><a href='#' style='text-decoration:none' ><img id='delete' title='Remove' src='/books/images/remove-mailid.gif'></a></div>"+"</div>";
							 		var valu =val+document.getElementById('email').innerHTML;
								    document.getElementById('email').innerHTML = valu;
								    document.getElementById('emailto').value = "";
								  	document.getElementById('emailto').focus();
								  	//document.getElementById('errors').style.display="none";
								  	Effect.Appear('email',{duration:0.0});		 
		  		 			 }
		  		 	}	
		  		 
		  		 	
		  		 	
  	            }	//else closing loop
  	        	arrlength=arrlength-1;
  	        }		//while closing loop
  	       
  	       	// If mail id's are repeated dispaly error message
  	        if(j==1 && notvalid==0)
		  		 	{		
		  		 		document.getElementById('errors').style.display="";
		  		 		document.getElementById('errors').innerHTML = "Please correct the following errors before proceeding:"+"<br><ul><li>"+"Email address already exists"+"</li><ul></br>"
		  		 		var emailto="";
		  		 		while(flag!=0)
		  		 		{	if (flag ==1)
		  		 			{	
		  		 				emailto =emailto+remails[flag-1];
		  		 			}
		  		 			else
		  		 			{	emailto =emailto+remails[flag-1]+",";
		  		 			}
		  		 			flag=flag-1;
		  		 		}
		  		 		document.getElementById('emailto').value=emailto;
		  		 		//j=0;
		  		 			
		  		 	}
		  	
		  	// If invalid mail id's dispaly error message 
		  	if(notvalid!=0 && j==0)
		  	{	
		  			str.focus();
					document.getElementById('errors').style.display="";
					var emailto=""
					while(notvalid!=0)
					{
							if (notvalid ==1)
		  		 			{	
		  		 				emailto =emailto+invalid[notvalid-1];
		  		 			}
		  		 			else
		  		 			{	emailto =emailto+invalid[notvalid-1]+",";
		  		 			}
		  		 			notvalid=notvalid-1;
					}
					
					document.getElementById('emailto').value=emailto;
					document.getElementById('errors').innerHTML = "Please correct the following errors before proceeding:"+"<br><ul><li>"+"Enter valid To email address"+"</li><ul>"
					//return false
		  	}
		  	
		  	// If invalid mail id's and repeated mail id's then display error messages.
		  	if (notvalid!=0 && j==1)
		  	{	
		  			str.focus();
					document.getElementById('errors').style.display="block";
					var emailto=""
					while(notvalid!=0)
					{
		  		 			emailto =emailto+invalid[notvalid-1]+",";
		  		 			notvalid=notvalid-1;
					}
					while(flag!=0)
		  		 		{	if (flag ==1)
		  		 			{	
		  		 				emailto =emailto+remails[flag-1];
		  		 			}
		  		 			else
		  		 			{	emailto =emailto+remails[flag-1]+",";
		  		 			}
		  		 			flag=flag-1;
		  		 		}
					document.getElementById('emailto').value=emailto;
					document.getElementById('errors').innerHTML = "Please correct the following errors before proceeding:"+"<br><ul><li>"+"Enter valid To email address"+"</li>"+"<li>"+"Email address already exists"+"</li></ui>"
					//return false
		  	}
 		}
 
 }
 

 function keydown()
 {	
  	var pre_value= " ";
   	var final_value = " ";
   	var text_val = "";
   	var divid = document.getElementById('email');
   	var theChildren = divid.childNodes;
   	
  	var i = 0;
 	
 	if (divid.hasChildNodes())
 	{
 		Effect.Appear('email',{duration:0.0});				
	}
	if(message == 1)
	{	
		document.getElementById('emailto').value="";
	}
		
	if(divid.childNodes.length<6)
	{	
		document.getElementById('email').style.width="250px";
		
		document.getElementById('email').style.overflow="hidden";	
			
	}
	if(divid.childNodes.length>=5)
	{	
		
		document.getElementById('email').style.height="70px";
		
		document.getElementById('email').style.width="260px";
		document.getElementById('email').style.overflow="auto";		
	}
	//document.getElementById('errors').style.display="none";
	message=0;	
 }

//On click of submit validate the from and To field.
//Collect all the 'To' email id's that are added and place in 'To' field
 function test()
 {	
 //	document.getElementById('msg').value="";
 //document.getElementById('captcha').value="";

 	validate_from();
 	message=1;
   	var pre_value= " ";
   	var final_value = " ";
   	var text_val = "";
   	var divid = document.getElementById('email');
   	var text_box = document.getElementById('emailto').value;
   		
   	text_box= Trim(text_box);
   	
   	var theChildren = divid.childNodes;
	document.getElementById('cancel').style.display="none";		
   	var i = 0;
 	if(text_box.indexOf(',')!=-1)
 	{
	
	}
	else
	{
	if (divid.hasChildNodes()){
			 	
				
					while (i < theChildren.length){
							var selText = theChildren[i].firstChild.id;
							//var selText = theChildren[i].firstChild.innerHTML;
			  				if ( text_box != selText)
			  				{	
								pre_value=selText+","+pre_value
							}	
							   
						++i;
						}
						
					}
				
				final_value = pre_value.substring(0,pre_value.length-2);
				
			   // text_val = document.getElementById('emailto').value;
			 	text_val=text_box
			  	
			    if(text_val.length > 0 && final_value.length == 0)
			    {
			        document.getElementById('emailto').value=text_val;
			    }
			    else if(text_val.length > 0)
			    {
			        document.getElementById('emailto').value=final_value+","+text_val;
			    }
			    else if(text_val.length==0)
			    {
			        document.getElementById('emailto').value=final_value; 
			    }
			   		 	
	}
	validate_to();
	document.getElementById('errors').style.display=""; 
	Effect.Fade('email',{duration:0.0});
 }
 
//Validate the 'from' field (Validating the from email id's)
function validate_from()
{	var from =0;
	var fromid=document.getElementById('emailfrom').value
	fromid= Trim(fromid);
	if (fromid != "")
	{	
	
		if (emailCheck(fromid)==false)
		 	{	
		 		document.getElementById('errors').value = "<li>Enter valid From email address</li>";
		 	
		 	}
		else
		{ 	
			document.getElementById('errors').value = "";
			document.getElementById('emailfrom').value = fromid;
		}
	}
	else
	{		
		 		document.getElementById('errors').value = "<li>Enter From email address</li>";
	}
	document.getElementById('msg').value=document.getElementById('errors').value;
}

//Validate the 'To' field (Validating the to email id's)
function validate_to()
{ 	
	
	var tomails = new Array();
	
 	tomails = document.getElementById('emailto').value.split(",");
 	
 	if (tomails != "")
 	{	
 	var tomails_length=tomails.length;
 	var mailid="";
	var loop =0;
	while (tomails_length!=0 )
 	{	mailid=tomails[tomails_length-1];
 		
		
			if (emailCheck(mailid)==false)
		 	{	while (loop == 0)
		 		{
		 		document.getElementById('errors').value += "<li>Enter valid To email address</li>";
		 		loop+=1;
		 		}
		 		
		 	}
		 	else
		 	{
		 		document.getElementById('errors').value += "";
		 	}
	 	
	 	tomails_length=tomails_length-1;
	 	
 	}
 	}
 	else
 	{ 	document.getElementById('errors').value += "<li>Enter To email address</li>";
 	}
 	document.getElementById('msg').value=document.getElementById('errors').value;
}
 
function remove_comma(mailinfo)
{	if (mailinfo.charAt((mailinfo.length)-1) =="," )
		{ mailinfo = mailinfo.substring(0,(mailinfo.length)-1);
			
		}
	else
	{ mailinfo=mailinfo;
	}
		return mailinfo;
}

//Validation of the email id
function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;':`^&\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */


return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {

return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {

return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid


return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {

return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {

return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {

return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {

return false;
}

// If we've gotten this far, everything's valid!
return true;
}

function Trim(str)
		{ // while(str.charAt(0) == (" ") )
		 // {  str = str.substring(1);
		 // }
		  while(str.charAt(str.length-1) == "," )
		  {  str = str.substring(0,str.length-1);
		  }
  		return str;
}

function splitemail(to)
{  	
	document.getElementById('emailto').value=final_value; 
}
	
	
