/****************************************************************
*  $RCSfile: Common.js,v $																	 	
*  $Revision: 1.1 $							
*  $Author: sackumar $							
*  $Date: 2007/09/25 13:05:54 $							
*								
*  Copyright (c) 2003 Quark Media house India Pvt Limited.	
*  All Rights Reserved						
*****************************************************************/

//Global variable to hold the value for PO BOX address Checkbox control field.
var IsPOBoxCheckedByUser = false;

//Global Variable to hold the control name that triggered the submit event.
var ControlToSubmit = "";

//This function handles the submit action and checks whether the page is submitted for Search or not.
//If the page is submitted for Serach, then it supresses the submit event, otherwise raises it.
function HandleSubmit(functionName)
{	
	if(ControlToSubmit == "txtSearchKeyword" || ControlToSubmit == "txtEmailSignUp")
	{
	    if(ControlToSubmit == "txtEmailSignUp")
	    {
	        if (functionName != null && functionName != "")
		    {	
		        //ControlToSubmit = "";
			    return eval(functionName);
		    }
		    else
		    {	
		        //ControlToSubmit = "";
			    return true;
		    }
	    }
		//Reset the variable
		ControlToSubmit = "";
		return false;
	}
	else
	{
		if(ControlToSubmit == "Login")
		{
			ControlToSubmit = "";
			
			if(document.forms[0].txtEMail.value == "")	
			{
				document.forms[0].txtEMail.focus();
			}
			else if(document.forms[0].txtPassword.value == "")
			{
				document.forms[0].txtPassword.focus();
			}

			//return eval(ValidateLogIn());
			return false;
		}
		else if (ControlToSubmit == "LoginWidget") {
			ControlToSubmit = "";

			//var ctrlPrefix = GetLoginWidgetControlsPrefix(e);

			//if (document.forms[0].elements[ctrlPrefix + "txtEMail"].value == "")	
			//{
			//	document.forms[0].elements[ctrlPrefix + "txtEMail"].focus();
			//}
			//else if (document.forms[0].elements[ctrlPrefix + "txtPassword"].value == "")
			//{
			//	document.forms[0].elements[ctrlPrefix + "txtPassword"].focus();
			//}

			return true;
		}
		else
		{
			if (functionName != null && functionName != "")
			{	
				return eval(functionName);
			}
			else
			{	
				return true;
			}
		}
	}
}

// Set to Sigle selection of radio buttion from a repeter control
function SetUniqueRadioButton(nameregex, current)
{

   re = new RegExp(nameregex);
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      if (elm.type == 'radio')
      {
         if (re.test(elm.name))
         {
            elm.checked = false;
         }
      }
   }
   current.checked = true;

}



/* SCRIPT FOR QUICK SEARCH START */
			
//This function checks whether the page is submitted for Search or not.
function fireOnSubmit(funcName)
{
    
	if(document.getElementById("submitDueTo").value=="txtSearch")
	{
		document.getElementById("submitDueTo").value='';return false;
	}
	else
	{
		if(funcName=="")
		{
			return true;
		}
		else
		{
			return(eval(funcName)());
		}
	}
}

function trimAll(sString) 
{
    while (sString.substring(0,1) == ' ')
    {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
   }

//LginWidget Script Start
   // To Validate Email and Password Fields
   function ValidateLoginWidgetFields(e, thisForm) {
   	ControlToSubmit = "LoginWidget";
   	var objForm = document.forms[0];

   	var inputKey;
   	if (window.event) {
   		inputKey = e.keyCode;
   	}
   	else if (e.which) {
   		inputKey = e.which;
   	}

   	if (inputKey == 13) {

   		var ctrlPrefix = GetLoginWidgetControlsPrefix(e);

   		var SelectedButton = ctrlPrefix.replace("$", "_") + "loginButtonLink";

   		if (document.getElementById(SelectedButton) != null) {
   			document.getElementById(SelectedButton).focus();
   		}

   		if (ValidateLoginWidget(e, '', thisForm)) {
   			return false;
   		}
   		else {
   			if (document.forms[0].elements[ctrlPrefix + "txtEMail"].value == "") {
   				document.forms[0].elements[ctrlPrefix + "txtEMail"].focus();
   			}
   			else if (document.forms[0].elements[ctrlPrefix + "txtPassword"].value == "") {
   				document.forms[0].elements[ctrlPrefix + "txtPassword"].focus();
   			}
   		}
   	}

   	return false;
   }

   // To Validate Email and Password Fields
   function ValidateLoginWidget(e, ClientID, thisForm) {

   	ControlToSubmit = "LoginWidget";

   	var field;

   	var ctrlPrefix = GetLoginWidgetControlsPrefix(e);

   	var objForm = document.forms[0];

   	if (objForm.elements[ctrlPrefix + "txtEMail"].value == "") {
   		alert("Email address should not be empty.");

   		field = objForm.elements[ctrlPrefix + "txtEMail"];
   		//Set the focus
   		field.focus();

   		objForm.elements[ctrlPrefix + "ctrlSetFocus"].value = "email";

   		//objForm.elements[ctrlPrefix + "txtEMail"].focus();
   		ControlToSubmit = "loginWidgetSubmit";
   		return false;
   	}
   	else {
   		if (CheckEmailFormat(objForm.elements[ctrlPrefix + "txtEMail"].value)) {
   			if (objForm.elements[ctrlPrefix + "txtPassword"].value == "") {
   				alert("Password should not be empty.");

   				field = objForm.elements[ctrlPrefix + "txtPassword"];
   				//Set the focus
   				field.focus();

   				objForm.elements[ctrlPrefix + "ctrlSetFocus"].value = "pwd";

   				//objForm.elements[ctrlPrefix + "txtPassword"].focus();
   				ControlToSubmit = "loginWidgetSubmit";
   				return false;
   			}
   			else if (objForm.elements[ctrlPrefix + "txtPassword"].value.length < 4) {
   				alert("You have entered an invalid password. Please re-enter your password.");
   				objForm.elements[ctrlPrefix + "txtPassword"].value = "";

   				field = objForm.elements[ctrlPrefix + "txtPassword"];
   				//Set the focus
   				field.focus();

   				objForm.elements[ctrlPrefix + "ctrlSetFocus"].value = "pwd";

   				//objForm.elements[ctrlPrefix + "txtPassword"].focus();
   				ControlToSubmit = "loginWidgetSubmit";
   				return false;
   			}

   			var btnClick = ctrlPrefix + "loginButtonLink";

   			var formElements = "";
   			for (var n = 0; n < thisForm.elements.length; n++) {
   				formElements = thisForm.elements[n].id;

   				if (formElements.indexOf("hdnusr") != -1) {
   					if (objForm.elements[formElements].value == "")
   						objForm.elements[formElements].value = objForm.elements[ctrlPrefix + "txtEMail"].value;
   				}

   				if (formElements.indexOf("hdnpwd") != -1) {
   					if (objForm.elements[formElements].value == "")
   						objForm.elements[formElements].value = objForm.elements[ctrlPrefix + "txtPassword"].value;
   				}
   			}

   			objForm.elements[ctrlPrefix + "ctrlSelected"].value = "true";

   			var SelectedButton = ctrlPrefix.replace("$", "_") + "loginButtonLink";

   			if (document.getElementById(SelectedButton) != null) {
   				document.getElementById(SelectedButton).focus();
   			}

   			//Function to check for Special Characters
   			if (loginWidgetchkSpecialCharacters()) {
   				if (ClientID != '')
   					__doPostBack(ClientID, '');
   				else
   					__doPostBack(btnClick, '');

   				ControlToSubmit = "loginWidgetSubmit";
   				return false;
   			}
   			else {
   				return false;
   			}
   		}
   		else {
   			alert("You have entered an invalid email address. Please re-enter your email address.");
   			objForm.elements[ctrlPrefix + "txtPassword"].value = "";

   			field = objForm.elements[ctrlPrefix + "txtEMail"];
   			//Set the focus
   			field.focus();
   			field.select();

   			objForm.elements[ctrlPrefix + "ctrlSetFocus"].value = "email";

   			//objForm.elements[ctrlPrefix + "txtEMail"].focus();
   			//objForm.elements[ctrlPrefix + "txtEMail"].select();
   			ControlToSubmit = "loginWidgetSubmit";
   			return false;
   		}
   	}
   }

   //	//This function clear the login fields username and password.
   //	//If input wrong username and password with special character.
   //	//Then "A potentially dangerous" error comes.
   //	function ClearLoginFields() {
   //		var objForm = document.forms[0];

   //		objForm.elements[ctrlPrefix + "txtEMail"].value = "";
   //		objForm.elements[ctrlPrefix + "txtPassword"].value = "";

   //		return true;
   //	}

   function GetLoginWidgetControlsPrefix(event) {
   	var theEvent = event || arguments.callee.caller.arguments[0];
   	var theTarget = theEvent.srcElement || theEvent.target;
   	if (theTarget.nodeType == 3) // defeat Safari bug
   		theTarget = theTarget.parentNode;

   	var arCtrlIDParts;
   	if (theTarget.name == '') {

   		if (theTarget.pathname != null && theTarget.pathname != '') {
   			arCtrlIDParts = theTarget.pathname.split('$');
   		}
   		else {

   			if (theTarget.parentNode.pathname != null && theTarget.parentNode.pathname != '') {
   				arCtrlIDParts = theTarget.parentNode.pathname.split('$');
   			}
   			else {
   				if (theTarget.href != null && theTarget.href.indexOf("javascript:") > -1) {
   					arCtrlIDParts = theTarget.href.split('$');
   				}
   				else if (theTarget.parentNode != null && theTarget.parentNode.href != '') {
   					arCtrlIDParts = theTarget.parentNode.href.split('$');
   				}
   				if (arCtrlIDParts[0] != '') {
   					arCtrlIDParts[0] = arCtrlIDParts[0].replace("javascript:", "");
   				}
   			}
   		}

   		if (arCtrlIDParts[0] != '') {
   			arCtrlIDParts[0] = arCtrlIDParts[0].replace("__doPostBack('", "");
   		}
   	}
   	else {
   		if (theTarget.name != '') {
   			arCtrlIDParts = theTarget.name.split('$');
   		}
   		else {
   			arCtrlIDParts = theTarget.href.split('$');

   			if (arCtrlIDParts[0] != '') {
   				arCtrlIDParts[0] = arCtrlIDParts[0].replace("javascript:__doPostBack('", "");
   			}
   		}
   	}

   	return arCtrlIDParts[0] + '$';
   }

//LginWidget Script End

//This function checks whether the user entered the keyword or not
//If entered, then redirect to the Search results page.
function SearchItem(txtSearchCategory, isVirtualDirectoryEnabled)
{

	if (ControlToSubmit == "loginWidgetSubmit") {

		if (loginWidgetSetFocus())
			ControlToSubmit = "";

		return false;
	}

	if (ControlToSubmit == "ShoppingCart") {

		ControlToSubmit = "";

		return false;
	}
	   
    /*var theform;
	if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1) {
		theform = document.forms["_ctl0"];
	}
	else {
		theform = document._ctl0;
	}*/
	
	//Set the controlname
	ControlToSubmit = "txtSearchKeyword";
		
	var strItemVal = document.forms[0].elements[txtSearchCategory].value;
	
	if(trimAll(strItemVal) == "" || strItemVal == null)
	{
		alert("You have not selected any search criteria. Please try again.");
		document.forms[0].elements[txtSearchCategory].focus();
		return false;
	}
	else if(!CheckKeywordSearch(strItemVal))
	{
		alert("Please enter valid search criteria.");
		document.forms[0].elements[txtSearchCategory].focus();
		return false;
	}
		
	var virdir = "";
	if(document.forms[0].elements[isVirtualDirectoryEnabled] != null)
	    virdir = document.forms[0].elements[isVirtualDirectoryEnabled].value;
	
	if(virdir.length > 1)
	{
	   
        var Page = location.href;
        var SlashAfterVirtualDirectory =Page.indexOf("/",Page.indexOf("/",Page.indexOf("/")+2)+1);
	    


	    //var lastQuestionMark = Page.length(".aspx");
	    var replaceTo = Page.substring(SlashAfterVirtualDirectory+1,location.href.length);
	
	    var ReplacedUrl;
	    
	    if( replaceTo.length > 0)	
	    	ReplacedUrl = Page.replace(replaceTo,"ProductSearch/QBasicSearchResults.aspx");// + "&DialogName=" + replaceTo;
	    else
		ReplacedUrl = Page + "ProductSearch/QBasicSearchResults.aspx"; // + "&DialogName=" + replaceTo;  
	
	    var strNavigateURL = ReplacedUrl; //'/ProductSearch/QBasicSearchResults.aspx?SearchType=_QUICK_SEARCH&BasicSearch=true';
	    strItemVal = escape(strItemVal);

	    strItemVal = ReplaceAllChars(strItemVal,'+','%2B');
	    strNavigateURL += '?SearchType=_QUICK_SEARCH&BasicSearch=true' + '&Keyword=' + strItemVal;
        //Redirect to the QQuickSearchResult page

	location.href = strNavigateURL;
	}
	else
	{
	    var Page = "http://" + location.host;
        //var SlashAfterVirtualDirectory =Page.indexOf("/",Page.indexOf("/",Page.indexOf("/")+2)+1);
	    //var lastQuestionMark = Page.length(".aspx");
	   //var replaceTo = Page.substring(SlashAfterVirtualDirectory+1,location.href.length);
	    var ReplacedUrl = Page+"/ProductSearch/QBasicSearchResults.aspx";//Page.replace(replaceTo,"ProductSearch/QBasicSearchResults.aspx");// + "&DialogName=" + replaceTo;
	    var strNavigateURL = ReplacedUrl; //'/ProductSearch/QBasicSearchResults.aspx?SearchType=_QUICK_SEARCH&BasicSearch=true';
	    strItemVal = escape(strItemVal);
	    strItemVal = ReplaceAllChars(strItemVal,'+','%2B');
	    strNavigateURL += '?SearchType=_QUICK_SEARCH&BasicSearch=true' + '&Keyword=' + strItemVal;
        //Redirect to the QQuickSearchResult page

	    location.href = strNavigateURL;

	    try {
	    	var theEvent = this.event || arguments.callee.caller.arguments[0];
	    	if (theEvent != null) {
	    		if (theEvent.type == "click") {
	    			var theTarget = theEvent.srcElement || theEvent.target;
	    			if (theTarget.nodeType == 3) // defeat Safari bug
	    				theTarget = theTarget.parentNode;

	    			if (theTarget != null) {
	    				if (theTarget.type != null && theTarget.type == "image") {
	    					return false;
	    				}
	    			}
	    		}
	    	}
	    }
	    catch (exception) {
	    	//Do nothing
	    }
	}
	return true;
}

function ReplaceAllChars(string,srcChar,destChar)
{
	while(string.indexOf(srcChar) > -1) 
	{
		string = string.replace(srcChar,destChar);
	}
	return string;
}

	//This function checks whether the user entered special character or not
function CheckSpecialChars(e, txtSearchCategory, isVirtualDirectoryEnabled)
{
	var inputKey;
	if(window.event) 
	{
		inputKey = e.keyCode;
	}
	else if(e.which)
	{
		inputKey = e.which;
	}
	
	if(!window.event)
	{
		ReplaceSpecialChars(txtSearchCategory);
	}

	if ( (inputKey == 60) || (inputKey == 62) )//|| (inputKey == 0) || (inputKey == 118) )
	{
		return false;
	}
	else if(inputKey == 13)					
	{
	    SearchItem(txtSearchCategory, isVirtualDirectoryEnabled);
	    return false;
	}
	return true;
}

function ReplaceSpecialChars(txtSearchCategory)
{
	var specialChar = /\<|>|/g;
	var searchData  = document.forms[0].elements[txtSearchCategory].value;
	document.forms[0].elements[txtSearchCategory].value = searchData.replace(specialChar,"");
}

function OnPasteRemoveSpecialChars(strSearchcategory)
{
	var specialChar = /\<|>|#@~!/g;
	//strSearchcategory =  document.forms[0].elements["txtSearchCategory"].value + window.clipboardData.getData("Text");
	//alert("clipBoardText - " + clipBoardText);
	clipBoardText = window.clipboardData.getData("Text").replace(specialChar,"");
	document.forms[0].elements["txtSearchCategory"].value = strSearchcategory.value + clipBoardText;
	return false;
}

/*Basic Serach Javascript End*/

			
function CheckSpecialCharsEmailSignUp(e)
{
    ControlToSubmit = "txtEmailSignUp";
    
	var inputKey;
	if(window.event) 
	{
		inputKey = e.keyCode;
	}
	else if(e.which)
	{
		inputKey = e.which;
	}
	
	if(!window.event)
	{
		ReplaceSpecialCharsEmailSignUp();
	}

	if ( (inputKey == 60) || (inputKey == 62) )//|| (inputKey == 0) || (inputKey == 118) )
	{
		return false;
	}
	else if(inputKey == 13)					
	{
		if(EmailSignUpSubmit(e))
		{
			var ctrlPrefix = GetEmailSignupControlsPrefix(e);
		
		    if(document.forms[0].elements[ctrlPrefix + "hdnActiveButton"] != null)
		    {
		        var btnActive = ctrlPrefix + document.forms[0].elements[ctrlPrefix + "hdnActiveButton"].value;
		        if (document.forms[0].elements[btnActive] != null && document.forms[0].elements[btnActive] != undefined) {
		            document.forms[0].elements[btnActive].focus();
		        }
		        __doPostBack(btnActive,'');
		    }

		    return true;
		}
		else
		{
		    return false;
		}
		//__doPostBack('"+document.forms[0].elements["EmailSignUp_hdnActiveButton"].value+"','');
	}
	return true;
}

function ReplaceSpecialCharsEmailSignUp()
{
    //var specialChar = /\<|>|/g;
    //var searchData  = document.forms[0].elements["EmailSignUp_txtEmailSignUp"].value;
    //document.forms[0].elements["EmailSignUp_txtEmailSignUp"].value = searchData.replace(specialChar,"");
}

function GetEmailSignupControlsPrefix(event)
{
	var theEvent = event || arguments.callee.caller.arguments[0];
	var theTarget = theEvent.srcElement || theEvent.target;
	if (theTarget.nodeType == 3) // defeat Safari bug
		theTarget = theTarget.parentNode;

	var arCtrlIDParts = theTarget.name.split('$');

	return arCtrlIDParts[0] + '$';
}
					
function EmailSignUpSubmit(event)
{
    //Set the controlname
	ControlToSubmit = "txtEmailSignUp";
	
	var ctrlPrefix = GetEmailSignupControlsPrefix(event);
	
	//Hidden varaibles
	if(document.forms[0].elements[ctrlPrefix + "IshdnEmailSignUp"] != null)
	{
	    var IshdnEmailSignUp = document.forms[0].elements[ctrlPrefix + "IshdnEmailSignUp"].value = false;
	}

	//Hidden TextEmailSignUp
	if(document.forms[0].elements[ctrlPrefix + "txtEmailSignUp"] != null)
	{
	    var strEmailVal = document.forms[0].elements[ctrlPrefix + "txtEmailSignUp"].value;
	}

	//Hidden Error Msgg
	if(document.forms[0].elements[ctrlPrefix + "hdnEmailErrorMsg"] != null )
	{
	    var strEmailErrorMsg = document.forms[0].elements[ctrlPrefix + "hdnEmailErrorMsg"].value;
	}

	if(strEmailVal == "" || strEmailVal == null)
	{
		alert("Please enter Valid Email Address.");
		SetEmailSignUpFocusOnError(ctrlPrefix);
		return false;
	}

	if(!CheckEmailFormat(strEmailVal))
	{
	    if(strEmailErrorMsg == "")
	        alert("Please enter Valid Email Address.");
	    else
	        alert(strEmailErrorMsg);
	    SetEmailSignUpFocusOnError(ctrlPrefix);
	    return false;
	}
	else
	{
	    if(document.forms[0].elements[ctrlPrefix + "IshdnEmailSignUp"] != null)
	    {
	        document.forms[0].elements[ctrlPrefix + "IshdnEmailSignUp"].value = true;
        }
	}

    if(document.forms[0].elements[ctrlPrefix + "hdnActiveButton"] != null)
    {
        var btnActive = ctrlPrefix + document.forms[0].elements[ctrlPrefix + "hdnActiveButton"].value;
        __doPostBack(btnActive,'');
    }

    //alert("btnActive"+btnActive);
 
	return true;	
}

//This function is used to set the focus
function SetEmailSignUpFocusOnError(ctrlPrefix)
{
    if(document.forms[0].elements[ctrlPrefix + "txtEmailSignUp"] != null)
	{
	    document.forms[0].elements[ctrlPrefix + "txtEmailSignUp"].focus();
	}
}

//This function is used for validating the email address. 
function CheckEmailFormat(strEmail) 
{

	//Check if the string starts with an integer				
	var firstChar = strEmail.charAt(0);
	var firstCharDigit = parseInt(firstChar);
	//if(!isNaN(firstCharDigit))
	//	return false;

	/*
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(strEmail))
	{
		return true;
	}
	else
	 return false;
	*/
	 //Space is not allowed.
	if (strEmail.indexOf(" ") != -1) 
		return false;
					
	first = 0; last = 0; firstDot=0; lastDot=0;
	// check the @ in an email address. It has to be exactly one @, not on first and not on last position.
	first	  = strEmail.indexOf("@");
	last	  = strEmail.lastIndexOf("@");
	firstDot  = strEmail.indexOf(".");
	lastDot   = strEmail.lastIndexOf(".");
					
	//Check for the string starts with .@ @. and continues dots.
	if (startsWith(strEmail,"..") || startsWith(strEmail,"@.") || startsWith(strEmail,".@") || startsWith(strEmail,"'"))
		return false;

	//Check if the string starts with an integer				
	//var firstChar = strEmail.charAt(0);
	//var firstCharDigit = parseInt(firstChar);
	//if(!isNaN(firstCharDigit))
	//	return false;
						
	if ((first > 0) && (first == last)  && (firstDot > 0) && (lastDot > last+1) && (strEmail.length > (lastDot+2)))
		return true;
	else
		return false;
	
	return true;
}

//This method check & hold the 
function OnPOBoxClickByUser()
{
	if( document.forms[0].elements["POBoxAddress"].checked == true )
		IsPOBoxCheckedByUser = true;
	else
		IsPOBoxCheckedByUser = false;
}		

/// This method remoces special characters and Return true if the address is a PO box address else returns false.
function CheckPOBoxAddress()
{	
	if( IsPOBoxCheckedByUser )
		 return ;
		 
	var sPecialChars = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\ |\./g;
	var IsPOBoxAddress = document.forms[0].elements["Address1"].value.replace(sPecialChars,"");
	
	if ( IsPOBoxAddress.toUpperCase().indexOf("POBOX") != -1 )
		document.forms[0].elements["POBoxAddress"].checked = true; 
	else
		document.forms[0].elements["POBoxAddress"].checked = false; 
}

//Check PO Address for Shipment
/// This method remoces special characters and Return true if the address is a PO box address else returns false.
function ShpCheckPOBoxAddress()
{
	if (IsPOBoxCheckedByUser)
		return;

	var sPecialChars = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\ |\./g;
	var IsPOBoxAddress = document.forms[0].elements["shpAddress1"].value.replace(sPecialChars, "");

	if (IsPOBoxAddress.toUpperCase().indexOf("POBOX") != -1)
		document.forms[0].elements["shpPOBoxAddress"].checked = true;
	else
		document.forms[0].elements["shpPOBoxAddress"].checked = false;
}

//Generic method to disable all buttons on form before submit
function DisableButtons()
{
	//Get all the button fields
	var elements = document.forms[0].getElementsByTagName("INPUT");
	for(i=0; i<elements.length; i++)
	{
		var field		= elements[i];
		var fieldType	= field.type;
		
		if (fieldType != null && ( fieldType == "button" || fieldType == "submit" || fieldType == "image"))
		{
			field.disabled = true;
		}
	}
	/*
    for (index=0; index<document.links.length; index++) 
    {
		var link = document.links[index];
		link.disabled = true;
	}
    for (index=0; index<document.anchors.length; index++) 
    {
		var link = document.anchors[index];
		link.disabled = true;
    }
    */
}

function DisableButtonsEx()
{
	//Get all the button fields
	var elements = document.forms[0].getElementsByTagName("INPUT");
	for(i=0; i<elements.length; i++)
	{
		var field		= elements[i];
		var fieldType	= field.type;
		
		if (fieldType != null)
		{
			if(fieldType == "button")
			{
				field.disabled = true;
			}
			else if(fieldType == "submit" || fieldType == "image")
			{
				if(elements[field.name + '_Dummy'])
				{
					field.style.display="none";
					elements[field.name + '_Dummy'].style.display="inline";
				}
			}
		}
	}

	/*
    for (index=0; index<document.links.length; index++) 
    {
		var link = document.links[index];
		link.disabled = true;
	}
    for (index=0; index<document.anchors.length; index++) 
    {
		var link = document.anchors[index];
		link.disabled = true;
    }
	*/
}

//Starts with function for string manupulation.
function startsWith(value, search)
{
	for(start=0;start<value.length+1-search.length;start++)
		if (value.substr(start,search.length) == search) return true;
	return false;
}

// This function Disable the right click
function DisableRightClick(e) //Function that will execute on right click
{	
	if (window.Event) 
	{
		if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
			return false;
	}		
	else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3))
	{
		alert("Right click is disable.");
		event.cancelBubble = true, event.returnValue = false;
		return false;
	}
	return true;
}

//This function trims the leading and trailing blanks
function trim(value)
{
	while(value.charAt(value.length-1) == " ")
	{
		value = value.substring(0,value.length-1);
	} 
	while(value.substring(0,1) ==" ")
	{
		value = value.substring(1,value.length);
	}
	return value;
}

//Generic Function to check for Special Characters.
function checkSpecialCharacters() {

	if (ControlToSubmit == "loginWidgetSubmit") {
		ControlToSubmit = "";
		return false;
	}
	
	var SPECIAL_CHARACTER_MSG = "The characters '<' or '>' are not allowed. Please re-enter the value.";
	
	//Get all the text fields
	var count = document.forms[0].elements.length;
	
	for(i=0; i<count; i++)
	{
		var field		= document.forms[0].elements[i];
		var fieldType	= field.type;
		
		if (fieldType != null && (fieldType == "text" || fieldType == "textarea" || fieldType == "password"))
		{
			if( field.name == "txtSearchCategory" && field.value != "" )
				field.value = "";
			
			if( field.name == "TextSearchWord" && field.value != "" )
			{
		        if(!CheckKeywordSearch(field.value))
			        {
			            alert("Please enter valid search criteria.");
			            return false;
			        }
			}
//			if( field.name == "EmailSignUp_txtEmailSignUp" && field.value != "" )
//				field.value = "";
					
			//Check for special characters
			if ((field.value.indexOf("<") > -1 || field.value.indexOf(">") > -1))
			{
				//Show the message
				alert(SPECIAL_CHARACTER_MSG);
				
				//Set the focus
				field.focus();
				field.select();
				
				return false;
			}
		}
	}
	return true;
}


//Login Widget Set Focus.
function loginWidgetSetFocus() {

	return true;
	//Get all the hidden fields
	var count = document.forms[0].elements.length;
	for (i = 0; i < count; i++) {
		var field = document.forms[0].elements[i];
		var fieldType = field.type;

		if (fieldType != null && (fieldType == "hidden")) {
			if (field.id.indexOf("ctrlSetFocus") != -1) {
				if (field.value == "email" || field.value == "pwd") {
					var selectField = field.id;

					if (field.value == "email")
						selectField = selectField.replace("ctrlSetFocus", "txtEMail");
					else
						selectField = selectField.replace("ctrlSetFocus", "txtPassword");

					if (document.getElementById(selectField) != null) {
						document.getElementById(selectField).focus();
						//document.getElementById(selectField).select();

						return false;
					}
				}
			}
		}
	}
	return true;
}


//Generic Function to check for Special Characters.
function loginWidgetchkSpecialCharacters() {

	var SPECIAL_CHARACTER_MSG = "The characters '<' or '>' are not allowed. Please re-enter the value.";

	//Get all the text fields
	var count = document.forms[0].elements.length;

	for (i = 0; i < count; i++) {
		var field = document.forms[0].elements[i];
		var fieldType = field.type;

		if (fieldType != null && (fieldType == "text" || fieldType == "textarea" || fieldType == "password")) {
			if (field.name == "txtSearchCategory" && field.value != "")
				field.value = "";

			if (field.name == "TextSearchWord" && field.value != "") {
				if (!CheckKeywordSearch(field.value)) {
					alert("Please enter valid search criteria.");
					return false;
				}
			}
			//			if( field.name == "EmailSignUp_txtEmailSignUp" && field.value != "" )
			//				field.value = "";

			//Check for special characters
			if ((field.value.indexOf("<") > -1 || field.value.indexOf(">") > -1)) {
				//Show the message
				alert(SPECIAL_CHARACTER_MSG);

				//Set the focus
				field.focus();
				field.select();

				return false;
			}
		}
	}
	return true;
}


//Generic Function to check the mandatory Fields.
function checkMandatoryFields(formName, fieldNames)
{
	var MANDATORY_FIELD_MSG = "Please complete the required fields.";
	//get form
	var objForm = formName;//document.forms[formName];
	//get the mandatory fields
	var mandatoryFields = fieldNames.split(",");
	
	var i=0;
	
	//To check the mandatory field has any value or not
	var isValueEntered = true;
	
	
	//iterate all the mandatory fields and check whether value is entered or not. If not show alert message
	//and set the focus to the field
	while(i<mandatoryFields.length && isValueEntered)
	{
		if(objForm.elements[mandatoryFields[i]] != null && objForm.elements[mandatoryFields[i]] != "undefined" && (trim(objForm.elements[mandatoryFields[i]].value) == "" || trim(objForm.elements[mandatoryFields[i]].value) == "{00000000-0000-0000-0000-000000000000}"))
		{
			isValueEntered = false;
			break;
		}
		i++;
	}
	
	if(!isValueEntered)
	{
		alert(MANDATORY_FIELD_MSG);
		if(!objForm.elements[mandatoryFields[i]].disabled)
		{
			objForm.elements[mandatoryFields[i]].focus();
			try
			{
				//Check the type, if textbox then select
				var objType = objForm.elements[mandatoryFields[i]].type;
				if (objType != null && objType == "text")
				{
					objForm.elements[mandatoryFields[i]].select();
				}
			}
			catch(exception)
			{
				//Do nothing
			}
		}
	}
	
	return isValueEntered;
}

//Method to mask the textbox for integer values
function maskInteger(e)
{	

	var inputKey;
	if(window.event) 
	{
		inputKey = e.keyCode;
	}
	else if(e.which)
	{
		inputKey = e.which;
	}
	
	if (inputKey != 13)
	{
		if ((inputKey < 48 || inputKey > 57) && (inputKey != 8) && (inputKey != 9))
		{
			return false;
		}
	}
	return true;
}

//Method to mask the textbox for decimal values
function maskDecimal(e)
{
	var inputKey;
	var inputValue;
	if(window.event) 
	{
		inputKey	= e.keyCode;
		inputValue	= e.srcElement.value;
	}
	else if(e.which)
	{
		inputKey	= e.which;
		inputValue	= e.target.value;
	}
	
	if (inputKey != 13)
	{
		if ((inputKey < 48 || inputKey > 57) && (inputKey != 8) && (inputKey != 9) && (inputKey != 46))
		{
			return false;
		}
		
		if (inputValue != null && inputValue.indexOf(".") != -1)
		{
			if (inputKey == 46)
			{
				return false;
			}
		}
	}
	return true;
}

//Method to format the Textbox value as 0.00 (to be used for onblur event)
function FormatPrecision(textbox,totallength,precisionlength)
{
	var val	= textbox.value;
	if(val == "")
	{
		return;
	}
	
	var index = val.indexOf(".");
	if(index != -1)
	{
		var valueBeforeDot = val.substr(0,index);
		var valueAfterDot  = val.substr(index+1,val.length);

		if(valueBeforeDot == "")
		{
			valueBeforeDot = "0";
		} 
		
		if(valueAfterDot != "")
		{ 
			if(valueAfterDot.length > precisionlength)
			{
				textbox.value = valueBeforeDot + "." + valueAfterDot.substr(0, precisionlength);
			}
			else
			{
				var zero = "0000";
				textbox.value = valueBeforeDot + "." + valueAfterDot + zero.substr(0, precisionlength - valueAfterDot.length);
			}
		}
		else
		{
			textbox.value = valueBeforeDot + ".00";
		}
	}
	else
	{	
		if(val == "")
		{
			val = "0";			
		}
		textbox.value = val + ".00";
	}
}

//Generic Function to Check whether the field value is Numeric
function isNumeric(fieldValue)
{
	var strValue = String(fieldValue);
	var len	= strValue.length;
	if(len>0)
	{
		for(var i=0; i < len; i++)
		{
			var charCode = strValue.charCodeAt(i); 
			if((charCode < 48 || charCode > 57))
			{
				return false;
			}
		}
		return true;
	}	
	return false;
}

function trimSpaceAndReturn(value)
{

	retval	=	new String(value);
	
	//Removing the extra spaces and "\r\n" in the end
	while(retval.charAt(retval.length-1) == " " || (retval.lastIndexOf("\n")!= -1 && retval.lastIndexOf("\n") == (retval.length - 2))) 
	{
		retval = retval.charAt(retval.length-1) == " " ? retval.substring(0,retval.length-1) : retval.substring(0,retval.length -2);
		
	} 
		
	//Removing the extra spaces and "\r\n" in the beginning
	while(retval.substring(0,1) == " " || retval.indexOf("\r\n") == 0)
	{
		retval = retval.substring(0,1) ==" " ? retval.substring(1,retval.length) : retval.substring(2,retval.length);
	}
	
	return retval;
}

////////////////////////////////////////////////////////////Modal Window functions starts here///////////////////////
var winModalWindow;
var RELOAD = "RELOAD";
var SUBMIT = "SUBMIT";
 
function IgnoreEvents()
{
	if (winModalWindow && !winModalWindow.closed) 
	{
		winModalWindow.focus();
		return false
	}
}

var mozillaversion16 = ((navigator.appName== "Netscape") && (navigator.userAgent.indexOf("Gecko/20040113")!=-1) && (navigator.userAgent.indexOf("rv:1.6")!=-1))
var mozillaversion11 = ((navigator.appName== "Netscape") && (navigator.userAgent.indexOf("Gecko/20020826")!=-1) && (navigator.userAgent.indexOf("rv:1.1")!=-1))
var netscapeVersion7 = ((navigator.appName== "Netscape") && (navigator.userAgent.indexOf("Netscape/7")!=-1))?true:false;
var ie50 = (navigator.userAgent.indexOf("MSIE 5.0")!=-1)?true:false; 
var Mac = (navigator.appVersion.indexOf("Mac")!=-1)?true:false; 

/*
This function will identify the browser whether it supports modal dialog or not.
If the browser doesn't support modal dialog then new window will be launched and
it will be act as a modal window.
*/
function ShowCustomizeDialog(Page,Width,Height)
{
	if (window.showModalDialog)
	{
		if(Mac && ie50)
		{
			LaunchSimulatedModalWindow(Page,Width,Height);
		}
		else
		{
			var retVal = "";
			var windowIE50 = (navigator.appVersion.indexOf("MSIE 5.0")!=-1)?true:false;   
   			var windows =(navigator.appVersion.indexOf("Windows")!=-1)?true:false; 

			//-----------WorkAround for the Problem in Windows/IE 5.0----------------
			//To solve the problem of opening a new window in IE 5.0, we should use
			//<iframe>. The following code will do the same.
			if(windowIE50 && windows)
			{
				var SlashAfterVirtualDirectory =Page.indexOf("/",Page.indexOf("/",Page.indexOf("/")+2)+1);
				var lastQuestionMark = Page.lastIndexOf("?");
				var replaceTo = Page.substring(SlashAfterVirtualDirectory+1,lastQuestionMark);
				var ReplacedUrl = Page.replace(replaceTo,"Common/QDialogLauncher.aspx") + "&DialogName=" + replaceTo;
				retVal = window.showModalDialog(ReplacedUrl,"ModalDialog","dialogWidth="+Width+"px;dialogHeight="+Height+"px;scrollbars=no");
			}
			else
			{
				retVal = window.showModalDialog(Page,"ModalDialog","dialogWidth="+Width+"px;dialogHeight="+Height+"px;scrollbars=no");		
			}
			
			if(retVal == RELOAD)
			{
				self.document.forms[0].submit(); //reload() is not supported by MAC IE 5.2
			}
			else if(retVal == SUBMIT)
			{
				self.document.forms[0].submit();
			}
			else
				return false;
		}
	}
	else
	{
		LaunchSimulatedModalWindow(Page,Width,Height);
	}
  
}
/*********** Used for launching simulated modal window for Netscape,Mozilla other than IE **********/
function LaunchSimulatedModalWindow(Page,Width,Height)
{
	if(navigator.appName == "Netscape")
	{
		window.top.captureEvents (Event.CLICK|Event.FOCUS)
	}
	window.top.onclick = IgnoreEvents
	window.top.onfocus = HandleFocus
	
	//call this method to disable the parent form elements and links.
	if(netscapeVersion7 || mozillaversion11 || mozillaversion16 || (Mac && ie50))
		disableForms();
	winModalWindow =  window.open (Page,"ModalDialog","dependent=yes,width="+Width+",height="+Height+", scrollbars=yes");
	window.opener = winModalWindow;
	winModalWindow.focus();
}
//************ Used to close the window **************/
function CloseWindow()
{
	if(window.showModalDialog)
	{
		if(Mac && ie50)
		{
			HandleFocus();
			window.parent.close();
		}
		else
			top.close();
	}
	else
	{
		HandleFocus();
		window.parent.close();
	}
}


function DefaultGoToHomePage()
{

window.location.href = "http://" + location.host;

}

var firstTime = true;
//Call the set focus method through setTimeOut as without setTimeout it gives some problems in Netscape 7 and Mozilla 1.6
function HandleFocus()
{
	if(netscapeVersion7 || mozillaversion11 || mozillaversion16)
		setTimeout("setFocus()", 50);
	else
		setFocus();
		
	return true;
}

function setFocus()
{
	
	if (winModalWindow)
	{
		if (!winModalWindow.closed)
		{
			winModalWindow.focus();
		}
		else
		{
			if(navigator.appName == "Netscape")
			{
				window.top.releaseEvents (Event.CLICK|Event.FOCUS)
			}
			window.top.onclick = ""
			if(netscapeVersion7 || mozillaversion11 || mozillaversion16 || (Mac && ie50))
				enableForms();
		}
    }
	return false
}

/*
Parent page which has child window should call this function on onUnload event 
to close the child window if it exists.
*/
function CloseChildOnParentUnLoad()
{
 if(window.opener.name == "ModalChild")
 {
	window.opener.close();
 }
 
}

/*
To close the child and relod the parent from the child.
This should be called from the child.
*/
function CloseChildReloadParent()
{
	if (window.showModalDialog)
	{
		window.returnValue = RELOAD;
		window.close();
	}
	else
	{
		window.opener.location.reload();
		window.close();
	}
}

/*
To close the child and submit the parent from the child.
This should be called from the child.
*/
function CloseChildSubmitParent()
{
	if (window.showModalDialog)
	{
		window.returnValue = SUBMIT;
		window.close();
	}
	else
	{
		window.opener.document.forms[0].submit();
		window.close();
	}
}

function CloseChildWindow()
{
	window.close();
}

function CheckFieldLength(field,len)
{
      if (field.value.length >= len)
            return false;
      return true;
}

function changeCursorOnMouseOver(field)
{
	var ie50 = (navigator.appVersion.indexOf("MSIE 5")!=-1)?true:false;  
	var windows =(navigator.appVersion.indexOf("Windows")!=-1)?true:false; 
	if(ie50 && windows)
	{
		field.style.cursor = 'hand';
		field.style.color = "C86837";
	}
	else
	{
		field.style.cursor = 'pointer';
		field.style.color = "C86837";
	}
}

function changeCursorOnMouseOut(field)
{
	field.style.cursor = 'default';
	field.style.color = "928D57";
}


// Since links in Netscape can't be disabled, preserve onclick event handlers while they're "disabled." 
// Restore when reenabling the main window.
var IELinkClicks
// Disable form elements and links and the anchors(Anchors should have the name or Id property).
function disableForms() 
{
	var index;
	IELinkClicks = new Array()
	disableFormElements();
    for (index = 0; index < document.links.length; index++) 
    {
		IELinkClicks[index] = document.links[index].onclick
        document.links[index].onclick = IgnoreEvents
    }
    var linkLength = document.links.length
    for (index = 0; index < document.anchors.length; index++) 
    {
		IELinkClicks[linkLength+index] = document.anchors[index].onclick
		document.anchors[index].onclick = IgnoreEvents
    }
}

/**
* The method disables various form elements of the passed form object.
*/
function disableFormElements()
{
	formObj = document.forms[0];
	if(!formObj || formObj == null)
	{
		return;
	}
	
	var elements = formObj.elements;
	var index;
	for(index = 0; index < elements.length; index++)
	{
		try
		{
			if(elements[index].type != "hidden")
			{
				if(elements[index].type == "text")
				{
					elements[index].readonly = true;
				}
				else if(elements[index].type == "select-one")
				{
					elements[index].onchange = "window.event.returnValue = false; return false;"
				}
				else if(elements[index].type != "radio" && elements[index].type != "checkbox")
				{
					elements[index].disabled = true;
				}
			}
		}
		catch(exception)
		{
			//dont do anything
		}
	}
}


// Restore IE form elements and links to normal behavior.
function enableForms() 
{
	enableFormElements();
    for (index = 0; index < document.links.length; index++) 
    {
		document.links[index].onclick = IELinkClicks[index]
    }
    var linksLength = document.links.length;
    for (index = 0; index < document.anchors.length; index++) 
    {
		document.anchors[index].onclick = IELinkClicks[linksLength+index]
    }
   
}
/**
* The method enables various form elements of the passed form object.
*/
function enableFormElements()
{
	formObj = document.forms[0];
	if(!formObj || formObj == null)
	{
		return;
	}
	
	var elements = formObj.elements;
	var index;
	for(index = 0; index < elements.length; index++)
	{
		try
		{
			if(elements[index].type != "hidden")
			{
				if(elements[index].type == "text")
				{
					elements[index].readonly = false;
				}
				else if(elements[index].type == "select-one")
				{
					elements[index].onchange = "window.event.returnValue = true; return true;"
				}
				else if(elements[index].type != "radio" && elements[index].type != "checkbox")
				{
					elements[index].disabled = false;
				}
			}
		}
		catch(exception)
		{
			//dont do anything
		}
	}
}
//Generic Function to Check whether the field value is AlphaNumeric
function isAlphaNumeric(fieldValue)
{
	
	var len = fieldValue.length;
	if(len>0)
	{
		for(var i=0; i < len; i++)
		{
			var strValue = fieldValue;
			var charCode = strValue.charCodeAt(i); 
			if((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <=90) || (charCode >=97 && charCode <= 122))
			{
				//return true;
			}
			else
			{
				return false;
			}
		}
		return true;
	}	
	return false;
}

//Generic Function to Check whether the field value is AlphaNumeric
function CheckKeywordSearch2(fieldValue)
{
    try
    {
	    var validSearch = false;
	    var len = fieldValue.length;
	    if(len>0)
	    {
		    for(var i=0; i < len; i++)
		    {
			    var strValue = fieldValue;
			    var charCode = strValue.charCodeAt(i);			
			    if ( ( charCode >= 48 && charCode <= 57 ) || ( charCode >= 65 && charCode <=90 ) || ( charCode >=97 && charCode <= 122) )
			    {
				    validSearch = true;
				    return true;
			    }
			    else
			    {
				    validSearch = false;
			    }
		    }    		
	    }	
	}catch(e)
	{
	    validSearch = false;
	}
	return validSearch;
}



//Generic Function to Check whether the field value is AlphaNumeric
function CheckKeywordSearch(fieldValue)
{
	var validSearch = false;
	var len = fieldValue.length;
	if(len>0)
	{
		for(var i=0; i < len; i++)
		{
			var strValue = fieldValue;
			var charCode = strValue.charCodeAt(i);			
			if((charCode == 46 || charCode == 45 || charCode == 32 ||charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <=90) || (charCode >=97 && charCode <= 122))
			{
				validSearch = true;
			}
			else
			{
				validSearch = false;
//				return validSearch;
			}
		}
		
		//4.1
		if(validSearch)
		{
		    if (CheckKeywordSearch2(fieldValue))
		    {
		        return true;
		    }
		}		
	}	
	return false;
}


//Populate the Shipment Types depending upon the country ID
//Requires the ShipmentTypesList mapping data to be embedded in the page
function PopulateShipmentTypes(dropdownList, countryID, defaultShipmentTypeID, showSelect)
{
	if (ShipmentTypesList != null)
	{
		//Check whether to show select
		var bShowSelect = true;
		if (showSelect != null)
		{
			bShowSelect = showSelect;
		}
	
		//Clear the Shipping Method List and re-populate it
		document.forms[0].elements[dropdownList].options.length = 0;
		
		if (countryID != null && countryID != "")
		{
			//Get the Shipment Types for the selected country
			var objShipmentTypes = ShipmentTypesList[countryID];
			var strShipmentTypeID;
			var strShipmentTypeValue;
			
			if (objShipmentTypes != null && objShipmentTypes.length > 0)
			{
				var index = 0;
				if (bShowSelect)
				{
					//Show the Select>>
					document.forms[0].elements[dropdownList].options[index] = new Option("Select >>","");
					index++;
				}
				var defaultShipmentTypeIDIndex = 0;
				//Populate the dropdown List with Shipment Types
				for(strShipmentTypeID in objShipmentTypes)
				{
					strShipmentTypeValue = objShipmentTypes[strShipmentTypeID];
					document.forms[0].elements[dropdownList].options[index] = new Option(strShipmentTypeValue,strShipmentTypeID);
					if( defaultShipmentTypeID != null && defaultShipmentTypeID != "" && strShipmentTypeID === defaultShipmentTypeID )
						defaultShipmentTypeIDIndex = index; 
					
					index++;
				}
				
				/*
				//////// ON MAC IE5.2 document.forms[0].elements[dropdownList].value STATEMENT IS NOT WORKING \\\\\\\
				//Select the default Shipment Type
				if (defaultShipmentTypeID != null && defaultShipmentTypeID != "")
				{
					document.forms[0].elements[dropdownList].value = defaultShipmentTypeID;
					if(document.forms[0].elements[dropdownList].value == null || document.forms[0].elements[dropdownList].value == "")
					{
						document.forms[0].elements[dropdownList].selectedIndex = 0;
					}
				}
				*/
				if( defaultShipmentTypeIDIndex != 0 )
					document.forms[0].elements[dropdownList].selectedIndex = defaultShipmentTypeIDIndex;
				else
					document.forms[0].elements[dropdownList].selectedIndex = 0;	
			}
			else
			{
				//Show the message Not Available
				document.forms[0].elements[dropdownList].options[0] = new Option("-- Not Available --","");
			}
		}
	}
}


////////////////////////////////////////////////////////////Modal Window functions ends here///////////////////////

//Method to mask the textbox for double quote  
function checkDoubleQuote(e)
{	
	var inputKey;
	if(window.event) 
	{
		inputKey = e.keyCode;
	}
	else if(e.which)
	{
		inputKey = e.which;
	}
	
	 
	if (inputKey == 34)
	{
		return false;
	}
	 
	return true;
}

//Max length for TextArea - typed in characters
function maxLength(field, maxChars) {
    if (field.value.length >= maxChars) {
        if (document.selection.createRange().text.length > 0) {
            event.returnValue = true;
            return true;
        }
        event.returnValue = false;
        return false;
    }
}
//Max length for TextArea - Pasted characters
function maxLengthPaste(field, maxChars) {
    event.returnValue = false;
    if ((field.value.length + window.clipboardData.getData("Text").length) > maxChars) {
        document.selection.createRange().text = window.clipboardData.getData("Text");
        field.value = field.value.substring(0, maxChars);
        return true;
    }
    event.returnValue = true;
}


function toggleDiv(divid, linkid, collapserString, expanderString)
{
	if(document.getElementById(divid) != null)
   {
	if (document.getElementById(divid).style.display == 'none')
	{
		document.getElementById(divid).style.display = 'block';

		if (document.getElementById('QBasicPersonalization1_myLinkA') != null)
			document.getElementById('QBasicPersonalization1_myLinkA').style.display = 'inline';

		//XHTML Handling
		if (document.getElementById('QBasicPersonalization1_dvPersonalizationRow') != null)
			document.getElementById('QBasicPersonalization1_dvPersonalizationRow').style.display = 'inline';

		document.getElementById(linkid).innerHTML = collapserString;
		document.getElementById(linkid).title = "Click to collapse"
	} else
	{
		document.getElementById(divid).style.display = 'none';
		document.getElementById(linkid).innerHTML = expanderString;
		document.getElementById(linkid).title = "Click to expand"
	}
   }

	if (document.getElementById("QBasicPersonalization1_PersonalizationHeaderColumn") != null)
	{
		if (IsPersonalizationChecked(document.getElementById("QBasicPersonalization1_PersonalizationHeaderColumn")))
			SetDisabled(document.getElementById(divid), false);
	}

	//XHTML Handling
	if (document.getElementById("QBasicPersonalization1_dvPersonalizationHeaderColumn") != null)
	{
		if (IsPersonalizationChecked(document.getElementById("QBasicPersonalization1_dvPersonalizationHeaderColumn")))
			SetDisabled(document.getElementById(divid), false);
	}
}

function IsPersonalizationChecked(el) {
    var IsChecked = false;
    if (el != null && el.type == "checkbox" &&
         el.id.indexOf('QBasicPersonalization1_chkPersonalization') != -1 &&
         el.checked == true) {
        return true;
    }
    if (el != null && el.childNodes != null && el.childNodes.length > 0) {
        for (var x = 0; x < el.childNodes.length; x++) {
            IsChecked = IsPersonalizationChecked(el.childNodes[x]);
            if (IsChecked)
                break;
        }
    }
    return IsChecked;
}

function EnableControls(chePersonalize, myDiv) {
    if (!chePersonalize.checked) {
        SetDisabled(document.getElementById(myDiv), true);
        if (document.getElementById("QBasicPersonalization1_hdnIsPersonalization") != null)
            document.getElementById("QBasicPersonalization1_hdnIsPersonalization").value = "0";

        SetValuesOnDisable(true);
    }
    else {
        SetDisabled(document.getElementById(myDiv), false);
        if (document.getElementById("QBasicPersonalization1_hdnIsPersonalization") != null)
            document.getElementById("QBasicPersonalization1_hdnIsPersonalization").value = "1";

        SetValuesOnDisable(false);
    }
}

function SetValuesOnDisable(val) {
    var iCount = 1;
    var controlId = '';
    if (val) {
        for (i = 0; i < document.forms[0].elements.length; i++) {
            var el = document.forms[0].elements[i];

            if (el.type == 'text' || el.type == 'textarea') {
                if (el.id.indexOf('QBasicPersonalization1_') != -1) {
                    controlId = "QBasicPersonalization1_hdnPostbackValue" + iCount;
                    if (document.getElementById(controlId) != null) {
                        document.getElementById(controlId).value = el.value;
                        iCount = iCount + 1;
                    }
                }
            }
            else if (el.type == 'select-one') {
                if (el.id.indexOf('QBasicPersonalization1_') != -1) {
                    controlId = "QBasicPersonalization1_hdnPostbackValue" + iCount;
                    if (document.getElementById(controlId) != null) {
                        document.getElementById(controlId).value = el.selectedIndex;
                        iCount = iCount + 1;
                    }
                }
            }
        }
    }
    else {
        for (i = 1; i <= 10; i++) {
            controlId = "QBasicPersonalization1_hdnPostbackValue" + i;
            if (document.getElementById(controlId) != null)
                document.getElementById(controlId).value = '';
        }
    }
}

function SetDisabled(el, val) {
    try {
        el.disabled = val;
    }

    catch (E) { }
    if (el.childNodes && el.childNodes.length > 0) {
        for (var x = 0; x < el.childNodes.length; x++) {
            SetDisabled(el.childNodes[x], val);
        }
    }
}

function ShowAlert(message) {
    alert(message);
}
//Method to mask the textbox for Alphabets
function maskAlphabet(e) {
    var inputKey;
    if (window.event) {
        inputKey = e.keyCode;
    }
    else if (e.which) {
        inputKey = e.which;
    }
    
    if (inputKey != 13) {
        if (((inputKey > 90 || inputKey < 65) && (inputKey > 122 || inputKey < 97)) && (inputKey != 8) && (inputKey != 9) && (inputKey != 32)) {
            return false;            
        }
    }
    return true;
}

function ValidateKitProductQuantity() {
	if (document.forms[0].elements["Quantity"] != null) {
		var qty = document.forms[0].elements["Quantity"].value;
		if (qty == "" || qty <= 0 || !isNumeric(qty)) {
			alert("Please enter a valid quantity.");
			document.forms[0].elements["Quantity"].focus();
			return false;
		}

		var minQty = parseInt(document.forms[0].elements["ProductValidationData$MinQty"].value, 10);
		var maxQty = parseInt(document.forms[0].elements["ProductValidationData$MaxQty"].value, 10);

		var inputQty = trim(qty) - 0;

		if (inputQty >= minQty) {
			if (inputQty > maxQty) {
				alert("The entered quantity is more than the maximum quantity (" + maxQty + ") allowed. You must edit the Quantity before you can continue.");
				document.forms[0].elements["Quantity"].focus();
				return false;
			}
		}
		else {
			alert("The entered quantity is less than the minimum quantity (" + minQty + ") allowed. You must edit the Quantity before you can continue.");
			document.forms[0].elements["Quantity"].focus();
			return false;
		}
	}
	return true;
}

function ValidatePersonalization() {

	if (!ValidateKitProductQuantity())
		return false;
		
    var strResponseType;
    var strResponseRequired;
    var errorlabel;
    var controlid;
    var IsRequired = true;
    var IsValid = true;

    if (document.getElementById("QBasicPersonalization1_PersonalizationHeaderColumn") != null)
    {
    	if (!IsPersonalizationChecked(document.getElementById("QBasicPersonalization1_PersonalizationHeaderColumn")))
    		return true;
    }
    //XHTML Handling
    if (document.getElementById("QBasicPersonalization1_dvPersonalizationHeaderColumn") != null)
    {
    	if (!IsPersonalizationChecked(document.getElementById("QBasicPersonalization1_dvPersonalizationHeaderColumn")))
    		return true;
    }

    for (i = 0; i < document.forms[0].elements.length; i++) {

        if (document.forms[0].elements[i].type == "text" || document.forms[0].elements[i].type == "textarea") {

            controlid = document.forms[0].elements[i].id.substring(22, document.forms[0].elements[i].id.length);
            errorlabel = "QBasicPersonalization1_err_Personalize" + controlid;

            ////
            if (document.forms[0].elements[i].attributes["ResponseRequired"] != null) {
                strResponseRequired = document.forms[0].elements[i].attributes["ResponseRequired"].value;

                if (strResponseRequired == "True" && document.forms[0].elements[i].value == '') {
                    IsValid = false;
                    if (document.getElementById(errorlabel) != null) {
                        document.getElementById(errorlabel).style.display = 'block';
                    }
                }
                else if (document.forms[0].elements[i].value != '') {

                    if (document.forms[0].elements[i].attributes["ResponseType"] != null) {
                        strResponseType = document.forms[0].elements[i].attributes["ResponseType"].value;
                        switch (strResponseType) {
                            case "Numeric":
                                if (!document.forms[0].elements[i].value.match(/^[0-9]*$/)) {
                                    if (document.getElementById(errorlabel) != null) {
                                        document.getElementById(errorlabel).style.display = 'block';
                                        IsValid = false;
                                    }

                                }
                                else {
                                    if (document.getElementById(errorlabel) != null) {
                                        document.getElementById(errorlabel).style.display = 'none';
                                    }
                                }
                                break;
                            case "Alphabetic":
                                if (!document.forms[0].elements[i].value.match(/^[a-zA-Z\s]*$/)) {
                                    if (document.getElementById(errorlabel) != null) {
                                        document.getElementById(errorlabel).style.display = 'block';
                                        IsValid = false;
                                    }

                                }
                                else {
                                    if (document.getElementById(errorlabel) != null) {
                                        document.getElementById(errorlabel).style.display = 'none';
                                    }
                                }
                                break;
                            case "String":
                                if (document.getElementById(errorlabel) != null) {
                                    document.getElementById(errorlabel).style.display = 'none';
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                else if (document.forms[0].elements[i].value == '') {
                    if (document.getElementById(errorlabel) != null) {
                        document.getElementById(errorlabel).style.display = 'none';
                    }
                }
            }
        }
        else if (document.forms[0].elements[i].type == "select-one"
                    && document.forms[0].elements[i].attributes["ResponseType"] != null
                    && document.forms[0].elements[i].attributes["ResponseRequired"] != null) {

            if (document.forms[0].elements[i].attributes["ResponseType"].value == "List"
            && document.forms[0].elements[i].attributes["ResponseRequired"].value == "True") {
                controlid = document.forms[0].elements[i].id.substring(22, document.forms[0].elements[i].id.length);
                errorlabel = "QBasicPersonalization1_err_Personalize" + controlid;

                if (document.forms[0].elements[i].selectedIndex == 0) {
                    if (document.getElementById(errorlabel) != null) {
                        document.getElementById(errorlabel).style.display = 'block';
                        IsValid = false;
                    }

                }
                else {
                    if (document.getElementById(errorlabel) != null) {
                        document.getElementById(errorlabel).style.display = 'none';

                    }
                }
            }
        }
    }
    if (IsValid) {
        if (document.getElementById('QBasicPersonalization1_lblErrorMsg') != null)
            document.getElementById('QBasicPersonalization1_lblErrorMsg').style.display = 'none';
    }
    else {
        if (document.getElementById('QBasicPersonalization1_lblErrorMsg') != null)
            document.getElementById('QBasicPersonalization1_lblErrorMsg').style.display = 'block';
    }
    return IsValid;
}

function CheckMaxLength(field, len, event) {
    var IE = (navigator.userAgent.indexOf("MSIE") != -1) ? true : false;
    var FF = (navigator.userAgent.indexOf("Firefox") != -1) ? true : false;
    var Saf = (navigator.userAgent.indexOf("Safari") != -1) ? true : false;

    if (field.value.length >= len && IE == true) {

        if (document.selection.createRange().text.length > 0) {
            event.returnValue = true;
            return true;
        }
        event.returnValue = false;
        return false;
    }
    else if (FF == true || Saf == true) {
        if (field.value.length >= len && event.keyCode != 8)
            return false;
        return true;
    }
    else {
        if (field.value.length >= len)
            return false;
        return true;
    }
    return true;
}

/***************************************************************
 *  $Log: Common.js,v $
 *  Revision 1.1  2007/09/25 13:05:54  sackumar
 *  Added changes related to Bug# 3248
 *
 *  Revision 1.16  2007/06/13 12:37:05  rlakshmi
 *  checking in for bug # 3235.
 *
 *  Revision 1.13  2005/09/29 15:09:35  avsingh
 *  Updated the IsNumeric() method.
 *
 *  Revision 1.12  2005/09/28 09:31:53  apsingh
 *  Fixed #387178.
 *
 *  Now email ID with numeric prefix accepted.
 *
 *  Revision 1.11  2005/09/28 04:31:43  avsingh
 *  Added support to simply return if textbox value is empty string in FormatPrecision() javascript method.
 *
 *  Revision 1.10  2005/09/26 11:25:26  avsingh
 *  - Added method maskDecimal() to mask the textbox for decimal values.
 *  - Added method FormatPrecision() to format the textbox value as 0.00
 *
 *  Revision 1.9  2005/09/22 05:51:08  apsingh
 *  Added function DisableRightClick().
 *
 *  Revision 1.8  2005/08/31 13:44:00  apsingh
 *  Fixed #381203.
 *
 *  Added ''(space) in specialChar array list.
 *
 *  Revision 1.7  2005/08/30 11:51:56  apsingh
 *  comment document.forms[formname] formname passing document.forms[0].
 *
 *  Revision 1.6  2005/08/25 15:40:13  avsingh
 *  Modified the DisableButtonsEx() javascript method.
 *
 *  Revision 1.5  2005/08/24 14:09:57  apsingh
 *  Added  OnPOBoxClickByUser(), CheckPOBoxAddress()
 *  for Automatic Identification of PO box address.
 *
 *  reviewer : sachin
 *
 *  Revision 1.4  2005/08/24 12:10:31  avsingh
 *  Added the javascript methods DisableButtons() and DisableButtonsEx().
 *
 *  Revision 1.3  2005/08/18 13:42:32  apsingh
 *  Added HandleSubmit function for Netscape Issues.
 *
 *  Revision 1.2  2005/08/12 12:28:27  apsingh
 *  Added SpecialCharacter.js method
 *  Handling of special characters.
 *
 *  Revision 1.1.1.1  2005/08/08 17:10:57  mercury_build
 *  Inital Check-in for QCMS 2.8 after 2.5 version
 *
 *  Revision 1.1.2.7  2005/07/04 10:49:30  apsingh
 *  If combo box is created with javascript then on mac IE5.2 comboBox.value assignment does not work.
 *  Changed the code to work with selectedIndex.
 *
 *  Revision 1.1.2.6  2005/06/13 15:12:57  avsingh
 *  Updated the javascript method checkMandatoryFields() for selecting fields.
 *
 *  Revision 1.1.2.5  2005/06/10 13:22:13  avsingh
 *  Modified the method PopulateShipmentTypes(). (related to International Shipping)
 *
 *  Revision 1.1.2.4  2005/06/06 14:17:16  avsingh
 *  Added support in method checkMandatoryFields() to select the related field in case the validation of field value fails.
 *
 *  Revision 1.1.2.3  2005/05/29 13:53:33  avsingh
 *  Added the common method maskInteger().
 *  Added the common method PopulateShipmentTypes().
 *
 *  Revision 1.1.2.2  2005/04/11 07:08:17  apsingh
 *  Fixed #336936
 *  Incorrect email id (starting with a numeric ) user account is created.
 *
 *  Revision 1.1.2.1  2005/03/16 11:09:07  sackumar
 *  Initial check-in for Estore 2.5.
 *
 *  Revision 1.1  2005/02/10 09:56:06  mdas
 *  Add Login.js and Common.js.
 *
 *  Revision 1.18.4.2  2005/02/02 13:38:55  mdas
 *  Fixed #333501, #333537
 *
 *  Revision 1.18.4.1  2004/11/23 11:37:48  mdas
 *  Credit Card security code changes.
 *
 *  Revision 1.19  2004/11/22 10:01:31  mdas
 *  Credit Card security code changes.
 *
 *  Revision 1.18  2004/09/15 13:22:22  mdas
 *  Changes done to open a modal dialog window through window.open for MAC IE 9.2 also
 *
 *  Revision 1.17  2004/09/14 12:29:29  mdas
 *  Added scrollbar=yes
 *
 *  Revision 1.16  2004/09/14 10:58:42  sackumar
 *  Added changes for the simulated modal dialog.
 *
 *  Revision 1.15  2004/09/02 11:31:31  mdas
 *  Added changeCursorOnMouseout function and chnaged the color to red on mouseover
 *
 *  Revision 1.14  2004/08/19 06:40:37  mdas
 *  Made cursor=hand property available for all versions gereater than  Internet Explorer 5 on Windows platform.
 *
 *  Revision 1.13  2004/08/06 11:48:42  mdas
 *  Handled Windows/IE 5.0 Modal Dialog problem.
 *
 *  Revision 1.12  2004/08/04 06:27:17  mdas
 *  Added new method "changeCursorOnMouseOver" for changing the mouse cursor shape.
 *
 *  Revision 1.11  2004/07/13 11:49:51  sackumar
 *  stop using the email format algorithm got from internet, instead use the algorithm used at Customer service and acll center.
 *
 *  Revision 1.10  2004/05/12 12:25:32  pvasikar
 *  While checking Form elements against undefined, check against "undefined" not against undefined.
 *
 *  Revision 1.9  2004/05/11 08:57:26  pvasikar
 *  reload() is replaced by submit() since reload() is not supported by MAC IE.
 *
 *  Revision 1.8  2004/05/04 06:48:32  pvasikar
 *  New Check Email Format function is added old one is removed.
 *
 *  Revision 1.7  2004/03/22 14:26:13  pvasikar
 *  Email validation done for special characters.
 *
 *  Revision 1.6  2004/03/15 07:27:09  pvasikar
 *  Error messages corrected as per usecase.
 *
 *  Revision 1.5  2004/02/18 14:37:54  pvasikar
 *  Added function to check the length of the field.
 *
 *  Revision 1.4  2004/02/17 14:45:24  mvijay
 *  Changes done for showing Modal Window
 *
 *  Revision 1.3  2004/02/17 05:07:48  pvasikar
 *  no message
 *
 *  Revision 1.2  2004/02/10 12:56:37  pvasikar
 *  no message
 *
 *  Revision 1.1.1.1  2004/01/28 04:37:56  mercury_build
 *  Initial Version
 *
 *  Revision 1.1  2004/01/22 13:17:17  nrajavelu
 *  no message
 *				  
 *  
 *
 *  Copyright (c) 2003 Quark Media house India Pvt Limited.	
 *  All Rights Reserved						
 ***************************************************************/

