/*
<!---============================================
Description:
Creation Date:
Created by:
Modified by (add):
20071206 Vinay Zip Code Validation
============================================--->
*/
//if (top.frames.length == 0) 
//top.document.location = "/sorry.cfm"; 

var phone_field_length=0;

function getZip(zip_field,province_field,city_field)	{
	var zip=document.getElementById(zip_field);
	
	if(zip.value.length > 0) {
		// send data to CF
		//DWRUtil.useLoadingMessage();
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'ax_getZip', zip.value, province_field, city_field, getZipResult);
	}
}

// call back function
function getZipResult (r) {
	// set city and state
	var selProv = document.getElementById(r.province_field);
	var txtCity = document.getElementById(r.city_field);
	txtCity.value=r.city;
	
    for (var i = 0 ; i < selProv.options.length ; i++)
        if (selProv.options[i].value == r.state)
            selProv.selectedIndex = i;

}

//20071206: START
function getValidatedZip(zip_field,province_field,city_field)	{
	var zip = document.getElementById(zip_field);
	if(zip.value.length > 0) {
		// send data to CF
		//DWRUtil.useLoadingMessage();
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'ax_getValidatedZip', zip.value, zip_field, province_field, city_field, getValidatedZipResult);
	}
}

// call back function
function getValidatedZipResult (r) {
	var selProv = document.getElementById(r.province_field);
	document.getElementById(r.city_field).value = r.city;// set city
	
    for (var i = 0 ; i < selProv.options.length ; i++){
        if (selProv.options[i].value == r.state)
            selProv.selectedIndex = i;
	}
	if (r.err.length > 0){
		alert(r.err);
		document.getElementById(r.zip_field).value = "";
		document.getElementById(r.zip_field).focus();
	} 
}
//20071206: END

function getShippingDate(date_field, shipping_method_field, zipcode_field, order_id_field, form_name, front_order)	{
	getDeliveryDate(date_field, shipping_method_field, zipcode_field, order_id_field, form_name, 0, front_order)
}

function getArrivalDate(date_field, shipping_method_field, zipcode_field, order_id_field, form_name, front_order)	{
	getDeliveryDate(date_field, shipping_method_field, zipcode_field, order_id_field, form_name, 1, front_order)
}

function getDeliveryDate(date_field, shipping_method_field, zipcode_field, order_id_field, form_name, type, front_order)	{
	var date=document.getElementById(date_field);
	var zipcode=document.getElementById(zipcode_field);
	var order_id=document.getElementById(order_id_field);
	
	// send data to CF
	//DWRUtil.useLoadingMessage();
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'ax_getShippingDate', date.value, zipcode.value, order_id.value, shipping_method_field, form_name, type, front_order,  getShippingDateResult);
}

// call back function
function getShippingDateResult(r) {
	var form = document.getElementById(r.form_name);
	var dates = "";
	var costs = "";
	var x = "";
	var list_date = "";
	var list_cost = "";
	var list_x = "";
	var label = "";
	var name = "";
	
	if(r.err.length > 0) {
		alert(r.err);
	} else {
		dates = r.shipping_date.split(",");
		costs = r.cost.split(",");
		x = r.x.split(",");
		
		for (var i=0;i<form.elements.length;i++) {
			var e = form.elements[i];
			if (e.name == r.shipping_method_field) {
				for (var j=0;j<dates.length;j++) {
					list_date = dates[j].split("|");
					list_cost = costs[j].split("|");
					list_x = x[j].split("|");
					if(list_date[0] == e.value) {
						label = document.getElementById(r.shipping_method_field + "_label_" + list_date[0]);
						
						if(label != null) {
							if(r.shipping_method_field != "shipping_method_id") {
								if(list_date[1].length == 0) {
									label.innerHTML = "Not Available <span style='color: cc0000; font-weight: bold;'>X</span>";
								} else {
									if(list_x[1] == "1")
										label.innerHTML = "Expected shipping date " + list_date[1] + " " + list_cost[1] + " <span style='color: cc0000; font-weight: bold;'>X</span>";
									else
										label.innerHTML = "Expected shipping date " + list_date[1] + " " + list_cost[1];
								}
							// Sorry guys, a complete hack here to repurpose this for the resellers order form
							} else if(r.form_name == "resellerOrderForm") {
								if(list_date[1].length == 0) {
									label.innerHTML = document.getElementById(r.shipping_method_field + "_" + list_date[0]).value + " (n/a <span style='color: cc0000; font-weight: bold;'>X</span>)";
								} else {
									if(list_x[1] == "1")
										label.innerHTML = document.getElementById(r.shipping_method_field + "_" + list_date[0]).value + " (" + r.type + " on " + list_date[1] + " <span style='color: cc0000; font-weight: bold;'>X</span>)";
									else
										label.innerHTML = document.getElementById(r.shipping_method_field + "_" + list_date[0]).value + " (" + r.type + " on " + list_date[1] + ")";
								}
							} else {
								if(list_date[1].length == 0) {
									label.innerHTML = document.getElementById(r.shipping_method_field + "_" + list_date[0]).value + " (" + list_cost[1] + " n/a <span style='color: cc0000; font-weight: bold;'>X</span>)";
								} else {
									if(list_x[1] == "1")
										label.innerHTML = document.getElementById(r.shipping_method_field + "_" + list_date[0]).value + " (" + list_cost[1] + " " + r.type + " on " + list_date[1] + " <span style='color: cc0000; font-weight: bold;'>X</span>)";
									else
										label.innerHTML = document.getElementById(r.shipping_method_field + "_" + list_date[0]).value + " (" + list_cost[1] + " " + r.type + " on " + list_date[1] + ")";
								}
							}
						}
						break;
					}
				}
			}
		}
	}
}

function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
				next_field.select();
			}
		}
	}
}

function setTimeFormat(txtBox){
	if(txtBox.value.length == 2){
		if (txtBox.value >= 0 && txtBox.value <= 12){
			txtBox.value = txtBox.value + ":";
		} else {
			alert('Time format incorrect. Please use 24 Hour format.');
			txtBox.value = '';
			txtBox.focus();
		}
	}else if(txtBox.value.length == 5){
		if (txtBox.value.substring(5,3) >= 0 && txtBox.value.substring(5,3) <= 59){
		} else {
			alert('Minute setting incorrect. Please try again.');
			txtBox.value='';
			txtBox.focus();
		}	
	}	
}

function timeCheck(txtBox){	
	if (txtBox.value.length < 5 && txtBox.value.length > 0){
		alert('Time setting incorrect. Please try again.');
		txtBox.value='';
		txtBox.focus();
	}  
}

function GeneratePassword() {
    if (parseInt(navigator.appVersion) <= 3) {
        alert("Sorry this only works in 4.0+ browsers");
        return true;
    }
    var length=8;
    var sPassword = "";
    length = 6;
    var noPunction = "checked";
    var randomLength = "";
    if (randomLength) {
        length = Math.random();
        length = parseInt(length * 100);
        length = (length % 7) + 6
    }

    for (i=0; i < length; i++) {
        numI = getRandomNum();
        if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }
        sPassword = sPassword + String.fromCharCode(numI);
		
    }
    document.client.client_password.value = sPassword
    return true;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function getRandomNum() {
    // between 0 - 1
    var rndNum = Math.random()
    // rndNum from 0 - 1000
    rndNum = parseInt(rndNum * 1000);
    // rndNum from 33 - 127
    rndNum = (rndNum % 94) + 33;
    return rndNum;
}

function checkPunc(num) {
    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }
    return false;
}

function checkGroup(check, name){
	var form = check.form;
	var checked = check.checked;
	
	for(var i=0;i<form.elements.length;i++) {
		var e = form.elements[i];
		if(e.name == name) {
			e.checked = checked;
		}
	}
}

function checkGroupByValue(check, name){
	var form = check.form;
	var checked = check.checked;
	var ids_search = "," + check.value + ",";
	
	for(var i=0;i<form.elements.length;i++) {
		var e = form.elements[i];
		if(e.name == name && ids_search.indexOf("," + e.value + ",") >= 0) {
			e.checked = checked;
		}
	}
}

function checkGroupIDs(check, name, ids){
	var form = check.form;
	var checked = check.checked;
	var idsArray = ids.split(",");
	
	for(var i=0;i<form.elements.length;i++) {
		var e = form.elements[i];
		if(e.name == name) {
			for(var j=0;j<idsArray.length;j++) {
				if(e.value == idsArray[j]) {
					e.checked = checked;
					break;
				}
			}
		}
	}
}

function checkAll(elementName){
     var boolValue = elementName.checked;
     for (var i=0;i<document.orderList.elements.length;i++)
     {
       var e = document.orderList.elements[i];
       if (e.name != elementName.name)
         e.checked = boolValue;
     }
}

function formatCurrency(num) {

	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))+','+	//Min removed Jun 01, 2004
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}


function show(obj)
{	
	if(!document.all && document.getElementById) {
		if(document.getElementById(obj)) document.getElementById(obj).style.display='';
	}else {
        	if(document.all[obj]) document.all[obj].style.display='';
	}
}

function hide(obj)
{
	if(!document.all && document.getElementById) {
		if(document.getElementById(obj)) document.getElementById(obj).style.display='none';
	}
	else {	
		if(document.all[obj]) document.all[obj].style.display='none';
	}
}

function hide(id, flag) {
	if(flag == 1) {
		document.getElementById("p_" + id).className = "show";
		document.getElementById("c_" + id).className = "hide";
		document.getElementById("e_" + id).className = "show";
	} else {
		document.getElementById("p_" + id).className = "hide";
		document.getElementById("c_" + id).className = "show";
		document.getElementById("e_" + id).className = "hide";
	}
}

function ccwin(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=230,height=180;,directories=no,status=no,scrollbars=no,resize=no,menubar=no" )
}
function newin1(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=500,height=350,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no" )
}
function newin2(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=700,height=600,directories=no,status=no,scrollbars=yes,resizable=no,menubar=no" )
}
function newin3(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=500,height=200,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no" )
}
function newin4(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=200,height=120,left=790,top=200,directories=no,status=no,scrollbars=no,resizable=no,menubar=no" )
}
function newin5(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=500,height=100,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no" )
}
function newin6(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=500,height=600,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no" )
}
function newin7(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=695,height=650,directories=no,status=no,scrollbars=yes,resizable=no,menubar=no" )
}
function newin8(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=420,height=200;,directories=no,status=no,scrollbars=no,resize=no,menubar=no" )
}
function newin9(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=700,height=400;,directories=no,status=no,scrollbars=yes,resize=no,menubar=no" )
}
function newin10(url)
{
newWindow = window.open(url,"NewWindow","toolbar=no,width=700,height=800,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no" )
}
// Set the horizontal and vertical position for the popup
PositionX = 400;
PositionY = 100;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)
defaultWidth  = 500;
defaultHeight = 500;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows
var AutoClose = true;

if (parseInt(navigator.appVersion.charAt(0))>=4){
var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;
function popImage(imageURL,imageTitle){
if (isNN){imgWin=window.open('about:blank','',optNN);}
if (isIE){imgWin=window.open('about:blank','',optIE);}
with (imgWin.document){
writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
writeln('width=250-(document.body.clientWidth-document.images[0].width);');
writeln('height=105-(document.body.clientHeight-document.images[0].height);');
writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
writeln('window.innerWidth=document.images["Min"].width;');writeln('window.innerHeight=document.images["Min"].height;}}');
writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
if (!AutoClose) writeln('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
else writeln('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
writeln('<img name="Min" src="'+imageURL+'" style="display:block"></body></html>');
close();		
}}

// for subscribe/unsubscribe
function emailCheck (emailStr) {
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
    alert("Email address seems incorrect (check @ and .'s)");
    return false;
}
var user=matchArray[1];
var domain=matchArray[2];
if (user.match(userPat)==null) {
    alert("The username doesn't seem to be valid.");
    return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
      for (var i=1;i<=4;i++) {
        if (IPArray[i]>255) {
            alert("Destination IP address is invalid!");
        return false;
        }
    }
    return true;
}
var domainArray=domain.match(domainPat);
if (domainArray==null) {
    alert("The domain name doesn't seem to be valid.");
    return false;
}
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if ((domArr[domArr.length-1] != "info") &&
    (domArr[domArr.length-1] != "name") &&
    (domArr[domArr.length-1] != "arpa") &&
    (domArr[domArr.length-1] != "coop") &&
    (domArr[domArr.length-1] != "aero")) {
        if (domArr[domArr.length-1].length<2 ||
            domArr[domArr.length-1].length>3) {
                alert("The address must end in a three-letter domain, or two letter country.");
                return false;
        }
}
if (len<2) {
   var errStr="This address is missing a hostname!";
   alert(errStr);
   return false;
}
return true;
}
function UPTvalidateform(thisform){
	if (emailCheck(thisform.email.value)){	

        if (document.getElementById('unsubscribe') 
            && !document.getElementById('unsubscribe').checked) {
		    
        } else {
            
        }
		return false;
	}else{
		return true;
	}
}

function removeGhost(obj, className) {
	
	if(obj.className != className) {
		obj.value = "";
		obj.className = className;
	}
	
}

function checkGhost(obj, className, msg) {
	
	if(obj.value.length == 0) {
		obj.className = className;
		obj.value = msg;
	}
	
}

function Right(str, n){
	if (n <= 0)     // Invalid bound, return blank string
    	return "";
	else if (n > String(str).length)   // Invalid bound, return
    	return str;                     // entire string
	else { // Valid bound, return appropriate substring
    	var iLen = String(str).length;
    	return String(str).substring(iLen, iLen - n);
 	}
}
