/*
    Version Control
    $URL: https://www.quru.com/svn/bonhams/Progress/Release/www/pubjs/publicRegister.js $
    Last Changed: $Date: 2010-02-04 16:21:42 +0000 (Thu, 04 Feb 2010) $ $Rev: 2817 $ by $Author: toby $
*/
var sAddressLink = new Array();

function searchAddr()
{
var sPostcode;
var sURL;
var sAddr1;
var sStreet = "";
var sLocality;
var sOptions
var iWidth = 640;
var iHeight = 480;
var iLeft;
var iTop;

	sURL = "/cgi-bin/gbicgi?reqtype=search_hier01&admcfg=public";

	sPostcode = window.document.forms[0].sPostcode.value;
	sAddr1 = window.document.forms[0].sAddr1.value;
	
	if (sPostcode != "")
	{
		sURL += "&ipf_walk=" + sPostcode;
		// Searching by Postcode, see if they've typed the building name too
		if (sAddr1 != "")
		{
			if (parseInt(sAddr1, 10) > 0)
				sURL += "&ipf_bldg=" + parseInt(sAddr1, 10);
			else
				sURL += "&ipf_bldg=" + sAddr1;
		}
	}
	else
	{
		// Is the street name in sAddr1 or sAddr2 ?
		if (parseInt(sAddr1, 10) > 0)
		{
			sURL += "&ipf_bldg=" + parseInt(sAddr1, 10);
			if (sAddr1.indexOf(" ") != -1)
				sStreet = sAddr1.substr(sAddr1.indexOf(" ") + 1);
		}
		else
		{
			sURL += "&ipf_bldg=" + sAddr1;
			sStreet = window.document.forms[0].sAddr2.value;
		}
		if (sStreet != "")
			sURL += "&ipf_strt=" + sStreet;

		// Add the locality (either the town or county)
		sLocality = window.document.forms[0].sTown.value;
		if (sLocality == "")
			sLocality = window.document.forms[0].sCounty.value;
		if (sLocality != "")
			sURL += "&ipf_lcty=" + sLocality;
	}

	iLeft = ((screen.availWidth - iWidth) / 2);
	iTop = ((screen.availHeight - iHeight) / 3);
	sOptions = "scrollbars,status,resizable";
	sOptions += ',top=' + iTop + ',left=' + iLeft + ',screenX=' + iLeft + ',screenY=' + iTop + ',width=' + iWidth + ',height=' + iHeight;
	window.open(sURL, 'searchAddr', sOptions);
}

function isblank(s)
{
	if (!s || s == "")
		return true;

	for(var i = 0; i < s.length; i++) 
	{
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
	return true;
}

function verify(f)
{
var msg;
var usrNameErr = "";
var empty_fields = "";
var errors = "";
var reg_exp_email = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
var index =0;
var sMandatory = ["sTitle", "sFirstName", "sLastName", "sAddr1",  "sTown", "sTelNo1",   "sEmail", "sPublicUserName", "sPublicPassword"];
var sOutputMsg = ["Title",  "First Name", "Last Name", "Address", "Town",  "Telephone", "Email",  "Username",        "Password"];
var sPCOptional = ["AF","CO","HK","IQ","MO","TP"];

   if (document.forms[0].sPublicUserName && ((document.forms[0].sPublicUserName.value.length > 16) || (document.forms[0].sPublicUserName.value.length < 6))) 
   {
      usrNameErr = "User name must be between 6-16 characters \n\n";
   }

   for (index = 0; index < sPCOptional.length; index++) 
   {
      if (document.forms[0].sCountryCode.value == sPCOptional[index]) 
      {
         break;
      }
   }
   if (index == sPCOptional.length) 
   {
      sMandatory.push("sPostcode");
      sOutputMsg.push("Post code/Zip code");
   }
   if (document.forms[0].sCountryCode.value == "US" || document.forms[0].sCountryCode.value == "CA") 
   {
      sMandatory.push("sState");
      sOutputMsg.push("State");
      sMandatory.push("sCounty");
      sOutputMsg.push("County");
   }

   for (index = 0; index < sMandatory.length; index++) {
      if (eval("document.forms[0]." + sMandatory[index]) && isblank(eval("document.forms[0]." + sMandatory[index] + ".value"))) {
         empty_fields += "\n          " + sOutputMsg[index];
      }
   }
   /*now we'll check if the email adress is valid*/ 
   if ((!isblank(document.forms[0].sEmail.value)) && !reg_exp_email.test(document.forms[0].sEmail.value)) 
   {
       alert(document.forms[0].sEmail.value + " is an invalid email address");
	   return false;
   }

   // Check the card details (if they are on the screen)
   if (empty_fields == "" && document.forms[0].sCardType)
   {
       if (document.forms[0].sCardType.value == "")
       {
           alert("You must select a card type");
           return false;
       }
       if (document.forms[0].sCardNo.value.length < 16)
       {
           alert("You must enter a valid card number");
           return false;
       }
       if (document.forms[0].sCardName.value.length < 2)
       {
           alert("You must enter the name on your card");
           return false;
       }
       if (document.forms[0].daCardEndDate.value.length < 6)
       {
           alert("You must select your card's expiry date");
           return false;
       }
   }

   /* Now, if there were any errors, then display the messages, and
      return false to prevent the form from being submitted. Otherwise
      return true.*/
   if (empty_fields == "")
   {
      	getElement("window", "sTown").disabled = false;
		getElement("window", "sCounty").disabled = false;
		getElement("window", "sState").disabled = false;
		return true;
   }
   
   msg  = "______________________________________________________\n\n";
   msg += "The form was not submitted because of the following error(s).\n";
   msg += "Please correct these error(s) and re-submit.\n";
   msg += "______________________________________________________\n\n";

   if (usrNameErr != "")
       msg+=usrNameErr;
   if (empty_fields) 
   {
        msg += "- The following required field(s) are empty:" + empty_fields + "\n";
        msg += "\n";
        alert(msg);
        return false;
   }
}

function reset_form()
{
	var msg;
	msg = "This will reset the form, are you sure?";
	if (confirm(msg))
		return true;
	else
		return false;
}


var bSubmitted = false;
function registerClient()
{
    if (bSubmitted)
        return;

    bSubmitted = true;
    document.forms[0].saction.value = "Add";
    if (verify(document.forms[0]))
    {
        document.forms[0].sPublicPassword.value = calcMD5(document.forms[0].sPublicPassword.value);
        document.forms[0].submit();
    }
    else
    {
        bSubmitted = false;
    }
}

function changeCountry(sLocation)
{
var iItem;
		
	if (!sCountryCode || sCountryCode == "")
		return;

	/* Select the initial country code */
	for (iItem = 0; iItem < document.forms[0].sCountryCode.options.length; iItem++)
	{
		if (document.forms[0].sCountryCode.options[iItem].value == sCountryCode)
		{
			if (bNetscape)
				window.setTimeout("document.forms[0].sCountryCode.options[" + iItem + "].selected = true;", 1);
			else
				document.forms[0].sCountryCode.options[iItem].selected = true;
			break;
		}
	}
}

function lookupPostcodeUS(sDisplayField)
{
	var sPostcode;
	var iDashpos;
	
	sPostcode = getValue("window", sDisplayField);
	iDashpos = sPostcode.indexOf('-');
	
	if (sPostcode != "<Not found>")
	{
		if (iDashpos == -1){
			sPostcode = sPostcode.substr(0,5);
		}else{
			sPostcode = sPostcode.substr(0,iDashpos);
		}
	}
	
	if (document.forms[0].sCountryCode.value == "US")
		disableCounty(true);
	else
	{
		disableCounty(false);
		blankAddressFields();
		if (document.forms[0].sCountryCode.value != 'US' && document.forms[0].sCountryCode.value != 'CA')
			return;
	}
	
	if (!sPostcode || sPostcode == '')
	{
		blankAddressFields();
		return;
	}
	
	setValue("window", "sSelectedPostcode", sPostcode);
	
	/* setup the lookupValueXML variables, DO NOT reorder these fields, as they *
	 * build the innerHTML in the populate Field function in this order.        */
	var sCellName = 'sCity,sCounty,sState,sZipCode,sCountry';
	var sSourceFields = 'PubZipCode,sZipCode=sSelectedPostcode,sCountry=sCountryCode';
	var sDestFields = 'sMultiTown,sMultiCounty,sMultiState,sMultiPostcode,sMultiCountryCode';
	var sScreenIDTo = 'HiddenZipCodes';
	
	/* call lookupValueXML as a multi result return */
	lookupValueXML(sScreenIDTo,sSourceFields,sCellName,sDestFields,'Multi');
}

function populateField(sDestField,sValue)
{
var sMultiValue = new Array();
	
	sMultiValue = sValue.split("||");
	
	// this one is the first one to be populated by each result returned from xml function
	if (sDestField == "sTown")
	{
		document.getElementById('hiddenAddress').innerHTML = "";
		
		// blank out the current global variable
		for (var iField = 0; iField < sAddressLink.length; iField++)
		{
			sAddressLink[iField] = '';
		}
	}
	
	/* if there is only one result then populate the field */
	if (sMultiValue.length == 1)
	{
	    // make sure the country code field is not blanked if no zipcode is found
	    if (sDestField == "sCountryCode" && sMultiValue[0] == "<Not found>")
	    	return;
	    setValue("window", sDestField, sMultiValue[0]);
	    return;
	}
	
	/* loop through the results and build the global variable */
	for (var iResult = 0; iResult < sMultiValue.length; iResult++)
	{
		if (sMultiValue[iResult] != '')
		{
			if (!sAddressLink[iResult] || sAddressLink[iResult] == '')
				sAddressLink[iResult] = sMultiValue[iResult];
			else 
				sAddressLink[iResult] += ", " + sMultiValue[iResult];
		}
	}
	
	// this one is the last one to be populated by each result returned from xml function
	if (sDestField == "sCountryCode")
	{
		// re-build the inner html
		oAddressObj = document.getElementById('hiddenAddress');
		oAddressObj.innerHTML = "";
		for (var iResult = 0; iResult < sMultiValue.length; iResult++)
		{
			if (oAddressObj.innerHTML == '')
				oAddressObj.innerHTML = "Please select an address from the following:";
			oAddressObj.innerHTML += "<br>&nbsp;&nbsp;&nbsp;&nbsp;option " + (iResult + 1).toString() + ") " + 
									 "<a href='javascript:selectAddress(" + iResult + ");' class=textlink>" +
									 sAddressLink[iResult] + 
									 "</a>";
		}
	}
}

function populatePostcodeUS(sDisplayField,sSelectedPostcode)
{
	var sPostcode;
	var iDashpos;
	
	sPostcode = getValue("window", sDisplayField);
	iDashpos = sPostcode.indexOf('-');
	
	if (iDashpos == -1){
		sPostcode = sPostcode.substr(5);
	}else{
		sPostcode = sPostcode.substr(iDashpos + 1);
	}
	sPostcode = sPostcode.replace(/ /, "");
	
	if (sPostcode == ''){
		sPostcode = sSelectedPostcode;
	}else{
		sPostcode = sSelectedPostcode + '-' + sPostcode;
	}
	
	setValue("window", sDisplayField, sPostcode, 1);
}

function disableCounty(bDisable)
{
    // since disabled elements cannot have the value retrieved by the server we enable the 
	// elements again in verify function just before submitting the page
	getElement("window", "sTown").disabled = bDisable;
	getElement("window", "sCounty").disabled = bDisable;
	getElement("window", "sState").disabled = bDisable;
}

function selectAddress(iResult)
{
var sValue;
var sMultiValue = new Array();

	sValue = getValue("window", "sMultiTown");
	sMultiValue = sValue.split("||");
	setValue("window", "sTown", sMultiValue[iResult]);
	
	// don't really need to fill in county as should be the same as the current value
	sValue = getValue("window", "sMultiCounty");
	sMultiValue = sValue.split("||");
	setValue("window", "sCounty", sMultiValue[iResult]);
}

function blankAddressFields()
{
	setValue("window", "sMultiCountryCode", "", true);
	//setValue("window", "sPostcode", "");
	setValue("window", "sSelectedPostcode", "");
	setValue("window", "sMultiPostcode", "");
	document.getElementById('hiddenAddress').innerHTML = "";
	setValue("window", "sTown", "");
	setValue("window", "sMultiTown", "");
	setValue("window", "sCounty", "");
	setValue("window", "sMultiCounty", "");
	setValue("window", "sState", "");
	setValue("window", "sMultiState", "");
}