/**
 * Signup Javascript file. This file is the external JS file for signup page.
 * 
 * @author 		Surendra
 * @copyright	(c) 2009 Linkive.com
 * @link		http://www.linkive.com
 */
	
	/**
	 * Global variable declaration 
	 * @global months
	 * @global integer days
	 * @global string orGID gets the guid of invitor from URL
	 * @global boolean emailThere
	 */
	

	var years 		= new Array(new Array(), new Array());	
	var months 		= new Array(new Array("January","February","March","April","May","June",
	"July","August","September","October","November","December"),new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12));
	var days 		= new Array(new Array(), new Array());
	var orGID 		= "";
	//if(getURLvar('ing') != "")
		//orGID = getURLvar('ing');
	var emailThere 	= false;
	
	
	/**
	 * Home page action
	 * @return unknown_type
	 */
	function addLoadEvent(func) 
	{
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') 
	  {
	    window.onload = func;
	  } 
	  else 
	  {
	    window.onload = function() {
					      oldonload();
					      func();
					    }
	  }
	}
	
	function prepareInputsForHints() {
		var inputs = document.getElementsByTagName("input");
		for (var i=0; i<inputs.length; i++){
			// test to see if the hint span exists first
			if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
				// the span exists!  on focus, show the hint
				inputs[i].onfocus = function () {
					this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
				}
				// when the cursor moves away from the field, hide the hint
				inputs[i].onblur = function () {
					this.parentNode.getElementsByTagName("span")[0].style.display = "none";
				}
			}
		}
		// repeat the same tests as above for selects
		var selects = document.getElementsByTagName("select");
		for (var k=0; k<selects.length; k++){
			if (selects[k].parentNode.getElementsByTagName("span")[0]) {
				selects[k].onfocus = function () {
					this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
				}
				selects[k].onblur = function () {
					this.parentNode.getElementsByTagName("span")[0].style.display = "none";
				}
			}
		}
	}
	addLoadEvent(prepareInputsForHints);
	
	
	/**
	 * A function to fill up the drop down list of month days and year of DOB field
	 * @global integer days for days drop downn field
	 * @global months for months drop downn field
	 * @global integer years for years drop downn field	
	 * @uses function populateList this to populate fields
	 */	
	function fillMonthDayYear()
	{
		// Initialising days array, with 31 days
		for(var i=1, j=0; i<32; i++, j++)
		{
			days[0][j] = i;	// This is for display
			days[1][j] = i; // This is for value
		}
		// Initialising years array, with years between 1900 and  current year
		for(var i=1900, j=0; i<2010; i++, j++)
		{
			years[0][j] = i; // This is for display
			years[1][j] = i; // This is for value
		}
		// Populate 3 fields with initialised arrays
		populateList(document.getElementById('selectMonth'), months);
		populateList(document.getElementById('selectDay'), days);
		populateList(document.getElementById('selectYear'), years);	
		
		return true;
	}
	
	/**
	 * A function to populate drop down list of month days and year of DOB field
	 * @param integer selectId display value of the select
	 * @param integer optArr value of the select
	 */
	function populateList(selectId, optArr)
	{
		for (var loop=0; loop<optArr[0].length; loop++)
		{
			var tempOpt = new Option(optArr[0][loop], optArr[1][loop]);
			selectId.options.add(tempOpt);
		}
	}
	/**
	* Function to remove all errors
	*
	*/
	function removeError(id)
	{
		document.getElementById(id).innerHTML = "";
		document.getElementById(id).style.backgroundColor="";
	}	


	/**
	*	To check whether given e-mail is a valid or not
	*/
	function verifyEmail(email)
	{	
		var email_reg = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
		if(email_reg.test(email))		
			return (true);		
		else		
			return (false);	 
	}	

	
	/**
	* New Validation function for every field
	*/
	function nameValidation(name)
	{
		if(name != "")
		{
			removeError('name-err');
			removeError('name-err2');
			//document.getElementById('name-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/checkbullet.gif></img>";
			return ;
		}
		else
		{
			removeError('name-err');
			removeError('name-err2');
			//document.getElementById('name-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/ex_mark.gif></img>";
			document.getElementById('name-err').innerHTML = "*This information is required";
			//document.f1.name.focus();
			return ;
		}
	}
	
	function passwordValidation(password)
	{
		
		if(password != "")
		{
			removeError('pwd-err');
			removeError('pwd-err2');
			//document.getElementById('pwd-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/checkbullet.gif></img>";
			
			
			
			var pwdfilter = /^([a-zA-Z0-9!@#$%^&amp;*()_+~`]{6,15})$/i
			var returnchk = pwdfilter.test(document.f1.password.value);
			if (returnchk == false)
			{
				//document.getElementById('pwd-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/wrong.GIF></img>";
				document.getElementById('pwd-err').innerHTML = '*Enter a password of length 6-20.';
				//document.f1.password.value 			= "";
				//document.f1.password.focus();
			    return ;
			}
		}
		else
		{
			removeError('pwd-err');
			removeError('pwd-err2');
			//document.getElementById('pwd-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/ex_mark.gif></img>";
			document.getElementById('pwd-err').innerHTML = '*This information is required.';
			//document.f1.password.focus();
			return ;
		
		}
	}
	
	function repassValidation(repassword)
	{	
		if((repassword != "") && (document.f1.retypepassword.value == document.f1.password.value))
		{
			removeError('repwd-err2');
		    removeError('repwd-err');
			//document.getElementById('repwd-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/checkbullet.gif></img>";
			
		}
		else
		{
                      //   document.getElementById('repwd-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/wrong.GIF></img>";
		         document.getElementById('repwd-err').innerHTML = '*Please verify your password .';
			//document.f1.retypepassword.focus();
			//return false;
		}
		
	}
	
	function ageValidation(age)
	{
		if(age != "")
		{
			
			var ageFilter   = /^[1-9]?[0-9]?$/   
			var returnCheck = ageFilter.test(age);
				if (returnCheck == false)
				{
					
					//document.getElementById('age-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/wrong.GIF></img>";
					document.getElementById('age-err').innerHTML = '*Enter a valid age.';
					document.f1.age.select();
					return false;
					
				}	
			removeError('age-err');
			//document.getElementById('age-err2').innerHTML  = "<img src="+siteURL+"application/views/templates/home/images/checkbullet.gif></img>";
			
		}
		else
		{
			//document.getElementById('age-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/ex_mark.gif></img>";
			document.getElementById('age-err').innerHTML = '*This information is required.';
			//document.f1.age.focus();
			return false;
		}	
			
	}
	
	function genderValidation(gender)
	{
		if (( document.f1.gender[0].checked == false) && (document.f1.gender[1].checked == false))
    	{    
    		//document.getElementById('gen-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/ex_mark.gif></img>";
        	document.getElementById('gen-err').innerHTML = '*Please select your Gender';
			return;
		}
		else
		{
			removeError('gen-err');
			//document.getElementById('gen-err2').innerHTML  = "<img src="+siteURL+"application/views/templates/home/images/checkbullet.gif></img>";
		}
	}
	
	
	/**
	 * A function to validate signup fields
	 */	
	function form_validation()
	{
		
		if(document.f1.name.value == '')
		{
			clearAllErrors();	// To clear the previous errors shown
			//clrImgErrors();
			document.getElementById('name-err').innerHTML = 'Enter a valid name';
			document.f1.name.focus();
			return;
		}
	
		if((document.f1.email.value == ''))
		{
			clearAllErrors();	// To clear the previous errors shown
			//clrImgErrors();
			document.getElementById('mail-err').innerHTML = 'Enter your Email';
			document.f1.email.value = '';
			document.f1.email.focus();
			return;
		}	
		
		// TODO: Shift this validation to default JS file
		var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
		var returnval 	= emailfilter.test(document.f1.email.value)
		if (returnval == false)
		{
			clearAllErrors();	// To clear the previous errors shown
			//clrImgErrors();
			document.getElementById('mail-err').innerHTML = 'Enter a valid email address';
			//document.f1.userid.value="";
			document.f1.email.select();
			return;
		}
		
		if(document.f1.password.value == '')
		{
			clearAllErrors();	// To clear the previous errors shown
			//clrImgErrors();
			document.getElementById('pwd-err').innerHTML = 'Enter the correct password';
			document.f1.password.focus();
			return;
		}
		
		var pwdfilter = /^([a-zA-Z0-9!@#$%^&amp;*()_+~`]{6,15})$/i
		var returnchk = pwdfilter.test(document.f1.password.value);
		if (returnchk == false)
		{
			clearAllErrors();	// To clear the previous errors shown
			//clrImgErrors();
			document.getElementById('pwd-err').innerHTML = 'Enter a password of length 6-20';
			document.f1.password.value 			= "";
			document.f1.retypepassword.value 	= "";
			document.f1.password.focus();
			return;
		}
	
		if(document.f1.retypepassword.value != document.f1.password.value)
		{
			if(document.f1.retypepassword.value == '')
			{
				clearAllErrors();	// To clear the previous errors shown
				//clrImgErrors();
				document.getElementById('repwd-err').innerHTML = 'Please repeat the password';
				document.f1.retypepassword.focus();
			}
			else
			{
				clearAllErrors();	// To clear the previous errors shown
				//clrImgErrors();
				document.getElementById('pwd-err').innerHTML = 'Passwords are not matching';
				document.f1.retypepassword.value 	= '';
				document.f1.password.value 			= '';
				document.f1.password.focus();
			}			
			return;
		}
	
			
		if(document.f1.age.value == '')
		{
			clearAllErrors();	// To clear the previous errors shown
			//clrImgErrors();
			document.getElementById('age-err').innerHTML = 'Please enter your age';
			document.f1.age.focus();
			return;
		}
		else
		{	
			var ageFilter   = /^[1-9]?[0-9]?$/   
			var returnCheck = ageFilter.test(document.f1.age.value);
				if (returnCheck == false)
				{
				clearAllErrors();	// To clear the previous errors shown
				//clrImgErrors();
				document.getElementById('age-err').innerHTML = 'Enter a valid age';
				document.f1.age.select();
				document.f1.age.focus();
				return;
				}
				if(document.f1.age.value <= 13)
				{
				document.location.href = siteURL+"home/underAge"
				return;
				}
		}
		if ( ( document.f1.gender[0].checked == false ) && ( document.f1.gender[1].checked == false ) )
    	{    	
    		//document.getElementById('gen-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/ex_mark.gif></img>";
        	document.getElementById('gen-err').innerHTML = '*Please select your Gender';
			return;
    	}
                if(document.f1.ing)
		document.f1.ing.value = orGID;			
		//if(emailThere)
			//return;
		//else
			document.f1.submit();
	
	}		

	
	function checkEMail(mail)
	{	
		// First check whether e-mail field is blank
		if(mail != "")
		{
			
			var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
			var returnval=emailfilter.test(document.f1.email.value);
			if (returnval==false)
			{
				removeError('mail-err2');
				removeError('mail-err');
				//document.getElementById('mail-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/wrong.GIF></img>";
				document.getElementById("mail-err").innerHTML="*Enter a valid email address.";
			}
			else
			{		
						
				xmlh = GetXmlHttpObject();
				var response = SendPostRequest(xmlh, siteURL+"user/checkEmail",'email='+mail, showAvailErr);

				
			}		
		}
		else
		{
			
			removeError('mail-err2');
			removeError('mail-err');
			//document.getElementById('mail-err2').innerHTML = "<img src='"+siteURL+"application/views/templates/home/images/wrong.GIF'></img>";
			document.getElementById('mail-err').innerHTML = "*Please enter your email address .";
			document.f1.email.value = "";
			//document.f1.email.focus();
			
		}
	}
	
	function showAvailErr()
	{ 
		if(xmlh.readyState < 4)
		{
			document.getElementById("mail-err2").innerHTML = "<img src="+siteURL+"/application/views/templates/home/images/loader.gif></img>"
		}
		if(xmlh.readyState == 4)
		{
			var res = xmlh.responseText;
			if(res == 0)
			{
			
				//document.getElementById("mail-err2").innerHTML="<img src = 'https://a248.e.akamai.net/sec.yimg.com/i/reg/checkbullet.gif'</img>";
				document.getElementById("mail-err").innerHTML="<b style='color:#48E90F;margin-left: 30px;'>Email is Available.</b>";
				return;	
			}
			else
			{	
				//document.getElementById('mail-err2').innerHTML = "<img src="+siteURL+"application/views/templates/home/images/wrong.GIF></img>";
				document.getElementById("mail-err").innerHTML="Entered Email already exists.";
				emailThere = true;
				//document.f1.email.value="";
				//document.f1.email.select();
				return;
			}
		}
	}
	
	/*****************************************************************************
	* Functions relating to login validation
	******************************************************************************/
	
	function signinValidation()
	{
		var usrbox = document.getElementById("email-in");
		var passbox = document.getElementById("pass-in");
	
		if(usrbox.value == "")
		{
			clearAllErrors();	// To clear the previous errors shown
			document.getElementById("error-mail").innerHTML = "<br />* Enter the email";
			usrbox.focus();
			return;
		}
		else if(verifyEmail(usrbox.value) == false)
		{
			clearAllErrors();	// To clear the previous errors shown
			document.getElementById("error-mail").innerHTML = "<br />* Enter a valid Email";
			usrbox.focus();
			return;
		}
		else if(passbox.value == "")
		{
			clearAllErrors();	// To clear the previous errors shown
			document.getElementById("error-pass").innerHTML = "<br />* Enter the Password";
			passbox.focus();
			return;
		}
		else	
		{//document.getElementById("login-form").submit();	
			xmlh			= GetXmlHttpObject();			
			var response	= SendPostRequest(xmlh,siteURL+"user/ajaxLogin", 'email_login='+usrbox.value+'&password_login='+passbox.value, showAuthenticationFailErr);
		}
	}
	
	/**
	*	To show the authentiaction fail to login
	**/
	function showAuthenticationFailErr()
	{
		if(xmlh.readyState == 4)
		{
			var res = xmlh.responseText;		
			if(res != 0)
			{
				var redirect_to = Get_Cookie('rurl');
				if(redirect_to)
				{
					Set_Cookie( 'rurl', '', '-3600', '/', '', '' );
					document.location.href = redirect_to;
				}
				else
					document.location.href = siteURL;
			}
			else
			{			
				clearAllErrors();	// To clear the previous errors shown
				document.getElementById("error-auth").innerHTML = "<br />Either email or Password is wrong!";			
				document.getElementById("pass-in").value 		= '';
				document.getElementById("email-in").select();
				return;				
			}			
		}
	}
	
	/**
	*	Clear all other error divs, before showing the error
	*/
	function clearAllErrors()
	{
		var errorTags = ['name-err', 'mail-err', 'pwd-err', 'repwd-err', 'age-err', 'gen-err', 'error-mail', 'error-pass', 'error-auth'];	// Error span ids
		for(var i=0; i<errorTags.length; i++)
		{
			document.getElementById(errorTags[i]).innerHTML = "";
		}
		return true;
	}

	/**
	*	Clear all 'image' error divs,before showing the error
	*/
	function clrImgErrors()
	{
		var errImageTags = ['name-err2', 'mail-err2', 'pwd-err2', 'repwd-err2', 'age-err2', 'gen-err2']; 	
		for(var j=0; j<errImageTags.length; j++)
		{
			document.getElementById(errImageTags[j]).innerHTML = "";
		}
		return true;
	}
	
	/*****************************************************************************
	* Functions relating Password Strength
	******************************************************************************/
	
	 function passwordChanged() 
	{
		 //var strength = document.getElementById('password_text');
		 var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
		 var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
		 var enoughRegex = new RegExp("(?=.{6,}).*", "g");
		 var pwd = document.getElementById("password");
			 if (pwd.value.length==0) 
			 {
				document.getElementById('strengthBox1').style.backgroundColor = "white";
				document.getElementById('strengthBox2').style.backgroundColor = "white";
				document.getElementById('strengthBox3').style.backgroundColor = "white";
				document.getElementById('strengthBox4').style.backgroundColor = "white";
			 }
			 else if (false == enoughRegex.test(pwd.value)) 
			 { 
				document.getElementById('strengthBox1').style.backgroundColor = "#4AE817";
			 }
			 else if (strongRegex.test(pwd.value)) 
			 { 
			 	document.getElementById('strengthBox4').style.backgroundColor = "#4AE817";
			 	document.getElementById('strengthBox1').style.backgroundColor = "#4AE817";
				document.getElementById('strengthBox2').style.backgroundColor = "#4AE817";
			 	document.getElementById('strengthBox3').style.backgroundColor = "#4AE817";
			 }
			 else if (mediumRegex.test(pwd.value)) 
			 { 
				document.getElementById('strengthBox1').style.backgroundColor = "#4AE817";
				document.getElementById('strengthBox2').style.backgroundColor = "#4AE817";
			 	document.getElementById('strengthBox3').style.backgroundColor = "#4AE817";
			 }
			 else
			 { 
				 document.getElementById('strengthBox1').style.backgroundColor = "#4AE817";
				 document.getElementById('strengthBox2').style.backgroundColor = "#4AE817";
		     }
	}
	
	
	

