//******************************************
// GENERIC FUNCTIONS
//******************************************

// Numeric check
function numericCheck(objTextbox,message){
	if (isNaN(dojo.byId(objTextbox).value))
	{
		alert(message);
		dojo.byId(objTextbox).focus();
		return false;
	}else{
		return true;
	}
}

// Highlight the current row selected
function highlight(key)
{
	document.getElementById(key).style.background='#FAFAFA';
}

// Un-highlight the row
function unhighlight(key)
{
	document.getElementById(key).style.background='#ECECEC';	
}	
	
// Checks the checkbox for its value and sets a var to be passed to setFlag()
function updateStatus(obj, id, url, formType)
{	
	if(obj.checked)
	{
		value=1;
	}else{
		value=0				
	}
	setFlag(id, value, url, formType);			
}

// Sets the active flag in the database to the appropriate value
function setFlag(id, value, url, formType)
{
	dojo.xhrGet( {
		url: 		"/main/" + url,
		content: 	{form_type: formType, id: id, value: value}, 
		handleAs:	"json",
		sync:		true,
		timeout: 10000,

		load: dojo.hitch(this, function(response, ioArgs) {
			return response;
		}),

		error: function(response, ioArgs) {		
			console.error("HTTP status code: ", ioArgs.xhr.status);
		}
	});		
}

// Prevents <script> tags from being allowed in a text input
function blockScript(val,form)
{
	if(val.search(/<scr/i) > -1)
	{
		alert ('SCRIPT tags are not allowed');
		return false;
	}else{
		form.submit();
		return true;
	}
}

// ???
function changeItems(myForm, SelCat) 
{
	if (SelCat == -1 || !SelCat) 
	{
		alert("A Group Must Be Selected.");
		return 0;
	}
	myForm.submit();
	return true;
}


//Checks for selected value in copy lists
function checkCopyList(selList,form)
{
	if (document.getElementById(selList).value == '')
	{
		alert("Please Select Items");
		return false;
	}else{
		document.getElementById(form).submit();
		return true;
	}
}


// Validates domain name format
function checkDomain(nname)
{
	var arr = new Array(
	'.com','.net','.org','.biz','.coop','.info','.museum','.name',
	'.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
	'.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
	'.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
	'.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
	'.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
	'.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
	'.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
	'.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
	'.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
	'.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
	'.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
	'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
	'.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
	'.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
	'.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
	'.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
	'.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
	'.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
	'.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
	'.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
	'.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
	'.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
	'.wf','.ye','.yt','.yu','.za','.zm','.zw');
		
	var mai = nname;
	var val = true;
	var dot = mai.lastIndexOf(".");
	var dname = mai.substring(0,dot);
	var ext = mai.substring(dot,mai.length);

	if(dot>2 && dot<57)
	{
		for(var i=0; i<arr.length; i++)
		{
	  		if(ext == arr[i])
	  		{
	 			val = true;
				break;
	  		}else{
	 			val = false;
	  		}
		}
		if(val == false)
		{
	  		alert("Your domain extension "+ext+" is not correct");
		 	return false;
		}else{
			for(var j=0; j<dname.length; j++)
			{
				var dh = dname.charAt(j);
				var hh = dh.charCodeAt(0);
				if((hh > 47 && hh<59) || (hh > 64 && hh<91) || (hh > 96 && hh<123) || hh==45 || hh==46)
				{
					if((j==0 || j==dname.length-1) && hh == 45)	
					{
						alert("Domain name should not begin are end with '-'");
						return false;
					}
				}else{
			 		alert("Your domain name should not have special characters");
					return false;
				}
			}
		}
	}else{
		alert("Your Domain name is too short/long");
		return false;
	}	
	return true;
}

// Validator for the search function
function checkSearch(theForm) {
	if (dojo.byId('search_text').value == "") {
		alert('Please enter search criteria.');
		dojo.byId('search_text').focus();
		return false;	
	}else{
		dojo.byId('search_form').submit();
		return true;
	}
}

function clearStates( objectname, message ) 
{
	objectname.options.length = 0;
	var optionName = new Option(message , "ZZ", false, false);
	objectname.options[0] = optionName;
}

function ConfirmDelete(url, message)
{
	var agree = confirm(message);
	if (agree)
	{
		top.location.replace (url);
		return true;
	} else {
		return false ;
	}
}

function ConfirmDeleteForm(form, message)
{
	var agree = confirm(message+'\n\nWARNING: This action cannot be undone.');
	if (agree)
	{
		document.getElementById(form).submit();
		return true;
	} else {
		return false ;
	}
}

function cursor_clear() 
{
	document.body.style.cursor = 'default';
}

function cursor_hand() 
{
  document.body.style.cursor = 'pointer';
}

function cursor_wait() 
{
	document.body.style.cursor = 'wait';
}

function displayPopUpText(message) 
{   
	alert(message);
}

function displayWindow(url, width, height, label) 
{
	if (!label)
	{
		label = "new_window";
	}
	LeftPosition = (screen.availWidth) ? (screen.availWidth-width)/2 : 0;
	TopPosition = (screen.availHeight) ? (screen.availHeight-height)/2 : 0;
	window.open(url,label,'width=' + width + ',height=' + height + ',resizable=yes,scrollbars=yes,menubar=no,status=no,left=' + LeftPosition + ',top=' +TopPosition);
}

function displayWindowResize(url, width, height, label) 
{
	if (!label) 
	{
		label = "new_window";
	}
	LeftPosition = (screen.availWidth) ? (screen.availWidth-width)/2 : 0;
	TopPosition = (screen.availHeight) ? (screen.availHeight-height)/2 : 0;
	
	window.open(url, label.replace(/\s/, '') ,'width=' + width + ',height=' + height + ',resizable=yes,scrollbars=yes,menubar=no,status=no,left=' + LeftPosition + ',top=' +TopPosition);
}

function DLayer(id,d) 
{
	var obj;
	if (!d) 
	{
		d=document;
	}
	if (d.all && (obj=d.all[id]) || d.layers && (obj=d.layers[id]) || d.getElementById && (obj=d.getElementById(id))) 
	{
		obj.setVisibility = setVisibility;
	}
	else if (d.layers) 
	{
		for(var i=0;i<d.layers.length;i++) 
		{
			if((obj = DLayer(id,d.layers[i].document))) 
			{
				break;
			}
		}
	}
	return obj;
}

function Email_Validator(theForm)
{
	if (dijit.byId('email_address').value == "")
	{
		alert("Please enter a value for the \"Email\" field.");
		dijit.byId('email_address').focus();
		return (false);
	}
	// test if valid email address, must have @ and .
	var checkEmail = "@.";
	var checkStr = dijit.byId('email_address').value;
	var EmailValid = false;
	var EmailAt = false;
	var EmailPeriod = false;
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkEmail.length;  j++)
		{
			if (ch == checkEmail.charAt(j) && ch == "@")
			{
				EmailAt = true;
			}
			if (ch == checkEmail.charAt(j) && ch == ".")
			{
				EmailPeriod = true;
			}
			if (EmailAt && EmailPeriod)
			{
				break;
			}
			if (j == checkEmail.length)
			{
				break;
			}
		}
		// if both the @ and . were in the string
		if (EmailAt && EmailPeriod)
		{
			EmailValid = true;
			break;
		}
	}
	if (!EmailValid)
	{
		alert("The \"email\" field must contain an \"@\" and a \".\".");
		dijit.byId('email_address').focus();
		return (false);
	}
	return (true);
}

function formatNumber(number, format, print) 
{  // use: formatNumber(number, "format")
	var separator = ",";  // use comma as 000's separator
	var decpoint = ".";  // use period as decimal point
	var percent = "%";
	var currency = "$";  // use dollar sign for currency
	
	if (print)
	{ 
		document.write("formatNumber(" + number + ", \"" + format + "\")<br>");
	}
		
	if (number - 0 != number){
		return null;  // if number is NaN return null
	}
	var useSeparator = format.indexOf(separator) != -1;  // use separators in number
	var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
	var useCurrency = format.indexOf(currency) != -1;  // use currency format
	var isNegative = (number < 0);
	number = Math.abs (number);
	if (usePercent){
		number *= 100;
	}
	format = strip(format, separator + percent + currency);  // remove key characters
	number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
    	var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      	nrightEnd = nrightEnd.substring(0, srightEnd.length);
      	if (nextChar >= 5){
      		nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up
      	}
		// patch provided by Patti Marcoux 1999/08/06
    	while (srightEnd.length > nrightEnd.length) {
        	nrightEnd = "0" + nrightEnd;
      	}

      	if (srightEnd.length < nrightEnd.length) {
        	nrightEnd = nrightEnd.substring(1);
        	nleftEnd = (nleftEnd - 0) + 1;
      	}
    } else {
      	for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        	if (srightEnd.charAt(i) == "0"){
        		nrightEnd += "0";  // append zero to RHS of number
        	}else{
        		break;
        	}
      	}
    }

    // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
    	nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator){
    	nleftEnd = separate(nleftEnd, separator);  // add separator
    }
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
	return output;
}

function getDate(name,theForm) 
{
	mywindow = window.open('', 'calendar', 'width=200,height=200,top=100,left=100');
	mywindow.location.href = 'calendar.php?f=' + name + '&theForm=' + theForm + '&n=0';
	mywindow.focus();
}
	
// THE FOLLOWING TWO FUNCTIONS NEED TO BE COMBINED
// BOTH ARE CALLED THROUGHOUT THE SYSTEM
function IsNumeric(strString)
{
   	//  check for valid numeric strings	
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;
	if (strString.length == 0)
	{
		return false;
	}

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
	   	if (strValidChars.indexOf(strChar) == -1)
	    {
	    	blnResult = false;
	    }
	}
	return blnResult;
}

function is_numeric(the_field)
{
	var checkOK = "0123456789";
	var checkStr = the_field;
	var allValid = true;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		{
			if (ch == checkOK.charAt(j))
			{
				break;
			}
			if (j == checkOK.length)
			{
				allValid = false;
				break;
			}
			if (ch != ",")
			{
				allNum += ch;
			}
		}
	}
	return allValid;
}

function IsPercentage(strString)
{
	//  check for valid numeric strings	
   	var strValidChars = "0123456789.";
   	var strChar;
   	var blnResult = true;
	if (strString.length == 0) 
	{
		return false;
	}
	//  test strString consists of valid characters listed above
   	for (i = 0; i < strString.length && blnResult == true; i++)
    {
    	strChar = strString.charAt(i);
      	if (strValidChars.indexOf(strChar) == -1)
        {
        	blnResult = false;
        }
	}
   	return blnResult;
}

function Jump(s) 
{
	var d = s.options[s.selectedIndex].value;
	location.href = d;
	s.selectedIndex=0;
} 

function LimitAttach() 
{
	var LimitAttachField;
	var extArray = new Array(".bmp", ".doc", ".eps", ".gif", ".jpeg", ".jpg", ".pdf", ".psd", ".png", ".tif", ".tiff", ".xls", ".txt");
	var form = LimitAttachField.form;
	var file = LimitAttachField.value;
	var allowSubmit = false;
	while (file.indexOf("\\") != -1) 
	{
		file = file.slice(file.indexOf("\\") + 1);
		ext = file.slice(file.indexOf(".")).toLowerCase();
	}
	for (var i = 0; i < extArray.length; i++) 
	{
		if (extArray[i] == ext) 
		{ 
			allowSubmit = true; break; 
		}
	}
	if (!allowSubmit) 
	{
		alert("You may upload only files that end in types:  " 	+ (extArray.join("  ")) + "\nPlease select a new file to upload and submit again.");
		return false;
	}
	return true;
}

function NewWindow(image_in, name, w, h, scroll) 
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable='+false+'';
	var win = window.open(image_in, name, winprops);
	if (parseInt(navigator.appVersion) >= 4)
	{ 
		win.window.focus(); 
	}
}

function openDetails(imageid) 
{
	var theURL = "imagedetails.php?imageid=" + imageid;
	window.open(theURL,"detailsWindow",'width=1100,height=750,resizable=no,scrollbars=yes,menubar=no,status=no,left=0,top=0');
}

function openTxtEditor(imageid) 
{
	var theURL = "TxtEditor.php?imageid=" + imageid;
	window.open(theURL,"TxtEditorWindow",'width=750,height=550,resizable=yes,scrollbars=yes,menubar=no,status=no,left=0,top=0');
}

function openWindow(url,width,height)
{
	var w = window.open (url, "win", 'height='+height +' ,width='+width + ' scrollbars=yes');
}

function openWindow_scroll(url,width,height, name) 
{ 
	if (!name)
			name = 'new_window';
	var w = window.open (url, name, 'height='+height +' ,width='+width +', scrollbars=yes, resizable=1, status=1'); 
}

function print_r(theObj)
{
	if(theObj.constructor == Array || theObj.constructor == Object)
	{
		document.write("<ul>");
	    for(var p in theObj)
	    {
	    	if(theObj[p].constructor == Array || theObj[p].constructor == Object)
	    	{
				document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
	        	document.write("<ul>");
	        	print_r(theObj[p]);
	        	document.write("</ul>");
	      	} else {
				document.write("<li>["+p+"] => "+theObj[p]+"</li>");
	      	}
	    }
		document.write("</ul>");
	}
}

function replaceSelValues (objectname, valuearray, message, curselection) 
{
	var t_state = new Array();
	objectname.options.length = 0;
	if (!message) 
	{
		message = "---Select---";
	}
	var optionName = new Option( message, "ZZ", false, false);
	objectname.options[0] = optionName;
	for (var i=0; i<valuearray.length; i++) 
	{
		t_state[0] = stringSplit ( valuearray[i], ',' );
		var length = objectname.length;
		if (curselection == t_state[0][1] ) 
		{
			var optionName = new Option(t_state[0][0], t_state[0][1], true, true);
		} else {
			var optionName = new Option(t_state[0][0], t_state[0][1], false, false);
		}
    	objectname.options[length] = optionName;
	}
	objectname.disabled = false;
}

function separate(input, separator) {  // format input using 'separator' to mark 000's
	input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
    	if (i != 0 && (input.length - i) % 3 == 0){
      		output += separator;
      	}
    	output += input.charAt(i);
    }
    return output;
}

function setVisibility(visibility) 
{
	var obj = this.style?this.style:this;
	obj.visibility = visibility;
}

function showDialog(item_id, base_path, type, preview)
{
	var dialog;
	switch (type)
	{
		case 'details':
			dialog = new rsi.itemDetails(
			{
				debug:		1,
				item_id:	item_id,
				base_path:	'http://'+base_path,
				preview:	preview
			});
			break;
			
		case 'version':
			dialog = new rsi.itemVersion(
			{
				debug:		1,
				item_id:	item_id,
				base_path:	'http://'+base_path
			});
			break;
	}
	dialog.show();
}

function showHistoryDialog(order_id,view)
{
	var dialog = new rsi.orderDetails(
	{
		debug:		1,
		order_id:	order_id,
		view:		view
	});
	
	dialog.show();
}

function showPaymentDialog(order_id,item_id,amount,company_id,trans,user_id,pay_item,cvv)
{
	// Type 0 = item payment
	// Type 1 = handling payment
	// Type 2 = shipping payment
	// Type 3 = tax payment
	var frm_id = Math.floor(Math.random()*100000);
	var dialog = new rsi.paymentDetails(
	{
		debug:		1,
		order_id:	order_id,
		item_id:	item_id,
		amount:		amount,
		company_id: company_id,
		trans:		trans,
		user_id:	user_id,
		frm_id:		frm_id,
		pay_item:	pay_item,
		cvv:		cvv
	});
	
	dialog.show();
}

function showPrevCustDialog(item_id,item_name,company,user){
	var dialog = new rsi.previousCustomizations(
	{
		debug:		1,
		item_id:	item_id,
		item_name:	item_name,
		user_id:	user,
		company_id:	company
	});
	
	dialog.show();
}

function stringSplit ( string, delimiter ) 
{ 
    if ( string == null || string == "" ) 
    { 
        return null; 
    } 
    else if ( string.split != null ) 
    { 
        return string.split ( delimiter ); 
    } else { 
        var ar = new Array(); 
        var i = 0; 
        var start = 0; 
        while( start >= 0 && start < string.length ) 
        { 
             var end = string.indexOf( delimiter, start ) ; 
             if( end >= 0 ) 
             { 
                 ar[i++] = string.substring( start, end ); 
                 start = end+1; 
             } else { 
                 ar[i++] = 
                 string.substring( start, string.length ); 
                 start = -1; 
             } 
        } 
        return ar; 
    } 
} 

function strip(input, chars) 
{  // strip all characters in 'chars' from input
	var output = "";  // initialise output string
  	for (var i=0; i < input.length; i++){
    	if (chars.indexOf(input.charAt(i)) == -1){
      		output += input.charAt(i);
   		}
   	}
	return output;
}

function switchMenu(obj) 
{
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) 
	{
		el.style.display = 'none';
	} else {
		el.style.display = '';
	}
}

function switchVisible(obj) 
{
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) 
	{
		el.style.display = 'none';
	} else {
		el.style.display = '';
	}
}

function testForEnter(e) 
{    
	var key;
	if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox      

     return (key != 13);
} 

function toggle_row(chk_box,item_id, old_sytle) 
{
	var tmp = document.getElementById(item_id);
	if (chk_box.checked) 
	{
		tmp.className='RowSelected';
	} else {
		tmp.className=old_sytle;
	}
}

function trim(field)
{
   	str = field.value;
	field.value = str.replace(/^\s*|\s*$/g,"");
}

function uploadImages(myForm) 
{
	if (myForm.image_upload_0_file.value.length == 0) 
	{
		alert("At Least One File Must Be Uploaded.");
		return 0;
	} 
	myForm.submit();
	return 1;
}

function validate_number(obj, min_field, max_field) 
{  
	if (!IsNumeric(obj.value)) 
	{
		alert("Only numbers are allowed in this field.");
		obj.value = 0;
		obj.focus();
	}
}

function validate_percentage(obj, lowval, hival) 
{  
	if (IsPercentage(obj.value)) 
	{
 		if ((parseFloat(obj.value) < 0.0) || (parseFloat(obj.value) > parseFloat(hival))) 
 		{   
			alert("Please enter a value between " + lowval + " and " + hival);
			obj.value = hival;
			obj.focus();
		}
	}else{
		alert("Please enter a value between " + lowval + " and " + hival);
		obj.value = lowval;
		obj.focus();
	}
}

function verifyAddressFormSimple() 
{
	var objForm = dojo.byId("frmShipAddr");
	message = "You must enter ";
    with (objForm) {
        if (txtContactName.value.length == 0) 
        { 
        	alert(message + "a contact name."); 
        	txtContactName.focus(); 
        	return false; 
        }
        if (txtAddress1.value.length == 0) 
        { 
        	alert(message + "an address."); 
        	txtAddress1.focus(); 
        	return false; 
        }
        if (txtCity.value.length == 0) 
        { 
        	alert(message + "a city."); 
        	txtCity.focus(); 
        	return false; 
        }
        if (selState.options[selState.selectedIndex].value == "ZZ") 
        { 
        	alert(message + "a state."); 
        	selState.focus(); 
        	return false; 
        }
        if (txtPostalCode.value.length == 0) 
        { 
        	alert(message + "a zip or postal code."); 
        	txtPostalCode.focus(); 
        	return false; 
        }
        if (selCountry.options[selCountry.selectedIndex].value == "ZZ") 
        { 
        	alert(message + "a country."); 
        	selState.focus(); 
        	return false; 
        }
        submit();
        return true;
    }    
}

function verifyDelete(Message,DeletePage) 
{
	if(confirm(Message)) 
	{
		location.replace(DeletePage);
		return true;
	}else{
		return false;
	}
}

// this function exists in different forms on several pages in the system. I think only one page calls this exact function
function verifyForm(theForm) 
{
	theForm.submit();
}



//*************************************************
//NEW RETAIL VIEW FUNCTIONS
//*************************************************

function processSelector(id, type)
{
	var box = new dijit.Dialog({title: 'Get Started', style: "width:500px; height:300px"});
	switch(type)
	{
		case "hybrid":
			box.setHref('/main/views/dialogs/process_selector_3.php?id=' +id);
		break;
		case "template":
			box.setHref('/main/views/dialogs/process_selector_2.php?id=' +id);
		break;
		case "upload":
			box.setHref('/main/views/dialogs/process_selector_1.php?id=' +id);
		break;
		default:
			box.setHref('/main/views/dialogs/process_selector_3.php?id=' +id);
		break;
	}
	box.show();
}

function addAddress(id, user)
{
	var box = new dijit.Dialog({title: 'Add Destination', style: "width:450px; height:550px"});
	box.setHref('/main/views/dialogs/add_address.php?type=add&key=' +id+ '&user='+user);
	box.startup();						
	box.show();
}

function checkUpdateAllShippingR(theForm) {
	//if (document.frmAllShipping.chkUpdateAllShipping.checked) {
	//	theForm.hdnAllShipping.value = true;
	//}
	theForm.submit();
}

function compareQuantities(mQty,pQty)
{
	if (parseInt(mQty.value) > parseInt(document.getElementById(pQty).value))
	{
		document.getElementById('qtyAlertDiv').style.display = '';
		var opts = document.getElementById(pQty).options;
		var x = 0;
		for ( var i in opts )
		{
			thisVal = opts[i].value;
			if (opts[i].value >= mQty.value){
			   opts.selectedIndex = i;
			   var x = 1;
			   break;
			}
		}
		if (x == 0)
		{
			document.getElementById('qtyAlertDiv').style.display = 'none';
			document.getElementById('qtyOverDiv').style.display = '';
			mQty.value = 0;
		}
	}else{
		document.getElementById('qtyAlertDiv').style.display = 'none';
		document.getElementById('qtyOverDiv').style.display = 'none';
	}
	return true;
}

function deActivateMailList(id, list_name, type) 
{
	var answer = confirm("Are you sure you want to delete "+list_name);
	
	if (answer) {	
		dojo.xhrGet(
		{
			url: 		"deleteUtility.php?mail_list_id="+id+"&type="+type,
			timeout:	50000,
			handleAs:	"text",
					
			load: function(response, ioArgs)
			{		
				var row = document.getElementById(id);
				row.parentNode.removeChild(row);; 
			},
			
			error: function(response, ioArgs)
			{
				alert("An error occured when removing your file.");
			}
		});

		return;
	}else{
		return 0;
	}
}

function editAddress(key, d, user, addr)
{
	var box = new dijit.Dialog({title: 'Edit Shipping Address', style: "width:450px; height:550px"});
	box.setHref('/main/views/dialogs/add_address.php?type=edit&key=' +key+ '&d=' +d+ '&user='+user+'&addr='+addr);
	box.startup();						
	box.show();
}

function launchCalendar(type,item) 
{
	switch (type){
		case "mailing":
			window.open("views/mailing/mailing_cal.php?item="+item, "mailing_date", "width=220,height=200");
		break;
		case "event":
			window.open("views/mailing/event_cal.php", "event_date", "width=220,height=200");
		break;
	}
	
}

function setPostageCost(type) 
{
	switch (type.value){
		case "first_class":
			document.getElementById('postage_cost').value = 0.36;
		break;
		case "standard":
			document.getElementById('postage_cost').value = 0.26;
		break;
		case "non-profit":
			document.getElementById('postage_cost').value = 0.15;
		break;
	}
	
}

function toggleDisplay(i) {
	document.getElementById(i).style.visibility = "visible";
	if(document.getElementById(i).style.display == "none" ) {
		document.getElementById(i).style.display = "";
	}
	else {
		document.getElementById(i).style.display = "none";
	}
}

function unmailedActions(objSelect,key,formType,remaining)
{
	 var strOption = objSelect.value;
	 switch (strOption)
	 {
	 	case "pickup":
			document.getElementById('pickupRow_'+key).style.display = "";
			document.getElementById('recycleRow_'+key).style.display = "none";
			document.getElementById('shipExtras_'+key).style.display = "none";
 		break;
	 	case "recycle":
	 		document.getElementById('pickupRow_'+key).style.display = "none";
			document.getElementById('recycleRow_'+key).style.display = "";
			document.getElementById('shipExtras_'+key).style.display = "none";
	  	break;
	 	case "ship":
	 		document.getElementById('pickupRow_'+key).style.display = "none";
			document.getElementById('recycleRow_'+key).style.display = "none";
			document.getElementById('shipExtras_'+key).style.display = "";
	  	break;
	 }
}

function updateAddressQty(qty_field, addresses, key, max_quantity, frm_name)
{
	var thisQty = dojo.byId(qty_field).value;
	var intTotal = 0;
	var intAddr = addresses - 1;
	for (i=0;i<=intAddr;i++)
	{
		intTotal = intTotal + parseInt(dojo.byId('qty_'+key+'_'+i).value);
	}
	if (thisQty > max_quantity){
		alert('Please check your quantities');
		dojo.byId('btn_checkout').style.display = "none";
		return false;
	}else{
		if (intTotal != max_quantity){
			dojo.byId(frm_name).submit();
			dojo.byId('btn_checkout').style.display = "none";
			return false;
		}else{
			dojo.byId(frm_name).submit();
			dojo.byId('btn_checkout').style.display = "";
			return true;
		}
	}
}

function updateFields(objSelect)
{
	var strAddress = objSelect.value;
	var arrAddress = strAddress.split('|');
	dojo.byId('txtContactName').value = arrAddress[0];
	dojo.byId('txtCompanyName').value = arrAddress[1];
	dojo.byId('txtAddress1').value = arrAddress[2];
	dojo.byId('txtAddress2').value = arrAddress[3];
	dojo.byId('txtAddress3').value = arrAddress[4];
	dojo.byId('txtCity').value = arrAddress[5];
	dojo.byId('selState').value = getStateByAbbr(arrAddress[6]);
	//dojo.byId('selState').attr('displayedValue',arrAddress[6]);
	//dojo.byId('selState').attr('value',arrAddress[6]);
	//dojo.attr(dojo.byId("selState"),"value",arrAddress[6]);
	dojo.byId('txtPostalCode').value = arrAddress[7];
	//dojo.byId('selCountry').value = arrAddress[8];
	dojo.byId('selState').focus();
	dojo.byId('txtemail_address').focus();
	return true;
}

function updateJobName(key,curname)
{
	var box = new dijit.Dialog({title: 'Edit Job Name', style: "width:325px; height:100px"});
	box.setHref('/main/views/dialogs/name_project.php?key=' +key+ '&curname='+curname);		
	box.startup();			
	box.show();
}

function updateQuantity(formname)
{
	document.getElementById(formname).submit();
}

function validateFile()
{
	var form = document.getElementById("upload_list");
	
	if (document.getElementById("mailing_list_file").value == '')
	{
		alert("Please browse for a file");
	}else{
		form.submit();
	}
}

function verifyBoxChecked(url,box,message)
{
	if (document.getElementById(box).checked == false){
		alert(message);
		return false;
	}else{
		window.location.href=url;
		return true;
	}
}


//*************************************************
// USER PROFILE FUNCTIONS
//*************************************************

function addUserToGroup() {
	selUsersLen = document.frmProfileSecurity.selUsers.length ;
	for ( i=0; i<selUsersLen ; i++){
        if (document.frmProfileSecurity.selUsers.options[i].selected == true ) {
            selUsersInGroupLen = document.frmProfileSecurity.selUsersInGroup.length;
            document.frmProfileSecurity.selUsersInGroup.options[selUsersInGroupLen]= new Option(document.frmProfileSecurity.selUsers.options[i].text, document.frmProfileSecurity.selUsers.options[i].value);
        }
    }

    for ( i = (selUsersLen -1); i>=0; i--){
        if (document.frmProfileSecurity.selUsers.options[i].selected == true ) {
            document.frmProfileSecurity.selUsers.options[i] = null;
        }
    }
}

function removeUserFromGroup() {
    selUsersInGroupLen = document.frmProfileSecurity.selUsersInGroup.length ;
       for ( i=0; i<selUsersInGroupLen ; i++){
           if (document.frmProfileSecurity.selUsersInGroup.options[i].selected == true ) {
               selUsersLen = document.frmProfileSecurity.selUsers.length;
               document.frmProfileSecurity.selUsers.options[selUsersLen]= new Option(document.frmProfileSecurity.selUsersInGroup.options[i].text, document.frmProfileSecurity.selUsersInGroup.options[i].value);
           }
       }
       for ( i=(selUsersInGroupLen-1); i>=0; i--) {
           if (document.frmProfileSecurity.selUsersInGroup.options[i].selected == true ) {
               document.frmProfileSecurity.selUsersInGroup.options[i] = null;
           }
       }
}


	
//******************************************	
// SHOPPING CART FUNCTIONS
//******************************************

function checkAddressCount(addressCount,rsa) 
{
	if (addressCount == 0) {
		alert("You must ship this order to at least one address.");
		return;
	}
	document.location.href = "mrc_cart.php?form_type=order_review&rsa=" +rsa;
}

function checkUpdateAllShipping(theForm) {
	if (document.frmAllShipping.chkUpdateAllShipping.checked) {
		theForm.hdnAllShipping.value = true;
	}
	theForm.submit();
}

function checkaddressQuantity(item_field, max_quantity, address_key, frm_name, current_value) {
	var field_name = item_field.name;
	
	if (!IsNumeric(item_field.value)){
		alert (item_field.value + ' must be a number between 1 and ' + max_quantity);
		item_field.value = 0;
		return false;
	} else {
		if (current_value >= item_field.value) {
			
			
		} else {
			if ((max_quantity + current_value) < item_field.value) {
				//alert (item_field.value + ' is more than currently available: ' + max_quantity );
				item_field.value = current_value;
				return false;
			}
		}
		
		
		
	}
	
	var myForm = eval('window.document.' + frm_name);
	
	myForm.submit();
	return true;
}

function checkaddressQuantity2(item_field, max_quantity, address_key, frm_name, current_value) {
	var field_name = item_field.name;
	
	if (!IsNumeric(item_field.value)){
		alert (item_field.value + ' must be a number between 1 and ' + max_quantity);
		item_field.value = 0;
		return false;
	} else {
		if (current_value >= item_field.value) {
			
			return true;
		} else {
			if ((max_quantity + current_value) < item_field.value) {
				alert (item_field.value + ' is more than currently available: ' + max_quantity );
				item_field.value = current_value;
				return false;
			}
		}
		
		
		
	}
	
	var myForm = eval('window.document.' + frm_name);
	
	//myForm.submit();
	return true;
}

function checkItemQuantity(objForm)	
{
	with (objForm) 
	{ 
    	if (quantity.value <= 0) 
    	{
        	alert("The amount of this item you are requesting must be greater than zero.");
        }else{
        	submit();
        }
	}
}

function checkOrderQuantity(objTextbox, approval_quantity, avail_quantity, item_ordered, allow_backorders, min_amount, bundle_quantity, price, price_layer, price_uc_layer, item_id, custom_approval_message, backorder_message, jit, user_currency, vdp, status, useApprovals) 
{
	if (isNaN(objTextbox.value))
	{
		alert("Please enter only digit characters for a quantity.");
		objTextbox.focus();
		objTextbox.select();
		return (false);
	}

	//	Set the initial price
	if (price_layer) 
	{ 
		if (eval( "price_array_" + item_id + ".length > 0")) 
		{
			var t_value = 0;
			if (objTextbox.type == "checkbox") 
			{
				if (objTextbox.checked) 
				{      
					t_value = 1;
				} else {
					t_value = 0;
				}
			} else {
				t_value = objTextbox.value;
			}
			if (t_value == 0) 
			{
				var unit_total_x;
				unit_total_x = DerivePrice(item_id, eval(t_value + 1));
				price_uc_layer.innerHTML = dojo.currency.format(unit_total_x); 
			} else {
				unit_total = DerivePrice(item_id, t_value);
				callCurrencyconverter (unit_total, user_currency, 'price_uc_' + item_id);
			}
			callCurrencyconverter (t_value * unit_total, user_currency, 'price_' + item_id);
		} else {
			callCurrencyconverter (t_value * price, user_currency, 'price_' + item_id);
		}
	}
	if (approval_quantity > 0) 
	{
    	if (objTextbox.value > approval_quantity) 
    	{
    		if (useApprovals == 1)
    		{
	        	if (custom_approval_message != '')
	        	{
					alert(custom_approval_message);
				} else {
					alert("The amount of this item you are requesting must be approved\nby an adminstrator before your order can be shipped.");
				}
    		} else {
    			alert("The amount of this item you are requesting must be below the order maximum");
    			objTextbox.value = approval_quantity;
    		}
        }
    }
    
	if (min_amount > 0 && objTextbox.value != 0) 
	{
		if (parseInt(objTextbox.value) < min_amount) 
		{
			alert("The amount of this item you are requesting must be above the order minimum");
			objTextbox.value = min_amount;
			if (price_layer) 
			{ 
				if (eval( "price_array_" + item_id+ ".length > 0")) 
				{
					unit_total = DerivePrice(item_id, min_amount);
					callCurrencyconverter (min_amount * unit_total, user_currency, 'price_' + item_id);
				} else {
					callCurrencyconverter (min_amount * price, user_currency, 'price_' + item_id);
				}
				price_layer.style.width = '2cm';
			}
		}
	}
				
	if (bundle_quantity > 1 && objTextbox.value != 0) 
	{
		if (objTextbox.value % bundle_quantity) 
		{
			alert("The amount of this item you are requesting must be in increments of " + bundle_quantity);
			var divVal = 0;
			var multVal = 0;
			divVal = (objTextbox.value / bundle_quantity);
			divVal = parseInt(divVal);
			multVal = divVal * bundle_quantity;
			if (multVal == 0)
			{
				objTextbox.value = bundle_quantity;
			}else{
				objTextbox.value = multVal;
			}
			if (price_layer) 
			{ 
				if (eval( "price_array_" + item_id+ ".length > 0")) 
				{
					unit_total = DerivePrice(item_id, bundle_quantity);
					callCurrencyconverter (bundle_quantity * unit_total, user_currency, 'price_' + item_id);
				} else {
					callCurrencyconverter (bundle_quantity * price, user_currency, 'price_' + item_id);
				}
			}
		}
    }
			
	if (objTextbox.value > avail_quantity) 
	{
		if (!(jit || vdp) && status != 'M' && status != 'K')
		{
			if (allow_backorders) 
			{
				alert("The amount of this item you are requesting is more than is currently available.\nThis item will be back ordered. " + backorder_message);
			} else {
                alert("The amount of this item you are requesting is more than is currently available.\nYour order is being adjusted to reflect the maximum amount available.");
                objTextbox.value = avail_quantity;
				if (price_layer) 
				{ 
					if (eval( "price_array_" + item_id+ ".length > 0")) 
					{
						unit_total = DerivePrice(item_id, avail_quantity);
						callCurrencyconverter (avail_quantity * unit_total, user_currency, 'price_' + item_id);
					} else {
						callCurrencyconverter (avail_quantity * price, user_currency, 'price_' + item_id);
					}
				}
			}
        }
    }
	return true;
}

function checkCheckBoxes(objForm) 
{
	var isChecked = 0;
	thisForm = dojo.byId(objForm);
	with (thisForm) 
	{
		for (i = 0; i < elements.length; i++)
		{
			if (elements[i].id.substr(0, 4) == "use_")
			{
				if (elements[i].checked == true)
				{
					isChecked = 1;
				}
			}
		}
	}
	if (isChecked == 1){
		thisForm.submit();
		return true;
	}else{
		alert ("You must check at least one list.");
		return false;
	}
}

function checkTotalOrderQuantity(objForm) 
{
	var total_ordered = new Number(0);
    with (objForm) 
    {
	    for (i = 0; i < elements.length; i++) 
	    {
    	    if (elements[i].id.substr(0, 9) == "quantity_") 
    	    {
    	    	if (isNaN(parseInt(elements[i].value))){
    	    		elements[i].value = 0;
    	    	}
        	    total_ordered = total_ordered + parseInt(elements[i].value);
            }
    	    if (elements[i].id.substr(0, 7) == "selQty_") {
    	    	if (elements[i].options[elements[i].selectedIndex].value > 0){
    	    		total_ordered = total_ordered + elements[i].options[elements[i].selectedIndex].value;
    	    	}
    	    }
        }
    }
	if (total_ordered == 0) 
	{
    	alert("You must order at least one item.  Please add an item to your order.");
        return false;
    }
    return true;
}

function fillVal(chkbox)
{
	//console.log(chkbox);
	if (document.getElementById(chkbox).checked == 1){
		document.getElementById(chkbox).value = 1;
	}else{
		document.getElementById(chkbox).value = 0;
	}
}

function imagePreview(image_url, width, height) 
{
	window.open("image_preview.php?img=" + image_url, "imgWin", "width=" + width + ",height=" + height + ",scrollbars");
}
	
function initCode(ccode)
{
	frm_cart_edit.coupon_code.value = ccode;
}

function launchApprovalWindow(item_id, ses_company, ses_user_id, itemkey) {
	window.open("approve_collateral.php?item_id=" + item_id + "&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id + "&key=" + itemkey , "cust_window", "width=740,height=575,scrollbars");
}

function launchApprovalWindow2(item_id, order_number) {
	window.open("/main/admin_approve_collateral.php?item_id=" + item_id + "&order_number=" + order_number  , "approval_window", "width=740,height=575,scrollbars");
}

function launchUploadWindow2(ses_company,ses_user_id,order_items, key){
	window.open("orderfile_upload.php?ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id + "&orderitems=" + order_items + "&key=" + key, "fileupload_window", "width=450,height=200,scrollbars,status");
}

function launchSearchContactWindow(refresh_it,kill_current_contacts, ses_company, ses_user_id) 
{
	window.open("search_contacts.php?refresh=" + refresh_it + "&kill_current_contacts=" + kill_current_contacts + "&ses_company_id" + ses_company + "ses_user_id" + ses_user_id, "contactWin", "width=740,height=600,scrollbars");
}

function openCropImage(imageid, width, height, server_address ) 
{
	var theURL = "crop_image_flash.php?item_id=" + imageid + "&target_width=" + width + "&target_height=" + height + "&server_address=" + server_address;
	window.open(theURL,"CROPWindow",'width=400,height=465,resizable=no,scrollbars=no,menubar=no,status=no,left=0,top=0');
}

function SaveCart(myForm) 
{
	alert ("Saving Cart");
	myForm.submit();
}

function showPriceChart(iconElement,itemID,show,feat)
{
	if (feat == 1){
		var elementID = 'featPriceChart';
		var flag = "F";
	}else{
		var elementID = 'priceChart';
		var flag = "";
	}
	if (show == 1){
		dojo.byId('priceText_' + itemID + flag).innerHTML = '<img src="/images/expand_neg.png" alt="collapse" onclick="showPriceChart(this,'+itemID+',0,'+feat+')" id="expandIcon_'+itemID + flag+'" style="cursor:pointer" /> Price:';
		dojo.byId(elementID + '_' + itemID).style.display = '';
	}else{
		dojo.byId(elementID + '_' + itemID).style.display = 'none';
		dojo.byId('priceText_' + itemID + flag).innerHTML = '<img src="/images/expand_plus.png" alt="expand" onclick="showPriceChart(this,'+itemID+',1,'+feat+')" id="expandIcon_'+itemID + flag+'" style="cursor:pointer" /> Price:';
	}
}

function subEditFRM(myForm) 
{
	myForm.submit();
}

function verifyAddressForm(objForm) 
{
	if (!checkTotalOrderQuantity(objForm))
	{
		return;
	}
    message = "You must enter ";
    with (objForm) 
    {
    	if (txtContactName.value.length == 0) 
    	{ 
    		alert(message + "a contact name."); 
    		txtContactName.focus(); 
    		return; 
    	}
        if (txtAddress1.value.length == 0) 
        { 
        	alert(message + "an address."); 
        	txtAddress1.focus(); 
        	return; 
        }
        if (txtCity.value.length == 0) 
        { 
        	alert(message + "a city."); 
        	txtCity.focus(); 
        	return; 
        }
        if (txtZIPCode.value.length == 0) 
        { 
        	alert(message + "an ZIP or postal code."); 
        	txtZIPCode.focus(); 
        	return; 
        }
        if (txtPhone.value.length == 0) 
        { 
        	alert(message + " a phone number."); 
        	txtPhone.focus(); 
        	return; 
        }
        submit();
    }
}

function verifyCategoryAllItems(objForm) 
{

	if (!checkTotalOrderQuantity(objForm))
	{ 
		return;
	}

	message = "You must enter ";
	with (objForm) 
	{
		submit();
    }
}


//***************************************************************
// OLD CATEGORY VIEW FUNCTIONS
//***************************************************************

function addQuantities(item,lng,form){
	var quant1 = 'document.frmMain_'+ item +'.English.value';
	var quant2 = 'document.frmMain_'+ item +'.German.value';
	var quant3 = 'document.frmMain_'+ item +'.French.value';
	var quant4 = 'document.frmMain_'+ item +'.Italian.value';
	var quant5 = 'document.frmMain_'+ item +'.Spanish.value';
	var quant6 = 'document.frmMain_'+ item +'.Swedish.value';
	var quant7 = 'document.frmMain_'+ item +'.Brazilian.value';
	var quant8 = 'document.frmMain_'+ item +'.Korean.value';
	var quant9 = 'document.frmMain_'+ item +'.Russian.value';
	var quant10 = 'document.frmMain_'+ item +'.Czech.value';
	var quant11 = 'document.frmMain_'+ item +'.Japanese.value';
	var quant12 = 'document.frmMain_'+ item +'.Polish.value';
	var quant13 = 'document.frmMain_'+ item +'.Finnish.value';
	var quant14 = 'document.frmMain_'+ item +'.Chinese.value';

	if ((eval(quant1) == '')){ quant1 = 0; }
	if ((eval(quant2) == '')){ quant2 = 0; }
	if ((eval(quant3) == '')){ quant3 = 0; }
	if ((eval(quant4) == '')){ quant4 = 0; }
	if ((eval(quant5) == '')){ quant5 = 0; }
	if ((eval(quant6) == '')){ quant6 = 0; }
	if ((eval(quant7) == '')){ quant7 = 0; }
	if ((eval(quant8) == '')){ quant8 = 0; }
	if ((eval(quant9) == '')){ quant9 = 0; }
	if ((eval(quant10) == '')){ quant10 = 0; }
	if ((eval(quant11) == '')){ quant11 = 0; }
	if ((eval(quant12) == '')){ quant12 = 0; }
	if ((eval(quant13) == '')){ quant13 = 0; }
	if ((eval(quant14) == '')){ quant14 = 0; }
	form.quantity.value = (parseInt(eval(quant1)) + parseInt(eval(quant2))+ parseInt(eval(quant3))+ parseInt(eval(quant4))+ parseInt(eval(quant5))+ parseInt(eval(quant6))+ parseInt(eval(quant7))+ parseInt(eval(quant8))+ parseInt(eval(quant9))+ parseInt(eval(quant10))+ parseInt(eval(quant11))+ parseInt(eval(quant12))+ parseInt(eval(quant13))+ parseInt(eval(quant14)));
	form.quantity2.value = form.quantity.value;
	form.languages.value = 'ENG:'+eval(quant1)+'|DEU:'+eval(quant2)+'|FRA:'+eval(quant3)+'|ITA:'+eval(quant4)+'|ESP:'+eval(quant5)+'|SVE:'+eval(quant6)+'|PTB:'+eval(quant7)+'|KOR:'+eval(quant8)+'|RUS:'+eval(quant9)+'|CSY:'+eval(quant10)+'|JAP:'+eval(quant11)+'|POL:'+eval(quant12)+'|FIN:'+eval(quant13)+'|ZHO:'+eval(quant14);

}

function DerivePrice(item_id, quantity) {
	var price_array;
	quantity = parseInt(quantity);
	
	eval( "price_array = price_array_" + item_id);
	for (var i=0; i<price_array.length; i++){
		var pieces = price_array[i].split( "|" );
		var low_num = parseInt(pieces[0]);
		var high_num = parseInt(pieces[1]);
		
		if (quantity>=low_num && quantity<=high_num) {
			return pieces[2];
			break;
		}
		}
	return pieces[2];
}

function massSubmit(objForm,item){
	var sku = item;
	with (objForm){ 
        if (objForm.quantity.value > 0){
        	submit();
        	var txt = 'Item '+ sku + ' submitted';
        	alert(txt);
        }
    }
}

function updateAddress() {
	message = "You must enter ";
	with (document.frmAddress) {
		if (txtContactName.value.length == 0) { alert(message + "a contact name."); txtContactName.focus(); return; }
		if (txtAddress1.value.length == 0) { alert(message + "an address."); txtAddress1.focus(); return; }
		if (txtCity.value.length == 0) { alert(message + "a city."); txtCity.focus(); return; }
		//if (selState.options[selState.selectedIndex].value == "ZZ") { alert(message + "a state."); selState.focus(); return; }
		if (txtZIPCode.value.length == 0) { alert(message + "an ZIP or postal code."); txtZIPCode.focus(); return; }
		if (txtPhone.value.length == 0) { alert(message + " a phone number."); txtPhone.focus(); return; }	
		
		hdnAction.value = "update_address";
		action = '<?= $SCRIPT_NAME ?>';
		submit();				
	}
}

//***************************************************************
// DATE HANDLING FUNCTIONS
//***************************************************************
var imagedateformat = 'mm/dd/yyyy'; //Set the dateformat
var today = new Date();
var day   = today.getDate();
var month = today.getMonth();
var year  = y2k(today.getYear());
var activeDateField;

function restart() 
{
    arryDate = new Array((parseInt(month)+1),day,year)
    activeResetFunction = eval(activeDateField.name+'JoinDate');
    activeDateField.value = activeResetFunction(arryDate);
    mywindow.close();
}

function y2k(number)    
{ 
	return (number < 1000) ? number + 1900 : number; 
}

//***************************************************************
// ITEM VALIDATION FUNCTIONS
//***************************************************************
function Main_Validator(theForm)
{
	if (theForm.item_number.value.length == 0)
	{
		alert("Please enter an Item Number.");
		theForm.item_number.focus();
		return (false);
	}

	if (theForm.item_name.value.length == 0)
	{
		alert("Please enter an Item Name.");
		theForm.item_name.focus();
		return (false);
	}

	if (theForm.item_desc.value.length == 0)
	{
		alert("Please enter an Item Description.");
		theForm.item_desc.focus();
		return (false);
	}
	
	if (theForm.item_exp_date.value.length == 0)
	{
		alert("Please enter an Item Expiration Date.");
		theForm.item_exp_date.focus();
		return (false);
	}
	return (true);
}

function validate_access_level(obj, lowval, hival) 
{  
	if (IsNumeric(obj.value)) 
	{
		if ((obj.value < lowval) || (obj.value > hival)) 
		{     
			alert("Please enter an access level between " +lowval+ " and " + hival);
			obj.value = hival;
			obj.focus();
		}
	}else{
		alert("Please enter a numeric entry between " +lowval+ " and " + hival);
		obj.value = lowval;
		obj.focus();
	}
}

//***************************************************************
// PROFILE VALIDATION FUNCTIONS
//***************************************************************
function Self_Registration_Validator(theForm)
{
	if (theForm.password.value.length < 1)
	{
		alert("Please enter at least 1 characters in the \"Password\" field.");
		theForm.password.focus();
		return (false);
	}
	// check if both password fields are the same
	if (theForm.password.value != theForm.c_password.value)
	{
		alert("Your Password cannot be confirmed, please make sure that the two passwords match.");
		theForm.c_password.focus();
		return (false);
	}
	message = "You must enter ";
    with(theForm) 
    {
		if (login_email.value.length == 0) 
		{ 
			alert(message + "an email address."); 
			login_email.focus(); 
			return (false); 
		}
		if (company.value.length == 0) 
		{ 
			alert(message + "a company name."); 
			company.focus(); 
			return (false); 
		}
		if (f_name.value.length == 0) 
		{ 
			alert(message + "a first name."); 
			f_name.focus(); 
			return (false); 
		}
		if (l_name.value.length == 0) 
		{ 
			alert(message + "a last name."); 
			l_name.focus(); 
			return (false); 
		}
		if (vphone_prefix.value.length == 0) 
		{ 
			alert(message + "a voice phone prefix."); 
			vphone_prefix.focus(); 
			return (false); 
		}
		if (vphone_area_code.value.length == 0) 
		{ 
			alert(message + "a voice phone area code."); 
			vphone_area_code.focus(); 
			return (false); 
		}
		if (vphone.value.length == 0) 
		{ 
			alert(message + "a voice number."); 
			vphone.focus(); 
			return (false); 
		}
		if (address1.value.length == 0) 
		{ 
			alert(message + "an address."); 
			address1.focus(); 
			return (false); 
		}
		if (city.value.length == 0) 
		{ 
			alert(message + "a city."); 
			city.focus(); 
			return (false); 
		}
		if ((State.options[State.selectedIndex].value == "ZZ")&&((selCountry.options[selCountry.selectedIndex].value == "US")||(selCountry.options[selCountry.selectedIndex].value == "CA"))) 
		{ 
			alert(message + "a state."); 
			State.focus(); 
			return (false); 
		}
		if (PostalCode.value.length == 0) 
		{ 
			alert(message + "an ZIP or postal code."); 
			PostalCode.focus(); 
			return (false); 
		}
		if (selCountry.options[selCountry.selectedIndex].value == "ZZ") 
		{ 
			alert(message + "a country."); 
			selCountry.focus(); 
			return (false); 
		}
	}
	return (true);
}

function Phone_Validator(theForm)
{
	if (theForm.Prefix.value == "")
	{
		alert("Please enter a value for the \"Prefix\" field.");
		theForm.Prefix.focus();
		return (false);
	}
	if (theForm.Area_Code.value == "")
	{
		alert("Please enter a value for the \"Area Code\" field.");
		theForm.Area_Code.focus();
		return (false);
	}
	if (theForm.PhoneNumber.value == "")
	{
		alert("Please enter a value for the \"Phone Number\" field.");
		theForm.PhoneNumber.focus();
		return (false);
	}
	if (!is_numeric(theForm.Area_Code.value))
	{
		alert("Please enter only digit characters in the \"Area Code\" field.");
		theForm.Area_Code.focus();
		theForm.Area_Code.select();
		return (false);
	}
	if (!is_numeric(theForm.PhoneNumber.value))
	{
		alert("Please enter only digit characters in the \"Phone Number\" field.");
		theForm.PhoneNumber.focus();
		theForm.PhoneNumber.select();
		return (false);
	}
	return (true);
}


//***************************************************************
// ITEM EDIT FUNCTIONS
//***************************************************************
function addcategorytolist() 
{
	selUsersLen = document.imageForm.avail_categories.length ;
	for ( i=0; i<selUsersLen ; i++)
	{
        if (document.imageForm.avail_categories.options[i].selected == true ) 
        {
            selUsersInGroupLen = document.imageForm.sel_categories.length;
            document.imageForm.sel_categories.options[selUsersInGroupLen]= new Option(document.imageForm.avail_categories.options[i].text, document.imageForm.avail_categories.options[i].value);
        }
    }
    for ( i = (selUsersLen -1); i>=0; i--)
    {
        if (document.imageForm.avail_categories.options[i].selected == true ) 
        {
            document.imageForm.avail_categories.options[i] = null;
        }
    }
}

function removecategoryfromlist() 
{
    selUsersInGroupLen = document.imageForm.sel_categories.length;
    for ( i=0; i<selUsersInGroupLen ; i++)
    {
        if (document.imageForm.sel_categories.options[i].selected == true ) 
        {
            selUsersLen = document.imageForm.avail_categories.length;
            document.imageForm.avail_categories.options[selUsersLen]= new Option(document.imageForm.sel_categories.options[i].text, document.imageForm.sel_categories.options[i].value);
        }
    }
    for ( i=(selUsersInGroupLen-1); i>=0; i--) 
    {
        if (document.imageForm.sel_categories.options[i].selected == true ) 
        {
            document.imageForm.sel_categories.options[i] = null;
        }
    }
}
	
function addItemtoGroup() 
{
	selUsersLen = document.imageForm.avail_groups.length ;
	for ( i=0; i<selUsersLen ; i++)
	{
        if (document.imageForm.avail_groups.options[i].selected == true ) 
        {
            selUsersInGroupLen = document.imageForm.sel_groups.length;
            document.imageForm.sel_groups.options[selUsersInGroupLen]= new Option(document.imageForm.avail_groups.options[i].text, document.imageForm.avail_groups.options[i].value);
        }
    }
    for ( i = (selUsersLen -1); i>=0; i--)
    {
        if (document.imageForm.avail_groups.options[i].selected == true ) 
        {
            document.imageForm.avail_groups.options[i] = null;
        }
    }
}

function removeItemfromGroup() 
{
    selUsersInGroupLen = document.imageForm.sel_groups.length ;
    for ( i=0; i<selUsersInGroupLen ; i++)
    {
        if (document.imageForm.sel_groups.options[i].selected == true ) 
        {
            selUsersLen = document.imageForm.avail_groups.length;
            document.imageForm.avail_groups.options[selUsersLen]= new Option(document.imageForm.sel_groups.options[i].text, document.imageForm.sel_groups.options[i].value);
        }
    }
    for ( i=(selUsersInGroupLen-1); i>=0; i--) 
    {
        if (document.imageForm.sel_groups.options[i].selected == true ) 
        {
            document.imageForm.sel_groups.options[i] = null;
        }
    }
}

function subFrm(){
	if (document.imageForm.item_number.value.length == 0)
	{
		alert("Please enter an Item Number.");
		document.imageForm.item_number.focus();
		return (false);
	}
	if (document.imageForm.item_name.value.length == 0)
	{
		alert("Please enter an Item Name.");
		document.imageForm.item_name.focus();
		return (false);
	}
	for (i=0; i<document.imageForm.sel_categories.length; i++) 
	{ 
		document.imageForm.sel_categories.options[i].selected = true; 
	}
	document.imageForm.sel_categories.name="sel_categories[]";
	for (i=0; i<document.imageForm.sel_groups.length; i++) 
	{ 
		document.imageForm.sel_groups.options[i].selected = true; 
	}
	document.imageForm.sel_groups.name="sel_groups[]";
	document.imageForm.submit();
	return true;
}




//***************************************************
// ITEM CUSTOMIZATION FUNCTIONS
//***************************************************

function launchAssetSelectorWindow(category_list, bin_list, item_list, field_name, asset_type, orientation, ses_company, ses_user_id, itemkey) 
{
	window.open("asset_browser.php?category_list=" + category_list + "&bin_list=" + bin_list + "&item_list=" + item_list + "&field_name=" + field_name + "&asset_type=" + asset_type + "&orientation=" + orientation +"&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id + "&key=" + itemkey, "cust_window", "width=740,height=575,scrollbars");
}

function launchOldOrderWindow(item_id, ses_company, ses_user_id) 
{
	window.open("retrieve_old_order_customization.php?item_id=" + item_id + "&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id, "old_order_window", "width=740,height=575,scrollbars");
}

function launchPreviewWindow(item_id, ses_company, ses_user_id, itemkey, template_type, order_number) 
{
	if ( val_customized_info() )
	{
    	window.open("preview_customization.php?item_id=" + item_id + "&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id + "&key=" + itemkey + "&template_type=" + template_type + "&order_number=" + order_number, "cust_window", "width=825,height=850,scrollbars=1,resizable=1");
    }
}

function launchPreviewWindowAdmin(item_id, ses_company, ses_user_id, order_number) 
{
	window.open("preview_customization.php?item_id=" + item_id + "&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id + "&order_number=" + order_number , "cust_window", "width=900,height=800,scrollbars");
}

function launchTemplateSelectorWindow(item_list, ses_company, ses_user_id, itemkey) 
{
	window.open("template_browser.php?item_list=" + item_list + "&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id + "&key=" + itemkey, "cust_window", "width=740,height=575,scrollbars");
}

function launchUploadWindow(category_list, bin_list, item_list, field_name, asset_type, orientation, ses_company, ses_user_id, min_upload_dpi, icc_profile, itemkey) 
{
	window.open("image_upload.php?category_list=" + category_list + "&bin_list=" + bin_list + "&item_list=" + item_list + "&field_name=" + field_name + "&asset_type=" + asset_type + "&orientation=" + orientation +"&ses_company_id=" + ses_company + "ses_user_id=" + ses_user_id + "&min_upload_dpi=" + min_upload_dpi + "&icc_profile=" + icc_profile + "&key=" + itemkey, "cust_window", "width=450,height=310,scrollbars,status");
}

function launchUploadWindowVW(category_list, bin_list, item_list, field_name, asset_type, orientation, ses_company, ses_user_id, min_upload_dpi, icc_profile, itemkey) 
{
	window.open("image_upload_vw.php?category_list=" + category_list + "&bin_list=" + bin_list + "&item_list=" + item_list + "&field_name=" + field_name + "&asset_type=" + asset_type + "&orientation=" + orientation +"&ses_company_id=" + ses_company + "ses_user_id=" + ses_user_id + "&min_upload_dpi=" + min_upload_dpi + "&icc_profile=" + icc_profile + "&key=" + itemkey, "cust_window", "width=520,height=310,scrollbars,status");
}

function launchUploadWindowDyn(category_list, bin_list, item_list, field_name, asset_type, orientation, ses_company, ses_user_id, min_upload_dpi, icc_profile)
{
	window.open("image_upload_dyn.php?category_list=" + category_list + "&bin_list=" + bin_list + "&item_list=" + item_list + "&field_name=" + field_name + "&asset_type=" + asset_type + "&orientation=" + orientation +"&ses_company_id=" + ses_company + "ses_user_id=" + ses_user_id + "&min_upload_dpi=" + min_upload_dpi + "&icc_profile=" + icc_profile, "cust_window", "width=450,height=310,scrollbars,status");
}

function launchUserGuideWindow(item_id, ses_company, ses_user_id) 
{
	window.open("display_user_guide.php?item_id=" + item_id + "&ses_company_id=" + ses_company + "&ses_user_id=" + ses_user_id, "guide_window", "width=740,height=575,scrollbars");
}

function update_format (field_val, format_template)
{
	var formater_object = stringSplit ( format_template, '' );
	var output_text = "";
	
	if (field_val.value) 
	{
		switch(format_template)
	    {
			case 'usd':
				to_format = strip(field_val.value, '$');
				output_text = formatNumber(to_format, "$,##0.00");
				break;
		    case 'phone_dashes':   
		    	var temp = parsePhoneNumber(field_val.value); 
				to_format = strip(temp, '-');
				output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1 $2-$3");
				break;
		    case 'phone_dashes_all':   
		    	var temp = parsePhoneNumber(field_val.value); 
				to_format = strip(temp, '-');
				output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
				break;	
			case 'phone_format_spaces':   
				var temp = parsePhoneNumber(field_val.value); 
				to_format = strip(temp, '-');
				output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1 $2-$3");
				break;
			case 'phone_dots':
				var temp = parsePhoneNumber(field_val.value); 
				to_format = strip(temp, '-');
				output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3");
				break;
			case 'phone_format_parens':   
				var temp = parsePhoneNumber(field_val.value); 
				to_format = strip(temp, '-');
				output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
				break;	
			case 'phone_format_parens_dashes':
				var temp = parsePhoneNumber(field_val.value); 
				to_format = strip(temp, '-');
				output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "($1)-$2-$3");
				break;	
			case 'integer': 
				output_text	 	= field_val.value;
				if (!IsNumeric(field_val.value)) 
				{
					alert("Only numbers are allowed in this field.");
					field_val.value = 0;
					output_text	 	= field_val.value;
				} 
				break;
			case 'decimal': 
				output_text	 	= field_val.value;
				if (!IsPercentage(field_val.value)) 
				{
					alert("Only numbers are allowed in this field.");
					field_val.value = 0;
					output_text	 	= field_val.value;
				} 
				break;
			case 'to_upper':   
				field_val.value = field_val.value.toUpperCase();
				output_text	 	= field_val.value.toUpperCase();
				break;
			case 'to_lower':   
				field_val.value = field_val.value.toLowerCase();
				output_text	 	= field_val.value.toLowerCase();
				break;
			case 'ucase_first':
				var words = new Array();
				words = stringSplit ( field_val.value, ' ' );
				field_val.value = '';
				for (count = 0; count < words.length; count++)
				{
					words[count] = words[count].substr(0, 1).toUpperCase() + words[count].substr(1).toLowerCase();
				}
				output_text = words.join(' ');
				break;	
		    case 'email_format':   
		    	alert("No, four feet, one horn, the horn isn't a foot"); 
		    	break;
		    case 'None':
				output_text	= field_val.value;
				break;
		    default:    
				for (count = 0; count < formater_object.length; count++)
				{
					if (formater_object[count] != "+") 
					{
						output_text = output_text + formater_object[count];
					} else {
						output_text = output_text + field_val.value;
					}
				}      
				break;
		}
	}
	field_val.value = output_text;
}

function parsePhoneNumber(phoneNumber)
{
	var temp = new String(phoneNumber);
	temp = temp.replace(/[^ 0-9]+/g,'');

	if (temp.length > 10) {
		if (temp.charAt(0) == 1) {
			alert ("Phone Number is larger than ten digits...\nRemoving preceeding 1. \nPlease validate the phone number");
			temp = temp.substr(1,10);
		} else {
			alert ("Phone Number is larger than ten digits...\nPlease validate the phone number");
			temp = temp.substr(0,10);
		}
	}
	return temp;
}

/**
 * Uber lame function
 *
 * Load phone numbers WITH their respective formatting.
 * Solves the issue where formatting isn't respected
 * until 'onchange' fires. This will handle it 'onLoad'.
 * I'm sure there's a better way, but IPS screams loud.
 *
 * @addresses #1111
 * @author Timothy G Majerus <tmajerus@responsivesolutions.net>
 */
function onLoadFormat(id, field_val, format_template)
{
	switch(format_template)
    {
	    case 'phone_dashes':   
	    	var temp = parsePhoneOnload(field_val); 
			to_format = strip(temp, '-');
			output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1 $2-$3");

			dojo.query("[id='"+id+"']")
				.forEach(function(node,i)
				{
					dojo.byId(node.id).value = output_text;
				}
			);		
	
			break;
	    case 'phone_dashes_all':   
	    	var temp = parsePhoneOnload(field_val); 
			to_format = strip(temp, '-');
			output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");

			dojo.query("[id='"+id+"']")
				.forEach(function(node,i)
				{
					dojo.byId(node.id).value = output_text;
				}
			);		

			break;	
		case 'phone_format_spaces':   
			var temp = parsePhoneOnload(field_val); 
			to_format = strip(temp, '-');
			output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1 $2-$3");

			dojo.query("[id='"+id+"']")
				.forEach(function(node,i)
				{
					dojo.byId(node.id).value = output_text;
				}
			);		
		
			break;
		case 'phone_dots':
			var temp = parsePhoneOnload(field_val); 
			
			to_format = strip(temp, '-');
			output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3");

			dojo.query("[id='"+id+"']")
				.forEach(function(node,i)
				{
					dojo.byId(node.id).value = output_text;
				}
			);		

			break;
		case 'phone_format_parens':	  
			var temp = parsePhoneOnload(field_val);
			
			to_format = strip(temp, '-');
			output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");

			dojo.query("[id='"+id+"']")
				.forEach(function(node,i)
				{
					dojo.byId(node.id).value = output_text;
				}
			);		
			
			break;	
		case 'phone_format_parens_dashes':
			var temp = parsePhoneOnload(field_val); 
			to_format = strip(temp, '-');
			output_text = to_format.replace(/(\d{3})(\d{3})(\d{4})/, "($1)-$2-$3");

			dojo.query("[id='"+id+"']")
				.forEach(function(node,i)
				{
					dojo.byId(node.id).value = output_text;
				}
			);		
			
			break;	
	    default:       
			break;
	}
}

/**
 * Uber lame function
 *
 * Load phone numbers WITH their respective formatting.
 * Solves the issue where formatting isn't respected
 * until 'onchange' fires. This will handle it 'onLoad'.
 * I'm sure there's a better way, but IPS screams loud.
 *
 * @addresses #1111 
 * @author Timothy G Majerus <tmajerus@responsivesolutions.net>
 */
function parsePhoneOnload(phoneNumber)
{
	temp = phoneNumber.replace(/[^ 0-9]+/g,'');
	temp = strip(temp, ' ');	

	if (temp.length > 10) {
		if (temp.charAt(0) == 1) {
			temp = temp.substr(1,10);
		} else {
			temp = temp.substr(0,10);
		}
	}
	return temp;
}

function UpdateTriggerValues(val, array_name) 
{
	var array_var = eval( "triggers_" + array_name) ;
	if (val.selectedIndex > 0) 
	{
		var var_changer = stringSplit  ( array_var[(val.selectedIndex -1)], "*" );
		for (var i=0; i<var_changer.length; i++) 
		{
			var field_bundle = stringSplit  (var_changer[i], "|");
			var field_to_change = eval ("document.customization_form." + field_bundle[0]);
			switch (field_to_change.type)
			{
				case "select": 
					//	Loop over fields to set this value...
					for (j=0; j < field_to_change.options.length; j++) 
					{ 
						if (field_to_change.options[j].value == field_bundle[1]) 
						{
							field_to_change.selectedIndex = j;
							break;
						}
				  	}
				  	break;
				  	
				case "text": 
					field_to_change.value = field_bundle[1];
				  	break;
			}
		}
	}
}

function val_customized_info ()
{
	var r_values	 	= document.customization_form.req_fields.value;
	if (r_values != "" ) 
	{
		var var_array	= r_values.split(",");
		counter 		= 0;
		while (counter < var_array.length)
 		{
			req_var_val = eval('document.customization_form.id_'+var_array[counter]+'.value');
			if (req_var_val == "-1" || req_var_val == "") 
			{
				alert ("All required fields must be completed");
				return false;
			}
  			counter+=1;
  		}
	}
	return true;
}


//**********************************************
// REPORTING FUNCTIONS
//**********************************************

function creatingReport() 
{
	alert("Your report is about to be generated. If you have selected a large amount of visitors, this process may take a few moments. Thank you.");
}


//**********************************************
// WAREHOUSE FUNCTIONS
//**********************************************

function CheckExportedOrders() 
{
	for (counter = 0; counter < OrdersFrm.checkbox.length; counter++){
		if (OrdersFrm.checkbox[counter].checked)	{ 
			alert(OrdersFrm.checkbox[counter].value);
		}
	}
}

function confirm_void()
{
	var blnAnswer=confirm("Void This Order?");
	if (blnAnswer){ 
		return true;
	}else{
		return false;
	}
}

function updShipCost(rbOpt)
{
	dojo.byId('txtShipCharge').value = Math.round(rbOpt.id*100)/100;
	dijit.byId('txtShipCharge').focus();
}

function validate_ship_quantity(obj, lowval, hival) 
{  
	if (IsNumeric(obj.value)) {
		if ((obj.value < lowval) || (obj.value > hival)) {     
			alert("Please enter a number between " +lowval+ " and " + hival);
			obj.value = hival
			obj.focus;
		}
	}else{
		alert("Please enter a number between " +lowval+ " and " + hival);
		obj.value = hival
		obj.focus;
	}
}

//**********************************************
//VT FUNCTIONS
//**********************************************

function calculate_text_leading() 
{
	var percentage = document.FRMformatting.t_leading.options[document.FRMformatting.t_leading.selectedIndex].value;
	var font_size = document.FRMformatting.max_font.value;
	document.FRMformatting.te_leading.value = font_size * (percentage / 100);
}

function saveSettings() 
{
	document.FRMformatting.submit();
}

function showUploadTab(box_id) 
{
	switchVisible('div_upload_' + box_id);
	switchVisible('div_upload_p_' + box_id );
}

function so_clearInnerHTML(obj) 
{
	// so long as obj has children, remove them
	while(obj.firstChild) obj.removeChild(obj.firstChild);
}


//**********************************************
// DLT FUNCTIONS
//**********************************************

function checkAll() 
{
	with (document.frmGroupItems) {
		chkboxLength = elements.length;
		for (i = 0; i < chkboxLength; i++) {
			elements[i].checked = true;
		}		
	}
}

function checkNone() 
{
	with (document.frmGroupItems) {
		chkboxLength = elements.length;
		for (i = 0; i < chkboxLength; i++) {
			elements[i].checked = false;
		}		
	}	
}

function sendCoOpData(order, user_id, frm_id, program_id, amount, element_id){
	if (numericCheck('coopAmount_'+element_id,'Please enter a numeric value')){
		dojo.xhrGet(
		{
			url: 		"co-opController.php",
			content: 	{
				order_number: 	order, 
				user_id: 		user_id,
				task: 			'applyPayment',
				program_id:		program_id,
				amount:			amount
			}, 
			timeout:	50000,
			handleAs:	"json",
				
			load: function(response, ioArgs)
			{		
				//console.dir(response);
				console.log(response);
				
				dojo.byId('pmtNumber_'+order+'_'+frm_id).value = response.id;
				dojo.byId('pmtNumber_'+order+'_'+frm_id).readOnly = true;
				dojo.byId('pmtAmount_'+order+'_'+frm_id).value = response.amount;
				dojo.byId('pmtAmount_'+order+'_'+frm_id).focus();
				dojo.byId('pmtAmount_'+order+'_'+frm_id).readOnly = true;
				dojo.byId(frm_id).submit();
			},
			
			error: function(response, ioArgs)
			{
				alert("An error occured.");
			}
		});
		return true;
	}else{
		return false;
	}
	
}

function processCreditCard(frm_id,order,user_id,frm_id){
	
	var old_submit = dojo.byId('tdPay_' 		+ order + '_' + frm_id).innerHTML;
	dojo.byId('cardAlert_'+ order + '_' + frm_id).innerHTML = '';
	dojo.byId('tdPay_' 		+ order + '_' + frm_id).innerHTML = '<span class="boldText8">Processing <img height="32" width="32" src="/dojo/dojo-1.3/dojox/widget/Standby/images/loading.gif"/></span>';
	dojo.xhrPost(
	{
		url: 		"payments.php",
		form:		frm_id,
		timeout:	50000,
		handleAs:	"json",
			
		load: function(response, ioArgs)
		{		
			if (response.error){
				dojo.byId('cardAlert_'+ order + '_' + frm_id).innerHTML = '<span class="alertText8">' + response.error + '</span>';
				dojo.byId('tdPay_' 		+ order + '_' + frm_id).innerHTML = old_submit;
				dojo.byId('btnSubmit_'+ order + '_' + frm_id).disabled=false;
				return false;
			}else{
				if (response.auth_code){
					dojo.byId('pmtPulldown_' 	+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('rowName_' 		+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('rowAddress_' 	+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('rowCity_' 		+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('rowState_' 		+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('rowZipcode_' 	+ order + '_' + frm_id).style.display = 'none';
					dojo.byId('rowCountry_' 	+ order + '_' + frm_id).style.display = 'none';

					dojo.byId('tdPay_'	+ order + '_' + frm_id).innerHTML = '<span class="greenText8">Approved</span><span class="boldText8">, Applying Payment <img height="32" width="32" src="/dojo/dojo-1.3/dojox/widget/Standby/images/loading.gif"/></span>';
					location.reload(true);
					return true;
				}else{
					dojo.byId('cardAlert_'+ order + '_' + frm_id).innerHTML = '<span class="alertText8">Unknown Error</span>';
					dojo.byId('tdPay_' 		+ order + '_' + frm_id).innerHTML = old_submit;
					dojo.byId('btnSubmit_'+ order + '_' + frm_id).disabled=false;
					return false;
				}
			}
			console.log(response);
		},
		
		error: function(response, ioArgs)
		{
			alert("An error occured.");
			return false;
		}
	});
	
}


function getCostCenterChild(selObj, level, order, frm_id, user_id){
	
	var dropdownIndex = selObj.selectedIndex;
	var dropdownValue = selObj[dropdownIndex].value;
	
	dojo.xhrGet(
	{
		url: 		"payments.php",
		content: 	{
			order_id: 		order,
			frm_id: 		frm_id, 
			user_id: 		user_id,
			type: 			'costcenters',
			level:			level,
			parent_id:		dropdownValue
		}, 
		timeout:	50000,
		handleAs:	"text",
			
		load: function(response, ioArgs)
		{		
			var csHTML = response;
			dojo.byId('costcenter'+level+'_'+ order + '_' + frm_id).innerHTML = csHTML;
		
			if (dropdownIndex >0)
			{
				dojo.byId('pmtCostCenter_'+ order + '_' + frm_id).value = dropdownValue;
				psAllowContinue('pmtCostCenter_'+ order + '_' + frm_id,order,frm_id);
			}
		},
		
		error: function(response, ioArgs)
		{
			log.dir(response);
			alert("An error occured.");
		}
	});
}


function ptSwitch(pmtSel,order,frm_id,user_id,cvv)
{
	switch(pmtSel.value)
	{
		case "C":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = '';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = '';
			if (cvv == 1){
				dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = '';
			} else {
				dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			}
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '<input type="button" disabled="disabled" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'"  value="Please Enter Credit Card Information" />';
		break;
			
		case "P":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\'btnSubmit_'+order+'_'+frm_id+'\').disabled=true;dojo.byId(\''+frm_id+'\').submit();" value="Submit" />';
			//dijit.byId('${frm_id}').submit();
		break;
		
		case "RSI_CO":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\'btnSubmit_'+order+'_'+frm_id+'\').disabled=true;dojo.byId(\''+frm_id+'\').submit();" value="Submit" />';
		break;
			
		case "RSI_CP":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = '';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '';
			//dojo.byId('rowPay_${order_id}_${frm_id}').style.display='';
			
			console.log('co-op started');
			var tmp_val =  dojo.byId('pmtAmount_' + order + '_' + frm_id).value;
			
			dojo.xhrGet(
			{
				url: 		"co-opController.php",
				content: 	{order_number: order, user_id: user_id,task: 'getAvailablePrograms', amount : dojo.byId('pmtAmount_' + order + '_' + frm_id).value}, 
				timeout:	50000,
				handleAs:	"json",
					
				load: function(response, ioArgs)
				{		
					console.dir(response);
					var coopHTML = '<fieldset>'
						+ '<legend class="legStd">Co-Op Account Data</legend>'
						+ '<table class="full">';
					if ( typeof(response.program)=='object'&&(response.program instanceof Array) )
					{
						for  ( rsp in response.program)
						{
							program = response.program[rsp];
							var coopHTML = coopHTML + '<tr class="b2bHeaderRow"><th>Program</th><th>Available Balance</th><th>Amount</th><th>Pay</th>'
							+ '<tr>'
							+ '<td class="text8">'+program.name+'</td>'
							+ '<td class="text8 alignright">$' + Math.round(program.availableBalance*100)/100 + '</td>'
							+ '<td class="text8 aligncenter">';
							
							if (program.availableBalance > 0){
								coopHTML = coopHTML + '<input type="text" class="text8" size="10" dojoType="dijit.form.NumberTextBox" name="coopAmount" id="coopAmount_'+program.id+'" value="' +Math.round(program.availableBalance*100)/100 +'" />';
							}
							
							coopHTML = coopHTML + '</td>'
							+ '<td class="text8 aligncenter">';
							if (program.availableBalance > 0){
								coopHTML = coopHTML + '<input type="button" class="b2bButton" value="Pay" onclick="sendCoOpData(\''+order+'\','+user_id+',\''+frm_id+'\','+program.id+', dojo.byId(\'coopAmount_'+program.id+'\').value,\''+program.id+'\')" />';
							}
							coopHTML = coopHTML + '</td>'
							+ '</tr>';
						}
					} else {
						program = response.program;
						var coopHTML = coopHTML + '<tr class="b2bHeaderRow"><th>Program</th><th>Available Balance</th><th>Amount</th><th>Pay</th>'
						+ '<tr>'
						+ '<td class="text8">'+program.name+'</td>'
						+ '<td class="text8 alignright">$' + Math.round(program.availableBalance*100)/100 + '</td>'
						+ '<td class="text8 aligncenter">';
						
						if (program.availableBalance > 0){
							coopHTML = coopHTML + '<input type="text" class="text8" size="10" dojoType="dijit.form.NumberTextBox" name="coopAmount" id="coopAmount_'+program.id+'" value="' +Math.round(program.availableBalance*100)/100 +'" />';
						}
						
						coopHTML = coopHTML + '</td>'
						+ '<td class="text8 aligncenter">';
						if (program.availableBalance > 0){
							coopHTML = coopHTML + '<input type="button" class="b2bButton" value="Pay" onclick="sendCoOpData(\''+order+'\','+user_id+',\''+frm_id+'\','+program.id+', dojo.byId(\'coopAmount_'+program.id+'\').value,\''+program.id+'\')" />';
						}
						coopHTML = coopHTML + '</td>'
						+ '</tr>';
					}
					
					
					coopHTML = coopHTML + '</table>'
						+ '</fieldset><br />';
					
					dojo.byId('coOpInput_'+ order + '_' + frm_id).innerHTML = coopHTML;
				},
				
				error: function(response, ioArgs)
				{
					switch(response.message){
						case "program is undefined":
							alert("No programs were found. Please choose another payment method.");
						break;
						default:
							alert("Please choose another payment method.");
						break;					
					}
				}
			});
		break;
			
		case "RSI_CS":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = '';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = '';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = 'none';
			psAllowContinue('pmtCostCenter_'+ order + '_' + frm_id,order,frm_id);
			dojo.xhrGet(
			{
				url: 		"payments.php",
				content: 	{
					order_id: 		order,
					frm_id: 		frm_id, 
					user_id: 		user_id,
					type: 			'costcenters',
					level:			0
				}, 
				timeout:	5000,
				handleAs:	"text",
					
				load: function(response, ioArgs)
				{		
					var csHTML = response;
					dojo.byId('costcenter0_'+ order + '_' + frm_id).innerHTML = csHTML;
				},
				
				error: function(response, ioArgs)
				{
					alert("An error occured.");
				}
			});
		break;
			
		case "RSI_PO":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = '';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = 'none';
			psAllowContinue('pmtNumber_'+ order + '_' + frm_id,order,frm_id);
			//dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\''+frm_id+'\').submit();" value="Submit" />';
		break;
		
		case "NP":
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\''+frm_id+'\').submit();" value="Submit" />';
		break;
			
		default:
			dojo.byId('coOpInput_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costcenterInput_'+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('userID_' 		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('costCenter_' 	+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cardNumber_' 	+ order + '_' + frm_id).style.display = '';
			dojo.byId('expDate_'		+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('cvv_' 			+ order + '_' + frm_id).style.display = 'none';
			dojo.byId('amountRow_' 		+ order + '_' + frm_id).style.display = '';
			dojo.byId('tdPay_' 			+ order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\'btnSubmit_'+order+'_'+frm_id+'\').disabled=true;dojo.byId(\''+frm_id+'\').submit();" value="Submit" />';
		break;
	}

}

function psAllowContinue(theField,order,frm_id,user_id)
{
	if (dojo.byId(theField).value != "")
	{
		if(dojo.byId('pmtType_'+ order + '_' + frm_id).value == "C")
		{
			dojo.byId('tdPay_' + order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\'btnSubmit_'+order+'_'+frm_id+'\').disabled=true;processCreditCard(\''+frm_id+'\',\''+order+'\',\''+user_id+'\',\''+frm_id+'\')" value="Submit" />';
		} else {
			dojo.byId('tdPay_' + order + '_' + frm_id).innerHTML = '<input type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" onclick="dojo.byId(\'btnSubmit_'+order+'_'+frm_id+'\').disabled=true;dojo.byId(\''+frm_id+'\').submit();" value="Submit" />';
		}
	} else {
		if(dojo.byId('pmtType_'+ order + '_' + frm_id).value == "C")
		{
			dojo.byId('tdPay_' + order + '_' + frm_id).innerHTML = '<input disabled="disabled" type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'"  value="Please Enter Credit Card Information" />';
		} else {
			dojo.byId('tdPay_' + order + '_' + frm_id).innerHTML = '<input disabled="disabled" type="button" class="b2bButton" id="btnSubmit_'+order+'_'+frm_id+'" value="Submit" />';
		}
	}
}

function ptSwitchRetail(pmtSel,total,tax,ship)
{
	var creditTotal = total - tax - ship;
	switch(pmtSel.value)
	{
		case "C":
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('couponCode').style.display = 'none';
			dojo.byId('userID').style.display = 'none';
			dojo.byId('cardNumber').style.display = '';
			dojo.byId('expDate').style.display = '';
			dojo.byId('cvv').style.display = '';
			dojo.byId('file').style.display = '';
			dojo.byId('amountRow').style.display = '';
			dojo.byId('pmtAmount').value = total.numberFormat("0.00");
			dojo.byId('nameRow').style.display = '';
			dojo.byId('addrRow').style.display = '';
			dojo.byId('cityRow').style.display = '';
			dojo.byId('stateRow').style.display = '';
			dojo.byId('zipRow').style.display = '';
			dojo.byId('countryRow').style.display = '';
		break;
			
		case "P":
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('couponCode').style.display = 'none';
			dojo.byId('userID').style.display = '';
			dojo.byId('cardNumber').style.display = 'none';
			dojo.byId('expDate').style.display = 'none';
			dojo.byId('cvv').style.display = 'none';
			dojo.byId('file').style.display = 'none';
			dojo.byId('amountRow').style.display = '';
			dojo.byId('pmtAmount').value = total.numberFormat("0.00");
			dojo.byId('nameRow').style.display = 'none';
			dojo.byId('addrRow').style.display = 'none';
			dojo.byId('cityRow').style.display = 'none';
			dojo.byId('stateRow').style.display = 'none';
			dojo.byId('zipRow').style.display = 'none';
			dojo.byId('countryRow').style.display = 'none';
		break;
		
		case "RSI_CO":
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('couponCode').style.display = '';
			dojo.byId('cardNumber').style.display = 'none';
			dojo.byId('expDate').style.display = 'none';
			dojo.byId('cvv').style.display = 'none';
			dojo.byId('file').style.display = 'none';
			dojo.byId('amountRow').style.display = 'none';
			dojo.byId('pmtAmount').value = creditTotal.numberFormat("0.00");
			dojo.byId('nameRow').style.display = 'none';
			dojo.byId('addrRow').style.display = 'none';
			dojo.byId('cityRow').style.display = 'none';
			dojo.byId('stateRow').style.display = 'none';
			dojo.byId('zipRow').style.display = 'none';
			dojo.byId('countryRow').style.display = 'none';
		break;
			
		case "RSI_CS":
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('costCenter').style.display = '';
			dojo.byId('couponCode').style.display = 'none';
			dojo.byId('cardNumber').style.display = 'none';
			dojo.byId('expDate').style.display = 'none';
			dojo.byId('cvv').style.display = 'none';
			dojo.byId('file').style.display = 'none';
			dojo.byId('amountRow').style.display = '';
			dojo.byId('pmtAmount').value = creditTotal.numberFormat("0.00");
			dojo.byId('nameRow').style.display = 'none';
			dojo.byId('addrRow').style.display = 'none';
			dojo.byId('cityRow').style.display = 'none';
			dojo.byId('stateRow').style.display = 'none';
			dojo.byId('zipRow').style.display = 'none';
			dojo.byId('countryRow').style.display = 'none';
		break;
			
		case "RSI_PO":
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('couponCode').style.display = 'none';
			dojo.byId('cardNumber').style.display = '';
			dojo.byId('expDate').style.display = 'none';
			dojo.byId('cvv').style.display = 'none';
			dojo.byId('file').style.display = 'none';
			dojo.byId('amountRow').style.display = '';
			dojo.byId('pmtAmount').value = creditTotal.numberFormat("0.00");
			dojo.byId('nameRow').style.display = 'none';
			dojo.byId('addrRow').style.display = 'none';
			dojo.byId('cityRow').style.display = 'none';
			dojo.byId('stateRow').style.display = 'none';
			dojo.byId('zipRow').style.display = 'none';
			dojo.byId('countryRow').style.display = 'none';
		break;
		
		case "NP":
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('couponCode').style.display = 'none';
			dojo.byId('cardNumber').style.display = 'none';
			dojo.byId('expDate').style.display = 'none';
			dojo.byId('cvv').style.display = 'none';
			dojo.byId('file').style.display = 'none';
			dojo.byId('amountRow').style.display = 'none';
			dojo.byId('pmtAmount').value = creditTotal.numberFormat("0.00");
			dojo.byId('nameRow').style.display = 'none';
			dojo.byId('addrRow').style.display = 'none';
			dojo.byId('cityRow').style.display = 'none';
			dojo.byId('stateRow').style.display = 'none';
			dojo.byId('zipRow').style.display = 'none';
			dojo.byId('countryRow').style.display = 'none';
		break;
			
		default:
			dojo.byId('costCenter').style.display = 'none';
			dojo.byId('couponCode').style.display = '';
			dojo.byId('cardNumber').style.display = '';
			dojo.byId('expDate').style.display = 'none';
			dojo.byId('cvv').style.display = 'none';
			dojo.byId('file').style.display = 'none';
			dojo.byId('amountRow').style.display = '';
			dojo.byId('pmtAmount').value = creditTotal.numberFormat("0.00");
			dojo.byId('nameRow').style.display = 'none';
			dojo.byId('addrRow').style.display = 'none';
			dojo.byId('cityRow').style.display = 'none';
			dojo.byId('stateRow').style.display = 'none';
			dojo.byId('zipRow').style.display = 'none';
			dojo.byId('countryRow').style.display = 'none';
		break;
	}

}

function getStateByAbbr(abbr)
{
	var usStates = new Array();
	usStates['AL'] = 'Alabama';
	usStates['AK'] = 'Alaska';
	usStates['AZ'] = 'Arizona';
	usStates['AR'] = 'Arkansas';
	usStates['CA'] = 'California';
	usStates['CO'] = 'Colorado';
	usStates['CT'] = 'Connecticut';
	usStates['DE'] = 'Delaware';
	usStates['DC'] = 'District of Columbia';
	usStates['FL'] = 'Florida';
	usStates['GA'] = 'Georgia';
	usStates['HI'] = 'Hawaii';
	usStates['ID'] = 'Idaho';
	usStates['IL'] = 'Illinois';
	usStates['IN'] = 'Indiana';
	usStates['IA'] = 'Iowa';
	usStates['KS'] = 'Kansas';
	usStates['KY'] = 'Kentucky';
	usStates['LA'] = 'Louisiana';
	usStates['ME'] = 'Maine';
	usStates['MD'] = 'Maryland';
	usStates['MA'] = 'Massachusetts';
	usStates['MI'] = 'Michigan';
	usStates['MN'] = 'Minnesota';
	usStates['MS'] = 'Mississippi';
	usStates['MO'] = 'Missouri';
	usStates['MT'] = 'Montana';
	usStates['NE'] = 'Nebraska';
	usStates['NV'] = 'Nevada';
	usStates['NH'] = 'New Hampshire';
	usStates['NJ'] = 'New Jersey';
	usStates['NM'] = 'New Mexico';
	usStates['NY'] = 'New York';
	usStates['NC'] = 'North Carolina';
	usStates['ND'] = 'North Dakota';
	usStates['OH'] = 'Ohio';
	usStates['OK'] = 'Oklahoma';
	usStates['OR'] = 'Oregon';
	usStates['PA'] = 'Pennsylvania';
	usStates['RI'] = 'Rhode Island';
	usStates['SC'] = 'South Carolina';
	usStates['SD'] = 'South Dakota';
	usStates['TN'] = 'Tennessee';
	usStates['TX'] = 'Texas';
	usStates['UT'] = 'Utah';
	usStates['VT'] = 'Vermont';
	usStates['VA'] = 'Virginia';
	usStates['WA'] = 'Washington';
	usStates['WV'] = 'West Virginia';
	usStates['WI'] = 'Wisconsin';
	usStates['WY'] = 'Wyoming';
	
	var thisState = usStates[abbr];
	return thisState;
}



function selectPageSetDocument(args)
{
	dojo.xhrGet({
		url:	'/main/documentTemplateController.php?action=get_info&id='+args.selected+'&c='+args.company_id,
		handleAs: 'json',
		timeout: (90*1000),
		load: function(response){
			
			console.debug(response);
			
			dojo.byId(args.target).innerHTML = response.payload;
		}
		
		
	});
}

function wait(args)
{
    if(args.action == 'start')
    {
    	var c = '<div style="background-color: #000000; opacity: .25; height: 100%; width: 100%"></div><div style="width: 200px; height: 90px; background-color: #FFFFFF; border: solid 2px #CCCCCC; opacity: 1; top: 100px; left: 35%; position: absolute; padding: 20px; text-align: center;"><img style="padding-right: 20px;" align="absmiddle" height="32" width="32" src="/dojo/dojo-1.3/dojox/widget/Standby/images/loading.gif"/><br> ' + args.message + '</div>';
    	dojo.create('div', { id: args.id, innerHTML: c, style: 'height: 100%; width: 100%; top: 0px; left: 0px; position: absolute'}, args.target);              
    } else {
    	dojo.destroy(args.id);
    }
}

