/* Project specific validation starts here */


//  This file is part of the jQuery formatCurrency Plugin.
//
//    The jQuery formatCurrency Plugin is free software: you can redistribute it
//    and/or modify it under the terms of the GNU General Public License as published 
//    by the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.

//    The jQuery formatCurrency Plugin is distributed in the hope that it will
//    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty 
//    of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License along with 
//    the jQuery formatCurrency Plugin.  If not, see <http://www.gnu.org/licenses/>.

(function($) {

	$.formatCurrency = {};

	$.formatCurrency.regions = [];

	// default Region is en
	$.formatCurrency.regions[''] = {
		symbol: '$',
		positiveFormat: '%s%n',
		negativeFormat: '(%s%n)',
		decimalSymbol: '.',
		digitGroupSymbol: ',',
		groupDigits: true
	};

	$.fn.formatCurrency = function(destination, settings) {

		if (arguments.length == 1 && typeof destination !== "string") {
			settings = destination;
			destination = false;
		}

		// initialize defaults
		var defaults = {
			name: "formatCurrency",
			colorize: false,
			region: '',
			global: true,
			roundToDecimalPlace: 2, // roundToDecimalPlace: -1; for no rounding; 0 to round to the dollar; 1 for one digit cents; 2 for two digit cents; 3 for three digit cents; ...
			eventOnDecimalsEntered: false
		};
		// initialize default region
		defaults = $.extend(defaults, $.formatCurrency.regions['']);
		// override defaults with settings passed in
		settings = $.extend(defaults, settings);

		// check for region setting
		if (settings.region.length > 0) {
			settings = $.extend(settings, getRegionOrCulture(settings.region));
		}
		settings.regex = generateRegex(settings);

		return this.each(function() {
			$this = $(this);

			// get number
			var num = '0';
			num = $this[$this.is('input, select, textarea') ? 'val' : 'html']();

			//identify '(123)' as a negative number
			if (num.search('\\(') >= 0) {
				num = '-' + num;
			}

			if (num === '') {
				return;
			}

			// if the number is valid use it, otherwise clean it
			if (isNaN(num)) {
				// clean number
				num = num.replace(settings.regex, '');
				
				if (num === '') {
					return;
				}
				
				if (settings.decimalSymbol != '.') {
					num = num.replace(settings.decimalSymbol, '.');  // reset to US decimal for arithmetic
				}
				if (isNaN(num)) {
					num = '0';
				}
			}
			
			// evalutate number input
			var numParts = String(num).split('.');
			var isPositive = (num == Math.abs(num));
			var hasDecimals = (numParts.length > 1);
			var decimals = (hasDecimals ? numParts[1].toString() : '0');
			var originalDecimals = decimals;
			
			// format number
			num = Math.abs(numParts[0]);
			if (settings.roundToDecimalPlace >= 0) {
				decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
				decimals = decimals.toFixed(settings.roundToDecimalPlace); // round
				if (decimals.substring(0, 1) == '2') {
					num = Number(num) + 1;
				}
				decimals = decimals.substring(2); // remove "0."
			}
			num = String(num);

			if (settings.groupDigits) {
				for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
					num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
				}
			}

			if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
				num += settings.decimalSymbol + decimals;
			}

			// format symbol/negative
			var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
			var money = format.replace(/%s/g, settings.symbol);
			money = money.replace(/%n/g, num);

			// setup destination
			var $destination = $([]);
			if (!destination) {
				$destination = $this;
			} else {
				$destination = $(destination);
			}
			// set destination
			$destination[$destination.is('input, select, textarea') ? 'val' : 'html'](money);

			if (hasDecimals && settings.eventOnDecimalsEntered) {
				$destination.trigger('decimalsEntered', originalDecimals);
			}

			// colorize
			if (settings.colorize) {
				$destination.css('color', isPositive ? 'black' : 'red');
			}
		});
	};

	// Remove all non numbers from text
	$.fn.toNumber = function(settings) {
		var defaults = $.extend({
			name: "toNumber",
			region: '',
			global: true
		}, $.formatCurrency.regions['']);

		settings = jQuery.extend(defaults, settings);
		if (settings.region.length > 0) {
			settings = $.extend(settings, getRegionOrCulture(settings.region));
		}
		settings.regex = generateRegex(settings);

		return this.each(function() {
			var method = $(this).is('input, select, textarea') ? 'val' : 'html';
			$(this)[method]($(this)[method]().replace('(', '(-').replace(settings.regex, ''));
		});
	};

	// returns the value from the first element as a number
	$.fn.asNumber = function(settings) {
		var defaults = $.extend({
			name: "asNumber",
			region: '',
			parse: true,
			parseType: 'Float',
			global: true
		}, $.formatCurrency.regions['']);
		settings = jQuery.extend(defaults, settings);
		if (settings.region.length > 0) {
			settings = $.extend(settings, getRegionOrCulture(settings.region));
		}
		settings.regex = generateRegex(settings);
		settings.parseType = validateParseType(settings.parseType);

		var method = $(this).is('input, select, textarea') ? 'val' : 'html';
		var num = $(this)[method]();
		num = num ? num : "";
		num = num.replace('(', '(-');
		num = num.replace(settings.regex, '');
		if (!settings.parse) {
			return num;
		}

		if (num.length == 0) {
			num = '0';
		}

		if (settings.decimalSymbol != '.') {
			num = num.replace(settings.decimalSymbol, '.');  // reset to US decimal for arthmetic
		}

		return window['parse' + settings.parseType](num);
	};

	function getRegionOrCulture(region) {
		var regionInfo = $.formatCurrency.regions[region];
		if (regionInfo) {
			return regionInfo;
		}
		else {
			if (/(\w+)-(\w+)/g.test(region)) {
				var culture = region.replace(/(\w+)-(\w+)/g, "$1");
				return $.formatCurrency.regions[culture];
			}
		}
		// fallback to extend(null) (i.e. nothing)
		return null;
	}

	function validateParseType(parseType) {
		switch (parseType.toLowerCase()) {
			case 'int':
				return 'Int';
			case 'float':
				return 'Float';
			default:
				throw 'invalid parseType';
		}
	}
	
	function generateRegex(settings) {
		if (settings.symbol === '') {
			return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
		}
		else {
			var symbol = settings.symbol.replace('$', '\\$').replace('.', '\\.');		
			return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
		}	
	}

})(jQuery);

jQuery(document).ready(function() {	
	//jQuery('#mainnavcontainer').show();
	jQuery('#smenu').show();
	jQuery('textarea#giftnotes').keyup(function(){		
		//get the limit from maxlength attribute
		var limit = parseInt(jQuery(this).attr('maxlength'));
		//get the current text inside the textarea
		var text = jQuery(this).val();
		//count the number of characters in the text
		var chars = text.length;
		
		//check if there are more characters then allowed
		if(chars > limit){
			//and if there are use substr to get the text before the limit
			var new_text = text.substr(0, limit);
			
			//and change the current text with the new text
			jQuery(this).val(new_text);
		}
	});		
    
if( jQuery('#isVisible').val()== "No"){
		jQuery('#rowNewCard').show();
        document.getElementById('new_card').checked=true;
        }else{
            //jQuery('#rowNewCard').hide();
        }

});

function test(frm){
	alert(frm);	
}

function contactValidiation(frm){
	//alert(frm);
    var error = "";
    $("#"+frm +" :input").each(function(){
        
        if($(this).attr('type') == "text" && $(this).attr('mandatory') == "true"){
            error += emptyCheck($(this));
        }else if($(this).is('textarea') && $(this).attr('mandatory') == "true"){
            error += emptyCheck($(this));
        }else if($(this).is('select') && $(this).attr('mandatory') == "true"){
            if($(this).val() == 0){
                error += "You didn't select "+ $(this).attr("title") +".\n";
            }
        }else if($(this).attr('type') == "checkbox" && $(this).attr('mandatory') == "true"){
            if(!$(this).is(':checked')){
                error += "You didn't select "+ $(this).attr("title") +".\n";
            }
        }
		 if($(this).attr("title")=='Email'){            
             var tfld = contacttrim($(this).val());
            if (tfld != "") {
               error += validateContactEmail($(this));
             }            
        }
		/* if($(this).attr("title")=='Telephone Number'){            
             var tfld = contacttrim($(this).val());
            if (tfld != "") {
               error += validatephone($(this));
             }            
        }*/
		
        
		
    });

    if (error == ""){
        return true;
    }
    alert(error);
    return false;
}
function changefocusa()
{
	    var midinit=document.getElementById('billMidInit').value;
    var ls=midinit.substr(midinit.length-1,1);
    var chk=ls.charCodeAt(0);
	//alert(chk);
	 if(!((chk >= 65 && chk <= 90)  ||( chk >= 97 && chk <= 122)  ) || (chk==32))
    {
        var newval=midinit.substr(0,midinit.length-1)
        document.getElementById('billMidInit').value=newval;
    }
    /*else if(document.getElementById('billMidInit').value.length == 1)
		{
		   document.getElementById('billLastName').focus();
	    }*/
		
}
function changefocus()
{
    var bphno1=document.getElementById('billPhone1').value;
    var ls=bphno1.substr(bphno1.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=bphno1.substr(0,bphno1.length-1)
        document.getElementById('billPhone1').value=newval;
    }
    else if(document.getElementById('billPhone1').value.length == 3)
	{
	   document.getElementById('billPhone2').focus();
    }
	
}

function changefocus1()
{

 var bphno2=document.getElementById('billPhone2').value;
    var ls=bphno2.substr(bphno2.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=bphno2.substr(0,bphno2.length-1)
        document.getElementById('billPhone2').value=newval;
    }
    else if(document.getElementById('billPhone2').value.length == 3)
	{
	   document.getElementById('billPhone3').focus();
    }

  
}

function changefocus2()
{
 var bphno3=document.getElementById('billPhone3').value;
    var ls=bphno3.substr(bphno3.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=bphno3.substr(0,bphno3.length-1)
        document.getElementById('billPhone3').value=newval;
    }
}





function changecellphone1()
{
    var cphno1=document.getElementById('billCell1').value;
    var ls=cphno1.substr(cphno1.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=cphno1.substr(0,cphno1.length-1)
        document.getElementById('billCell1').value=newval;
    }
    else if(document.getElementById('billCell1').value.length == 3)
	{
	   document.getElementById('billCell2').focus();
    }

}

function changecellphone2()
{

 var cphno2=document.getElementById('billCell2').value;
    var ls=cphno2.substr(cphno2.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=cphno2.substr(0,cphno2.length-1)
        document.getElementById('billCell2').value=newval;
    }
    else if(document.getElementById('billCell2').value.length == 3)
	{
	   document.getElementById('billCell3').focus();
    }


}

function changecellphone3()
{
 var cphno3=document.getElementById('billCell3').value;
    var ls=cphno3.substr(cphno3.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=cphno3.substr(0,cphno3.length-1)
        document.getElementById('billCell3').value=newval;
    }
}




function changephoneno1()
{
    var sphno1=document.getElementById('shipPhone1').value;
    var ls=sphno1.substr(sphno1.length-1,1);
    var chk=ls.charCodeAt(0);
    
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById('shipPhone1').value=newval;
    }
    else if(document.getElementById('shipPhone1').value.length == 3)
	{
	   document.getElementById('shipPhone2').focus();
    }

}

function changephoneno2()
{

 var sphno2=document.getElementById('shipPhone2').value;
    var ls=sphno2.substr(sphno2.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=sphno2.substr(0,sphno2.length-1)
        document.getElementById('shipPhone2').value=newval;
    }
    else if(document.getElementById('shipPhone2').value.length == 3)
	{
	   document.getElementById('shipPhone3').focus();
    }


}


function changephoneno3()
{
 var cphno3=document.getElementById('shipPhone3').value;
    var ls=cphno3.substr(cphno3.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=cphno3.substr(0,cphno3.length-1)
        document.getElementById('shipPhone3').value=newval;
    }
}



function changecellfocus(){
    if(document.getElementById('billCell1').value.length == 3)
 {
    document.getElementById('billCell2').focus();
    }
}
function changecellfocus2(){
    if(document.getElementById('billCell2').value.length == 3)
 {
    document.getElementById('billCell3').focus();
    }
}

 
function validateLoginFormOnSubmit(theForm) {
    theForm.action.value="login";
    var reason = "";
    reason += validateEmail(theForm.loginemail);
    reason += validatePassword(theForm.loginpasswd);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    
    return true;
}

function validateRegisterFormOnSubmit(theForm) {
	 theForm.action.value="register";
	 var reason = "";
	 var email;
	 var pass;
	 var cregisteremail;
	 var confirmpass;
	 
	    reason += validatetextfields(theForm.firstname);
	 if (reason!="") reason = reason.replace("The required field","First Name")
	    reason += validatetextfields(theForm.lastname);
	 if (reason!="") reason = reason.replace("The required field","Last Name")
	    reason += validateEmail(theForm.registeremail);
	 if (reason!="") email = reason.replace("The required field","Email")
	 	 reason += validateConfirmEmail(theForm.cregisteremail);
	 if (reason!="") cregisteremail = reason.replace("The required field","Email")
	     reason += validatePassword(theForm.registerPasswd);
	 if (reason!="") pass = reason.replace("The required field","Password") 
	 	  reason += validateConfirmPassword(theForm.cregisterPasswd);
	 if (reason!="") confirmpass = reason.replace("The required field","Password") 
	     reason += validateEmpty(theForm.street);
	 if (reason!="") reason = reason.replace("The required field","Address")
	    reason += validateEmpty(theForm.city);
	 if (reason!="") reason = reason.replace("The required field","City")
	    reason += validateselectfields(theForm.country);
	 if (reason!="") reason = reason.replace("The required field","Country")
	    reason += validateZipCodess(theForm.zip);
	 if (reason!="") reason = reason.replace("The required field","Zip")
	    reason += validateselectfields(theForm.state2);
	 if (reason!="") reason = reason.replace("The required field","State")
	    reason += validatePhoneSections("phone");
	 if (reason!="") reason = reason.replace("The required field","Phone")
	 
	 reason += validatetextfields(theForm.captcha);
	 if (reason!="") reason = reason.replace("The required field","Captcha")

         
	 
	    if (email!="" && cregisteremail!="") reason += compareEmail(theForm.registeremail,theForm.cregisteremail);
	 if (pass!="" && confirmpass!="") reason += comparePassword(theForm.registerPasswd,theForm.cregisterPasswd);
	 
	    
	 if (reason != "") {
	        alert("Some fields need correction:\n" + reason);
	        return false;
	    }
	    return true;
	}

/*function validateSchoolsignupFormOnSubmit(theForm) {
//theForm.action.value="register";
	 var reason = "";
	 var email;
	 var pass;
	 var cregisteremail;
	 var confirmpass;

	 
	 
	    reason += validateEmail(theForm.registeremail);
	 if (reason!="") email = reason.replace("The required field","Email")
	 
	 reason += validateConfirmEmail(theForm.cregisteremail);
	 if (reason!="") cregisteremail = reason.replace("The required field","Email")
	 
	    reason += validatePassword(theForm.registerPasswd);
	 if (reason!="") pass = reason.replace("The required field","Password") 
	 
	  reason += validateConfirmPassword(theForm.cregisterPasswd);
	 if (reason!="") confirmpass = reason.replace("The required field","Password") 
	  
	    reason += validatetextfields(theForm.firstname);
	 if (reason!="") reason = reason.replace("The required field","First Name")
	    reason += validatetextfields(theForm.lastname);
	 if (reason!="") reason = reason.replace("The required field","Last Name")
	    reason += validateEmpty(theForm.street);
	 if (reason!="") reason = reason.replace("The required field","Address")
	    reason += validateEmpty(theForm.city);
	 if (reason!="") reason = reason.replace("The required field","City")
	    reason += validateselectfields(theForm.country);
	 if (reason!="") reason = reason.replace("The required field","Country")
	    reason += validateselectfields(theForm.state2);
	 if (reason!="") reason = reason.replace("The required field","State")
	    reason += validateZipCodess(theForm.zip);
	 if (reason!="") reason = reason.replace("The required field","Zip")
	    reason += validatePhoneSections("phone");
	 if (reason!="") reason = reason.replace("The required field","Phone")
	 
	 reason += validatetextfields(theForm.captcha);
	 if (reason!="") reason = reason.replace("The required field","Captcha")
	 
	    if (email!="" && cregisteremail!="") reason += compareEmail(theForm.registeremail,theForm.cregisteremail); 
	 if (pass!="" && confirmpass!="") reason += comparePassword(theForm.registerPasswd,theForm.cregisterPasswd);
	 
	    
	 if (reason != "") {
	        alert("Some fields need correction:\n" + reason);
	        return false;
	    }
	    return true;
	}*/

function validateSchoolsignupFormOnSubmit(theForm) {
//theForm.action.value="register";
	 var reason = "";
	 var email;
	 var pass;
	 var cregisteremail;
	 var confirmpass;

	  reason += validatetextfields(theForm.schoolname);
	 if (reason!="") reason = reason.replace("The required field","State")



          reason += validatetextfields(theForm.firstname);
	 if (reason!="") reason = reason.replace("The required field","First Name")
	    reason += validatetextfields(theForm.lastname);
	 if (reason!="") reason = reason.replace("The required field","Last Name")
	 
	    reason += validateEmail(theForm.registeremail);
	 if (reason!="") email = reason.replace("The required field","Email")
	 
	 reason += validateConfirmEmail(theForm.cregisteremail);
	 if (reason!="") cregisteremail = reason.replace("The required field","Email")
	 
	    reason += validatePassword(theForm.registerPasswd);
	 if (reason!="") pass = reason.replace("The required field","Password") 
	 
	  reason += validateConfirmPassword(theForm.cregisterPasswd);
	 if (reason!="") confirmpass = reason.replace("The required field","Password") 
	  
	   
	    reason += validateEmpty(theForm.street);
	 if (reason!="") reason = reason.replace("The required field","Address")
	    reason += validateEmpty(theForm.city);
	 if (reason!="") reason = reason.replace("The required field","City")
	    reason += validateselectfields(theForm.country);
	 if (reason!="") reason = reason.replace("The required field","Country")
	    reason += validateselectfields(theForm.state2);
	 if (reason!="") reason = reason.replace("The required field","State")
	    reason += validateZipCodess(theForm.zip);
	 if (reason!="") reason = reason.replace("The required field","Zip")
	    reason += validatePhoneSections("phone");
	 if (reason!="") reason = reason.replace("The required field","Phone")
	 
	 reason += validatetextfields(theForm.captcha);
	 if (reason!="") reason = reason.replace("The required field","Captcha")
	 
	    if (email!="" && cregisteremail!="") reason += compareEmail(theForm.registeremail,theForm.cregisteremail); 
	 if (pass!="" && confirmpass!="") reason += comparePassword(theForm.registerPasswd,theForm.cregisterPasswd);
	 
	    
	 if (reason != "") {
	        alert("Some fields need correction:\n" + reason);
	        return false;
	    }
	    return true;
}

function forgotPassword(theForm) {
    theForm.action.value="login";
    var reason = "";
    reason += validateEmail(theForm.loginemail);
    //reason += validatePassword(theForm.loginpasswd);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    
    return true;
}



/*function forgotPassword(type){
   
    var reason = "";
    if(type=='login'){
    reason += validateEmail(document.frmLogin.loginemail);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }else{
        document.frmLogin.actionParam.value="lostpass";
        document.frmLogin.submit();
    }
    }else{

    	 reason += validateEmail(document.logintocheckout.loginemail);
         //alert(reason);
    	    if (reason != "") {
    	        alert("Some fields need correction:\n" + reason);
    	        return false;
    	    }else{
                //alert("lostpass");
    	        document.logintocheckout.actionParam.value="lostpass";
    	        //formsubmit();
                document.logintocheckout.submit();
                
        }
        
    }
    
}*/
//function formsubmit(){
//    if(document.logintocheckout){
//        alert("hello");
//    }
//    document.logintocheckout.submit();
//    return true;
//}


function showhidePass() {
	if( document.getElementById('changepass').style.display=='none' ){
	   jQuery("#changepass").show();
	   jQuery("#buttonrow").show();
           jQuery("#buttonrow1").hide();
	 }else{
	   jQuery("#changepass").hide();
	   jQuery("#buttonrow").hide();
           jQuery("#buttonrow1").show();
	   if(document.getElementById('changepasserr')){jQuery("#changepasserr").hide();}
	 }
}

function loadShipAddys(){
	jQuery("#shiplist").html('<p><span class=processing>Loading...</span></p>');
	jQuery('#shiplist').load("/fetchaddress/");
}

function addAddress(){
	// alert(jQuery("#addshipform").html().length);
	if (jQuery("#addshipform").html().length==0){
		jQuery('#addshipform').replaceWith("<div id='addshipform'></div>");
		jQuery('#addshipform').load('/addaddress/');
	}
}

function submitShipAddress(){
	//alert('submit');
        document.getElementById("errormsg").style.visibility='hidden';
	var reason = "";
	reason += validateEmpty(document.getElementById('shipFirstName'));	
	if (reason!="") reason = reason.replace("The required field","First Name");
	
	reason += validateEmpty(document.getElementById('shipLastName'));	
	if (reason!="") reason = reason.replace("The required field","Last Name");
	
	reason += validateEmpty(document.getElementById('shipAddress'));	
	if (reason!="") reason = reason.replace("The required field","Address");
	
	reason += validateEmpty(document.getElementById('shipCity'));	
	if (reason!="") reason = reason.replace("The required field","City");
	
	reason += validateEmpty(document.getElementById('shipState'));	
	if (reason!="") reason = reason.replace("The required field","State");

	reason += validateZipCodess(document.getElementById('shipZip'));	
	if (reason!="") reason = reason.replace("The required field","Zip");	
	
	reason += validatePhoneSections("shipPhone");	
	if (reason!="") reason = reason.replace("The required field","Phone");
		
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{		
		jQuery("#addshipform").hide();
		jQuery("#ajaxLoader").show();
		jQuery.post("/address",{
			fname: jQuery("input#shipFirstName").val(),
			lname: jQuery("input#shipLastName").val(),
			company : jQuery("input#shipCompany").val(),
			address:jQuery("input#shipAddress").val(),
			address2:jQuery("input#shipAddress2").val(),
			city:jQuery("input#shipCity").val(),				
			state: jQuery("#shipState option:selected").val(),
			zip: jQuery("input#shipZip").val(),
			phone: jQuery("input#shipPhone1").val()+'-'+jQuery("input#shipPhone2").val()+'-'+jQuery("input#shipPhone3").val(),			
			pl: "add"
		 }, function(data) {
			jQuery("#addshipform").html('');
			jQuery("#ajaxLoader").hide();
			loadShipAddys();
	 }); 
	return false;
	}	
}

function showHideShipRow(id) {
	//alert('Editing');
	document.getElementById("errormsg").style.visibility='hidden';
	if( document.getElementById('editShipRow'+id).style.display=='none' ){
		jQuery("#displayShipRow"+id).hide();
		jQuery("#editShipRow"+id).show();
	}else{
		jQuery("#displayShipRow"+id).show();
	   	jQuery("#editShipRow"+id).hide();
	}
}

function updateShipRow(id){	
	var reason = "";
	reason += validateEmpty(document.getElementById('shipFirstName'+id));
	if (reason!="") reason = reason.replace("The required field","First Name");
	reason += validateEmpty(document.getElementById('shipLastName'+id));
	if (reason!="") reason = reason.replace("The required field","Last Name");
	reason += validateEmpty(document.getElementById('shipAddress'+id));
	if (reason!="") reason = reason.replace("The required field","Address");
	reason += validateEmpty(document.getElementById('shipCity'+id));
	if (reason!="") reason = reason.replace("The required field","City");
	if(document.getElementById('shipState'+id).value=='...'){
		if (reason!="")   
	        reason += "The required field","State";
		else
			reason = "State";
	}
	reason += validateZipCodess(document.getElementById('shipZip'+id));
	reason += validatePhoneSections(id+"shipPhone");
	
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{
		jQuery("#addshipform").hide();
		jQuery("#ajaxLoader").show();
		jQuery.post("/address",{
			id: id,
			fname: jQuery("input#shipFirstName"+id).val(),
			lname: jQuery("input#shipLastName"+id).val(),
			company : jQuery("input#shipCompany"+id).val(),
			address: jQuery("input#shipAddress"+id).val(),
			address2: jQuery("input#shipAddress2"+id).val(),
			city: jQuery("input#shipCity"+id).val(),				
			state: jQuery("#shipState"+id+" option:selected").val(),
			zip:  jQuery("input#shipZip"+id).val(),
			phone: jQuery("input#"+id+"shipPhone1").val()+'-'+jQuery("input#"+id+"shipPhone2").val()+'-'+jQuery("input#"+id+"shipPhone3").val(),				
			contactid: jQuery("input#contactId"+id).val(),
			accountid: jQuery("input#accountId"+id).val(),
			pl: "update"
		 }, function(data) {		 
			 jQuery("#addshipform").html('');
			 jQuery("#ajaxLoader").hide();
			 loadShipAddys();
	 });
	}
}

function deleteShipRow(id){
	document.getElementById("errormsg").style.visibility='hidden';
	jQuery("#ajaxLoader").show();
	jQuery.post('/deleteshippingaddress',{
		contactId:jQuery("input#contactId"+id).val()
	},function(){ 
		loadShipAddys();
		jQuery("#ajaxLoader").hide();
	}); 
}

function loadPayments(){
	//alert('test');
	jQuery("#paymentlist").html('<p><span class=processing>Loading...</span></p>')
	jQuery('#paymentlist').load("/paymentdetail");
}

function addPayment(){
	if (jQuery("#payform").html().length==0){
		jQuery('#payform').replaceWith("<div id='payform'></div>");
		jQuery('#payform').load('/addcreditcard');
	}
}

function showHideBillRow(id) {
 if( document.getElementById('editBillRow'+id).style.display=='none' ){
   jQuery("#displayBillRow"+id).hide();
   jQuery("#editBillRow"+id).show();
 }else{
	jQuery("#displayBillRow"+id).show();
   	jQuery("#editBillRow"+id).hide();
 }
}

function deleteBillRow(id){
	jQuery("#payform").hide();
	jQuery("#ajaxLoader").show();
		jQuery.post('/deletebillingaddress',{
			contactId:jQuery("input#contactId"+id).val(),
			creditCartId:jQuery("input#creditCartId"+id).val()
		}, function(data) {
			jQuery("#payform").html('');
			jQuery("#ajaxLoader").hide();
			loadPayments();
	 });
}

function savePayment(){	
	var reason = "";
	var validCCN = "";
	var validCVV = "";
	reason += validateEmpty(document.getElementById('billFirstName'));
	if (reason!="") reason = reason.replace("The required field","First Name");
	reason += validateEmpty(document.getElementById('billLastName'));
	if (reason!="") reason = reason.replace("The required field","Last Name");
	reason += validateEmpty(document.getElementById('billAddress'));
	if (reason!="") reason = reason.replace("The required field","Address");
	reason += validateEmpty(document.getElementById('billCity'));
	if (reason!="") reason = reason.replace("The required field","City");
	reason += validateEmpty(document.getElementById('billState'));
	if (reason!="") reason = reason.replace("The required field","State");
	reason += validateZipCodess(document.getElementById('billZip'));
	reason += validatePhoneSections("billPhone");
	/*reason += validateEmpty(document.getElementById('txtNameonCard'));
	if (reason!="") reason = reason.replace("The required field","Name on card");*/
	reason += validateEmpty(document.getElementById('selCardType'));
	if (reason!="") reason = reason.replace("The required field","Credit Card Type");
        reason +=validateEmpty(document.getElementById('txtCreditCard'));
        if (reason!="") reason = reason.replace("The required field","Credit Card Number");

        if(document.getElementById('txtCreditCard').value.length!=0){       
	validCCN = validateCreditCardNumber(document.getElementById('selCardType'), document.getElementById('txtCreditCard'));
	if(validCCN !="") {
		//document.getElementById('txtCreditCard').style.background = 'Yellow';
		reason += validCCN;
	}
	}

	reason += validateEmpty(document.getElementById('selExpMonth'));
	if (reason!="") reason = reason.replace("The required field","Expiration Month");
	reason += validateEmpty(document.getElementById('selExpYear'));
	if (reason!="") reason = reason.replace("The required field","Expiration Year");
	if (reason=="") reason += validateExpDate(document.getElementById('selExpMonth').value,document.getElementById('selExpYear').value)
	 reason +=validateEmpty(document.getElementById('txtCardVerificationValue'));
        if (reason!="") reason = reason.replace("The required field","Card Verification Value");

	if(document.getElementById('txtCardVerificationValue').value.length!=0){
        validCVV = validateCvvCode(document.getElementById('selCardType'), document.getElementById('txtCardVerificationValue'));
        if(validCVV!=""){
             //document.getElementById('txtCardVerificationValue').style.background = 'Yellow';
             reason += validCVV;
        } 
	} 
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}else{
           
		jQuery("#payform").hide();
		jQuery("#ajaxLoader").show();
		jQuery.post("/createcreditcard",{
                        
			fname: jQuery("input#billFirstName").val(),
			lname: jQuery("input#billLastName").val(),
			company : jQuery("input#billCompany").val(),
			address:jQuery("input#billAddress").val(),
			address2:jQuery("input#billAddress2").val(),
			city:jQuery("input#billCity").val(),				
			state: jQuery("#billState option:selected").val(),
			zip: jQuery("input#billZip").val(),
			phone: jQuery("input#billPhone1").val()+'-'+jQuery("input#billPhone2").val()+'-'+jQuery("input#billPhone3").val(),
			cname: jQuery("input#billFirstName").val()+' '+jQuery("input#billLastName").val(),
			ctype: jQuery("#selCardType option:selected").val(),
			cnum: jQuery("input#txtCreditCard").val(),
			cmonth: jQuery("#selExpMonth option:selected").val(),
			cyear: jQuery("#selExpYear option:selected").val(),			
			cvv:jQuery("input#txtCardVerificationValue").val(),		
			pl:"add"
                       

		 }, function(data) {	   		
			jQuery("#payform").html('');
			jQuery("#ajaxLoader").hide();
			 // AfterSavePayment(data);
			loadPayments();
	 }); 
	}
}





function loginToCheckoutValidate(frm,chk) {

	//alert(chk);
        if(chk==1)
            {
	var elem = document.getElementById(frm).elements;
	var str = '';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text')) {
			if ( elem[i].name == 'email' && trim(elem[i].value).length == 0) {
				str = 'The required field has not been filled in.\n';
                                elem[i].style.background = 'Yellow';
				/*if (trim(elem[i].value).length == 0)
					elem[i].style.background = 'Yellow';
				else
					elem[i].style.background = 'White';*/
			} else if ((elem[i].name == 'email') && (elem[i].value.length != 0)) {
				str += validateEmail(elem[i]);
                                //elem[i].style.background = 'Yellow';
			}
		}
		if ((elem[i].type == 'password')) {
			if (elem[i].name == 'pass' && trim(elem[i].value).length == 0) {
				str = 'The required field has not been filled in.\n';
                                elem[i].style.background = 'Yellow';
				/*if (trim(elem[i].value).length == 0)
					elem[i].style.background = 'Yellow';
				else
					elem[i].style.background = 'White';*/
			} else if ((elem[i].name == 'email') && (elem[i].value.length != 0)) {
				str += validatePassword(elem[i]);
                               // elem[i].style.background = 'Yellow';
			}
		}
	}
	if (str != '') {

            
		alert(str);
		return false;
	}
        document.logintocheckout.actionParam.value="login";
	return true;
            }else if(chk==2)
                {
                    //alert(frm);
                    var reason = "";
                    reason += validateEmail(document.logintocheckout.email);
                    if (reason != "") {
                  alert("Some fields need correction:\n" + reason);
                  return false;
              }else{
                  document.logintocheckout.actionParam.value="lostpass";
                  //return true;
                  //$(button.logintocheckout).submit();
                //  $("#logintocheckout").submit();
                 $.post("/logintocheckout", {
            actionParam:$("#actionParam").val(),
email:$("#email").val()

        },
        function(data){
//            alert(data);
//            if(data == "1")
//                {
//                 alert("sddsds");
//
//                }
         $("#error_msg").html(data);
            //document.getElementById("error_msg").innerHTML=data;
            //alert(data);
           
            //alert(data);
        });
                 // $("form:second").submit();
                  //return true;
                 // document.logintocheckout.submit();
                 // document.logintocheckout.submit();

       //document.forms["logintocheckout"].submit();
       //return true;
       //document.logintocheckout.submit();
    }
                    //alert("GAHIAI");

                }

}

/*function checkoutStep1Validate(frm,buttonId) {
	alert('1 HERE YOU ARE  !');
	var elem = document.getElementById(frm).elements;
	
	var reason = "";	
	var validZip = "";
	var validBillEmail = "";
	var validBillCEmail = "";
	var validBillPhone= "";
	var validShipPhone = "";
	var validBillCell = "";
	var validBillPassword = "" ;
    var validBillCPassword = "";
    var emailFlag = false;
	var str = 'Following required field has not been filled in.\n';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text') || (elem[i].type == 'password')) {
			if ( ( (elem[i].id != 'billMidInit')
					&& (elem[i].id != 'billCell1')
					&& (elem[i].id != 'billCell2')
					&& (elem[i].id != 'billCell3')				
					&& (elem[i].id != 'billPhone1')
					&& (elem[i].id != 'billPhone2')
					&& (elem[i].id != 'billPhone3')	
					&& (elem[i].id != 'shipPhone1')
					&& (elem[i].id != 'shipPhone2')
					&& (elem[i].id != 'shipPhone3')				
					&& (elem[i].id != 'billCompany')
					&& (elem[i].id != 'billAddress2')
					&& (elem[i].id != 'shipCompany')
					&& (elem[i].id != 'shipAddress2'))) {
				reason += validateEmpty(document.getElementById(elem[i].id));
				if (reason != "")
					//alert(elem[i].title);
					reason = reason.replace("The required field", elem[i].title);
			}			
			if ((elem[i].name == 'billZip' || elem[i].name == 'shipZip') && (elem[i].value.length != 0)) {
				validZip = validateZipCode(elem[i]);
			}			
			if ((elem[i].name == 'billEmail') && (elem[i].value.length != 0)) {
				emailFlag= true;
				validBillEmail = validateEmail(elem[i]);
				if(validBillEmail!='') validBillEmail = validBillEmail.replace("email", (elem[i].title).toLowerCase());
			}
			if ((elem[i].name == 'billcEmail') && (elem[i].value.length != 0)) {
				validBillCEmail = validateEmail(elem[i]);
				if(validBillCEmail!='') validBillCEmail = validBillCEmail.replace("email", (elem[i].title).toLowerCase());
			}
			if(((elem[i].name == 'billPass') && (elem[i].value.length != 0))){
			validBillPassword = validatePassword(elem[i]);
			if(validBillPassword!='') validBillPassword = validBillPassword.replace("password", (elem[i].title).toLowerCase());
			}

			if(((elem[i].name == 'billcPass') && (elem[i].value.length != 0))){
			validBillCPassword = validatePassword(elem[i]);
			if(validBillCPassword!='') validBillCPassword = validBillCPassword.replace("password", (elem[i].title).toLowerCase());
			}
		}
		if((elem[i].name == 'billState' || elem[i].name == 'shipState') && (elem[i].value == 0)){
			
			reason += elem[i].title + " has not been selected.\n";
			//elem[i].style.background = 'Yellow';
		}
		if(elem[i].name == 'billState' && (elem[i].value != 0)){			
			elem[i].style.background = 'none';
		}
		if(elem[i].name == 'shipState' && (elem[i].value != 0)){			
			elem[i].style.background = 'none';
		}
	}
	validBillPhone = validateCheckoutPhoneSections('billPhone','Bill Phone');
	validShipPhone = validateCheckoutPhoneSections('shipPhone','Ship Phone');
	if(document.getElementById('billCell1').value.length!=0 || document.getElementById('billCell2').value.length!=0 || document.getElementById('billCell3').value.length!=0)
	validBillCell = validateCheckoutPhoneSections("billCell",'Bill Cell Phone');
	reason += validZip + validBillPhone +  validBillCell + validBillEmail + validBillCEmail + validBillPassword + validBillCPassword + validShipPhone;		

	if(emailFlag){
		if (reason=="" && (document.getElementById('billEmail').value != document.getElementById('billcEmail').value)){
			reason = "Email addresses does not match."
		}
		if (reason=="" && (document.getElementById('billPass').value != document.getElementById('billcPass').value)){
			reason = "Passwords does not match."
		}
	}	
	if (reason != "") {		
		str+= reason;
		alert(str);
		return false;
	}
	if (jQuery('#termsAndCond').attr("checked")) {
        disableAddToBag(buttonId);
        return true;	
	}else{
		jQuery('#termsId').removeClass('isChecked');
		jQuery('#termsId').addClass('isNotChecked');
	    alert(jQuery('#termsAndCond').attr("title") + " has not been selected");
	    return false;
	}	
}*/


function checkoutStep1Validate(frm,buttonId) {
	//alert('1 HERE YOU ARE  !');
	var elem = document.getElementById(frm).elements;
	
	var reason = "";	
	var validZip = "";
	var validBillEmail = "";
	var validBillCEmail = "";
	var validBillPhone= "";
	var validShipPhone = "";
	var validBillCell = "";
	var validBillPassword = "" ;
    var validBillCPassword = "";
    var emailFlag = false;
	var str = 'Following required field has not been filled in.\n';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text') || (elem[i].type == 'password')) {
			
			if(document.getElementById('shipPhone1') == null){
				
				if ( ( (elem[i].id != 'billMidInit')
						&& (elem[i].id != 'billCell1')
						&& (elem[i].id != 'billCell2')
						&& (elem[i].id != 'billCell3')				
						&& (elem[i].id != 'billPhone1')
						&& (elem[i].id != 'billPhone2')
						&& (elem[i].id != 'billPhone3')	
						&& (elem[i].id != 'billCompany')
						&& (elem[i].id != 'billAddress2')
						
						
						
						
				)) {
					reason += validateEmpty(document.getElementById(elem[i].id));
					if (reason != "")
						reason = reason.replace("The required field", elem[i].title);
				}	
				
			}else{
			
				if ( ( (elem[i].id != 'billMidInit')
						&& (elem[i].id != 'billCell1')
						&& (elem[i].id != 'billCell2')
						&& (elem[i].id != 'billCell3')				
						&& (elem[i].id != 'billPhone1')
						&& (elem[i].id != 'billPhone2')
						&& (elem[i].id != 'billPhone3')	
						
						&& (elem[i].id != 'shipPhone1')
						&& (elem[i].id != 'shipPhone2')
						&& (elem[i].id != 'shipPhone3')				
						&& (elem[i].id != 'billCompany')
						&& (elem[i].id != 'billAddress2')
						&& (elem[i].id != 'shipCompany')
						&& (elem[i].id != 'shipAddress2')
						
				)) {
					reason += validateEmpty(document.getElementById(elem[i].id));
					if (reason != "")
						reason = reason.replace("The required field", elem[i].title);
					
				}
			}
			
				
			if(document.getElementById('shipPhone1') == null){
				if ((elem[i].name == 'billZip') && (elem[i].value.length != 0)) {
					validZip = validateZipCode(elem[i]);
				}
			}else{
				if ((elem[i].name == 'billZip' || elem[i].name == 'shipZip') && (elem[i].value.length != 0)) {
					validZip = validateZipCode(elem[i]);
				}
			}
						
			
			
			if ((elem[i].name == 'billEmail') && (elem[i].value.length != 0)) {
				emailFlag= true;
				validBillEmail = validateEmail(elem[i]);
				if(validBillEmail!='') validBillEmail = validBillEmail.replace("email", (elem[i].title).toLowerCase());
			}
			if ((elem[i].name == 'billcEmail') && (elem[i].value.length != 0)) {
				validBillCEmail = validateEmail(elem[i]);
				if(validBillCEmail!='') validBillCEmail = validBillCEmail.replace("email", (elem[i].title).toLowerCase());
			}
			if(((elem[i].name == 'billPass') && (elem[i].value.length != 0))){
			validBillPassword = validatePassword(elem[i]);
			if(validBillPassword!='') validBillPassword = validBillPassword.replace("password", (elem[i].title).toLowerCase());
			}

			if(((elem[i].name == 'billcPass') && (elem[i].value.length != 0))){
			validBillCPassword = validatePassword(elem[i]);
			if(validBillCPassword!='') validBillCPassword = validBillCPassword.replace("password", (elem[i].title).toLowerCase());
			}
		}
		if(document.getElementById('shipPhone1') == null){
			if((elem[i].name == 'billState') && (elem[i].value == 0)){
				reason += elem[i].title + " has not been selected.\n";
			}
		}else{
			if((elem[i].name == 'billState' || elem[i].name == 'shipState') && (elem[i].value == 0)){
				reason += elem[i].title + " has not been selected.\n";
			}
		}
		if(elem[i].name == 'billState' && (elem[i].value != 0)){			
			elem[i].style.background = 'none';
		}
		if(document.getElementById('shipState')){
			if(elem[i].name == 'shipState' && (elem[i].value != 0)){			
				elem[i].style.background = 'none';
			}
		}
	}
	validBillPhone = validateCheckoutPhoneSections('billPhone','Bill Phone');
	if(document.getElementById('shipPhone')){
		validShipPhone = validateCheckoutPhoneSections('shipPhone','Ship Phone');
	}
	
	if(document.getElementById('billCell1').value.length!=0 || document.getElementById('billCell2').value.length!=0 || document.getElementById('billCell3').value.length!=0)
	validBillCell = validateCheckoutPhoneSections("billCell",'Bill Cell Phone');
	reason += validZip + validBillPhone +  validBillCell + validBillEmail + validBillCEmail + validBillPassword + validBillCPassword + validShipPhone;		

	if(emailFlag){
		if (reason=="" && (document.getElementById('billEmail').value != document.getElementById('billcEmail').value)){
			reason = "Email addresses does not match."
		}
		if (reason=="" && (document.getElementById('billPass').value != document.getElementById('billcPass').value)){
			reason = "Passwords does not match."
		}
	}	
	if (reason != "") {		
		str+= reason;
		alert(str);
		return false;
	}
	if(document.getElementById('termsAndCond')){
		if (jQuery('#termsAndCond').attr("checked")) {
	        disableAddToBag(buttonId);
	        return true;	
		}else{
			jQuery('#termsId').removeClass('isChecked');
			jQuery('#termsId').addClass('isNotChecked');
		    alert(jQuery('#termsAndCond').attr("title") + " has not been selected");
		    return false;
		}	
	}else{
		disableAddToBag(buttonId);
        return true;
	}
}

function checkoutStep2Validate(frm,buttonId) {
	
	
	
	var flag = document.getElementById('hidCCType').value;
    var profileId='';
	var cardType="";
    var cardError="";
	var existCardType="";
        var cvvValue = '';
	if(flag ==""){
	var elem = document.getElementById(frm).elements;
	var count = document.getElementsByName('PayMethodGroup1').length;		
	for (var i=0; i < count; i++)
	   {
	   if (document.getElementsByName('PayMethodGroup1')[i].checked)
	      var cardType = document.getElementsByName('PayMethodGroup1')[i];
	   }	

    var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
	for(i=0;i<paymentDetailsGroup.length;i++){
	    if(paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value!='new'){
	    	   profileId = paymentDetailsGroup[i].value;
	   }
          }

    	for ( var i = 0; i < elem.length; i++) {
     	if((elem[i].type == 'password') && (elem[i].alt =='cvvText')){
		elem[i].style.background = 'none';
	}
  	}
	     document.getElementById('creditCartId').value = profileId;
	var str = "";	
	var validCVV = "";
        var existValidCVV = "";
	var validCCN = "";
	var validED = "";
	if(profileId==''){
	if(cardType!=""){
	for ( var i = 0; i < elem.length; i++) {
		if (((elem[i].type == 'text') || (elem[i].type == 'password')) && elem[i].alt!='cvvText') {
			if (elem[i].name != 'PayMethodGroup1'){		
				if (trim(elem[i].value).length == 0){
					elem[i].style.background = 'Yellow';
					str = 'The required field has not been filled in.\n';
				}else{					
					elem[i].style.background = 'none';
				}
			}			
			if ((elem[i].name == 'ccId') && (elem[i].value.length != 0)) {
				validCVV = validateCvvCode(cardType, elem[i]);
				if(validCVV!="")
					elem[i].style.background = 'Yellow';
			}
			if ((elem[i].name == 'ccNum') && (elem[i].value.length != 0)) {
				validCCN = validateCreditCardNumber(cardType, elem[i]);
				if(validCCN!="")
					elem[i].style.background = 'Yellow';
			}
		}
		
	}
		validED += validateExpDate(document.getElementById('ccExpMonth').value,document.getElementById('ccExpYear').value)
			if(validED!=""){
					document.getElementById('ccExpMonth').style.background = 'Yellow';
					document.getElementById('ccExpYear').style.background = 'Yellow';				
				}else{
					document.getElementById('ccExpMonth').style.background = 'none';
					document.getElementById('ccExpYear').style.background = 'none';
	}
	}else
  		cardError = "Please select the credit card type.";
    }
	if(profileId!=''){
	cvvValue = document.getElementById(profileId).value;
        existCardType = document.getElementById('cardType'+profileId).value;
             if(cvvValue!=''){
                  existValidCVV = validateCvvCodeforExistCard(existCardType,cvvValue);
                  if(existValidCVV!='')
		        document.getElementById(profileId).style.background = 'Yellow';
                  else
                        document.getElementById('ccId').value = cvvValue;
             }else
	     {
		  str = 'The required field has not been filled in.\n';
		  document.getElementById(profileId).style.background = 'Yellow';
             }

	}
	str += validCCN + validED + validCVV + existValidCVV +cardError;	
	if (str != "") {		
		alert(str);
		return false;
	}	
        disableAddToBag(buttonId);
	return true;
	}
}

function _checkoutStep2Validate(frm,buttonId) {
	alert('checkoutStep2Validate');
	var flag = document.getElementById('hidCCType').value;
    var profileId='';
	var cardType="";
    var cardError="";
	var existCardType="";
    var cvvValue = '';
	if(flag ==""){
	var elem = document.getElementById(frm).elements;
	var count = document.getElementsByName('PayMethodGroup1').length;		
	for (var i=0; i < count; i++)
	   {
	   if (document.getElementsByName('PayMethodGroup1')[i].checked)
	      var cardType = document.getElementsByName('PayMethodGroup1')[i];
	   }	

    var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
	for(i=0;i<paymentDetailsGroup.length;i++){
	    if(paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value!='new'){
	    	   profileId = paymentDetailsGroup[i].value;
	   }
          }

    	for ( var i = 0; i < elem.length; i++) {
     	if((elem[i].type == 'password') && (elem[i].alt =='cvvText')){
		elem[i].style.background = 'none';
	}
  	}
	document.getElementById('creditCartId').value = profileId;
	var str = "";	
	var validCVV = "";
    var existValidCVV = "";
	var validCCN = "";
	var validED = "";
	if(profileId==''){
	if(cardType!=""){
	for ( var i = 0; i < elem.length; i++) {
		if (((elem[i].type == 'text') || (elem[i].type == 'password')) && elem[i].alt!='cvvText') {
			if (elem[i].name != 'PayMethodGroup1'){		
				if (trim(elem[i].value).length == 0){
					elem[i].style.background = 'Yellow';
					str = 'The required field has not been filled in.\n';
				}else{					
					elem[i].style.background = 'none';
				}
			}			
			if ((elem[i].name == 'ccId') && (elem[i].value.length != 0)) {
				validCVV = validateCvvCode(cardType, elem[i]);
				if(validCVV!="")
					elem[i].style.background = 'Yellow';
			}
			if ((elem[i].name == 'ccNum') && (elem[i].value.length != 0)) {
				validCCN = validateCreditCardNumber(cardType, elem[i]);
				if(validCCN!="")
					elem[i].style.background = 'Yellow';
			}
		}
		
	}
		validED += validateExpDate(document.getElementById('ccExpMonth').value,document.getElementById('ccExpYear').value)
			if(validED!=""){
					document.getElementById('ccExpMonth').style.background = 'Yellow';
					document.getElementById('ccExpYear').style.background = 'Yellow';				
				}else{
					document.getElementById('ccExpMonth').style.background = 'none';
					document.getElementById('ccExpYear').style.background = 'none';
	}
	}else
  		cardError = "Please select the credit card type.";
    }
	alert(profileId);
	if(profileId!=''){
	cvvValue = document.getElementById(profileId).value;
        existCardType = document.getElementById('cardType'+profileId).value;
        alert(existCardType);
             if(cvvValue!=''){
                  existValidCVV = validateCvvCodeforExistCard(existCardType,cvvValue);
                  alert(existValidCVV);
                  if(existValidCVV!='')
		        document.getElementById(profileId).style.background = 'Yellow';
                  else
                        document.getElementById('ccId').value = cvvValue;
             }else
	     {
		  str = 'The required field has not been filled in.\n';
		  document.getElementById(profileId).style.background = 'Yellow';
             }

	}
	str += validCCN + validED + validCVV + existValidCVV +cardError;	
	if (str != "") {		
		alert(str);
		return false;
	}	
        disableAddToBag(buttonId);
	return true;
	}
}

$( function() {
	$("select#billExistAddr").change( function() {
		var id = $(this).val();
		//alert(id);
		if( id == "") {
			//alert(id);
			jQuery("input#billFirstName").val("");
			jQuery("input#billMidInit").val("");
			jQuery("input#billLastName").val("");
			jQuery("input#billCompany").val("");
			jQuery("input#billAddress1").val("");
			jQuery("input#billAddress2").val("");
			jQuery("input#billCity").val("");
			jQuery("select#billState").val(0);
			jQuery("input#billZip").val("");
			jQuery("input#billPhone1").val("");
			jQuery("input#billPhone2").val("");
			jQuery("input#billPhone3").val("");
			jQuery("input#billCell1").val("");
			jQuery("input#billCell2").val("");
			jQuery("input#billCell3").val("");
			jQuery("input#billingAddressId").val("");

			$("input#billFirstName").attr("readonly",false);
			$("input#billMidInit").attr("readonly",false);
			$("input#billLastName").attr("readonly",false);
			$("input#billCompany").attr("readonly",false);
			$("input#billAddress1").attr("readonly",false);
			$("input#billAddress2").attr("readonly",false);
			$("input#billCity").attr("readonly",false);
			$("input#billState").attr("readonly",false);
			$("input#billZip").attr("readonly",false);
			$("input#billPhone1").attr("readonly",false);
			$("input#billPhone2").attr("readonly",false);
			$("input#billPhone3").attr("readonly",false);
			$("input#billCell1").attr("readonly",false);
			$("input#billCell2").attr("readonly",false);
			$("input#billCell3").attr("readonly",false);
		}
		var aId = 'selectBilling_' + id;
		var content = document.getElementById(aId).innerHTML;
		var mySplitResult = content.split("||");

		var fName = mySplitResult[0];
		var mName = mySplitResult[1];
		var lName = mySplitResult[2];
		var company = mySplitResult[3];
		var address1 = mySplitResult[4];
		var address2 = mySplitResult[5];
		var city = mySplitResult[6];
		var state = mySplitResult[7];
		var zip = mySplitResult[8];
		var country = mySplitResult[9];
		var phone1 = mySplitResult[10];
		var phone2 = mySplitResult[11];
		var phone3 = mySplitResult[12];
		var mobphone1 = mySplitResult[13];
		var mobphone2 = mySplitResult[14];
		var mobphone3 = mySplitResult[15];
		var addressId = mySplitResult[16];

		jQuery("input#billFirstName").val(fName);
		jQuery("input#billMidInit").val(mName);
		jQuery("input#billLastName").val(lName);
		jQuery("input#billCompany").val(company);
		jQuery("input#billAddress1").val(address1);
		jQuery("input#billAddress2").val(address2);
		jQuery("input#billCity").val(city);
		jQuery("select#billState").val(state);
		jQuery("input#billZip").val(zip);
		jQuery("input#billPhone1").val(phone1);
		jQuery("input#billPhone2").val(phone2);
		jQuery("input#billPhone3").val(phone3);
		jQuery("input#billCell1").val(mobphone1);
		jQuery("input#billCell2").val(mobphone2);
		jQuery("input#billCell3").val(mobphone3);
		jQuery("input#billingAddressId").val(addressId);

		$("input#billFirstName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billMidInit").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billLastName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billCompany").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billAddress1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billAddress2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billCity").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billState").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billZip").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billPhone1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billPhone2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billPhone3").attr("readonly",true).css({'padding':'3px 3px 3px 0px', 'height':'15px'});
		$("input#billCell1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billCell2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#billCell3").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
	})
})


$( function() {
	$("select#shipExistAddr").change( function() {
		var id = $(this).val();
		if( id == "") {
			jQuery("input#shipFirstName").val("");
			jQuery("input#shipLastName").val("");
			jQuery("input#shipCompany").val("");
			jQuery("input#shipAddress1").val("");
			jQuery("input#shipAddress2").val("");
			jQuery("input#shipCity").val("");
			jQuery("select#shipState").val(0);
			jQuery("input#shipZip").val("");
			jQuery("input#shipPhone1").val("");
			jQuery("input#shipPhone2").val("");
			jQuery("input#shipPhone3").val("");
			jQuery("input#shippingAddressId").val("");
			jQuery("input#shippingContactId").val("");

			$("input#shipFirstName").attr("readonly",false);
			$("input#shipLastName").attr("readonly",false);
			$("input#shipCompany").attr("readonly",false);
			$("input#shipAddress1").attr("readonly",false);
			$("input#shipAddress2").attr("readonly",false);
			$("input#shipCity").attr("readonly",false);
			$("input#shipState").attr("readonly",false);
			$("input#shipZip").attr("readonly",false);
			$("input#shipPhone1").attr("readonly",false);
			$("input#shipPhone2").attr("readonly",false);
			$("input#shipPhone3").attr("readonly",false);
		}
		var aId = 'selectShipping_' + id;
		var content = document.getElementById(aId).innerHTML;
		var mySplitResult = content.split("||");

		var fName = mySplitResult[0];
		var lName = mySplitResult[1];
		var company = mySplitResult[2];
		var address1 = mySplitResult[3];
		var address2 = mySplitResult[4];
		var city = mySplitResult[5];
		var state = mySplitResult[6];
		var zip = mySplitResult[7];
		var country = mySplitResult[8];
		var phone1 = mySplitResult[9];
		var phone2 = mySplitResult[10];
		var phone3 = mySplitResult[11];
		var addressId = mySplitResult[12];
		var emailId = mySplitResult[13];
		var contactId = mySplitResult[14];

		jQuery("input#shipFirstName").val(fName);
		jQuery("input#shipLastName").val(lName);
		jQuery("input#shipCompany").val(company);
		jQuery("input#shipAddress1").val(address1);
		jQuery("input#shipAddress2").val(address2);
		jQuery("input#shipCity").val(city);
		jQuery("select#shipState").val(state);
		jQuery("input#shipZip").val(zip);
		jQuery("input#shipPhone1").val(phone1);
		jQuery("input#shipPhone2").val(phone2);
		jQuery("input#shipPhone3").val(phone3);
		jQuery("input#shippingAddressId").val(addressId);
		jQuery("input#shippingContactId").val(contactId);

		$("input#shipFirstName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipLastName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipCompany").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipAddress1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipAddress2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipCity").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipState").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipZip").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipPhone1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipPhone2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipPhone3").attr("readonly",true).css({'padding':'3px 3px 3px 0px', 'height':'15px'});
	})
})



$( function() {
	$("select#shipExistAddrpaypal").change( function() {
		
	
		var id = $(this).val();
		if( id == "") {
			jQuery("input#shipExistAddrpaypal").val("");
			jQuery("input#shipFName").val("");
			jQuery("input#shipLName").val("");
			jQuery("input#shipcompany").val("");
			jQuery("input#shipAddress1").val("");
			jQuery("input#shipAddress2").val("");
			jQuery("input#shipcity").val("");
			jQuery("select#shipstate").val(0);
			jQuery("input#shipzip").val("");
			jQuery("input#shipphone1").val("");
			jQuery("input#shipphone2").val("");
			jQuery("input#shipphone3").val("");
			jQuery("input#shippingAddressId").val("");
			jQuery("input#shippingContactId").val("");
			jQuery("input#ShipExistAccountId").val("");

			$("input#shipFName").attr("readonly",false);
			$("input#shipLName").attr("readonly",false);
			$("input#shipcompany").attr("readonly",false);
			$("input#shipAddress1").attr("readonly",false);
			$("input#shipAddress2").attr("readonly",false);
			$("input#shipcity").attr("readonly",false);
			$("input#shipstate").attr("readonly",false);
			$("input#shipzip").attr("readonly",false);
			$("input#shipphone1").attr("readonly",false);
			$("input#shipphone2").attr("readonly",false);
			$("input#shipphone3").attr("readonly",false);
		}
				
		var aId = 'selectShipping_' + id;
		var accountId = 'shipaccid'+id;
		var AccId = document.getElementById(accountId).value;
		
		jQuery("input#ShipExistAccountId").val(AccId);
		
		var content = document.getElementById(aId).innerHTML;
		var mySplitResult = content.split("||");

		var fName = mySplitResult[0];
		var lName = mySplitResult[1];
		var company = mySplitResult[2];
		var address1 = mySplitResult[3];
		var address2 = mySplitResult[4];
		var city = mySplitResult[5];
		var state = mySplitResult[6];
		var zip = mySplitResult[7];
		var country = mySplitResult[8];
		var phone1 = mySplitResult[9];
		var phone2 = mySplitResult[10];
		var phone3 = mySplitResult[11];
		var addressId = mySplitResult[12];
		var emailId = mySplitResult[13];
		var contactId = mySplitResult[14];

		jQuery("input#shipFName").val(fName);
		jQuery("input#shipLName").val(lName);
		jQuery("input#shipcompany").val(company);
		jQuery("input#shipAddress1").val(address1);
		jQuery("input#shipAddress2").val(address2);
		jQuery("input#shipcity").val(city);
		jQuery("select#shipstate").val(state);
		jQuery("input#shipzip").val(zip);
		jQuery("input#shipphone1").val(phone1);
		jQuery("input#shipphone2").val(phone2);
		jQuery("input#shipphone3").val(phone3);
		jQuery("input#shippingAddressId").val(addressId);
		jQuery("input#shippingContactId").val(contactId);

		/*$("input#shipFirstName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipLastName").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipCompany").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipAddress1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipAddress2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipCity").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipState").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipZip").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipPhone1").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipPhone2").attr("readonly",true).css({'padding':'3px', 'height':'15px'});
		$("input#shipPhone3").attr("readonly",true).css({'padding':'3px 3px 3px 0px', 'height':'15px'});*/
	})
})




function validateFormOnSubmitFrd() {	
    var reason = "";
    var yourEmail = "";
    var friendEmail = "";
    reason += validateEmpty(document.getElementById('yourname'));
	if(reason!='')
  	reason = reason.replace("The required field","Your Name");
    yourEmail = validateEmail(document.getElementById('youremail'));
	if(yourEmail!='')
  	yourEmail = yourEmail.replace("email","your email");
    reason += validateEmpty(document.getElementById('friendname'));
	if(reason!='')
  	reason = reason.replace("The required field","Friend Name");
    friendEmail += validateEmail(document.getElementById('friendemail'));
	if(friendEmail!='')
  	friendEmail = friendEmail.replace("email","friend email");
    /*if((document.getElementById('txtCAPTCHA').value.length == 0))
        document.getElementById('txtCAPTCHA').style.background = 'Yellow';
    else if((document.getElementById('txtCAPTCHA').value.length != 0))
        document.getElementById('txtCAPTCHA').style.background = 'White';*/

	reason += yourEmail + friendEmail;
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        //alert("Please be sure highlighted fields contain valid information.");
        return false;
    }

    return true;
}

function sortBy(sortBy) {
	//alert('here');
    document.getElementById('so').value=sortBy;
    document.frmsortby.submit();
}

function disableAddToBag(itemId){
   jQuery("#"+itemId).attr("disabled","disabled");
}

function validateQuantity(frm) {
	//alert('Quantity');
    var elem = document.getElementById(frm).elements;
    var str = "";
    var validNo = "";
    for ( var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if ( elem[i].name == 'hidItemQty[]') {
                var regExp = new RegExp('^[0-9]*$');
                if (trim(elem[i].value).length == 0){
                    elem[i].style.background = 'Yellow';
                    str = "The required field has not been filled in.";
                } else if( !(regExp.test(elem[i].value) && parseInt(elem[i].value,10) > 0) ){
                    elem[i].style.background = 'Yellow';
                    validNo = "Highlighted item's quantity is not valid.";
                } else {
                    elem[i].style.background = 'none';
                }
            }
        }
    }
    str += validNo;
    if (str != '') {
        alert(str);
        return false;
    }
    return true;
}

/*function calculateShipping(element, value){
	//alert('shipping');
	var zip = document.getElementById('zip').value;
	var str = "";
	var validZip = "";
   var regExp = new RegExp('^[0-9]*$');
   if (trim(zip).length == 0){
   	document.getElementById('zip').style.background = 'Yellow';
      str = "The required field has not been filled in.\n";
   } else if( !(regExp.test(zip))  ){
      document.getElementById('zip').style.background = 'Yellow';
      validZip = "Zip code is not valid.\n";
   } else if (trim(zip).length < 5){
   	document.getElementById('zip').style.background = 'Yellow';
   	str = "Zip code is not valid...\n";   	
   } else {
      document.getElementById('zip').style.background = 'White';
   } 
	
   str += validZip;
   if (str != '') {
   	alert(str);
      return false;
   }else{
	  
   	$("#"+element).val(value);
   	return true;
   }   
}*/

function calculateShipping(element, value){
	//alert('shipping');
	var zip = document.getElementById('zip').value;
	var str = "";
	var validZip = "";
   var regExp = new RegExp('^[0-9]*$');
   if (trim(zip).length == 0){
   	document.getElementById('zip').style.background = 'Yellow';
      str = "The required field has not been filled in.\n";
   } else if( !(regExp.test(zip))  ){
      document.getElementById('zip').style.background = 'Yellow';
      validZip = "Zip code is not valid.\n";
   } else if (trim(zip).length < 5){
   	document.getElementById('zip').style.background = 'Yellow';
   	str = "Zip code is not valid...\n";   	
   } else {
      document.getElementById('zip').style.background = 'none';
   } 
	
   str += validZip;
   if (str != '') {
   	alert(str);
      return false;
   }else{
	  
   	$("#"+element).val(value);
   	return true;
   }   
}


function changeShippingOption(shipMethod,postalCode,status){
	//alert('shipping option');
	var temp = shipMethod;
	$("#shipMethod").val(temp);
	
	$("#shippingstatus").val(temp);
	if (jQuery('#willCallRadio').attr("checked")) {
		
		document.getElementById("zip").value="";
		jQuery("#zip").attr("readonly",true).val('').css({'background-color':'#D4D4D4'});
		jQuery("#gobtn").attr("disabled","disabled");		
    		var shippingAmount = '0.00' ;
    		var result = (parseFloat(shippingAmount) + parseFloat($("#hiddensubtotal").val()) + 
		parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    		$("#hiddentotal").val(result);
    		$("#hiddenshipmethod").val(temp);
    		$("#hiddenshipping").val(shippingAmount);
    		$('#hiddentotal').formatCurrency('#total');
    		$('#hiddenshipping').formatCurrency('#shipping');
		jQuery('#shippmentDiv').hide();
		/*jQuery('#one').hide();
		jQuery('#two').hide();*/
  		if(shippingAmount==0){
    			$('#shippingdiv').hide();
}
  		else{
    			$('#shippingdiv').show();
}
    			$("#hiddentotal").hide();
    			$("#hiddenshipping").hide();	
	} else {
	/*	jQuery('#one').show();
		jQuery('#two').show();*/
		jQuery("#zip").attr("readonly",false).val(postalCode).css({'background-color':''});
		jQuery("#gobtn").removeAttr("disabled");	
		jQuery('#shippmentDiv').show();
		if(status=='Yes')	
 		jQuery("#shipMethod").removeAttr("disabled");
    		updateTotalValue();
	}
}

function updateTotalValue(){
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode"+temp).val()) ;
    var result = (parseFloat($("#shipcode"+temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshippingmethodid").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    $('#hiddentotal').formatCurrency('#total');
    $('#hiddenshipping').formatCurrency('#shipping');
  if(shippingAmount==0)
   {
	  $('#shipping').hide();
	  $('#shippingdiv').hide();
   }
	
  else
   {
   $('#shippingdiv').show();
   $('#shipping').show(); 
   
   $("#hiddentotal").hide();
   $("#hiddenshipping").hide();
   }
 /*   $("#total").html(res.val());    */

}

function updateTotalValues(inPage){
	//alert('update to values');
	if(inPage=='cart'){
		jQuery("#zip").attr("readonly",false);
		jQuery("#gobtn").removeAttr("disabled");
 		jQuery("#shipMethod").removeAttr("disabled");
	    jQuery('#shippingRadio').attr("checked","checked");
	}
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode"+temp).val()) ;
    var result = (parseFloat($("#shipcode"+temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    $('#hiddentotal').formatCurrency('#total');
    $('#hiddenshipping').formatCurrency('#shipping');
    //alert(shippingAmount);
  if(shippingAmount==0){
	  $('#shipping').hide();    
	  $('#shippingdiv').hide();
  }
  else{
    $('#shippingdiv').show();
    $('#shipping').show();
    $("#hiddentotal").hide();
    $("#hiddenshipping").hide();
  }
 /*   $("#total").html(res.val());    */

}

function wayToCheckout(ele) {
	//alert('way to checkout');
	//alert(ele);
	
	
    if(ele == 'securecheckout') {
        document.getElementById('checkout_action').value="secureCheckout";
        return true;
    } 
    if(ele == 'directpaypal') {
    	
        document.getElementById('checkout_action').value="directpaypal";
        return true;
    } 
    else if(ele == 'paypalcheckout') {
    	
    	
        document.getElementById('checkout_action').value="paypalcheckout";
        
       
        for (var i=0; i < document.cartfrm.willCallRadio.length; i++)
        {
        	
        if (document.cartfrm.willCallRadio[i].checked)
           {
           var ship_status = document.cartfrm.willCallRadio[i].value;
           }
        }
        document.getElementById('shippingstatus').value = ship_status;
       
       
    	
        return true;
    } 
    else {
        document.getElementById('checkout_action').value="googleCheckout";
        return true;
    }
}

function googleChecktoutValidate(frm) {
	//alert('1 HERE YOU ARE  !');
	var elem = document.getElementById(frm).elements;
	
	var reason = "";
	var validZip = "";
	var validShipPhone = "";
	var str = 'Following required field has not been filled in.\n';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text')) {
			if ((elem[i].id != 'shipcompany')
                && (elem[i].id != 'shipphone1')
                && (elem[i].id != 'shipAddress2')
                && (elem[i].id != 'shipphone2')
                && (elem[i].id != 'shipphone3')) {
				
				//var chkval= trimchk(document.getElementById(elem[i].id));
				reason += validategoogleEmpty(document.getElementById(elem[i].id));
				//alert(reason);
				if (reason != "")
					reason = reason.replace("The required field", elem[i].title);
				
			}
			if ((elem[i].name == 'shipzip') && (elem[i].value.length != 0)) {
				
				validZip = validateZipCodess(elem[i]);
			
			}
		}
		if(elem[i].name == 'shipstate' && (elem[i].value == 0)){
			
			reason += elem[i].title + " has not been selected.\n";
			elem[i].style.background = 'Yellow';
		}else if(elem[i].name == 'shipstate' && (elem[i].value != 0)){
			elem[i].style.background = 'none';
		}   
	}
    
	validShipPhone = validatePhoneSections('shipphone');
   
	reason += validZip + validShipPhone;
	if (reason != "") {
		str+= reason;
		alert(str);
		return false;
	}
	var shipmethodval = document.getElementById('shipMethod').value;
	if(shipmethodval == '')
	{
		alert( "Please Select Shipping Method");
		document.getElementById('shipMethod').style.background = 'Yellow';
		return false;
	}
	return true;
}



function paypalChecktoutValidate(frm) {
	//alert('1 HERE YOU ARE  !');
	var elem = document.getElementById(frm).elements;
	
	var reason = "";
	var validZip = "";
	var validShipPhone = "";
	var str = 'Following required field has not been filled in.\n';
	for ( var i = 0; i < elem.length; i++) {
		if ((elem[i].type == 'text')) {
			if ((elem[i].id != 'shipcompany')
                && (elem[i].id != 'shipphone1')
                && (elem[i].id != 'shipAddress2')
                && (elem[i].id != 'shipphone2')
                && (elem[i].id != 'shipphone3')) {
				
				//var chkval= trimchk(document.getElementById(elem[i].id));
				reason += validategoogleEmpty(document.getElementById(elem[i].id));
				//alert(reason);
				if (reason != "")
					reason = reason.replace("The required field", elem[i].title);
				
			}
			if ((elem[i].name == 'shipzip') && (elem[i].value.length != 0)) {
				
				validZip = validateZipCodess(elem[i]);
			
			}
		}
		if(elem[i].name == 'shipstate' && (elem[i].value == 0)){
			
			reason += elem[i].title + " has not been selected.\n";
			elem[i].style.background = 'Yellow';
		}else if(elem[i].name == 'shipstate' && (elem[i].value != 0)){
			elem[i].style.background = 'none';
		}   
	}
    
	validShipPhone = validatePhoneSections('shipphone');
   
	reason += validZip + validShipPhone;
	if (reason != "") {
		str+= reason;
		alert(str);
		return false;
	}
   
	var shipmethodval = document.getElementById('shipMethod').value;
	if(shipmethodval == '')
	{
		alert( "Please Select Shipping Method");
		document.getElementById('shipMethod').style.background = 'Yellow';
		return false;
	}
	
	
	return true;
}


function trimchk(s)
{//alert(s);
  return s.replace(/^\s+|\s+$/, '');
  
}

function toggleShipping() {
	//alert('copy & paste');
	jQuery("input#shipFirstName").val(jQuery("input#billFirstName").val());
	jQuery("input#shipLastName").val(jQuery("input#billLastName").val());
	jQuery("input#shipCompany").val(jQuery("input#billCompany").val());
	jQuery("input#shipAddress1").val(jQuery("input#billAddress1").val());
	jQuery("input#shipAddress2").val(jQuery("input#billAddress2").val());
	jQuery("input#shipCity").val(jQuery("input#billCity").val());
	jQuery("select#shipState").val(jQuery("select#billState").val());
	jQuery("input#shipZip").val(jQuery("input#billZip").val());
	jQuery("select#shipCountry").val(jQuery("select#billCountry").val());
	jQuery("input#shipPhone1").val(jQuery("input#billPhone1").val());
	jQuery("input#shipPhone2").val(jQuery("input#billPhone2").val());
	jQuery("input#shipPhone3").val(jQuery("input#billPhone3").val());
	jQuery("select#shipExistAddr").val();
}

function AddNewShipTo() {
	//alert('new');
	jQuery("input#shipFirstName").val('');
	jQuery("input#shipLastName").val('');
	jQuery("input#shipCompany").val('');
	jQuery("input#shipAddress1").val('');
	jQuery("input#shipAddress2").val('');
	jQuery("input#shipCity").val('');
	jQuery("select#shipState").val(0);
	jQuery("input#shipZip").val('');
	jQuery("select#shipCountry").val(0);
	jQuery("input#shipPhone1").val('');
	jQuery("input#shipPhone2").val('');
	jQuery("input#shipPhone3").val('');
	jQuery("select#shipExistAddr").val();

	$("input#shipFirstName").attr("readonly",false);
	$("input#shipLastName").attr("readonly",false);
	$("input#shipCompany").attr("readonly",false);
	$("input#shipAddress1").attr("readonly",false);
	$("input#shipAddress2").attr("readonly",false);
	$("input#shipCity").attr("readonly",false);
	$("input#shipState").attr("readonly",false);
	$("input#shipZip").attr("readonly",false);
	$("input#shipCountry").attr("readonly",false);
	$("input#shipPhone1").attr("readonly",false);
	$("input#shipPhone2").attr("readonly",false);
	$("input#shipPhone3").attr("readonly",false);
}

function displayCVVContent(cardType){
	 if(cardType=="amex"){
	   jQuery("#amextxtCCID").show();
	   jQuery("#deftxtCCID").hide(); 
	  }else{
	    jQuery("#amextxtCCID").hide();
	    jQuery("#deftxtCCID").show(); 
	 }
	}

function giftNote() {
	if (jQuery('#addgiftcheck').attr("checked")) {
		jQuery("#addgiftsub").hide();
		jQuery("#addgiftrow").show();
	} else {
		jQuery("#addgiftrow").hide();
		jQuery("#addgiftsub").show();
		jQuery("#giftnotes").val('');
	}
}

function image1(value){
var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
    if(value=="new"){
        document.getElementById('rowNewCard').style.display="block";
	for(i=0;i<paymentDetailsGroup.length;i++){
	           jQuery("input#"+paymentDetailsGroup[i].value).val('');
		   jQuery("input#"+paymentDetailsGroup[i].value).css({'background-color':'#ebe8de'});
		   jQuery("input#"+paymentDetailsGroup[i].value).attr("readonly",true);
          }
    }else {
        //document.getElementById('rowNewCard').style.display="none";
        document.getElementById('new_card').checked=false;
	jQuery("input#ccId").val('');
	for(i=0;i<paymentDetailsGroup.length;i++){
	    if(paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value!='new'){
	    	   jQuery("input#"+paymentDetailsGroup[i].value).val('');
		   jQuery("input#"+paymentDetailsGroup[i].value).css({'background-color':'#fff'});
		   jQuery("input#"+paymentDetailsGroup[i].value).attr("readonly",false);
	   }else{
		   jQuery("input#"+paymentDetailsGroup[i].value).val('');
		   jQuery("input#"+paymentDetailsGroup[i].value).css({'background-color':'#ebe8de'});
		   jQuery("input#"+paymentDetailsGroup[i].value).attr("readonly",true);
		}
          }
    }
}

function validateLoginFormOnSubmit(theForm) {	
    theForm.action.value="login";
    var reason = "";
    reason += validateEmpty(theForm.loginemail);
    reason += validateEmail(theForm.loginemail);
	reason += validatePassword(theForm.loginpasswd);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}

function validateLoginPassForm(theForm) {
	//alert(theForm);
	//alert("jjh");
	document.getElementById("errormsg2").style.visibility='hidden';
//alert("gfg");
	var reason = "";
        var pass;
	reason += validateEmpty(theForm.txtNewFirstName);
	if (reason!="") reason = reason.replace("The required field","First Name")
	reason += validateEmpty(theForm.txtNewLastName);
	if (reason!="") reason = reason.replace("The required field","Last Name")
	reason += validateEmail(theForm.txtNewLogin);

        reason += validateOldPassword(theForm.txtOldPassword);
	if (reason!="") pass = reason.replace("The required field","Old Password")

        reason += validateNewPassword(theForm.txtNewPassword);
	if (reason!="") pass = reason.replace("The required field","New Password")

        /*if (theForm.txtOldPassword.value.length!=0)
		reason += validatePassword(theForm.txtOldPassword);
	if (theForm.txtNewPassword.value.length!=0)
		reason += validatePassword(theForm.txtNewPassword);*/

	if (reason != "") {
	alert("Some fields need correction:\n" + reason);
	return false;
	}
	jQuery("#changepass").hide();
	jQuery("#buttonrow").hide();
	jQuery("#ajaxLoader").show();
	document.frmchangepass.submit();
}

/* Project specific validation ends here */


/* Generic validation starts here */

function emptyCheck(fld) {
    var error = "";
    var tfld = trim(fld.val());
    if (tfld == "") {
        error = "You didn't enter "+ fld.attr("title") +".\n";
    }
    return error;
}

function trim(s) {
	return s.replace(/^\s+|\s+$/, '');
}

function validateEmpty(fld) {
    var error = "";
    //alert(fld.name);
    if (fld.value.length == 0) {
        //fld.style.background = 'Yellow';
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'none';
    }
    if(fld.type == 'select-one'){
    	if(fld.value == 0){
    		//fld.style.background = 'Yellow';
            error = "The required field has not been filled in.\n"
    	}else{
    		fld.style.background = 'none';
    	}    	
    }
    return error;
}

function validategoogleEmpty(fld) {
    var error = "";
    //alert(fld.name);
	var elem=trimchk(fld.value);
    if (elem.length == 0) {
        //fld.style.background = 'Yellow';
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'none';
    }
    if(fld.type == 'select-one'){
    	if(fld.value == 0){
    		//fld.style.background = 'Yellow';
            error = "The required field has not been filled in.\n"
    	}else{
    		fld.style.background = 'none';
    	}    	
    }
    return error;
}

/*function validatetextfields(fld) { 

	var error = "";
	    //var illegalChars = /[\W_]/; // allow only letters and numbers
		var illegalChars = /^([A-Za-z 0-9])$/;
	    //var error=fld.name;
    if (fld.value == "") {
        //fld.style.background = 'Yellow';
        error =" : You didn't enter any text.\n";
    } else if (illegalChars.test(fld.value)) {
    	var error = "";
    	error = " :The textfield contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'White';
    }
    if (error == ""){
    return error;
    } else {
		 if(fld.name == "firstname")
		 {
			 names ="First name"; 
		 }
		 else if(fld.name == "lastname")
		 {
			 names ="Last name"; 
		 }
		 else if(fld.name == "schoolname")
		 {
			 names ="School name"; 
		 }
		 else if(fld.name == "captcha[input]")
		 {
			 names ="Captcha[input]"; 
		 }
		 else
		 {
			 names=fld.name;
		 }
    	error= names + error;
	}
    return error;
}*/

function validatetextfields(fld) {
    //alert(fld.name);
    var error = "";
	//alert(theForm.schooljs.value);
	//alert(document.getElementById('schooljs').value);
	/*if(fld.name == "schoolname")
		 {
				  var i;
				  var marketexist;
				  var ajaxids= document.getElementById('schooljs').value;
				  //alert(ajaxids);
				  var marketname=ajaxids.split(',');
				  //alert(marketname.length);
				  for(i=0;i<marketname.length;i++)
				  {  //alert(marketname[i]);
					  //alert(document.getElementById("schoolname").value);
					 if(document.getElementById("schoolname").value == marketname[i])
					 {    //alert(marketname[i]);
						  marketexist = 1;
					 }
				  
				  }
		 }*/
	    //var illegalChars = /^([A-Za-z 0-9])$/;
		
		
		var illegalChars = /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/;
		///[\W_]/; // allow only letters and numbers
	    //var error=fld.name; if(regs.test(address) == false)
    if (fld.value == "") {
        //fld.style.background = 'Yellow';
        error =" : You didn't enter any text.\n";
    }
    else if(fld.name == 'schoolname')
        {
            
           // alert(fld.value.length);
          if(fld.value.length < 5)
               {
           var error = "";
    	   error = " :The schoolname should have minimum length 5 characters.\n";
                   
               }
               else if(fld.value.length > 100)
               {
           var error = "";
    	   error = " :The schoolname should have maximum length 100 characters.\n";

               }

        }


    else if(illegalChars.test(fld.value) == false) {
		//alert('dfdg');
    	var error = "";
    	error = " :The textfield contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } 
	/*else if(fld.name == "schoolname" && marketexist != 1)
	{
		 error = " : Not Avaiable.\n";
	}*/
	else {
        fld.style.background = 'none';
    }
    if (error == ""){
    return error;
    } else {
		 if(fld.name == "firstname")
		 {
			 names ="First name"; 
		 }
		 else if(fld.name == "lastname")
		 {
			 names ="Last name"; 
		 }
		 else if(fld.name == "schoolname")
		 {
			 names ="School name"; 
		 }
		 else if(fld.name == "captcha[input]")
		 {
			 names ="Captcha[input]"; 
		 }
		 else
		 {
			 names=fld.name;
		 }
    	error= names + error;
	}
    return error;
}

function validateEmail(fld) {
    var error="";
    var tfld = trimchk(fld.value);                        // value of field with
														// whitespace trimmed
														// off
    // var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
   // var emailFilter = new RegExp('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$');
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    // var emailFilter =
	// /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
    // var emailFilter = new
	// RegExp('[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}');
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (tfld == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              // test email for
														// illegal characters
        //fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        //fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        var st;
    	fld.style.background = 'none';
        
        /*alert(chk);*/
    }
    return error;
}


function contacttrim(s) {
    return s.replace(/^\s+|\s+$/, '');
}

function validateContactEmail(fld) {
    var error = "";
    var tfld = contacttrim(fld.val());
   // var emailFilter = new RegExp('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$');
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;

    if (tfld == "") {
        error = "You didn't enter "+ fld.attr("title") +".\n";
    } else if (!emailFilter.test(tfld)) { // test email for
        // illegal characters
        error = "Please enter a valid "+ fld.attr("title") + ".\n";
    } else if (tfld.match(illegalChars)) {
        error = "The " +fld.attr("title") + " contains illegal characters.\n";
    }

    return error;
}


function validateConfirmEmail(fld) {
    var error="";
    var tfld = trimchk(fld.value);                        // value of field with
														// whitespace trimmed
														// off
    // var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    //var emailFilter = new RegExp('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$');
	var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    // var emailFilter =
	// /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
    // var emailFilter = new
	// RegExp('[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}');
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (tfld == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter an confirm email address.\n";
    } else if (!emailFilter.test(tfld)) {              // test email for
														// illegal characters
        //fld.style.background = 'Yellow';
        error = "Please enter a valid confirm email address.\n";
    } else if (fld.value.match(illegalChars)) {
        //fld.style.background = 'Yellow';
        error = "The confirm email address contains illegal characters.\n";
    } else {
        var st;
    	fld.style.background = 'none';
        
        /*alert(chk);*/
    }
    return error;
}

function validatePassword(fld) {
   
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if (fld.value.length < 8) {
        error = "The password length should be 8 characters minimum. \n";
        //fld.style.background = 'Yellow';
    } else if (fld.value.length > 14) {
        error = "The password length should be 14 characters maximum. \n";
        //fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
        //fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'none';
    }
    return error;
}



function validateOldPassword(fld) {

    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter a Old Password.\n";
    } else if (fld.value.length < 8) {
        error = "The Old Password length should be 8 characters minimum. \n";
        //fld.style.background = 'Yellow';
    } else if (fld.value.length > 14) {
        error = "The Old Password length should be 14 characters maximum. \n";
        //fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The Old Password contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The Old Password must contain at least one numeral.\n";
        //fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'none';
    }
    return error;
}


function validateNewPassword(fld) {

    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter a New Password.\n";
    } else if (fld.value.length < 8) {
        error = "The New Password length should be 8 characters minimum. \n";
        //fld.style.background = 'Yellow';
    } else if (fld.value.length > 14) {
        error = "The New Password length should be 14 characters maximum. \n";
        //fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The New Password contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The New Password must contain at least one numeral.\n";
        //fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'none';
    }
    return error;
}





function validateConfirmPassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter a confirm password.\n";
    } else if (fld.value.length < 8) {
        error = "The confirm password length should be 8 characters minimum. \n";
        //fld.style.background = 'Yellow';
    } else if (fld.value.length > 15) {
        error = "The confirm password length should be 14 characters maximum. \n";
        //fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The confirm password contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The confirm password must contain at least one numeral.\n";
        //fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'none';
    }
    return error;
}

function compareEmail(fld,fld1) {
	
	var error = "";	
	if(fld1.value !="")
		fld1.style.background = 'none';
            if(fld.value && fld1.value !== "" )
                {
	if (fld.value != fld1.value) {
		
		//fld.style.background = 'Yellow';
		//fld1.style.background = 'Yellow';
        error = "Email and Confirmation Email did not match.\n";
    }
                }
	return error;
}

function comparePassword (fld,fld1) {
	var error = "";		
	if(fld1.value !="")
		fld1.style.background = 'none';
             if(fld.value && fld1.value !== "" )
                {
	if (fld.value != fld1.value) {
		//fld.style.background = 'Yellow';
		//fld1.style.background = 'Yellow';
        error = "Password and Confirmation Password did not match.";
    }
                }
	return error;
	}
 
function validatePhoneSections(fldname) {
    //alert('phone validation');
    
    var error = "";
    var s1 = document.getElementById(fldname+'1')
    var s2 = document.getElementById(fldname+'2')
    var s3 = document.getElementById(fldname+'3')
    
    fld = s1.value + s2.value + s3.value;

	
    if (fld == "") {
        error = "The phone number has not been filled in.\n";
        //s1.style.background = 'Yellow';
        //s2.style.background = 'Yellow';
        //s3.style.background = 'Yellow';
		
    } else if (isNaN(fld)) {
        error = "The phone number contains illegal characters.\n";
		
        //s1.style.background = 'Yellow';
        //s2.style.background = 'Yellow';
        //s3.style.background = 'Yellow';
    } else if (fld.length < 10) {
        error = "The phone number is the wrong length.\n";
        //s1.style.background = 'Yellow';
        //s2.style.background = 'Yellow';
        //s3.style.background = 'Yellow';
    } else {
        s1.style.background = 'none';
        s2.style.background = 'none';
        s3.style.background = 'none';
    }    
	
    return error;
}

function validateCheckoutPhoneSections(fldname,title) {
    var error = "";

    var s1 = document.getElementById(fldname+'1')
    var s2 = document.getElementById(fldname+'2')
    var s3 = document.getElementById(fldname+'3')
    fld = s1.value + s2.value + s3.value;

    if (fld == "") {
        error = title+" has not been filled in.\n";
        //s1.style.background = 'Yellow';
        //s2.style.background = 'Yellow';
        //s3.style.background = 'Yellow';
    } else if (isNaN(parseInt(fld))) {
        error = title+" contains illegal characters.\n";
        //s1.style.background = 'Yellow';
        //s2.style.background = 'Yellow';
        //s3.style.background = 'Yellow';
    } else if (fld.length < 10) {
        error = title+" is the wrong length.\n";
        //s1.style.background = 'Yellow';
        //s2.style.background = 'Yellow';
        //s3.style.background = 'Yellow';
    } else {
        s1.style.background = 'none';
        s2.style.background = 'none';
        s3.style.background = 'none';
    }
    return error;
}

function validateselectfields(fld) { 
	var error = "";
	    //var illegalChars = /[\W_]/; // allow only letters and numbers
	    var error=fld.name;
	    var error1=fld.selectedIndex;
	    if ((fld.selectedIndex) == "") {
	    	//fld.style.background = 'Yellow';
			
		if(error == "country")
		 {
			 error ="Country"; 
		 }
		 else if(error == "state2")
		 {
			 error ="State"; 
		 }
		 else if(error == "schoolname")
		 {
			 error ="Schoolname"; 
		 }
		 
	    	error = error + " : Unselected.\n";
	    }else {
	    	error = "";
	    }	    
    return error;
}
 
 function validatephone(fld) {
	    var error = "";
	    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

	   if (fld.value == "") {
	        error = "You didn't enter a phone number.\n";
	        //fld.style.background = 'Yellow';
	    } else if (isNaN(parseInt(stripped))) {
	        error = "The phone number contains illegal characters.\n";
	        //fld.style.background = 'Yellow';
	    } else if (!(stripped.length == 10)) {
	        error = "The phone number is the wrong length. Make sure you included an area code.\n";
	        //fld.style.background = 'Yellow';
	    }
	    return error;
	}

 function validateRadio(fld) {
  var error="";
  var radio_choice = false;
  var count;
  //fld.style.background = 'Yellow';
  
  // Loop from zero to the one minus the number of radio button selections
  for (count = 0; count < fld.length; count++) {
   // If a radio button has been selected it will return true
   // (If not it will return false)
	  if (fld[count].checked)
	   radio_choice = true; 
  }
  if (!radio_choice) {
   error="Please select a Title.\n"
   // fld.style.background = 'Yellow';
  }
 return error;
 }
 
function validateZipCode(fld) {		
    var error = "";
    var regExp = new RegExp('^[0-9]*$');
    if(fld.value.length != 5 ){
        //fld.style.background = 'Yellow';
        error += "Please enter your 5 digit or 5 digit+4 zip code.\n";
    } else if( !(regExp.test(fld.value)) ) {
        //fld.style.background = 'Yellow';
        error += "Not a valid Zip Code.\n";
    } else
    	fld.style.background = 'none';
    
    return error;
}

function validateCreditCardNumber(optName, fldId) {
    var error="";
    // Get the text of the selected card type
    var cardType = optName.value;
    // Get the value of the CVV code
    var ccnNumber = fldId.value;
    var ccnDigits = 0;
    switch (cardType.toUpperCase()) {
        case '002':
        case '001':
        case '004':
            ccnDigits = 16;
            break;
        case '003':
            ccnDigits = 15;
            break;
        default:
            return false;
    }
    var regExp = new RegExp('[0-9]{' + ccnDigits + '}');
    if( !(ccnNumber.length == ccnDigits && regExp.test(ccnNumber)) ) {
        error = "Invalid Credit Card Number.\n";
    }
    return error;
}

function validateExpDate(expmo,expyr) {
    var error="";
    var ccExpYear = expyr;
    var ccExpMonth = expmo;
    var expDate=new Date();
    expDate.setFullYear(ccExpYear, ccExpMonth, 1);
    var today = new Date();
    // alert(expDate+'=='+today);
    if (expDate < today) {
        // Credit Card is expire
        // expmo.style.background = 'Yellow';
        // expyr.style.background = 'Yellow';
        error = "Credit Card is expired.\n";
    }
    return error;
}

function validateCvvCode(optName, fldId) {
    var error="";
    // Get the text of the selected card type
    var cardType = optName.value;
    // Get the value of the CVV code
    var cvvCode = fldId.value;
    var cvvDigits = 0;
    switch (cardType.toUpperCase()) {
        case '002':
        case '001':
        case '004':
            cvvDigits = 3;
            break;
        case '003':
            cvvDigits = 4;
            break;
        default:
            return false;
    }
    var regExp = new RegExp('[0-9]{' + cvvDigits + '}');
    if( !(cvvCode.length == cvvDigits && regExp.test(cvvCode)) ) {
        error = "Invalid CVV Code.\n";
    }
    return error;
}

function validateCvvCodeforExistCard(cardType,cvvCode) {
    var error="";
    var cvvDigits = 0;
    switch (cardType.toUpperCase()) {
        case 'VISA':
        case 'MASTER':
        case 'DISCOVER':
            cvvDigits = 3;
            break;
        case 'AMERICAN EXPRESS':
            cvvDigits = 4;
            break;
        default:
            return false;
    }
    var regExp = new RegExp('[0-9]{' + cvvDigits + '}');
    if( !(cvvCode.length == cvvDigits && regExp.test(cvvCode)) ) {
        error = "Invalid CVV Code.\n";
    }
    return error;
}


function formatCurrency(num) {
	//alert('format');
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

/* Generic validation ends here */
/*tabbed panels*/

function switchtab(el, id) {
    tabs = document.getElementById('tabs').getElementsByTagName('a');
    for (i = 0; i < tabs.length; i++) tabs[i].className = '';
    tabs = document.getElementById('content').getElementsByTagName('div');
    for (i = 0; i < tabs.length; i++) tabs[i].style.display = 'none';
    el.className = 'sel';
    document.getElementById(id).style.display = 'block';
    return false;
}

var xmlSaleInvHttp;

function switchtab(id) {

    vartabs = document.getElementById('tabs').getElementsByTagName('a');
    for (i = 0; i < vartabs.length; i++) vartabs[i].className = '';
    vartabs = document.getElementById('content').getElementsByTagName('div');
    for (i = 0; i < vartabs.length; i++) vartabs[i].style.display = 'none';
    document.getElementById('tablink' + id).className = 'sel';
    document.getElementById('tab' + id).style.display = 'block';
    return false;
}

//pagination

function paginationByPage(pageno)
{
    document.getElementById('page').value=pageno;
    document.frmsortby.submit();
}

function validateQuantityAtItem(frm,itemId) {
   // alert("hello");
    var elem = document.getElementById(frm).elements;
    var str = "";
    var validNo = "";
    var bulkOrder = "";
    var maxQty = document.getElementById('maximumOrderQuantity').value;
    for ( var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if ( elem[i].name == 'itemQty') {
                var regExp = new RegExp('^[0-9]*$');
                if (trim(elem[i].value).length == 0){
                    elem[i].style.background = 'Yellow';
                    str = "The required field has not been filled in.";
                } else if( !(regExp.test(elem[i].value) && parseInt(elem[i].value,10) > 0) ){
                    elem[i].style.background = 'Yellow';
                    validNo = "Highlighted item's quantity is not valid.";
                } else if(parseInt(elem[i].value,10) > parseInt(maxQty,10)){
                    elem[i].style.background = 'Yellow';
                    bulkOrder = "Please contact us for quantity orders.";
                } else {
                    elem[i].style.background = 'none';
                }
            }
        }
    }
    str += validNo + bulkOrder;
    if (str != '') {
        alert(str);
        return false;
    }
	disableAddToBag(itemId);
    return true;
}


//added by kannan

function validateZipCodes(fld) {		

    var error = "";
   // var regExp = new RegExp('^[0-9]*([-])$');
      var regExp = /^([0-9]{5})+\-([0-9]{4})$/;
          
    /*if(fld.value.length != 5 ){*/
	if(fld.value.length < 5 ){
        //fld.style.background = 'Yellow';
        error += "Please enter your 5 digit or 5 digit+4 zip code.\n";
    } else if( !(regExp.test(fld.value)) ) {
        //fld.style.background = 'Yellow';
        error += "Not a valid Zip Code.\n";
    } else
    	fld.style.background = 'none';
    
    return error;
}

function validateZipCodess(fld) {  
   
    var error = "";
     var valid = "0123456789-";
     var hyphencount = 0;
     var field = fld.value;

     if (field.length!=5 && field.length!=10) {
         // alert("Please enter your 5 digit or 5 digit+4 zip code.");
         // return false;
         error = "Please enter your 5 digit or 5 digit+4 zip code.\n";
     }
     for (var i=0; i < field.length; i++) {
         temp = "" + field.substring(i, i+1);
         if (temp == "-") hyphencount++;
         if (valid.indexOf(temp) == "-1") {
             error = "Invalid characters in your zip code.  Please try again.\n";
         }
         if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
             error = "The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'. Please try again.\n";
         }
     }
	  if(field == '00000-0000')
     {
      error = "Invalid zip code.\n";
      
     }else if(field == '00000'){
      error = "Invalid zip code.\n";
     }
	 
     if (error.length>0){
         //fld.style.background = 'Yellow';
     }
     else{
         fld.style.background='none';
     }

     return error;

}

function enlarge(el) {
	
    alternates = el.parentNode.parentNode.getElementsByTagName('div');
    for (i = 0; i < alternates.length; i++) alternates[i].className = 'alternate';
    el.parentNode.className = 'alternate enlarged';
    document.getElementById('largeimg').src = el.getAttribute('largefiles');
	
	document.getElementById('largeimg').srcdd = el.getAttribute('largefiles');
	document.getElementById('txt_img').value = "";
	//alert(document.getElementById('txt_img').value);
	
}

/*function myPopup2(img) {
	var hid = document.getElementById('txt_img').value;
	//alert(hid);

	//var im = img.getAttribute('src'); 
	var im = img.getAttribute('srcdd');
	//alert(im);
	window.open( "<img src='+img+'", "myWindow", 
	"status = 1, height = 300, width = 300, resizable = 0" )
	//alert(document.getElementById('itemname').innerHTML);
	OpenWindow=window.open("", "newwin", "toolbar=no,scrollbars="+scroll+",menubar=no");
	OpenWindow.document.write("<HTML>")
    OpenWindow.document.write("<BODY>")
	OpenWindow.document.write("<table><tr><td>"+document.getElementById('itemname').innerHTML+"</td></tr>")
	if(hid == "")
	{
	OpenWindow.document.write("<tr><td><img src='"+document.getElementById('largeimg').srcdd+"' /></td></tr>")
	}else
	{
	//OpenWindow.document.write("<tr><td><img src='"+document.getElementById('largeimg').src+"' /></td></tr>")
		 OpenWindow.document.write("<tr><td><img src='"+document.getElementById('txt_imgs').value+"' /></td></tr>")
	}
	OpenWindow.document.write("<tr align='left'><td><a onclick=suc();>Close</a></td></tr>")
	OpenWindow.document.write("</table>")
	OpenWindow.document.write("</BODY>")
	OpenWindow.document.write("</HTML>")
	OpenWindow.document.close()
	self.name="main"
	//window.open(img,'width=404,height=316,resizable=1');
	
	}
	
*/

function myPopup2(img) {
	 var hid = document.getElementById('txt_img').value;
	 //alert(hid);

	 //var im = img.getAttribute('src'); 
	 var im = img.getAttribute('srcdd');
	 //alert(im);
	 /*window.open( "<img src='+img+'", "myWindow", 
	 "status = 1, height = 300, width = 300, resizable = 0" )*/
	 //alert(document.getElementById('itemname').innerHTML);
	 //OpenWindow=window.open("", "newwin", "toolbar=no,scrollbars="+scroll+",menubar=no");
	 OpenWindow=window.open("", "newwin", "toolbar=no,scrollbars="+scroll+",menubar=no,resizable = 1");
	 OpenWindow.document.write("<HTML>")
	    OpenWindow.document.write("<BODY>")
	 OpenWindow.document.write("<table><tr><td>"+document.getElementById('itemname').innerHTML+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:window.close();' style='text-decoration:none;'><img src='images/btn_close_window.gif' border='0' /></a></td></tr>")
	 if(hid == "")
	 {
	 OpenWindow.document.write("<tr><td><img src='"+document.getElementById('largeimg').srcdd+"' /></td></tr>")
	 }else
	 {//alert('kannan');
	 //alert(document.getElementById('txt_imgs').value);
	 OpenWindow.document.write("<tr><td><img src='"+document.getElementById('txt_imgs').value+"' /></td></tr>")
	 }
	 //OpenWindow.document.write("<tr><td><a href='javascript:window.close();' style='text-decoration:none;'>Close</a></td></tr>")
	 OpenWindow.document.write("</table>")
	 OpenWindow.document.write("</BODY>")
	 OpenWindow.document.write("</HTML>")
	 OpenWindow.document.close()
	 self.name="main"
	 //window.open(img,'width=404,height=316,resizable=1');
	 
	 }


	function suc()
	{
	   window.close();	
	}
	
	function phone_focus()
	{
		if(document.getElementById('billPhone1').value.length == 3)
		{
		   document.getElementById('billPhone2').focus();
	    }
		
	}
	
	
	function phone_focus1()
	{
		if(document.getElementById('billPhone2').value.length == 3)
		{
		   document.getElementById('billPhone3').focus();
	    }
		
	}
	
	
	function google_phone()
	{
		
		if(document.getElementById('shipphone1').value.length == 3)
		{
		   document.getElementById('shipphone2').focus();
	    }
		
	}
	
	
	function google_phone1()
	{
		if(document.getElementById('shipphone2').value.length == 3)
		{
		   document.getElementById('shipphone3').focus();
	    }
		
	}

	
	function popup_terms(url) {
		newwindow=window.open(url,'name','scrollbars=yes');
		if (window.focus) {newwindow.focus()}
		return false;
	}


function numberchk(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipPhone1').value=newval;
    } else if(document.getElementById('shipPhone1').value.length == 3)
	{
	   document.getElementById('shipPhone2').focus();
    }
       
}
function numberchk1(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipPhone2').value=newval;
    }else if(document.getElementById('shipPhone2').value.length == 3)
	{
	   document.getElementById('shipPhone3').focus();
    }
       
}
function numberchk2(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipPhone3').value=newval;
    }
       
}



function paynumberchk(phnos)
{
   
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('billPhone1').value=newval;
    } else if(document.getElementById('billPhone1').value.length == 3)
	{
	   document.getElementById('billPhone2').focus();
    }

}
function paynumberchk1(phnos)
{

    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('billPhone2').value=newval;
    } else if(document.getElementById('billPhone2').value.length == 3)
	{
	   document.getElementById('billPhone3').focus();
    }

}



function paynumberchk2(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('billPhone3').value=newval;
    }

}





/*function numberchk(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipPhone1').value=newval;
    } else if(document.getElementById('shipPhone1').value.length == 3)
	{
	   document.getElementById('shipPhone2').focus();
    }

}*/



















function numberchk3(phnos)
{
    var phno=phnos.value;
	//alert(phno);
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipphone1').value=newval;
    } else if(document.getElementById('shipphone1').value.length == 3)
	{
	   document.getElementById('shipphone2').focus();
    }
       
}
function numberchk4(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipphone2').value=newval;
    } else if(document.getElementById('shipphone2').value.length == 3)
	{
	   document.getElementById('shipphone3').focus();
    }
       
}
function numberchk5(phnos)
{
    var phno=phnos.value;
    var ls=phno.substr(phno.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=phno.substr(0,phno.length-1)
        document.getElementById('shipphone3').value=newval;
    }
       
}



function changeshipphoneno_1()
{
    
    var sphno1=document.getElementById('shipphone1').value;
    var ls=sphno1.substr(sphno1.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById('shipphone1').value=newval;
    }
    else if(document.getElementById('shipphone1').value.length == 3)
	{
	   document.getElementById('shipphone2').focus();
    }

}


function changeshipphoneno_2()
{

    var sphno1=document.getElementById('shipphone2').value;
    var ls=sphno1.substr(sphno1.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById('shipphone2').value=newval;
    }
    else if(document.getElementById('shipphone2').value.length == 3)
	{
	   document.getElementById('shipphone3').focus();
    }

}



function changeshipphoneno_3()
{

    var sphno1=document.getElementById('shipphone3').value;
    var ls=sphno1.substr(sphno1.length-1,1);
    var chk=ls.charCodeAt(0);
    if(!(chk >= 48 && chk <= 57) || (chk==32))
    {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById('shipphone3').value=newval;
    }
   

}



//function changefetchphoneno_1(acc_id)
//{
//
//    var shipphone1;
//    shipphone1 = document.getElementById(acc_id+"shipPhone1").value;
//    alert(shipphone1);
//
//
////ealert(id);
////    var sphno1=document.getElementById('shipphone1').value;
////    var ls=sphno1.substr(sphno1.length-1,1);
////    var chk=ls.charCodeAt(0);
////    if(!(chk >= 48 && chk <= 57) || (chk==32))
////    {
////        var newval=sphno1.substr(0,sphno1.length-1)
////        document.getElementById('shipphone1').value=newval;
////    }
////    else if(document.getElementById('shipphone1').value.length == 3)
////	{
////	   document.getElementById('shipphone2').focus();
////    }
//
//}



function autotab1(original,id_val,acc_id){

if(id_val == "1")
    {
        //alert("Hai1");
        var sphno1 = document.getElementById(acc_id+"shipPhone1").value;
        var ls=sphno1.substr(sphno1.length-1,1);
         var chk=ls.charCodeAt(0);
      if(!(chk >= 48 && chk <= 57) || (chk==32))
     {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById(acc_id+"shipPhone1").value=newval;
      }
        var destination = document.getElementById(acc_id+"shipPhone2");
    }else if(id_val == "2")
        {
           var sphno1 = document.getElementById(acc_id+"shipPhone2").value;
        var ls=sphno1.substr(sphno1.length-1,1);
         var chk=ls.charCodeAt(0);
      if(!(chk >= 48 && chk <= 57) || (chk==32))
     {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById(acc_id+"shipPhone2").value=newval;
      }
        var destination = document.getElementById(acc_id+"shipPhone3");
}else if(id_val == "3")
    {
 var sphno1 = document.getElementById(acc_id+"shipPhone3").value;
        var ls=sphno1.substr(sphno1.length-1,1);
         var chk=ls.charCodeAt(0);
      if(!(chk >= 48 && chk <= 57) || (chk==32))
     {
        var newval=sphno1.substr(0,sphno1.length-1)
        document.getElementById(acc_id+"shipPhone3").value=newval;
      }

   }
   // alert(destination);
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
destination.focus()
}













function updateGoogleShippingCharge(){


var limit = parseInt('5');

		//get the current text inside the textarea
		var text = $('input#shipzip').val();
		//count the number of characters in the text
		var chars = text.length;
                if(chars >= limit){

                    $("#updateShippingCharge").load('/loadshipmethod',{
		zipCode:$('input#shipzip').val(),
                shipMethod: $('input#hiddenshipmethod').val()
});
}
}


function updateGoogleShippingCharge1(){


	var limit = parseInt('5');

			//get the current text inside the textarea
			var text = $('input#shipzip').val();
			//count the number of characters in the text 
			var chars = text.length;
	                if(chars >= limit){

	                    $("#updateShippingCharge").load('/loadshipmethodpaypal',{
			zipCode:$('input#shipzip').val(),
			paypalloadship:$('input#paypalloadship').val(),
	                shipMethod: $('input#hiddenshipmethod').val()
	});
	}
	}

function updateGoogleShippingChargeload(shipid){


	var limit = parseInt('5');

			//get the current text inside the textarea
			var text = $('input#shipzip').val();
			//count the number of characters in the text 
			var chars = text.length;
	                if(chars >= limit){

	                    $("#updateShippingCharge").load('/loadshipmethodpaypal',{
				zipCode:$('input#shipzip').val(),
			paypalloadship:$('input#paypalloadship').val(),
			
	                shipMethod: shipid
	});
	                    
	                 
	}
	}
function doPrintReceipt(orderNo) {
  $().ready(function() {	  
      newWindow = window.open("printreceipt/"+orderNo, "OrderedInformation", "menubar=1, resizable=1, width=920, height=900, scrollbars=yes");
      //newWindow.document.title = "Receipt";      
      newWindow.moveTo(0,0);
      newWindow.focus();
      
  });
}

 function zooming (adiv,id,i)
 {
         /*alert(adiv);
         alert(id);
         alert(i);*/
         //
         //
	 //var s=document.getElementById(id).src;
	 //alert(id);
	 document.getElementById('samples'+i).src=id;
	 document.getElementById('sample'+i).style.visibility="visible";
 }
 
 function zoomout (adiv,i)
 {
	 document.getElementById('sample'+i).style.visibility="hidden";
 }
 
 function newsletter(){
     
    //alert($('#lastname').val());
  var reason="";
  reason += validatetextfieldsnews($("#firstname").val(),'First Name');
  reason += validatetextfieldsnews($("#lastname").val(),'Last Name');
  reason +=  validatenewsEmail($("#Email").val(),'Email')
  reason += validatePhoneSections1($("#phone1").val(),$("#phone2").val(),$("#phone3").val(),'Phone');
  reason += validatetextfieldscomment($("#Comment").val(),'Comment');
  
	 
  


    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    
    $.post("/newsletter", {
            firstname : $('#firstname').val(),
            lastname: $('#lastname').val(),
            Email:$('#Email').val(),
            phone1:$('#phone1').val(),
           phone2:$('#phone2').val(),
            phone3:$('#phone3').val(),
            Comment:$('#Comment').val()
           

        },
        function(data){
            //alert(data);
            if(document.getElementById("newsletteremail")){
           //alert("hello");
           document.getElementById("newsletteremail").innerHTML=data;
             document.getElementById("firstname").value="";
           document.getElementById("lastname").value="";
           document.getElementById("Email").value="";
           document.getElementById("phone1").value="";
           document.getElementById("phone2").value="";
           document.getElementById("phone3").value="";
           document.getElementById("Comment").value="";
           //$('#newsletteremail')(data);
            }
            //alert(data);
        });
return true;
}



function validatePhoneSections1(fld,fld1,fld2,fldname) {
/*alert(fld);
alert(fld1);
alert(fld2);
alert(fldname);*/
//alert(fldname);
	var error = "";

        fldvalues1 = fld + fld1 + fld2;
         if (fldvalues1 == "") {
        error = "The phone number has not been filled in.\n";
         }else if (isNaN(fldvalues1)) {
        error = "The phone number contains illegal characters.\n";
         }else if (fldvalues1.length < 10) {
         error = "The phone number is the wrong length.\n";
         }
return error;
}














function validatetextfieldsnews(fld,fldname) {
//alert(fld);
	var error = "";
	    var illegalChars = /[\W_]/; // allow only letters and numbers
	    //var error=fld.name;
    if (fld == "") {
        //fld.style.background = 'Yellow';
        error =" : You didn't enter any text.\n";
    } else if (illegalChars.test(fld)) {
    	var error = "";
    	error = " :The textfield contains illegal characters.\n";
        //fld.style.background = 'Yellow';
    } 
    if (error == ""){
    return error;
    } else {
       // alert(fldname);
	names=fldname;
		 
    	error= names + error;
        //alert(error);
	}
    return error;
}



function validatetextfieldscomment(fld,fldname) {
//alert(fld);
	var error = "";
	    //var illegalChars = /[\W_]/; // allow only letters and numbers
	    //var error=fld.name;
    if (fld == "") {
        //fld.style.background = 'Yellow';
        error =" : You didn't enter any text.\n";
    }
//    else if (illegalChars.test(fld)) {
//    	var error = "";
//    	error = " :The textfield contains illegal characters.\n";
//        //fld.style.background = 'Yellow';
//    }
    if (error == ""){
    return error;
    } else {
       // alert(fldname);
	names=fldname;

    	error= names + error;
        //alert(error);
	}
    return error;
}











function validatenewsEmail(fld,fldname) {
    var error="";
    var tfld = trimchk(fld);                        // value of field with
														// whitespace trimmed
														// off
    // var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
   // var emailFilter = new RegExp('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$');
	var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    // var emailFilter =
	// /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
    // var emailFilter = new
	// RegExp('[a-z0-9._%+-]+@(?:[a-z0-9-]+\.)+[a-z]{2,4}');
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (tfld == "") {
        //fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              // test email for
														// illegal characters
        //fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.match(illegalChars)) {
        //fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } 
    return error;
}

function auto(marketname,marketid)
{
	document.getElementById("schoolname").value=marketname;
	document.getElementById("marketid").value=marketid;
	document.getElementById("autosuggest").style.display="none";
}

function Autosuggestsearch()
{
	//alert($('#schoolname').val());
	
	 $.post("/autosuggestsearch", {
            searchval : $('#schoolname').val()
            
        },
        function(data){
            //alert(data);
           //document.getElementById("jj").value=data;
		   if(data == 1)
		   {
		    document.getElementById("fail").innerHTML="Please contact info@swathijewelleries.com to add school.";  
		   }
		    else if(data == 2)
		   {
			   document.getElementById("fail").innerHTML="";
		    }
		   else
		   {
			//alert('suc');
           document.getElementById("autosuggest").innerHTML=data;
		   document.getElementById("autosuggest").style.display="block";
		   document.getElementById("fail").innerHTML="";
		   }
		   
		   setInterval('updatedivnone()',40000);
           //$('#newsletteremail')(data);
           
            //alert(data);
        });
}

function updatedivnone()
{
	document.getElementById("autosuggest").style.display="none";
}
function chgst()
{
document.getElementById('selExpMonth').focus();
}

function chgst2()
{
document.getElementById('selExpYear').focus();
}
function chgst3()
{
document.getElementById('txtCardVerificationValue').focus();
}


function searchAction(){
   // alert("sdsd");
        var q= $('#search').val();
        if(q == '' || q == 'search Swathijewelleries'){
            alert('Please enter valid data');
            return false;
        }
        return true;
    }



//   function forgotPasswordchk(type){
//
//    var reason = "";
//    if(type=='login'){
//    reason += validateEmail(document.frmLogin.loginemail);
//    if (reason != "") {
//        alert("Some fields need correction:\n" + reason);
//        return false;
//    }else{
//        document.frmLogin.actionParam.value="lostpass";
//        document.frmLogin.submit();
//    }
//    }else{
//        alert("sdsdsds");
//    	 reason += validateEmail(document.logintocheckout.email);
//    	    if (reason != "") {
//    	        alert("Some fields need correction:\n" + reason);
//    	        return false;
//    	    }else{
//    	        document.logintocheckout.actionParam.value="lostpass";
//                $('#logintocheckout').submit();
//
//    	        //document.logintocheckout.submit();
//    	    }
//    }
//}

function forgotPasswordchk(type){
    
    var reason = "";
    if(type=='login'){
    reason += validateEmail(document.frmLogin.loginemail);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }else{
        document.frmLogin.actionParam.value="lostpass";
        document.frmLogin.submit();
    }
    }else{
        alert("hello"+type);
    	 reason += validateEmail(document.logintocheckout.email);
    	    if (reason != "") {
    	        alert("Some fields need correction:\n" + reason);
    	        return false;
    	    }else{
    	        document.logintocheckout.actionParam.value="lostpass";
                $('#logintocheckout').submit();

    	        //document.logintocheckout.submit();
    	    }
    }
}



/*function validatePhoneSections1(fld,fldname) {
//alert(fld);
//alert(fldname);
	var error = "";

        if (fld == "") {
        error = "The phone number has not been filled in.\n";
         }else if (isNaN(fld)) {
        error = "The phone number contains illegal characters.\n";
         }else if (fld.length < 10) {
         error = "The phone number is the wrong length.\n";
         }
return error;
}*/









