/*
loadScript('//<?php echo JSURL; ?>/public/js/ajax-api<?php echo JSVERSION; ?>.js', function(){
    messageObj = new DHTML_modalMessage();
    messageObj.setShadowDivVisible(false);
    messageObj.setHardCodeHeight(0);
});
*/
function unset_mail()
{
        //alert('');
        document.getElementById('verifyEmailId').innerHTML='';
        document.getElementById('verifyEmailId').style.display="none";
        setCookie('resend_email','NOT SHOW');
        //alert(getCookie('resend_email'));
}
function loadScript(url, callback){
    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}




function isRestrictedWord(word) {
    return false;
}
function sendverificationmail()
{
// sent ajax request for verfication
}
function validaterecoverpassword(obj)
{
        validationResponse = RecoverPswdForm(obj);
	var returnFlag = true;
	if(validationResponse !== true)
	{
		returnFlag = false;
		return returnFlag;
	}	
}
function validateRegistrationForm(obj)
{	
	validationResponse = validateForm(obj);	
	var returnFlag = true;
	if(validationResponse !== true)
	{
		returnFlag = false;
		return returnFlag;
	}
}
function validateForm(objForm) {
	
	var cstyle     =document.getElementById('covered_area').style.display;
	var pstyle     =document.getElementById('plot_area').style.display;
	var flag = validateFields(objForm);
	
	if(flag != true){
		//return false;
	}


    var pro_covered_area 	= document.getElementById('pro_covered_area').value;
    var pro_plot_area    	= document.getElementById('pro_plot_area').value;
	var covered_area_unit 	= document.getElementById('covered_area_unit').value;
    var plot_area_unit   	= document.getElementById('plot_area_unit').value;
	
	document.getElementById('pro_plot_area_error').parentNode.style.display = 'none';
    document.getElementById('pro_plot_area_error').innerHTML = "";
	document.getElementById('plot_area_unit_error').parentNode.style.display = 'none';
	document.getElementById('plot_area_unit_error').innerHTML = "";
	document.getElementById('covered_area_unit_error').parentNode.style.display = 'none';
	document.getElementById('covered_area_unit_error').innerHTML = "";
	document.getElementById('covered_area_unit_error').parentNode.style.display = 'none';
	document.getElementById('covered_area_unit_error').innerHTML = "";
	
	if(cstyle=='' && pstyle==''){
	//alert(cstyle);	
	if(trim(pro_covered_area)=='' && trim(pro_plot_area)==''){
			document.getElementById('pro_plot_area_error').parentNode.style.display = 'inline';
			document.getElementById('pro_plot_area_error').innerHTML = "Please fill atleast Covered Area or Plot/ Land Area. ";
			flag = false;
			//return false;			
	}
	if(trim(pro_covered_area)!='' && trim(covered_area_unit)=='-1' ){
			document.getElementById('covered_area_unit_error').parentNode.style.display = 'inline';
			document.getElementById('covered_area_unit_error').innerHTML = "Please select covered Area Unit. ";
			flag = false;
			//return false;			
	} 
	if(trim(pro_plot_area)!='' && trim(plot_area_unit)=='-1' ){
			document.getElementById('plot_area_unit_error').parentNode.style.display = 'inline';
			document.getElementById('plot_area_unit_error').innerHTML = "Please select Plot Area Unit. ";
			flag = false;
			//return false;			
	} 
		
	}
	else if(cstyle=='' && pstyle=='none'){
	if(trim(pro_covered_area)==''){
			document.getElementById('pro_covered_area_error').parentNode.style.display = 'inline';
			document.getElementById('pro_covered_area_error').innerHTML = "Please fill Covered Area. ";
			flag = false;
			//return false;			
	} 
	if(trim(pro_covered_area)!='' && trim(covered_area_unit)=='-1' ){
			document.getElementById('covered_area_unit_error').parentNode.style.display = 'inline';
			document.getElementById('covered_area_unit_error').innerHTML = "Please select covered Area Unit. ";
			flag = false;
			//return false;			
	} 	
		
	}
	else if(cstyle=='none' && pstyle==''){
	if(trim(pro_plot_area)==''){
			document.getElementById('pro_plot_area_error').parentNode.style.display = 'inline';
			document.getElementById('pro_plot_area_error').innerHTML = "Please fill Plot Area. ";
			flag = false;
			//return false;			
	} 
	if(trim(pro_plot_area)!='' && trim(plot_area_unit)=='-1' ){
			document.getElementById('plot_area_unit_error').parentNode.style.display = 'inline';
			document.getElementById('plot_area_unit_error').innerHTML = "Please select Plot Area Unit. ";
			flag = false;
			//return false;			
	} 
    		
	}

    var total_price_style     		=document.getElementById('total_price').style.display;
	var per_unit_price_style  		=document.getElementById('per_unit_price').style.display;
	//alert(total_price_style);
	var monthly_rent_style    		=document.getElementById('monthly_rent').style.display;
	var monthly_unit_price_style  	=document.getElementById('monthly_unit_price').style.display;
        
    var pro_total_price 			= document.getElementById('pro_total_price').value;
    
	var pro_monthly_rent   			= document.getElementById('pro_monthly_rent').value;
	
	var pro_per_unit_price 			= document.getElementById('pro_per_unit_price').value;
	var per_unit_price_unit         = document.getElementById('per_unit_price_unit').value;
    var per_unit_area_type   		= document.getElementById('per_unit_area_type').value;
	
	var monthly_unitprice   		= document.getElementById('monthly_unitprice').value;
	var monthely_rent_unit   		= document.getElementById('monthely_rent_unit').value;
	var monthely_rent_orderedby		= document.getElementById('monthely_rent_orderedby').value;
	
	
	document.getElementById('pro_per_unit_price_error').parentNode.style.display = 'none';
    document.getElementById('pro_per_unit_price_error').innerHTML = "";
	document.getElementById('per_unit_price_unit_error').parentNode.style.display = 'none';
	document.getElementById('per_unit_price_unit_error').innerHTML = "";
	document.getElementById('per_unit_area_type_error').parentNode.style.display = 'none';
	document.getElementById('per_unit_area_type_error').innerHTML = "";
	document.getElementById('pro_total_price_error').parentNode.style.display = 'none';
	document.getElementById('pro_total_price_error').innerHTML = "";
	
	document.getElementById('monthly_unitprice_error').parentNode.style.display = 'none';
    document.getElementById('monthly_unitprice_error').innerHTML = "";
	document.getElementById('monthely_rent_unit_error').parentNode.style.display = 'none';
	document.getElementById('monthely_rent_unit_error').innerHTML = "";
	document.getElementById('monthely_rent_orderedby_error').parentNode.style.display = 'none';
	document.getElementById('monthely_rent_orderedby_error').innerHTML = "";
	document.getElementById('pro_monthly_rent_error').parentNode.style.display = 'none';
	document.getElementById('pro_monthly_rent_error').innerHTML = "";
    
	if(total_price_style=='' && per_unit_price_style==''){
	//alert("khkj");	
	if(trim(pro_total_price)=='' && trim(pro_per_unit_price)==''){
			document.getElementById('pro_per_unit_price_error').parentNode.style.display = 'inline';
			document.getElementById('pro_per_unit_price_error').innerHTML = "Please fill atleast Total price Or Per Unit price.";
			flag = false;
			//return false;			
	}
	if(trim(pro_per_unit_price)!='' && trim(per_unit_price_unit)=='-1' ){
			document.getElementById('per_unit_price_unit_error').parentNode.style.display = 'inline';
			document.getElementById('per_unit_price_unit_error').innerHTML = "Please select Per Unit Price Unit.";
			flag = false;
			//return false;			
	} 
	if(trim(pro_per_unit_price)!='' && trim(per_unit_area_type)=='-1' ){
			document.getElementById('per_unit_area_type_error').parentNode.style.display = 'inline';
			document.getElementById('per_unit_area_type_error').innerHTML = "Please select Per Unit Area Type. ";
			flag = false;
			//return false;			
	} 
	//return false;	
	} 
	if(total_price_style=='' && per_unit_price_style=='none'){
	//alert("khkj");	
	if(trim(pro_total_price)==''){
			document.getElementById('pro_total_price_error').parentNode.style.display = 'inline';
			document.getElementById('pro_total_price_error').innerHTML = "Please fill Total price.";
			flag = false;
			//return false;			
	}
	 
	//return false;	
	}
	
   /* if(total_price_style=='none' && per_unit_price_style==''){
	//alert("khkj");	
	if(trim(pro_per_unit_price)==''){
			document.getElementById('pro_per_unit_price_error').parentNode.style.display = 'inline';
			document.getElementById('pro_per_unit_price_error').innerHTML = "Please fill Per Unit price.";
			return false;			
	}
	if(trim(pro_per_unit_price)!='' && trim(per_unit_price_unit)=='-1' ){
			document.getElementById('per_unit_price_unit_error').parentNode.style.display = 'inline';
			document.getElementById('per_unit_price_unit_error').innerHTML = "Please select Per Unit Price Unit.";
			return false;			
	} 
	if(trim(pro_per_unit_price)!='' && trim(per_unit_area_type)=='-1' ){
			document.getElementById('per_unit_area_type_error').parentNode.style.display = 'inline';
			document.getElementById('per_unit_area_type_error').innerHTML = "Please select Per Unit Area Type. ";
			return false;			
	} 
	return false;	
	}*/
	if(monthly_rent_style=='' && monthly_unit_price_style==''){
	//alert("khkj");	
	if(trim(monthly_unitprice)=='' && trim(pro_monthly_rent)==''){
			document.getElementById('monthly_unitprice_error').parentNode.style.display = 'inline';
			document.getElementById('monthly_unitprice_error').innerHTML = "Please fill atleast Monthly Rent Or Monthly Per Unit price.";
			flag = false;
			//return false;			
	}
	if(trim(monthly_unitprice)!='' && trim(monthely_rent_unit)=='-1' ){
			document.getElementById('monthely_rent_unit_error').parentNode.style.display = 'inline';
			document.getElementById('monthely_rent_unit_error').innerHTML = "Please select Monthly Unit Price Unit.";
			flag = false;
			//return false;			
	} 
	if(trim(monthly_unitprice)!='' && trim(monthely_rent_orderedby)=='-1' ){
			document.getElementById('monthely_rent_orderedby_error').parentNode.style.display = 'inline';
			document.getElementById('monthely_rent_orderedby_error').innerHTML = "Please select Monthly Unit Area Type. ";
			
			flag = false;
			//return false;			
	} 
	//return false;	
	} 
	if(monthly_rent_style=='' && monthly_unit_price_style=='none'){
	//alert("khkj");	
	if(trim(pro_monthly_rent)==''){
			document.getElementById('pro_monthly_rent_error').parentNode.style.display = 'inline';
			document.getElementById('pro_monthly_rent_error').innerHTML = "Please fill Total price.";
			
			flag = false;
			//return false;			
	}
	//return false;	
	}
	
return flag;
}
function validate_security()
{
	var quest = $('SSQ_security').value;
	var ans = $('ans_security').value;
	if (quest == '-1' || ans == '') {		
		document.getElementById('ans_security_error').parentNode.style.display = 'inline';
		document.getElementById('ans_security_error').innerHTML = 'Please enter required details.';
		return false;
	} else {
		document.getElementById('ans_security_error').parentNode.style.display = 'none';
		document.getElementById('ans_security_error').innerHTML = '';
		return true;
	}
}

function validate_forgot()
{
	var flag = validateFields($('frm1'));
	if(flag != true){ return false; } else { return true;}	
}
function validate_emailid()
{
	var url = '/user/checkExistEmail/';
	var mysack = new sack();
	mysack.requestFile = url;
	mysack.method = 'POST';
	mysack.setVar( "emailid", $('reg_email').value );	
	mysack.onCompletion = function()
	{	
		var str = mysack.response;			
		if(str == '1')
		{	
			$('reg_email_error').parentNode.style.display = 'block';
			$('reg_email_error').innerHTML = "Email already exist, Choose other";	
			return false;
		}
		if(str == '0')
		{
			$('reg_email_error').innerHTML = "";
			$('reg_email_error').parentNode.style.display = 'none';
			return true;
		}
		
	};
	mysack.runAJAX();
}
function validate_captcha()
{
	var url = '/user/validate_captcha/'+document.getElementById('seccode').value+'/seccode';
	var mysack = new sack();
	mysack.requestFile = url;
	mysack.method = 'POST';
	mysack.onCompletion = function()
	{
		var str = mysack.response;			
		if(str == '0')
		{			
			$('seccode_error').parentNode.style.display = 'block';
			$('seccode_error').innerHTML = 'Code do not match, Please try again.';	
			return false;
		}
		if(str == '1')
		{
			$('seccode_error').innerHTML = "";
			$('seccode_error').parentNode.style.display = 'none';
			return true;
		}
	};
	mysack.runAJAX();
}



function checkRequired(field){
    var requiredFlag;
    if(field.getAttribute('required')) {
        requiredFlag = true;
    } else {
        if(field.value != '') {
            requiredFlag = true;
        } else {
            requiredFlag = false;
        }
    }
    return requiredFlag;
}
function overlayHackLayerForIE(overlayId, spanArea){
    overlayHackForIE(overlayId, spanArea);
}

function overlayHackForIE(overlayId, spanArea){
    var iframeElement = $('iframe_div');
    if(iframeElement != null) {
        var iframStyleElement = iframeElement.style;
        if(iframeElement.getAttribute('container') !='' && iframeElement.getAttribute('container') != overlayId && iframStyleElement.display != 'none') {
            dissolveOverlayHackForIE();
        }
        iframeElement.setAttribute('container',overlayId);
        iframeElement.container = overlayId;
        iframStyleElement.display = 'block';
        iframStyleElement.width = spanArea.offsetWidth + 'px';
        iframStyleElement.height = spanArea.offsetHeight + 'px';
        iframStyleElement.top = obtainPostitionY(spanArea) +'px';
        iframStyleElement.left = obtainPostitionX (spanArea)+'px';
        if ($(overlayId).style.zIndex != 0 || $(overlayId).style.zIndex!= '') {
            iframStyleElement.zIndex = parseInt($(overlayId).style.zIndex) -1;
        } else {
            iframStyleElement.zIndex = 1000;
        }
    }
}
function enableElement(eleId)
{
	if($(eleId))
		$(eleId).disabled = false;
}
function disableElement(eleId)
{
	if($(eleId))
		$(eleId).disabled = true;
}
function upLoadJsOnDemand(jsToUpLoad,isVersioned){	
	var jsIncluded = $('cvsJsIncludedOnPage').value;
	if($('cvsJsIncludedOnPage')){
		if(jsIncluded.indexOf(jsToUpLoad) != -1){
			return;
		}
	}
	jsIncluded += ','+jsToUpLoad;
	if(!(isVersioned)){
		jsToUpLoad = '//'+JSURL+'/public/js/'+jsToUpLoad+'.js';
	}else{
		jsToUpLoad = '//'+JSURL+'/public/js/'+jsToUpLoad+JSVERSION+'.js';
	}
	
	var js = document.createElement('script');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src',jsToUpLoad);
	js.setAttribute('defer', 'defer');
	document.body.appendChild(js);
	$('cvsJsIncludedOnPage').value = jsIncluded;
	return;	
}
function insertWbr(str,offSet)
{
     return str.replace(eval("/[^ ]{"+offSet+",}?/g"),'$&<wbr/>');
}

function randNum()
{
	return Math.floor(Math.random() * 1000000);
}
function reloadCaptcha(imageId,secvariable,width1,height1)
{
    randomkey = Math.floor(Math.random() * 1000000);
	width1 = (typeof(width1) != 'undefined')?width1:100;
	height1 = (typeof(height1) != 'undefined')?height1:40;
    if(typeof(secvariable) == 'undefined')
    {
    $(imageId).src = "/public/captcha/CaptchaSecurityImages.php?width="+width1+"&height="+height1+"&characters=5&junk="+ randomkey;
    }
    else
    {
    $(imageId).src = "/public/captcha/CaptchaSecurityImages.php?width="+width1+"&height="+height1+"&characters=5&junk="+ randomkey+"&secvariable="+secvariable;
    }
}
function validateEmail(email, caption, maxLength, minLength) {
    if(email.length ==0 && (typeof(minLength)) && minLength ==0){
        return true;
    }
    var filter = /^((([a-z]|[A-Z]|[0-9]|\-|_)+(\.([a-z]|[A-Z]|[0-9]|\-|_)+)*)@((((([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9]|\-){0,61}([a-z]|[A-Z]|[0-9])\.))*([a-z]|[A-Z]|[0-9])([a-z]|[A-Z]|[0-9]|\-){0,61}([a-z]|[A-Z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/
        if(email == '') {
            return  "Please enter your "+ caption +".";
        }else if(!filter.test(email)) {
            return "The "+ caption +" specified is not correct.";
        }
    return true;
}
var validateFieldsFocusElement = null;
function validateFields(objForm) {
	
    var returnFlag = true;
    for(var formElementsCount=0; formElementsCount<objForm.elements.length; formElementsCount++) {
        var formElement = objForm.elements[formElementsCount];
        if(formElement.getAttribute('validate')) {
            var methodName = formElement.getAttribute('validate');
			var textBoxContent = trim(formElement.value);
            textBoxContent = stripHtmlTags(textBoxContent);
			var flagForContent = true;
			if((typeof(formElement.type) != 'undefined') && ((formElement.type=='select-one') || (formElement.type=='select-multiple'))){
				var flagForContent = false;
			}
			if(flagForContent){
            	formElement.value = textBoxContent;
			}
	    var strictCheck = false; 	
            if((formElement.getAttribute('validateSpecial')) && (formElement.getAttribute('validateSpecial') == 'strict')){	
		var strictCheck = true;
		textBoxContent = escape(textBoxContent);
	    }
	    if(!strictCheck){
		textBoxContent = textBoxContent.replace(/[(\n)\r\t\"\'\\]/g,' ');
		textBoxContent = textBoxContent.replace(/[^\x20-\x7E]/g,'');
	    }	
            var textBoxMaxLength  = formElement.getAttribute('maxlength');
            var textBoxMinLength  = formElement.getAttribute('minlength');
            var displayprop = formElement.style.display ;
            var caption;
            try{
                caption  = formElement.getAttribute('caption');
            } catch(e){
                caption = 'field';
            }

            if((!checkRequired(formElement) || displayprop == "none")) { 
            if(displayprop == "none") { 
            $(formElement.id +'_error').parentNode.style.display = 'none';
            $(formElement.id +'_error').innerHTML = '';
            }
            continue;
            }
            var multipleValidateMethods = methodName.split(',');
            var validationResponse;
            for(var multipleValidateMethodCount = 0, validateMethodName;validateMethodName = multipleValidateMethods[multipleValidateMethodCount++];) {
                validateMethodName = trim(validateMethodName);
                var methodSignature = validateMethodName+ '("'+ textBoxContent +'", "'+ caption +'", '+ textBoxMaxLength +', '+ textBoxMinLength +',' + formElement.getAttribute('required') + ')';
                        validationResponse = eval(methodSignature);
                        if(validationResponse !== true) { break; }
            }
            if(validationResponse !== true) {
	            $(formElement.id +'_error').parentNode.style.display = 'inline';
	            $(formElement.id +'_error').innerHTML = validationResponse;
                if ( validateFieldsFocusElement === null ) {
                    validateFieldsFocusElement = $(formElement.id);
                }
	            returnFlag = false;
            } else {
                //alert(formElement.id);
	            $(formElement.id +'_error').parentNode.style.display = 'none';
	            $(formElement.id +'_error').innerHTML = '';
	 	  	if(!checkProfanity(formElement, caption)) { returnFlag = false;continue; }
            }
		} else {
			try{
				var caption  = formElement.getAttribute('caption');
	        	var textBoxMaxLength  = formElement.getAttribute('maxlength');
	            var textBoxMinLength  = formElement.getAttribute('minlength');
	            textBoxMinLength = textBoxMinLength == null ? 0 :  textBoxMinLength;
	            textBoxMaxLength = textBoxMaxLength == null ? 0 :  textBoxMaxLength;
                    if(((formElement.value.length > textBoxMaxLength || formElement.value.length < textBoxMinLength) && (formElement.value.length != 0) && (textBoxMaxLength != 0)) && (formElement.type == 'text' || formElement.type=='textarea')) {
	           		$(formElement.id +'_error').parentNode.style.display = 'inline';
                    if (textBoxMinLength == textBoxMaxLength ) {      
	            	        $(formElement.id +'_error').innerHTML = 'Please fill the '+ caption + ' with '+ textBoxMaxLength +' characters.';
                    } else {
                            $(formElement.id +'_error').innerHTML = 'Please fill the '+ caption + ' within the range of '+ textBoxMinLength + ' to '+ textBoxMaxLength +' characters.';      
                    }      
	            	returnFlag = false;
	            	continue;
	            } else {
	            	$(formElement.id +'_error').parentNode.style.display = 'none';
	            }
	        	if(!checkProfanity(formElement, caption)) { returnFlag = false;  continue; }
	        } catch(e){}
		}
    }
    try{
        if ( validateFieldsFocusElement !== null ){
            validateFieldsFocusElement.focus();
            validateFieldsFocusElement  = null;
        }
    } catch(e) {}
    return returnFlag;
}

function checkProfanity(formElement, caption) {
    var profanityCheck ;
    try {
        profanityCheck = formElement.getAttribute('profanity');
    } catch (e) {
        profanityCheck = false;
    }
	try{
    	if((formElement.getAttribute('readonly')) && (formElement.getAttribute('readonly')!== null)) return true;
	}catch (e){}
    profanityCheck = true;
    if (formElement.type == "text"  || formElement.type == "textarea") {
       if(profanityCheck){
	  var textBoxContent = trim(formElement.value);
	  formElement.value = textBoxContent;
	  textBoxContent = textBoxContent.replace(/[(\n)\r\t\"\']/g,' ');
	      textBoxContent = textBoxContent.replace(/[^\x20-\x7E]/g,'');
	  var profaneResponse = isProfane(textBoxContent);
	  if(profaneResponse !== false) {
	     try {
		$(formElement.id +'_error').parentNode.style.display = 'inline';
		$(formElement.id +'_error').innerHTML = 'Please don\'t use objected words ('+ profaneResponse +') for the ' + caption;
		return false;
	     } catch (e) {}
	  } else {
	     try {
		if($(formElement.id +'_error').innerHTML.indexOf('objected words') > -1) {
		   $(formElement.id +'_error').parentNode.style.display = 'none';
		   $(formElement.id +'_error').innerHTML = '';
		}
		return true;
	     } catch (e) {}
	  }
       } else {
	  return true;
       }
    }
    else {
       return true;
    }
}

function validateStr(str, caption, maxLength,minLength, allowedChars){
	if(document.getElementById('allCities')){
	if(document.getElementById('allCities').checked && caption=="City"){
		str="1";
	}
	}
     str = str.replace(/[^\x20-\x7E]/g,'');
      if (checkHtmlTags(str)){
		return "HTML tags will be removed.";
	}
    if(str.length == '') {
        return  "Please enter the "+ caption +".";
    }else if(str.length > maxLength) {
        //return caption+ " cannot exceed "+ maxLength +" characters.";
        return "Please use a maximum of "+maxLength+" characters for "+caption;
    } else if(str.length<minLength) {
        return "The " + caption+ " must contain atleast "+ minLength +" characters.";
    } else {
        str = removeNewLineCharacters(str) ; 
        str = str.toLowerCase();
        //str = str.replace(/[:;?.\-_!,\/]/g,' ');	As per Bug Id#31054.
        var strArray = str.split(" ");
        for(var strArrayCount = 0; strArrayCount < strArray.length; strArrayCount++) {
            if((strArray[strArrayCount].length > 32) && (strArray[strArrayCount].search(/(http|https)?(:\/\/)/) == -1)) {
                return caption + " cannot contain any word exceeding 32 characters.";
            } else {
                if(isRestrictedWord(strArray[strArrayCount])) {
                    return false;
                }
            }
        }
        return true;
    }
}

function validateSecurityCode(str, caption, maxLength,minLength, allowedChars){
   if(str.length > maxLength) {
        return "Please enter the "+caption+" as shown in the image.";
    } else if(str.length<minLength) {
        return "Please enter the "+caption+" as shown in the image.";
    } else {
        return true;
    }
}
function validateSelect(str,caption,maxLength,minLength) {
   if(str.length =='') {
	return "Please select "+caption+".";
     }
    return true;
}
function removeNewLineCharacters(str) {
	if (str.indexOf('\r\n')!=-1)
	str = str.replace ( /\r\n/g, ' ' );
  	else if (str.indexOf('\r')!=-1)
    str = str.replace ( /\r/g, ' ' );
  	else if (str.indexOf('\n')!=-1)
    str = str.replace ( /\n/g, ' ' );
  return str;
}
function changeEmail(email,caption,maxlength,minlength)
{
	var flag = validateEmail(email,caption,maxlength,minlength);
	if(flag != true)
	{
	$('newemail_error').parentNode.style.display = 'inline';
	$('newemail_error').innerHTML = flag;
	return false;
	}
	else
	{
		var xmlHttp = getXMLHTTPObject();
		xmlHttp.onreadystatechange=function() {
			if(xmlHttp.readyState==4) {
				var response = xmlHttp.responseText;
			reloadCaptcha('changeEmailCaptacha','seccodechangeemail');
			if(response == "exists")
			{
			$('newemail_error').innerHTML = 'Email you provided already exists.Please provide a valid email-id';
			$('newemail_error').parentNode.style.display = 'inline';
			$('changecapt_error').innerHTML = '';
			$('changecapt_error').parentNode.style.display = 'none';
			}
			if(response == "same")
			{
			$('newemail_error').innerHTML = 'You have provided your old email-id.Please give an alternate email-id if you wish to change it.';
			$('newemail_error').parentNode.style.display = 'inline';
			$('changecapt_error').innerHTML = '';
			$('changecapt_error').parentNode.style.display = 'none';
			}

			if(response == 1)
			{
			$('newemail_error').innerHTML = 'Email changed successfully.Verification mail is sent to the email provided by you.Please verify your email to enjoy the benefits of gharbana.com.';
			var usercookie = getCookie('user').split("|");
			var value = email + "|" + usercookie['1'] + "|pendingverification";
			setCookie("user",value);
			window.setTimeout(function(){window.location.reload();}, 5000);
			$('newemail_error').parentNode.style.display = 'inline';
			$('changecapt_error').innerHTML = '';
			$('changecapt_error').parentNode.style.display = 'none';
			}
				} 
			if(response == "code")
			{
			$('changecapt_error').innerHTML = 'Please enter the Security Code as shown in the image.';
			$('changecapt_error').parentNode.style.display = 'inline';
			$('newemail_error').innerHTML = '';
			$('newemail_error').parentNode.style.display = 'none';
			}
			}
		var url = '/user/Userregistration/changeEmail/'+ email + '/' + $('changeCapt').value;
	xmlHttp.open("POST",url,true);
	xmlHttp.setRequestHeader("Content-length", 0);
	xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(null);
		return false;
	}
}
function validateDisplayName(str,caption, maxLength,minLength, allowedChars){
	var strToValidate = trim(unescape(str));
	var allowedChars = /^([A-Za-z0-9\s](,|\.|_|-){0,2})*$/;
	if(strToValidate == '')
		return "Please enter your "+caption;

	if(strToValidate.length < minLength)
		return caption+" should be atleast "+ minLength +" characters.";

	if(strToValidate.length > maxLength)
		return caption+" cannot exceed "+ maxLength +" characters.";

	var result = allowedChars.test(strToValidate);
	if(result == false)
		return "The " + caption+" can not contain special characters.";

	return true;
}

function validateAlphabetic(str,caption, maxLength,minLength, allowedChars){
	var strToValidate = trim(str);
	var allowedChars = /^[a-zA-Z]+$/;
	if(strToValidate == '')
		return "Please enter the "+caption;

	if(strToValidate.length < minLength)
		return caption+" should be atleast "+ minLength +" characters.";

	if(strToValidate.length > maxLength)
		return caption+" cannot exceed "+ maxLength +" characters.";

	var result = allowedChars.test(strToValidate);
	if(result == false)
		return caption+" should be alphabetic.";

	return true;
}

function validateStringCityValue(str,caption, maxLength,minLength, allowedChars){
	var strToValidate = trim(str);
	var allowedChars = /^[a-zA-Z0-9\s_-]+$/;
	if(strToValidate == '')
		return "Please enter the "+caption;

	if(strToValidate.length < minLength)
		return caption+" should be atleast "+ minLength +" characters.";

	if(strToValidate.length > maxLength)
		return caption+" cannot exceed "+ maxLength +" characters.";

	var result = allowedChars.test(strToValidate);
	if(result == false)
		return caption+" can not contain special characters.";

	return true;
}

function validateUrl(url, caption) {
    var filter = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w\[\]\|`<>:{}!\^\*\(\)]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(url == '') {
        return  "Please enter the "+ caption +".";
    }else if(!filter.test(url)){
        return "Please enter "+ caption +" in correct format";
    }
    return true;
}

    function validateInteger(number, caption, maxLength, minLength) {
        if (number.toString().length==0 && minLength==0) {
            return true;
        }
        var filter = /^(\d)+$/;
        if(!filter.test(number)){
            return 'Please fill the '+ caption +' with correct numeric value';
        }
        minLength = typeof(minLength) != undefined ? minLength : 0;
        maxLength = typeof(maxLength)!= undefined ? maxLength : number.toString().length;
        if(number.toString().length > maxLength || number.toString().length < minLength) {
            if (maxLength !== minLength) {
                return 'Please fill the '+ caption +' with '+ minLength +' to '+ maxLength +' digits';
            } else {
                return 'Please fill the '+ caption +' with '+ maxLength +' digits';
            }
        }
        return true;
    }

function validateLandlineInteger(number,caption,maxlength,minlength,required) {
    var filter = /^(\d)+$/;
    if(number != '')
    {
        if(!filter.test(number)){
            return "Please enter your correct " + caption;
        }
        

        if(maxlength == minlength && (number.length  > maxlength || number.length < minlength))
            return "The " + caption + " must have " + maxlength + " digits only";
        if(number.length < minlength){
            return "The " + caption + " must contain minimum " + minlength + " digits";
        }
        if(number.length > maxlength){
            return "The " + caption + " can contain maximum " + maxlength + " digits";
        }
        return true;
    }
    if(number == '' && required) {
        return "Please enter your contact number";
    }
    return true;
}

function validateMobileInteger(number,caption,maxlength,minlength,required) {
    var filter = /^(\d)+$/;
    if(number != '')
    {
        if(!filter.test(number)){
            return "Please enter your correct " + caption;
        }
        if((number.substr(0,1) != 9)&&(number.substr(0,1) != 8))
        return "The mobile number can start with 9 or 8 only.";
        if(maxlength == minlength && (number.length  > maxlength || number.length < minlength))
            return "The mobile number must have " + maxlength + " digits only";
        if(number.length < minlength){
            return "The mobile number must contain minimum " + minlength + " digits";
        }
        if(number.length > maxlength){
            return "The mobile number can contain maximum " + maxlength + " digits";
        }
        return true;
    }
    if(number == '' && required) {
        return "Please enter your "+ caption;
    }
    return true;
}

function validateZip(number, caption, maxLength, minLength) {
    var filter = /^(\d)+$/;
    if(!filter.test(number)){
        return "Please fill the field with correct numeric value";
    }
    else {
        if(number.length > maxLength || number.length<minLength) {
            return "Please fill the field with valid zip/pincode 5-6 digits.";
        }
    }
    return true;
}


function validateDate(dateStr, caption, maxLength) {
    if(dateStr == ''){
        return "Please enter the "+ caption;
    } else if(!validateStr(dateStr,10)){
        return "Please enter date in correct format of yyyy-mm-dd";
    }
    var dateArray = dateStr.split("-");
    if(dateArray.length < 3 ) {
        return "Please enter date in correct format of yyyy-mm-dd";
    }
    var eneterdYear = dateArray[0];
    var eneterdMonth = dateArray[2];
    var eneterdDay = dateArray[1];
    if((validateInteger(eneterdYear,4) != true) ||( validateInteger(eneterdMonth,2) != true) || ( validateInteger(eneterdDay,2) != true)) {
        return "Please enter date in correct format of yyyy-mm-dd with all the values as numbers";
    }
    return true;
}

function validateStartDate(){
    var startDate = $('start_date').value;
    var startDateValidationResponse = validateDate(startDate,$('start_date').getAttribute('caption'),$('start_date').getAttribute('maxLength'));
    if(startDateValidationResponse === true){
        $('start_date_error').innerHTML= '';
        return true;
    }else{
        $('start_date'+'_error').parentNode.style.display = 'block';
        $('start_date'+'_error').innerHTML= startDateValidationResponse;
    }
    return startDateValidationResponse;
}

function validateEndDate(dateStr, caption, maxLength){
    var dateResponse = validateDate(dateStr, caption, maxLength);
    var startDate = $('start_date').value;
    if(validateStartDate() !== true && !$('end_date').getAttribute('required')) { return '';}

    if(dateResponse === true) {
        var startDateArr = startDate.split('-');
        var endDateArr = dateStr.split('-');
		startDateArr[1] = (startDateArr[1].indexOf('0')==0) ? startDateArr[1].replace('0','') : startDateArr[1];
		endDateArr[1] = (endDateArr[1].indexOf('0')==0) ? endDateArr[1].replace('0','') : endDateArr[1];
		startDateArr[2] = (startDateArr[2].indexOf('0')==0) ? startDateArr[2].replace('0','') : startDateArr[2];
		endDateArr[2] = (endDateArr[2].indexOf('0')==0) ? endDateArr[2].replace('0','') : endDateArr[2];
        var startDate =new Date(parseInt(startDateArr[0]), parseInt(startDateArr[1])-1, parseInt(startDateArr[2]));
        var endDate =new Date(parseInt(endDateArr[0]), parseInt(endDateArr[1])-1, parseInt(endDateArr[2]));
        var one_day=1000*60*60*24;
        var dateDiff = Math.ceil((endDate.getTime()-startDate.getTime())/(one_day));
        if(dateDiff >= 0 ) {
            if(dateDiff > 90) {
                return 'The difference between End date and Start date should not be more than 90 days.';
            }else {
                return true;
            }
        } else {
            return 'End date should be greater than Start Date';
        }
    } else {
        return dateResponse;
    }
}

function validateTime(timeStr, caption, maxLength) {
    var timeArray = timeStr.split(":");
    if(timeStr == "") {
        return "Please enter the "+ caption;
    } else if(timeArray.length < 2 ) {
        return "Please enter the "+ caption +" in correct format of hh:mm";
    }
    var eneterdHour = timeArray[0];
    var eneterdMinute = timeArray[1];
    if((validateInteger(eneterdHour,2) != true) ||( validateInteger(eneterdMinute,2) != true)) {
        return "Please enter the "+ caption +" in correct format of hh:mm";
    }
    if(parseInt(eneterdHour) > 12 || (parseInt(eneterdHour) < 0 && eneterdHour.indexOf(0) != 0)){
        return "Please enter the "+ caption +" in correct format of hh:mm with all the values in numbers";
    }
    if(parseInt(eneterdMinute) > 59 || (parseInt(eneterdMinute) < 0 && eneterdMinute.indexOf(0) != 0)){
        return "Please enter the "+ caption +" in correct format of hh:mm with all the values in numbers";
    }
    return true;
}

function validateEndTime(timeStr, caption, maxLength) {
    var timeResponse = validateTime(timeStr, caption, maxLength);
    if($('end_date_error').innerHTML != '') {return '';}
    if(timeResponse === true) {
        if($('start_date').value == $('end_date').value || $('end_date').value == ''){
            var startTime = $('start_time').value;
            var startTimeStamp = ($('startTimeStampAM').checked) ? $('startTimeStampAM').value : $('startTimeStampPM').value;

            var endTimeStamp = ($('endTimeStampAM').checked) ? $('endTimeStampAM').value : $('endTimeStampPM').value;

            var endTime = $('end_time').value;
            var startTimeArr = startTime.split(':');
            var endTimeArr = endTime.split(':');
            var startHour = (startTimeArr[0].indexOf('0') > 0) ? startTimeArr[0] : startTimeArr[0].replace('0','');
            var endHour = (endTimeArr[0].indexOf('0') > 0 )? endTimeArr[0] : endTimeArr[0].replace('0','');
            startHour = parseInt(startHour) + parseInt(startTimeStamp);
            endHour = parseInt(endHour) + parseInt(endTimeStamp);
            if(startHour >= endHour) {
                return 'Please enter the End time greater than Start time';
            }else {
                $('end_time_error').innerHTML = '';
                return true;
            }
        } else {
            return true;
        }
    } else {
        return timeResponse;
    }
}
function checkDisAllowedWord(str){
	str = str.replace(/[^\x20-\x7E]/g,'');
	var disallowdWordsList = base64_decode("bWVyYWNhcmVlcmd1aWRlfG1lcmFjYXJlZXJndWlkfHJlYWNoQGluZHJhaml0LmlufHd3dy5pbmRyYWppdC5pbnwwOTgxMDIyNTExNA==");
	var url_pattern = new RegExp(disallowdWordsList,"i");
	var dissallowedWord = url_pattern.exec(str);
	if(dissallowedWord != null){
		return dissallowedWord;
	}
	return true;
}
function isProfane(str) {
/*code start to avoid dissallowed chars */
var responseValue = checkDisAllowedWord(str);
if(responseValue !== true){
	return responseValue;
}
/*code end to avoid dissallowed chars */
var profaneWordsBag = eval(base64_decode('WyJzdWNrIiwiZnVjayIsImRpY2siLCJwZW5pcyIsImN1bnQiLCJwdXNzeSIsImhvcm55Iiwib3JnYXNtIiwidmFnaW5hIiwiYmFiZSIsImJpdGNoIiwic2x1dCIsIndob3JlIiwid2hvcmlzaCIsInNsdXR0aXNoIiwibmFrZWQiLCJpbnRlcmNvdXJzZSIsInByb3N0aXR1dGUiLCJzZXgiLCJzZXh3b3JrZXIiLCJzZXgtd29ya2VyIiwiYnJlYXN0IiwiYnJlYXN0cyIsImJvb2IiLCJib29icyIsImJ1dHQiLCJoaXAiLCJoaXBzIiwibmlwcGxlIiwibmlwcGxlcyIsImVyb3RpYyIsImVyb3Rpc20iLCJlcm90aWNpc20iLCJsdW5kIiwiY2hvb3QiLCJjaHV0IiwibG9yYSIsImxvZGEiLCJyYW5kIiwicmFuZGkiLCJ0aGFyYWsiLCJ0aGFyYWtpIiwidGhhcmtpIiwiY2hvZCIsImNob2RuYSIsImNodXRpeWEiLCJjaG9vdGl5YSIsImdhYW5kIiwiZ2FuZCIsImdhbmR1IiwiZ2FhbmR1IiwiaGFyYWFtaSIsImhhcmFtaSIsImNodWRhaSIsImNodWRuYSIsImNodWR0aSIsImJhZGFuIiwiY2hvb2NoaSIsInN0YW4iLCJuYW5naSIsIm5hbmdhIiwibmFuZ2UiLCJwaHVkZGkiLCJmdWRkaSIsImxpZmVrbm90cyIsIjA5ODEwMTEyOTU0IiwiYWJpZGphbiIsInNpZXJyYS1MZW9uZSIsInNlbmVnYWwiLCJzaWVycmEgbGVvbmUiLCJsdWNreSBtYW4iLCJzaXJhIiwibWFkaGFyY2hvZCIsInRoYWJvIiwiZnVja2VkIiwiZnVja2luZyIsInB1YmxpYyBzaXRlIiwiRGFrdSIsInByaXZhdGUgbWFpbCIsInByaXZhdGUgbWFpbGJveCIsInNleHkiLCJqb2JzIHZhY2FuY2llcyIsIm9tbmkgY2l0eSIsImJhc3R1cmQiLCJqZWhhZCIsInRlbmRlcm5lc3MgY2FyZSIsIm1lcmFjYXJlZXJndWlkZS5jb20iLCJtZXJhY2FyZWVyZ3VpZGUiXQ=='));
	var words = str.split(" ");
	for(var wordsCount = 0; wordsCount < words.length; wordsCount++) {
		for(var profaneWordsCount = 0; profaneWordsCount < profaneWordsBag.length; profaneWordsCount++) {
			if(words[wordsCount] == profaneWordsBag[profaneWordsCount]) {
				return profaneWordsBag[profaneWordsCount];
			}
		}
	}
    return false;
}
function selectMultiComboBox(comboBox, valuesToSelect) {
    for(var i=0; i < comboBox.options.length; i++) {
       comboBox.options[i].selected = false;
        for(var j=0; j<valuesToSelect.length; j++){
           if(comboBox.options[i].value == valuesToSelect[j]) {
              comboBox.options[i].selected = true;
              break;
         }
      }
    }
    return true;
}
function truncateString(str, numChars) {
    str = trim(str);
    if(str.length > numChars) {
        str = str.substr(0,numChars-3);
        str +='...';
    }
    return str;
}

function showElement(showElement) {
    if(showElement) {
	showElement.style.display = '';
        showElement.style.display = 'inline';
    }
}
function hideElement(hideElement) {
    if(hideElement) {
	hideElement.style.display = '';
        hideElement.style.display = 'none';
    }
}

function getElementsByClassName(parent,tag,classIE)
{
    var arrElements = (tag == "*" && parent.all)? parent.all :parent.getElementsByTagName(tag);
    var arrReturn = new Array();
    var classIE = classIE.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + classIE + "(\\s|$)");
    for(var i=0; i<arrElements.length; i++)
    {
        var oElement = arrElements[i];
        if(oRegExp.test(oElement.className))
        {
            arrReturn.push(oElement);
        }
    }
    return arrReturn;
}
function addOnFocusToopTip(objForm)
{
    for(var formElementsCount=0; formElementsCount<objForm.elements.length; formElementsCount++) {
        var formElement = objForm.elements[formElementsCount];
        if (formElement.getAttribute('tip')){
            formElement.onfocus = showTip;
        }
    }
}
function addOnBlurValidate(objForm)
{
	
    for(var formElementsCount=0; formElementsCount<objForm.elements.length; formElementsCount++) {
       var formElement = objForm.elements[formElementsCount];
       if(formElement.getAttribute('validate') || formElement.getAttribute('blurMethod') || formElement.getAttribute('blurmethod')) {
	  formElement.onblur = function () {
		  
	     try{	 
	 	    hidetip();
	     }catch(e){}	
         var returnFlag = true;
         if (this.getAttribute('blurMethod')) {
             returnFlag = eval(this.getAttribute('blurMethod'));
         }else if (this.getAttribute('blurmethod')) {
             returnFlag = eval(this.getAttribute('blurmethod'));
         }
         if(!returnFlag) { return false; }
	     if (this.getAttribute('validate')) {
			 
	            var methodName = this.getAttribute('validate');
				
				var textBoxContent = trim(this.value);
				
				var flagForContent = true;
				if((typeof(this.type) != 'undefined') && ((this.type=='select-one') || (this.type=='select-multiple'))){
					var flagForContent = false;
				}
				if(flagForContent){
					this.value = textBoxContent;
				}
	            textBoxContent = textBoxContent.replace(/[(\n)\r\t\"\'\\]/g,' ');
                textBoxContent = textBoxContent.replace(/[^\x20-\x7E]/g,'');
	            var textBoxMaxLength  = this.getAttribute('maxlength');
	            var textBoxMinLength  = this.getAttribute('minlength');
	            var caption  = this.getAttribute('caption');
                 
				$(this.id +'_error').parentNode.style.display = 'none';
				$(this.id +'_error').innerHTML = '';

	            if(!checkRequired(this)) {return true;}

                var multipleValidateMethods = methodName.split(',');
                var validationResponse;
                for(var multipleValidateMethodCount = 0, validateMethodName;validateMethodName = multipleValidateMethods[multipleValidateMethodCount++];) {
                    validateMethodName = trim(validateMethodName);
                    var methodSignature = validateMethodName+ '("'+ textBoxContent +'", "'+ caption +'", '+ textBoxMaxLength +', '+ textBoxMinLength +',' + this.getAttribute('required') + ')';
                            validationResponse = eval(methodSignature);
                            if(validationResponse !== true) { break; }
                }
				
	            if(validationResponse !== true) {
		            $(this.id +'_error').parentNode.style.display = 'inline';
		            $(this.id +'_error').innerHTML = validationResponse;
		            returnFlag = false;
		        } else {
		            $(this.id +'_error').parentNode.style.display = 'none';
		            $(this.id +'_error').innerHTML = '';
		        }

	        	if(checkProfanity(this, caption)) { return true;}
		     }
		  }
          } else {
          formElement.onblur = function () {

          if(this.id == ''){
          }
          else{
              try{
                  hidetip();
              }catch(e){}
              var caption  = this.getAttribute('caption');
              try{
                  $(this.id +'_error').parentNode.style.display = 'none';
                  var textBoxMaxLength  = this.getAttribute('maxlength');
                  var textBoxMinLength  = this.getAttribute('minlength');
                  textBoxMinLength = textBoxMinLength == null ? 0 :  textBoxMinLength;
                  textBoxMaxLength = textBoxMaxLength == null ? 0 :  textBoxMaxLength;
                  if(((this.value.length > textBoxMaxLength || this.value.length < textBoxMinLength) && (this.value.length != 0) && (textBoxMaxLength != 0)) && (this.type == 'text' || this.type=='textarea')) {
                      $(this.id +'_error').parentNode.style.display = 'inline';
                      $(this.id +'_error').innerHTML = 'Please fill the '+ caption + ' within the range of '+ textBoxMinLength + ' to '+ textBoxMaxLength +' characters.';
                      return true;
                  } else {
                      $(this.id +'_error').parentNode.style.display = 'none';
                  }
                  if(checkProfanity(this, caption)) {
                      return true;
                  }
              }
              catch(e){
              }
          }
          }
          }

    }
}
function stripHtmlTags(str)
{
	var tags = /(<([^>]+)>)/ig;
	plainstr = str.replace(tags, "");
	return plainstr;
}
function checkHtmlTags(str)
{
	var tags = /(<([^>]+)>)/ig;
	return tags.test(str);
}
function base64_decode( data ) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64)      enc += String.fromCharCode(o1);
        else if (h4 == 64) enc += String.fromCharCode(o1, o2);
        else               enc += String.fromCharCode(o1, o2, o3);
    } while (i < data.length);

    return enc;
}
function htmlspecialchars(str){
      return str.replace(/&/g, "&amp;").replace(/</g,"&lt;").replace(/>/g, "&gt;").replace(/'/g, "&#039;").replace(/"/g, "&quot;");
}
function wordwrap( str, int_width, str_break, cut ) {
	var i, j, s, r = str.split("\n");
	if(int_width > 0) for(i in r){
		for(s = r[i], r[i] = ""; s.length > int_width;
				j = cut ? int_width : (j = s.substr(0, int_width).match(/\S*$/)).input.length - j[0].length || int_width,
				r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? str_break : "")
		   );
		r[i] += s;
	}
	return r.join("\n");
}
function base64_encode( data ) {
	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, enc="", tmp_arr = [];
	data = utf8_encode(data);
	do { // pack three octets into four hexets
	o1 = data.charCodeAt(i++);
	o2 = data.charCodeAt(i++);
	o3 = data.charCodeAt(i++);
	bits = o1<<16 | o2<<8 | o3;
	h1 = bits>>18 & 0x3f;
	h2 = bits>>12 & 0x3f;
	h3 = bits>>6 & 0x3f;
	h4 = bits & 0x3f;
	tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);
	enc = tmp_arr.join('');
	switch( data.length % 3 ){
	case 1:
		enc = enc.slice(0, -2) + '==';
		break;
	case 2:
		enc = enc.slice(0, -1) + '=';
		break;
	}
	return enc;
}
function utf8_encode ( string ) {
    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "";
    var start, end;
    var stringl = 0;
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}
function validateResponse(str, caption, maxLength,minLength, allowedChars){
     str = str.replace(/[^\x20-\x7E]/g,'');
      if (checkHtmlTags(str))
		return "HTML tags will be removed.";
    if(str.length == '') {
        return  "Please type your "+ caption +" here.";
    }else if(str.length > maxLength) {
        return "Please use a maximum of "+maxLength+" characters for "+caption;
    } else if(str.length<minLength) {
        return "The " + caption+ " must contain atleast "+ minLength +" characters.";
    } else {
        str = removeNewLineCharacters(str) ; 
        str = str.toLowerCase();
        var strArray = str.split(" ");
        for(var strArrayCount = 0; strArrayCount < strArray.length; strArrayCount++) {
            if((strArray[strArrayCount].length > 32) && (strArray[strArrayCount].search(/(http|https)?(:\/\/)/) == -1)) {
                return caption + " cannot contain any word exceeding 32 characters.";
            } else {
                if(isRestrictedWord(strArray[strArrayCount])) {
                    return false;
                }
            }
        }
        return true;
    }
}
function checkCountry(selectCountryName, selectCityName,selectLocationName,selectCountryOtherName, selectCityOtherName,selectLocationOtherName){
	objCountry = document.getElementById(selectCountryName);
	objCity = document.getElementById(selectCityName);
	objCountryOther = document.getElementById(selectCountryOtherName);
	objCityOther = document.getElementById(selectCityOtherName);
        objLocationOther = document.getElementById(selectLocationOtherName);
	objLocation = document.getElementById(selectLocationName);

	if(objCountry.options[objCountry.selectedIndex].value == 99999){
		objCountryOther.style.display = 'block';
		//objCity.value = '0';
		objCity.style.display = 'none';
		document.getElementById(objCity.id+"_error").innerHTML='';
		objCityOther.style.display = 'block';

                objLocation.style.display = 'none';
		document.getElementById(objLocation.id+"_error").innerHTML='';
		objLocationOther.style.display = 'block';
	}
	else{
		objCountryOther.style.display = 'none';
		document.getElementById(objCountryOther.id+"_error").innerHTML='';
	}
	if(objCountry.options[objCountry.selectedIndex].value != 12){
		//objCity.value = '0';
		objCity.style.display = 'none';
		document.getElementById(objCity.id+"_error").innerHTML='';
		objCityOther.style.display = 'block';

                objLocation.style.display = 'none';
		document.getElementById(objLocation.id+"_error").innerHTML='';
		objLocationOther.style.display = 'block';
	} 
	else{
		objCity.style.display = 'block';
		objCityOther.style.display = 'none';
		document.getElementById(objCityOther.id+"_error").innerHTML='';

                objLocation.style.display = 'block';
		document.getElementById(objLocation.id+"_error").innerHTML='';
		objLocationOther.style.display = 'none';
	}
}
function validateConfirmPassword(password,confirmpassword)
{
	var validateres = false;
	var validateres = validateStr(document.getElementById(confirmpassword).value, 'Confirm Password', 20,5);
	if(validateres !== true)
	{
		document.getElementById(confirmpassword + '_error').style.display = 'block';
		document.getElementById(confirmpassword +'_error').innerHTML = validateres;
		return false;
	}
	else
	{
		document.getElementById(confirmpassword + '_error').style.display = 'none';
		document.getElementById(confirmpassword +'_error').innerHTML = '';

	}
	if(document.getElementById(password).value != document.getElementById(confirmpassword).value)
	{
		document.getElementById(confirmpassword + '_error').style.display = 'block';
		document.getElementById(confirmpassword +'_error').innerHTML = 'Password & Confirm Password do not match';
		return false;
	}
	else
	{
		document.getElementById(confirmpassword + '_error').style.display = 'none';
		document.getElementById(confirmpassword +'_error').innerHTML = '';
		return true;
	}
}
function checkOtherTexBox(onChangeId, relativeId, onChangeOtherId, relativeOtherId){	
	objonChangeId = document.getElementById(onChangeId);
	objonChangeOtherId = document.getElementById(onChangeOtherId);	
	if(relativeId!=''){
	objrelativeId = document.getElementById(relativeId);
	}
	if(relativeOtherId!=''){
	objrelativeOtherId = document.getElementById(relativeOtherId);
	}
	if(objonChangeId.options[objonChangeId.selectedIndex].value == 99999){
		objonChangeOtherId.style.display = 'block';

                objrelativeId.style.display = 'none';
		document.getElementById(objrelativeId.id+"_error").innerHTML='';
		objrelativeOtherId.style.display = 'block';
	}
	else{		
		objonChangeOtherId.style.display = 'none';
		document.getElementById(objonChangeOtherId.id+"_error").innerHTML = '';
                cityValue=objonChangeId.options[objonChangeId.selectedIndex].value;
                show_locality_list(cityValue);
                //alert(cityValue);
                objrelativeId.style.display = 'block';
		document.getElementById(objrelativeId.id+"_error").innerHTML='';
		objrelativeOtherId.style.display = 'none';
	}
}

function show_locality_list(cityValue)
{
    var url = '/user/get_location_list/';
    var mysack = new sack();
    mysack.requestFile = url;
    mysack.method = 'POST';
    mysack.setVar( "CityId",cityValue);
    mysack.onError = function() { alert('oops!!! error occoured.Please try again.' )};
    mysack.onCompletion = function()
    {
                    var str = mysack.response;
                    $('location_div').parentNode.style.display = 'inline';
                    $('location_div').innerHTML = str;

            return false;
    };
    mysack.runAJAX();
	
}
function checkOtherLocalityTexBox(onChangeId, relativeId, onChangeOtherId, relativeOtherId){
	objonChangeId = document.getElementById(onChangeId);
	objonChangeOtherId = document.getElementById(onChangeOtherId);
	if(relativeId!=''){
	objrelativeId = document.getElementById(relativeId);
	}
	if(relativeOtherId!=''){
	objrelativeOtherId = document.getElementById(relativeOtherId);
	}
	if(objonChangeId.options[objonChangeId.selectedIndex].value == 99999){
		objonChangeOtherId.style.display = 'block';
	}
	else{
		objonChangeOtherId.style.display = 'none';
		document.getElementById(objonChangeOtherId.id+"_error").innerHTML = '';
	}
}
function validateLoginId(loginId)
{
	var validateres = false;
	var validateres = validateEmail(document.getElementById(loginId).value, 'Email', 125,9);
	if(validateres !== true)
	{
		document.getElementById(loginId + '_error').parentNode.style.display = 'inline';
		document.getElementById(loginId +'_error').innerHTML = validateres;
		return false;
	}
	else
	{
		document.getElementById(loginId + '_error').parentNode.style.display = 'none';
		document.getElementById(loginId +'_error').innerHTML = '';
			var url = '/user/checkExistEmail/';
			var mysack = new sack();
			mysack.requestFile = url;
			mysack.method = 'POST';
			mysack.setVar( "emailid", $('reg_email').value );
			mysack.onError = function() { alert('oops!!! error occoured.Please try again.' )};
			mysack.onCompletion = function()
			{
				var str = mysack.response;				
				if(str == 1)
				{
					$('reg_email_error').parentNode.style.display = 'inline';
					$('reg_email_error').innerHTML = "Sorry, the ID that you are looking for is taken.";					
				}
				if(str != 1)
				{
					$('reg_email_error').parentNode.style.display = 'inline';
					$('reg_email_error').innerHTML = "<b style='color:#03c311'>Hurry, The ID you've chosen is available</b>";
				}
				closeMessage();
				return false;
			};
			mysack.runAJAX();
	}
}
function validatePhoto(obj)
{	
	var returnFlag = true;
	if($('myPhoto').value==''){		
		$('myPhoto_error').innerHTML = "Please select the photo";
		returnFlag = false;
	} else {
		var value = $('myPhoto').value;
		var to_num = $('myPhoto').value.length;
		var start_num = eval(to_num-3);
		result = value.substring(start_num, to_num);		
		if(result == "gif" || result == "jpg" || result == "jpeg"){			
			$('myPhoto_error').innerHTML = "";
		} else {			
			$('myPhoto_error').innerHTML = "Please correct the image format";
			returnFlag = false;
		}
	}	
	if($('tc').checked!=true){		
		$('tc_error').innerHTML = "Terms & condition should be checked";
		returnFlag = false;
	} else {
		$('tc_error').innerHTML = "";
	}
	if(returnFlag!== true)
	{
		returnFlag = false;
		return returnFlag;
	}	
}
function updatePassword(obj){
	validationResponse = updatePswdForm(obj);	
	var returnFlag = true;
	if(validationResponse !== true)
	{
		returnFlag = false;
		return returnFlag;
	}	
}
function updatePswdForm(obj)
{
	var flag = validateFields(obj);
    if(flag != true){
		returnFlag = false;
	} else {
		returnFlag = true;
	}
	if(document.getElementById('np') && document.getElementById('rp'))
	{
		if(document.getElementById('np').value != document.getElementById('rp').value)
		{
			document.getElementById('rp_error').parentNode.style.display = 'inline';
			document.getElementById('rp_error').innerHTML = 'Password & Confirm Password do not match';
			returnFlag = false;
		}
		else
		{

			if(trim(document.getElementById('cp').value != ''))
			{
				document.getElementById('rp_error').parentNode.style.display= 'none';
				document.getElementById('rp_error').innerHTML = '';
			}
		}
	}
	return returnFlag;
}
function validSaveProfile(obj){	
	validationResponse = SaveProfile(obj);	
	if(validationResponse !== true)
	{
		returnFlag = false;
		return returnFlag;
	}	
}
function SaveProfile(objForm) {	
	if(document.getElementById('reg_countryOther').style.display != "none" && trim(document.getElementById('reg_countryOther').value) == "Enter the country"){
		document.getElementById('reg_countryOther').value='';
	}
	if(document.getElementById('reg_cityOther').style.display != "none" && trim(document.getElementById('reg_cityOther').value) == "Enter the city"){
		document.getElementById('reg_cityOther').value='';
	}	
    var flag = validateFields(objForm);
    if(flag != true){
		returnFlag = false;
	} else {
		returnFlag = true;
	}	
	return returnFlag;
}
function selectComboBox(comboBox, valueToSelect) {
	try{
		for(var i=0; i < comboBox.options.length; i++) {
                    
			comboBox.options[i].setAttribute('selected',false);
			if(comboBox.options[i].value == valueToSelect) {
			   comboBox.options[i].setAttribute('selected',true);
			   comboBox.options[i].selected = true;
			   break;
			}
		}
	} catch(e) {}
	return true;
}
