//#########################################################################################################  
//	# File Name: common.js
//	# File Version: v 1.0
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	# Last Modified By:
//	# Last modified On:
//######################################################################################################### 

//==================================================================================================== 
//  Function Name : IsEmpty 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : checks whether a field has value or is blank, it returns false if a field 
//  is empty otherwise true. 
//  Parameters: fld : Field name to be check for blank.
//	string msg : Message if field is blank.	
//---------------------------------------------------------------------------------------------------- 

var customShowIndustry = false;
var customShowRole = false;
var customShowJob = false;
var UK_COUNTRY_ID = 253;

function IsEmpty(fld,msg) 
{
	fld.value = Trim(fld.value);
	if((fld.value == "" || fld.value.length == 0) && (msg == '')) 
	{ 
		return false; 
	} 
	if(fld.value == "" || fld.value.length == 0) 
	{ 
		alert(msg); 
		fld.focus(); 
		return false; 
	} 
	return true; 
} 

//==================================================================================================== 
//  Function Name : Trim 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : Removes leading and trailing spaces from field values. 
//  Parameters: fld : Field name to be Trim.
//---------------------------------------------------------------------------------------------------- 
function Trim(fld)
{
	while(''+fld.charAt(0)==' ')
		fld=fld.substring(1,fld.length);
	while(''+fld.charAt(fld.length-1)==' ')
		fld=fld.substring(0,fld.length-1);
	
	while(''+fld.charCodeAt(0)==13 || ''+fld.charCodeAt(0)==10)
		fld=fld.substring(1,fld.length);
	while(''+fld.charCodeAt(fld.length-1)==13 || ''+fld.charCodeAt(fld.length-1)==10)
		fld=fld.substring(0,fld.length-1);
	return fld;
}

//==================================================================================================== 
//  Function Name : IsEmail 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : checks Email validity. Email must have character @ followed by one or more 
//  dots. It returns flase if Email is invalid otherwise true. 
//  Parameters: fld : Field name to be check for email.
//	string msg : Message if field is not valid email.	
//---------------------------------------------------------------------------------------------------- 
function IsEmail(fld,msg) 
{ 
	fld.value = Trim(fld.value);
	var regex = /^([\w\+-]+(?:\.[\w\+-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	
	if(!regex.test(fld.value)) 
	{ 
		alert(msg); 
		fld.focus(); 
		return false; 
	} 
	return true; 
} 

//==================================================================================================== 
// Function Name : IsZip 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
// Purpose : checks if zip field value is of length 5 or 9 . (for U.S. zip code). 
// It returns false if it contains alphabetic chars. or length is not as 
// specified. 
// Parameters: fld : Field name to be check for zipcode validation.
// string msg : Message if field is not valid zipcode.	
//---------------------------------------------------------------------------------------------------- 
function IsZip(fld,msg) 
{ 
	var num = /^[\d]+$/; 
	
	if(!num.test(fld.value) || (fld.value.length !=5 && fld.value.length !=9)) 
	{ 
		alert(msg); 
		fld.focus(); 
		return false; 
	} 
	return true; 
} 

//==================================================================================================== 
//  Function Name : chkSplChar 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : checks if field value contains only alphanumeric and '_' charactes. Also checks 
//  that alphabetical chars. and '_' must have to be come first and followed by 
//  numbers. It returns false if above conditions will not satisfy otherwise true. 
//  Parameters: fld : Field name to be check for validation.
//	string msg : Message if field is not valid.	
//---------------------------------------------------------------------------------------------------- 
function chkSplChar(fld,msg)
{
		var strParam=fld.value;
		//var strPat =/^[a-zA-Z0-9\s#.,']+$/;
		var strPat =/^[a-zA-Z0-9\s#.,_\-\/\']+$/;
	
		if(fld.value.length>0)
		{
			if(strParam.match(strPat)==null)
			{
				alert(msg+" can't contain Special Characters.");
				fld.focus(); 	
				return false;
			}	
		}
		return true;
}

//==================================================================================================== 
//  Function Name : Isnumber 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : 
//  Parameters: fld : Field name to be check for validation.
//	string msg : Message if field is not valid.	
//---------------------------------------------------------------------------------------------------- 
function Isnumber(fld,msg) 
{ 
    fld.value = Trim(fld.value);
	var regex = /^[0-9]*$/; 
	if(!regex.test(fld.value)) 
	{ 
		alert(msg); 
		fld.focus(); 
		return false; 
	} 
	return true; 
} 

//==================================================================================================== 
//  Function Name : checkZip 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : 
//  Parameters: fld : Field name to be check for validation.
//	string msg : Message if field is not valid.	
//---------------------------------------------------------------------------------------------------- 
function checkZip(fld,msg) 
{ 
	var regex = /(.zip|.ZIP)$/; 
	if(!regex.test(fld.value)) 
	{ 
		alert(msg); 
		fld.focus(); 
		return false; 
	} 
	return true; 
} 

//==================================================================================================== 
//  Function Name : getTodaysDate 
//	# Created By: Maulik Chandarana
//	# Created On: 14 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : 
//  Parameters: 
//---------------------------------------------------------------------------------------------------- 
function getTodaysDate()
{
	var today = new Date();
	var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");

	var curr_date = today.getDate();
	if (curr_date < 10)
	{
		curr_date = "0"+curr_date;
	}
	var curr_month = today.getMonth();
	var curr_year = today.getFullYear();
	var CurrentDate = curr_year + "-" + m_names[curr_month] + "-" + curr_date;

	return(CurrentDate);
}

/*#====================================================================================================
#  Function Name :  ajaxShowStates
#  Created By: Sarvesh Borkar
#  Created On: 25 Jan 2008
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To fetch state dropdown on change of country dropdown
#  Parameters: countryId ->Id of the selected country
#  Called from:addedit_clients.php
#----------------------------------------------------------------------------------------------------
*/
function ajaxShowStates(countryId)
{
	xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert (translate('browser_not_support_ajax'));
        return;
    }
    
     var url="ajaxStateDropdown.php";
     url=url+"?country_id="+countryId;
     xmlHttp.onreadystatechange=stateChanged
     xmlHttp.open("GET",url,true);
     xmlHttp.send(null);
}


/*#====================================================================================================
#  Function Name :  GetXmlHttpObject
#  Created By: Sarvesh Borkar
#  Created On: 25 Jan 2008
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To create xmlhttpobject
#  Parameters: 
#  Called from:ajaxShowStates()
#----------------------------------------------------------------------------------------------------
*/
var xmlHttp
function GetXmlHttpObject()
{
    var objXMLHttp=null
    if (window.XMLHttpRequest)
    {
        objXMLHttp=new XMLHttpRequest()
    }
    else if (window.ActiveXObject)
    {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    return objXMLHttp
}

/*#====================================================================================================
#  Function Name :  stateChanged
#  Created By: Sarvesh Borkar
#  Created On: 25 Jan 2008
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To populate div tag
#  Parameters: 
#  Called from:ajaxShowStates()
#----------------------------------------------------------------------------------------------------
*/
function stateChanged()
{

    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
      // alert(xmlHttp.responseText);
       document.getElementById('div_states').innerHTML=xmlHttp.responseText
    }
}
function validate2Digit(element,msg){
    var number=element.value;
    var k,newvalue;
    k=number.match(/^\d+\.?\d*$/);
    if(k!=undefined){
        newvalue=Math.round(k[0]*100)/100;
        element.value=newvalue;
    }
    else{
      alert(msg);
      element.focus();
      return false;
    }
  return true;
}
//====================================================================================================
//    File Name        :    isProperCanadaZip
//    # File Version: v 1.0
//    # Created By: Ramprasad.V
//    # Created On: 8 July 2008
//    # Last Modified By:
//    # Last modified On:
//    # Purpose : This is to restrict the special characters while entering canada zipcode
//    # parameters:formField--It represents form field that have to be checked
//----------------------------------------------------------------------------------------------------
function isProperCanadaZip(formField) 
{	
	var result = true;
	var string = formField.length;
	var iChars = ".?\\~!^_-+=*|,\":<>[]{}`\';()@&$#%";
	for (var i = 0; i < string; i++)
	{
		if (iChars.indexOf(formField.charAt(i)) != -1)
		result = false;
	}
 return result;
}

/*
#====================================================================================================
#  Function Name    :    fnShowHideAccountDetails()
#  Created By: Sarvesh Borkar
#  Created On: 23 July 2008
#  Last Modified By: Gauri Sawaikar
#  Last modified On: 18 Aug 2009
#  Purpose : to show and hide industry and job dropdowns on reg and my account page
#  Parameters: optEmploymentStatusId : Employment status id
#----------------------------------------------------------------------------------------------------
*/
function fnShowHideAccountDetails(optEmploymentStatusId)
{
  	intRetiredEmplStatusId = document.getElementById('hdRetiredEmplStatusId').value;
	intStudentEmplStatusId = document.getElementById('hdStudentEmplStatusId').value;
	intHomemakerEmplStatusId = document.getElementById('hdHomemakerEmplStatusId').value;
	intUnemployedEmplStatusId = document.getElementById('hdUnemployedEmplStatusId').value;
		
	if((optEmploymentStatusId!=intRetiredEmplStatusId) && (optEmploymentStatusId!=intStudentEmplStatusId) && (optEmploymentStatusId!=intHomemakerEmplStatusId) && (optEmploymentStatusId!=intUnemployedEmplStatusId))
	{
		if(validateIndustry || customShowIndustry){document.getElementById('industry_tr').style.display="";}
		if(validateJob || customShowJob){document.getElementById('job_tr').style.display="";}
		if(validateRole || customShowRole){document.getElementById('role_tr').style.display="";}			
	}
	else
	{
		if(validateIndustry || customShowIndustry){
			document.getElementById('industry_tr').style.display="none";
			document.getElementById('optIndustryId').selectedIndex ="";
		}
		if(validateJob || customShowJob){
			document.getElementById('job_tr').style.display="none";
			document.getElementById('optJobTitleId').selectedIndex ="";
		}
		if(validateRole || customShowRole){
			document.getElementById('role_tr').style.display="none";
			document.getElementById('optRoleId').selectedIndex ="";
		}

	}
}

<!-- PreLoad Wait - Script -->
/*
#====================================================================================================
#  Function Name    :    fnPreloadPage()
#  Created By: Abhiijit G.
#  Created On: 04 Nov 2008
#  Last Modified By: 
#  Last modified On: 
#  Purpose : to show PreLoad Wait
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/
function fnPreloadPage() { //DOM
	if (document.getElementById){
	document.getElementById('prepage').style.visibility='hidden';
	document.getElementById('profileQuestionsId').style.visibility='visible';
	
	}else{
		if (document.layers){ //NS4
		document.prepage.visibility = 'hidden';
		}
		else { //IE4
		document.all.prepage.style.visibility = 'hidden';
		}
	}
	if (!document.getElementById){
		
		function toggleAlert() {
			toggleDisabled(document.getElementById('profileQuestionId'));
		}
		
		function toggleDisabled(el) {
			try {
				el.disabled = el.disabled ? false : true;
			}
			catch(E){
			}
				if (el.childNodes && el.childNodes.length > 0) {
				for (var x = 0; x < el.childNodes.length; x++) {
					toggleDisabled(el.childNodes[x]);
					}
				}
			}
	}
}
// End -->

/*#====================================================================================================
#  Function Name :  fnDisableButtonsOnSubmit
#  Created By: saiyesh
#  Created On: 22nd Oct 2008
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To Disable the buttons on a page onSubmit of the form untill the page is loaded
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/
var flagDisableButton = 0;
function fnDisableButtonOnSubmit(frm)
{
	if(flagDisableButton !=0) 
	{
		return false;
	}
	flagDisableButton=1;
	
	var elements = document.getElementsByTagName('input');
	for(var j =0; j<elements.length; j++)
	{
			if(elements[j].disabled!=true && (elements[j].type == 'image' || elements[j].type == 'submit' || elements[j].type == 'button'))
			{
					var clone = document.createElement("input");
					
					if(elements[j].type=="image" )
					{
						clone.src=elements[j].src;
						clone.type = "image";
					}
					else
					{
						clone.type = "button";
					}
									
					clone.className = elements[j].className;
					clone.value=elements[j].value;
					clone.size = elements[j].size;					
					clone.style.width=elements[j].style.width;
					clone.style.height=elements[j].style.height;
					clone.disabled=true;
					 
					elements[j].style.display="none";					
					
					if(elements[j].nextSibling)
					{
						elements[j].parentNode.insertBefore(clone,elements[j].nextSibling);
					}
					else
					{
						elements[j].parentNode.appendChild(clone);	
					}
				}
	}	
}

/*#====================================================================================================
#  Function Name :  fnDisableLink
#  Created By: saiyesh
#  Created On: 22nd Oct 2008
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To Disable the links
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/

function fnDisableLink(linkId)
{
	if(document.getElementById(linkId)!=null)
	{
		var clone = document.createElement("a");
		var ele = document.getElementById(linkId);
		var parent = document.getElementById(linkId).parentNode;

		clone.innerHTML = ele.innerHTML; //duplicate visible properties
		clone.className = ele.className;
	
		ele.style.display = "none"; //hide active link
		//insert clone into proper place
		if(ele.nextSibling)
		{
			parent.insertBefore(clone,ele.nextSibling);	
		}
		else
		{
			parent.appendChild(clone);
		}
	}
	
}


/*#====================================================================================================
#  Function Name :  fnRightSizeImage
#  Created By: saiyesh
#  Created On: 17th Nov 2008
#  Last Modified By: saiyesh
#  Last modified On: 
#  Purpose : To scale the image upto a specified width/height ratio
#  Parameters: 	strImageId: id of image element
#				intMaxWidth: max width to be alowed, image could be scaled to width below this to maitain the aspect ratio
#				intMaxHeightL max height to be alowed, image could be scaled to shorter height to maitain the aspect ratio
#----------------------------------------------------------------------------------------------------
*/

function fnRightSizeImage(strImageId,intMaxWidth,intMaxHeight)
{
	var image = document.getElementById(strImageId);
	image.style.visibility='hidden';
	var ratio = image.width / image.height; //get image aspect ratio

	if(image.height > intMaxHeight) //adjust by height
	{
		var width = ratio * intMaxHeight; //calc width based on max height
		image.height = intMaxHeight; //set height
		image.width = width; //set width
	}
	if(image.width > intMaxWidth) //adjust by width
	{
		var height = intMaxWidth/ratio; //calc height based on max width
		image.width = intMaxWidth; //set width
		image.height = height; //set height
	}

	image.style.visibility='';	
	return;
}

//====================================================================================================
//  Function Name :  fnShowHideDOMChildInfo
//  Created By: saiyesh mahambrey
// Created On: 30th April 2009
//  Last Modified By: 
//  Last modified On: 
//  Purpose : To show/hide the area for child info inputs
//  Parameters: Action = Show / Hide
//----------------------------------------------------------------------------------------------------
function fnShowHideDOMChildInfo(strAction,page,strCountryType)
{
	var TD = document.getElementById('tdChildInfo');
	var TR = document.getElementById('trChildInfo');
	if(strAction=='SHOW' && TD.style.display=="none")
	{
		ajaxGetChildInfoDOM(strCountryType,page);
		TD.style.display="";
		TR.style.display="";
	}
	else if(strAction=='HIDE' && TD.style.display=="")
	{
		if(fnRemoveChildren())
		{
			TD.innerHTML='';
			TD.style.display="none";
			if(TR != null) {
			TR.style.display="none";
			} else {
				document.getElementById('addAnotherChild').style.display = "none";
			}
			document.getElementById('hdChildCount').value=0;
		}
		else
		{
			document.getElementById('rdChildrenUnder18_Y').checked='checked';	
		}
	}
}

/*#====================================================================================================
#  Function Name :  ajaxGetChildInfoDOM
#  Created By: saiyesh mahambrey
#  Created On: 1st may 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To fetch child info form DOM
#  Parameters: countryId ->Id of the selected country
#  Called from:registration_step2.php
#----------------------------------------------------------------------------------------------------
*/
function ajaxGetChildInfoDOM(strCountryType,strPage)
{
	count = parseInt(document.getElementById('hdChildCount').value)+1;
	if(count > 8)
	{
		alert(translate(new Array('not_more_children',8)));
		return false;
	}
	else
	{
		document.getElementById('hdChildCount').value=count;
		$.get("ajaxGetChildInfoDOM.php",{ strCountryType : strCountryType,count:count,page : strPage},
				function(data)
				{
					var eleSpan = document.createElement('span');
					eleSpan.innerHTML=data;
					document.getElementById('tdChildInfo').appendChild(eleSpan);
				},
			'text');		
	}
}
/*#====================================================================================================
#  Function Name :  fnRemoveChildInfoDOM
#  Created By: saiyesh mahambrey
#  Created On: 1st may 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To fetch child info form DOM
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/
function fnRemoveChildInfoDOM(position)
{
	cntChild = parseInt(document.getElementById('hdChildCount').value)
	position = parseInt(position);

	if(!confirm(translate(new Array('confirm_child_remove',position))))
		return false;
	
	if(document.getElementById('user_child_'+position))
		var user_child_id = document.getElementById('user_child_'+position).value;
	
	for(i=position;i<=cntChild;i++)
	{
		iNext=(parseInt(i)+1);
		if(document.getElementById('male_'+iNext))
		{
			document.getElementById('male_'+i).checked = document.getElementById('male_'+iNext).checked;
			document.getElementById('female_'+i).checked = document.getElementById('female_'+iNext).checked;
			
			document.getElementById('optDayId_'+i).selectedIndex = document.getElementById('optDayId_'+iNext).selectedIndex;
			document.getElementById('optMonthId_'+i).selectedIndex = document.getElementById('optMonthId_'+iNext).selectedIndex;
			document.getElementById('optYearId_'+i).selectedIndex = document.getElementById('optYearId_'+iNext).selectedIndex;
			
			document.getElementById('user_child_'+i).value = document.getElementById('user_child_'+iNext).value;
		}
		else
		{
			if(user_child_id != 0 && cntChild>1)
			{
				$.get("ajaxGetChildInfoDOM.php",{ user_child_id : user_child_id, action:'remove' });						
			}
			else if(user_child_id != 0 && cntChild==1)
			{
				$.get("ajaxGetChildInfoDOM.php",{ action:'remove_ALL' });						
			}			
			document.getElementById('tdChildInfo').removeChild(document.getElementById('table_'+i).parentNode);
			document.getElementById('hdChildCount').value=cntChild-1;
			if(cntChild-1 == 0)
			{
				fnShowHideDOMChildInfo('HIDE');
				document.getElementById('rdChildrenUnder18_N').checked='checked';
			}
		}
	}
}
/*#====================================================================================================
#  Function Name :  fnRemoveChildren
#  Created By: saiyesh mahambrey
#  Created On: 14th may 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To Remove All children info from table for a particular user
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/
function fnRemoveChildren()
{
	if(document.getElementById('user_child_1') && document.getElementById('user_child_1').value != 0)
	{
		if(confirm(translate('children_under_18_info_will_be_lost')))
		{
			$.get("ajaxGetChildInfoDOM.php",{ action:'remove_ALL' });
			return true;
		}
		else
		{
			return false;	
		}
	}
	else if(document.getElementById('hdChildCount').value!=0)
	{ 
		if(confirm(translate('children_under_18_info_will_be_lost')))
		{
			$.get("ajaxGetChildInfoDOM.php",{ action:'remove_ALL' });
			return true;
		}
		else
		{
			return false;
		}
	}
	return true;
}
/*#====================================================================================================
#  Function Name :  fnValidateChildInfo
#  Created By: saiyesh mahambrey
#  Created On: 7th may 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To fetch child info form DOM
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/
function fnValidateChildInfo()
{
	cntChild = parseInt(document.getElementById('hdChildCount').value);

	for(i=1;i<=cntChild;i++)
	{
		if(document.getElementById('male_'+i) && document.getElementById('user_child_'+i).value=='0')
		{
			// Check that Date Year/Month/Date is entered by user
			if(document.getElementById('optYearId_'+i).value=='')
			{
				alert(translate(new Array('select_valid_birth_date_for_child',i)));
				document.getElementById('optYearId_'+i).focus();
				return false;
			}
			else if(document.getElementById('optMonthId_'+i).value=='')
			{
				alert(translate(new Array('select_valid_birth_date_for_child',i)));
				document.getElementById('optMonthId_'+i).focus();
				return false;				
			}
			else if(document.getElementById('optDayId_'+i).value=='')
			{
				alert(translate(new Array('select_valid_birth_date_for_child',i)));
				document.getElementById('optDayId_'+i).focus();
				return false;				
			}
			if(!fnCheckValidDate(document.getElementById('optYearId_'+i).value,
								document.getElementById('optMonthId_'+i).value,
								document.getElementById('optDayId_'+i).value))
			{
				alert(translate(new Array('select_valid_birth_date_for_child',i)));
				document.getElementById('optDayId_'+i).focus();
				return false;	
			}
			
			if(document.getElementById('male_'+i).checked!=true && document.getElementById('female_'+i).checked!=true)
			{
				alert(translate(new Array('specify_child_gender',i)));
				document.getElementById('male_'+i).focus();
				return false;
			}
			
			var today = new Date();
			// Check that calculated age is not more than 18 years.
			if(
				   (parseInt(today.getFullYear(),10) - parseInt(document.getElementById('optYearId_'+i).value,10) == 18 
				&& parseInt(today.getMonth(),10)+1 > parseInt(document.getElementById('optMonthId_'+i).value,10))
			   ||
				   (parseInt(today.getFullYear(),10) - parseInt(document.getElementById('optYearId_'+i).value,10) == 18 
				&& parseInt(today.getMonth(),10)+1 == parseInt(document.getElementById('optMonthId_'+i,10).value)
				&& parseInt(today.getDate(),10) >= parseInt(document.getElementById('optDayId_'+i).value,10))
			   )
			{
				alert(translate(new Array('child_not_under_18',i)));
				document.getElementById('optYearId_'+i).focus();
				return false;
			}
			// Check that birthdate is not a future date
			if(
				   (parseInt(today.getFullYear(),10) == parseInt(document.getElementById('optYearId_'+i).value,10)
			   && parseInt(today.getMonth(),10)+1 < parseInt(document.getElementById('optMonthId_'+i).value,10))
			||
				   (parseInt(today.getFullYear(),10) == parseInt(document.getElementById('optYearId_'+i).value,10) 
				&& parseInt(today.getMonth(),10)+1 == parseInt(document.getElementById('optMonthId_'+i,10).value)
				&& parseInt(today.getDate(),10) < parseInt(document.getElementById('optDayId_'+i).value,10))
			)
			{
				alert(translate(new Array('birth_date_cannot_be_future',i)));
				document.getElementById('optYearId_'+i).focus();
				return false;
			}
		}		
	}
	return true;
}

/*#====================================================================================================
#  Function Name :  fnCheckValidDate
#  Created By: saiyesh mahambrey
#  Created On: 22nd May 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To fetch child info form DOM
#  Parameters: 
#----------------------------------------------------------------------------------------------------
*/
function fnCheckValidDate(Year,Month,Day)
{
	if(Year=='' || Month=='' || Day=='')
	{
		return false;	
	}	
	if(Year%100 != "0")
	{
		if(Year%4 == "0")
		{
			if( (Month=="02" && Day=="30") || (Month=="02" && Day=="31") || (Month=="04" && Day=="31") || (Month=="06" && Day=="31") || (Month=="09" && Day=="31") || (Month=="11" && Day=="31") )
			{
				return false;
			}
		}
		else
		{
			if( (Month=="02" && Day=="29") || (Month=="02" && Day=="30") || (Month=="02" && Day=="31") || (Month=="04" && Day=="31") || (Month=="06" && Day=="31") || (Month=="09" && Day=="31") || (Month=="11" && Day=="31") )
			{
				return false;
			}
		}
	}
	else if(Year%400 == "0")
	{
		if( (Month=="02" && Day=="30") || (Month=="02" && Day=="31") || (Month=="04" && Day=="31") || (Month=="06" && Day=="31") || (Month=="09" && Day=="31") || (Month=="11" && Day=="31") )
		{
			return false;
		}
	}
	return true;
}
/*#====================================================================================================
#  Function Name :  translate
#  Created By: Vivek Samant
#  Created On: 20 April 2009
#  Last Modified By: Richard Fernandes
#  Last modified On: 30 May 2009
#  Purpose : To translate the javascript alert messages in the language selected
#  Parameters: 	msg: message id of the JS message
#				
#----------------------------------------------------------------------------------------------------
*/
function translate(msg)
{ 
	if(!isArray(msg)){
		var message = "JSONObject.messages[0]"+"."+msg; 
		var message = eval(message);
		return message;
	}
	else{
		var message = "JSONObject.messages[0]"+"."+msg[0]; 
		var message = new String(eval(message));
		return message.replace('%%d%%',msg[1]);
	}
}

//====================================================================================================
//  Function Name: docObj
//  Created By: Richard Fernandes
//  Created On:  6 May 2009
//  Last Modified By: 
//  Last modified On: 
//  Purpose : To obtain an HTML element's object
//  Parameters: elemId : Id of the HTML element
//----------------------------------------------------------------------------------------------------
function docObj(elemId){
	if(document.getElementById(elemId))
		return document.getElementById(elemId);
	else
		return false;
}

//====================================================================================================
//  Function Name: hasValue
//  Created By: Richard Fernandes
//  Created On:  6 May 2009
//  Last Modified By: 
//  Last modified On: 
//  Purpose : To check if a JS variable has a value
//  Parameters: variable: the variable
//----------------------------------------------------------------------------------------------------
function hasValue(variable){
	return (variable!=undefined && variable!="undefined" && variable!="");
}

//====================================================================================================
//  Function Name: hide
//  Created By: Richard Fernandes
//  Created On: 6 May 2009
//  Last Modified By: 
//  Last modified On: 
//  Purpose : To hide a HTML element
//  Parameters: elemId : Id of the HTML element
//----------------------------------------------------------------------------------------------------
function hide(elemId){
	var element = docObj(elemId);
	if(element){
		element.style.display = 'none';
		element.style.visibility = 'hidden';
	}
}

//====================================================================================================
//  Function Name: show
//  Created By: Richard Fernandes
//  Created On: 6 May 2009
//  Last Modified By: 
//  Last modified On: 
//  Purpose : To unhide a HTML element
//  Parameters: elemId : Id of the HTML element
//----------------------------------------------------------------------------------------------------
function show(elemId){
	var element = docObj(elemId);
	if(element){
		element.style.display = 'block';
		element.style.visibility = 'visible';
	}
}

//====================================================================================================
//  Function Name: showTableRow
//  Created By: Richard Fernandes
//  Created On:6 May 2009
//  Last Modified By: 
//  Last modified On: 
//  Purpose : To unhide a table row
//  Parameters: elemId : Id of the HTML element
//----------------------------------------------------------------------------------------------------
function showTableRow(elemId){
	var element = docObj(elemId);
	if(element){
		element.style.display = '';
		element.style.visibility = 'visible';
	}
}

//==================================================================================================== 
//  Function Name : iHTML
//	# Created By: Richard Fernandes
//	# Created On: 6 May 2009
//	Last Modified By:
//	Last modified On:
//  Purpose : assigns the innerHTML for an HTML element
//  Parameters: 
//			elemId : Id of the HTML element
//			HTML : the HTML to assign
//---------------------------------------------------------------------------------------------------- 
function iHTML(elemId,HTML) 
{ 
	var element = docObj(elemId);
	element.innerHTML = HTML;
}

//==================================================================================================== 
//  Function Name : isArray
//	# Created By: Richard Fernandes
//	# Created On: 30 May 2009
//	Last Modified By:
//	Last modified On:
//  Purpose : Determine if an object is an array
//  Parameters: obj
//---------------------------------------------------------------------------------------------------- 
function isArray(obj) {
return (obj.constructor.toString().indexOf("Array") != -1);
}
//====================================================================================================
//    Function Name    :    str_replace(search, replace, str)
//    Created By: Abhay Deotare
//    Created On: 24 Dec 2008
//    Last Modified By: 
//    Last modified On: 
//    Purpose : To replace the specified string from given string 
//    Parameters: search - The string which needs to be replace
//    			  replace - The string which is been replace by search string
//    			  str - 	string 
//----------------------------------------------------------------------------------------------------
function str_replace (search, replace, str)
{
	var result = '';
	var oldi = 0;
	for (i = str.indexOf (search); i > -1; i = str.indexOf (search, i))
	{
		result += str.substring (oldi, i);
		result += replace;
		i += search.length;
		oldi = i;
	}
	return result + str.substring (oldi, str.length);
}

//==================================================================
//    Function Name    :    loadCBC
//    Created By: Richard Fernandes
//    Created On: 29 July 2009
//    Last Modified By: 
//    Last modified On: 
//    Purpose : To write the CBC file to DOM
//----------------------------------------------------------------------------------------------------
function loadCBC(domain,protocol){
	//detect availability of Flash START
	var strFlashVer = $("#flashjs").flash.hasFlash.playerVersion();
	var arrFlashVer = new Array();
	arrFlashVer= strFlashVer.split(",");
	var hasFlash = arrFlashVer[0]==0?false:true;
	//detect availability of Flash END
	width = 1;
	height = 1;
	if(hasFlash){
		if(!docObj('CBCholder')){
			var div = document.createElement('DIV');
			div.id = 'CBCholder';
			document.body.appendChild(div);
		}
		docObj('CBCholder').innerHTML = 
		'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+width+'" height="'+height+'" id="banner_prescreener_data" align="middle">'
		+'<param name="allowScriptAccess" value="always" />'
		//+'<param name="movie" value="http://'+domain+'/flash/banner_prescreener_data.swf?cb='+new Date().getTime()+'" />'
		+'<param name="movie" value="'+domain+'/flash/banner_prescreener_data.swf" />'
		+'<param name="quality" value="high" />'
		+'<param name="bgcolor" value="#ffffff" />'
		//+'<embed src="http://'+domain+'/flash/banner_prescreener_data.swf?cb='+new Date().getTime()+'" quality="high" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="banner_prescreener_data" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />'
		+'<embed src="'+domain+'/flash/banner_prescreener_data.swf" quality="high" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="banner_prescreener_data" align="middle" allowScriptAccess="always"  type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />'
		+'</object>';
	}
}

//==================================================================
//    Function Name    :    autoPopulateRegistration
//    Created By: Richard Fernandes
//    Created On: 29 July 2009
//    Last Modified By: 
//    Last modified On: 
//    Purpose : To autopopulate registration step1/step2
//----------------------------------------------------------------------------------------------------
function autoPopulateRegistration(country,zip,gender,income,ethnicity){
	switch(getBaseName(location.href)){
		case 'registration_step1.php':
			if(document.frmRegistrationStep1.optCountryId.value=='' || document.frmRegistrationStep1.optCountryId.value==0){
			//set country, zip, gender
			document.frmRegistrationStep1.txtZipPostal.value = zip;
			var arrGender = document.frmRegistrationStep1.rdGender;
			for(i=0;i<arrGender.length;i++){
				if(arrGender[i].value=='Male'){
					if(gender=='Male')
						arrGender[i].checked = true;
					else
						arrGender[i].checked = false;
				}
				
				if(arrGender[i].value=='Female'){
					if(gender=='Female')
						arrGender[i].checked = true;
					else
						arrGender[i].checked = false;
				}
			}
			document.frmRegistrationStep1.optCountryId.value = country;
			getRegMgmtSettingsForStep1(country,document.frmRegistrationStep1.optLanguageId.value,document.frmRegistrationStep1,'RegistrationStep1');
			}
			break;
		case 'registration_step2.php':
			//set income,ethnicity
			if(validateIncome){
				if(docObj('optAnnualHouseholdIncomeId').value=='' || docObj('optAnnualHouseholdIncomeId').value==0){
				docObj('optAnnualHouseholdIncomeId').value = income;
				}
			}
			if(validateEthnicity){
				if(docObj('optEthnicityId').value=='' || docObj('optEthnicityId').value==0){
				docObj('optEthnicityId').value = ethnicity;
				}
			}
			break;
	}
}

/*#====================================================================================================
#  Function Name :  getBaseName
#  Created By: Richard Fernanades
#  Created On: 29 July 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : To get the base file name 
#----------------------------------------------------------------------------------------------------
*/
function getBaseName(file){
	var arrParts = file.split('/');
	var arrSubParts = arrParts[arrParts.length-1].split('?');
	return arrSubParts[0];
}

/*
#====================================================================================================
#  Function Name    :    fnGetJobTileValuesForRole
#  Created By: Gauri Sawaikar
#  Created On: 18 Aug 2009
#  Last Modified By: 
#  Last modified On: 
#  Purpose : Get Filtered Job/Title Dropdown from Role/Dept Id from ajax call
#  Parameters: frm : User Selected Role Id
#----------------------------------------------------------------------------------------------------
*/
function fnGetJobTileValuesForRole(optRoleId,strBaseFileName)
{
	//incase JobTitle Dropdown is not shown, do not make ajax call
	if(!document.getElementById('div_jobTitle'))
	 return;
	if(optRoleId=="")
		optRoleId=0;
	var objXmlHttp;
	objXmlHttp = GetXmlHttpObject();
	if(objXmlHttp == null)
	{
		alert(translate('browser_not_support_ajax'));
	}
	else
	{
		url = "get_jobTitle_dropdown.php";
		url += '?hdRoleId='+optRoleId+'&baseFileName='+strBaseFileName;
		objXmlHttp.onreadystatechange = function()
		{
			if(objXmlHttp.readyState==4 || objXmlHttp.readyState=='complete')
			{
				//convert the JSON string returned to a JS array
				var JSONObj = eval("(" + objXmlHttp.responseText + ")");
				//alert(JSONObj.toString());
				iHTML('div_jobTitle',JSONObj['job_title_dropdown']);
			}
		}
		objXmlHttp.open("GET",url,true);
		objXmlHttp.send(null);			
	}

}



function getFlashVersion()
{ 
	// Major version of Flash required
	var requiredMajorVersion = 6;
	// Minor version of Flash required
	var requiredMinorVersion = 0;
	// Minor version of Flash required
	var requiredRevision = 65;
	//Initialize
	var detMajorVersion = 0,detMinorVersion=0,detRevision=0;
	var arrFlashData = new Array();
	arrFlashData["hasRequiredflashVersion"] = 0;
	arrFlashData["detMajorVersion"] = detMajorVersion;
	//Falsh Version
	var strFlashVer = $("#flashjs").flash.hasFlash.playerVersion();
	var arrFlashVer = new Array();
	arrFlashVer= strFlashVer.split(",");
	
	if(arrFlashVer.length)
	{
		detMajorVersion = parseInt(arrFlashVer[0]);
		detMinorVersion = parseInt(arrFlashVer[1]);
		detRevision = parseInt(arrFlashVer[2]);
		
		if((detMajorVersion > requiredMajorVersion) || ((detMajorVersion == requiredMajorVersion) && (detRevision >= requiredRevision) && (detRevision >= requiredMinorVersion)))
		{
			arrFlashData["hasRequiredflashVersion"] = 1;
		}
	} 
	return(arrFlashData);
}

function submitForm(FlashCookieVal,isNewCookie,FPvalue)
{ 	  
	if(docObj('cookieval'))
	  document.getElementById('cookieval').value = FlashCookieVal;
	if(docObj('isNewCookie'))
	  document.getElementById('isNewCookie').value = isNewCookie;
	  document.getElementById('jsform').submit();  
} 

function _call_process_flash_cookie(FlashCookieVal)
{
	flash.call("process_flash_cookie",FlashCookieVal);
}

/*
#====================================================================================================
#  Function Name    :    fnShowScamAlert
#  Created By: Richard Fernandes
#  Created On: 23 March 2010
#  Last Modified By: 
#  Last modified On: 
#  Purpose : to open scam alert ifo window
#----------------------------------------------------------------------------------------------------
*/
function fnShowScamAlert() {
	window.open( "scamalert.html", "myWindow", "status = 1, height = 475, width = 450, resizable = 0, left=0, top=0 " );
}

function updateFp(FlashCookieVal,isNewCookie,FPvalue){
	if(docObj('cookieval'))
		 document.getElementById('cookieval').value = FlashCookieVal;
	if(docObj('isNewCookie'))
		 document.getElementById('isNewCookie').value = isNewCookie;
	}
	
function OldLogoutFacebookUser()
{
	var logoutLink = document.getElementById('hdLogoutLink').value;
		
	var fbCookieName = "loggedin_as_facebook_user=";
	var fbCookie = "";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(fbCookieName) == 0) 
			fbCookie = c.substring(fbCookieName.length,c.length);
	}

	if(fbCookie == 1) {
		//delete the cookie
		document.cookie = 'loggedin_as_facebook_user=; expires=Thu, 01-Jan-70 00:00:01 GMT;';	
		FB.logout(function() { window.location = logoutLink + 'index.php?mode=logout';} );
		 
	} else {
		window.location = logoutLink + 'index.php?mode=logout';
	}

}

function logoutFacebookUser()
{
    if (typeof IN != "undefined" && IN.User.isAuthorized()) IN.User.logout(OldLogoutFacebookUser);
    else OldLogoutFacebookUser();
}

function _call_set_flash_cookie(key,value)
{
	flash.call("set_flash_cookie",key,value);
}

function _call_get_flash_cookie(key)
{
	flash.call("get_flash_cookie",key);
}

/*=====================================================
* Function Name    :    getTraditionalCookie
* Created By: sarvesh borkar
* Created On: 12th August 2009
* Last Modified By: 
* Last modified On: 
* Purpose : To fetch the value of Queue Traditional Cookie
* Parameters: c_name -- cookie name
*=====================================================
*/

function getTraditionalCookie(c_name)
{
  if(document.cookie.length>0)
  {
	  c_start = document.cookie.indexOf(c_name + "=");
	  if (c_start !=-1)
	  {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	  }
  }
   return "";
}

/*=====================================================
* Function Name    :    setTraditionalCookie
* Created By: sarvesh borkar
* Created On: 12th August 2009
* Last Modified By: 
* Last modified On: 
* Purpose : To set the Traditional Cookie
* Parameters: c_name -- cookie name, value -- cookie value ,expiredays -- cookie expiry
*=====================================================
*/
function setTraditionalCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

//==================================================================================================== 
//  Function Name : isHidden
//	# Created By: Richard Fernandes
//	# Created On: 18 Jan 2008
//	Last Modified By:
//	Last modified On:
//  Purpose : checks if a an HTML element is hidden
//  Parameters: elemId : Id of the HTML element
//---------------------------------------------------------------------------------------------------- 
function isHidden(elemId) 
{ 
	if(typeof(elemId)=='object'){
		var element = elemId;
	}
	else{
		var element = docObj(elemId);
	}
	if(element.style.display == 'none' || element.style.visibility == 'hidden'){
		return true;
	}
	return false;
}

//==================================================================================================== 
//  Function Name : checkCityInfo
//  Created By:Harsh Aghicha
//  Created On: 28 Oct 2010
//  Last Modified By:
//  Last modified On:
//  Purpose : checks if city option is selected
//  Parameters: frm : form element
//---------------------------------------------------------------------------------------------------- 
function checkCityInfo(frm)
{	
	with(frm)
    {
		if(Trim(optCityId.value) == "")
		{
			 alert(translate('enter_city'));
			 optCityId.focus();
			 return false;
		}
	}
}

/*#====================================================================================================
#  Function Name 		:  	fnShowAutoDonatePopup
#  Created By			: 	Dinesh Kudtarkar
#  Created On			: 	26 Oct 2010
#  Last Modified By		: 
#  Last modified On		: 
#  Purpose 				: 
#  Parameters			: 
#----------------------------------------------------------------------------------------------------
*/
function fnShowAutoDonatePopup() {
	$(document).ready(function() {
	$("#CompleteLink").fancybox({
					'autoDimensions'	: true,
	                'width'             : 500,
	                'height'            : 400,
	                'hideOnOverlayClick': false,
	                'scrolling'			: 'no',
	                'padding':0,
	                'showActivity'      : true
	            });
	$("#CompleteLink").trigger('click');
	});
}



/*#====================================================================================================
#  Function Name 		:  	fnAjaxValidateZipcode
#  Created By			: 	Richard Fernandes
#  Created On			: 	5 May 2011
#  Last Modified By		: 
#  Last modified On		: 
#  Purpose 				: 
#  Parameters			: 
#----------------------------------------------------------------------------------------------------
*/
function fnAjaxValidateZipcode(intCountryId,strZipCode) {
	$.ajax({
		type: "POST",
		url: "ajaxValidateZipcode.php",
		dataType: "text",
		async: false,
		data: ({COUNTRY_ID:intCountryId,ZIPCODE:escape(strZipCode)}),
		success: function(data, status, request){
			if(data=='INVALID'){
				$('#validated_zip').val('0');
			}
			if(data=='VALID'){
				$('#validated_zip').val('1');
			}
		}
	});
}

