/** Base64 encodes a string into a base64 or UTF-8 encoded string
	and also decodes the encoded string. Interchangeable with
	Usage Examples:
	  Base 64:
		encoded_str = Base64.encode("input");
			or
		decoded_str = Base64.decode("input");
	  UTF-8:
	  	encoded_utf_str = Base64.utf8_encode(input);
	  		or
	  	decoded_utf_str = Base64.utf8_decode(input);
*/
var Base64 = {
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64.utf8_encode(input);

		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
		}
		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = Base64.utf8_decode(output);
		return output;
	},

	// public method for UTF-8 encoding
	utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// public method for UTF-8 decoding
	utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = 0;
		var c1 = 0;
		var c2 = 0;

		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
};


/**
  simpleModalOptions Object
  used for eric martin's jQuery simpleModal plugin
  http://www.ericmmartin.com/projects/simplemodal/

  Contains properties and functions for modal window
  rendering options.

  Speeds can also be written in milliseconds
  e.g. openSpeed: 2000 //  = 2 seconds

 */


var simpleModalOptions = {

	openSpeed: 'slow',
	closeSpeed: 'fast',

	open: function(dialog) {
        screenWidth = $(window).width();
        screenHeight = $(window).height();
        width = $(dialog.container).width();
        left = (screenWidth/2) - (width/2);
		$(dialog.container).css({left: left});
	      dialog.overlay.fadeIn(this.openSpeed, function () {
          	dialog.container.slideDown(this.openSpeed, function () {
            	dialog.data.fadeIn(this.openSpeed);
          	});
		});
	},

	close: function(dialog) {
	      dialog.data.fadeOut(this.closeSpeed, function () {
          	dialog.container.slideUp(this.closeSpeed, function () {
            	dialog.overlay.fadeOut(this.closeSpeed, function() {
                	$.modal.close();
                });
          	});
		});
	}
};


/*This function takes three parameters.  Needs to be invoked on the
  onkeyup event on the form element. When the user types the moveLength
  number of characters in the currentElement, the cursor automatically
  moves to the nextElement.
*/
function moveToNextElement(currentElement, moveLength, nextElement){
	if(currentElement.value.length == moveLength){
		nextElement.focus();
	}
}

/*
	This function takes a text input and gives an alert if the input
	is not a valid email address format. Also, shifts the focus back
	to the input field on the form.
*/
function checkFormatEmail(emailElement){
	var email_address = emailElement.value;
	if (!(email_address.indexOf(".") > 0 && email_address.indexOf("@") > 0)){
		alert("Please enter a valid email address.");
		emailElement.focus();
	}
}

function isValidEmail(str) {
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(pattern.test(str)){
		return true;
    }else{
		return false;
    }
	//return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

/*
	Initiates a list purchase session.
*/
function PurchaseList(campaign_type){
	window.open("/purchaselist/begin/?campaign_type=" + campaign_type, 'usadata', 'width=825,height=665,scrollbars=yes,resizable=yes');
}
/*
	Initiates a duplicate list purchase session.
*/
function reorderList(list_db_type, usadata_order_id){
	window.open("/purchaselist/duplicate/" + list_db_type + "/" + usadata_order_id, 'usadata', 'width=825,height=665,scrollbars=yes,resizable=yes');
}
/*
	Resumes a List Search session
*/
function resumeSearch(enc_list_id){
	window.open("/purchaselist/resume/"+enc_list_id, 'usadata', 'width=825,height=665,scrollbars=yes,resizable=yes');
}
/*
	Exports a USAData search result
*/
function exportSearchResults(sessionDetails) {
	showProcessLayer("processing_screen");
	document.location.href="/purchaselist/export_search_results/?" + sessionDetails;
	setTimeout("hideLayer('processing_screen')",4000);
}
/*
	Generic AJAX query handler. Expects two parameters: queryHandler,
	queryString.
	queryHandler: gets prefixed with sucess and failure for the function
				  names that will handle the success or failure of the
				  query.
	queryString: gets suffixed by "/ajaxquery/" and that url is then
				 called by the function.
*/
function queryAJAX(queryHandler, queryString){
	var ajaxURL = "/ajaxquery/" + queryString;
	var successHandler = "success" + queryHandler;
	var failureHandler = "ajaxFailureHandler";
	var postalData = YAHOO.util.Connect.asyncRequest('GET', ajaxURL, { success:eval(successHandler), failure:eval(failureHandler), cache:false });
}

/*
	Generic AJAX query handler. Expects two parameters: queryHandler,
	queryString.
	queryHandler: gets prefixed with sucess and failure for the function
				  names that will handle the success or failure of the
				  query.
	queryString: gets suffixed by "/ajaxquery/" and that url is then
				 called by the function.
*/
function postAJAX(queryForm, queryString, postType){
	var ajaxURL = "/ajaxquery/" + queryString;
	var formObject = document.getElementById(queryForm);
	switch (postType){
		case "FormPost":
			var callback = null;
			file_submit = false;
			ssl_submit = true;
			break;
		case "FilePost":
			var callback = null;
			file_submit = true;
			ssl_submit = true;
			break;
	}
	YAHOO.util.Connect.setForm(formObject, file_submit, ssl_submit);
	var postData = YAHOO.util.Connect.asyncRequest("POST", ajaxURL, callback);
}

/*
	Function parses an XML String and returns an XML object
*/
function parseXMLString(xmlText){
	var xmlDoc;
	// code for IE
	if (window.ActiveXObject){
		var doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(xmlText);
	}else{
	// code for Mozilla, Firefox, Opera, etc.
		var parser=new DOMParser();
		var doc=parser.parseFromString(xmlText,"text/xml");
	}
	return doc.documentElement;
}


/*
	Function finds postal code in
*/
/*
function doPostalQuery(FormName, prefix){
	if (prefix === undefined ) {
		var handlerFunction = "PostalCodes";
		var postal_code_val = document.forms[FormName].postal_code.value;
	} else {
		var postal_code = prefix + "postal_code";
		var handlerFunction = "PostalCodesInv";
		var postal_code_val = document.forms[FormName].inv_postal_code.value;
	}
	if (postal_code_val != "" && postal_code_val.length > 4){
		queryURL = "postalcode/" + postal_code_val;
		//method defined in site_tools.js
		queryAJAX(handlerFunction, queryURL);
	}
}
*/

function doPostalQuery(FormName){
	var handlerFunction = "PostalCodes";
	var postal_code_val = document.forms[FormName].postal_code.value;
	if (postal_code_val != "" && postal_code_val.length > 4){
		queryURL = "postalcode/" + postal_code_val;
		//method defined in site_tools.js
		queryAJAX(handlerFunction, queryURL);
	}
}

/*
	Success handler for the postalCodes Ajax query.
*/
function successPostalCodes(o){
	var root = o.responseXML.documentElement;
	var oCity = root.getElementsByTagName('city')[0].firstChild.nodeValue;
	var oRegionCode = root.getElementsByTagName('regionCode')[0].firstChild.nodeValue;
	var oCountryCode = root.getElementsByTagName('countryCode')[0].firstChild.nodeValue;
	var oCountryName = root.getElementsByTagName('countryName')[0].firstChild.nodeValue;

	if (oCity == "INVALID" || oRegionCode == "INVALID" || oCountryCode == "INVALID") {
		divAddress = document.getElementById("ajax_address_data");
		divAddress.style.display = "block";
		divAddress.innerHTML = "Invalid Zip/Postal Code. Please try again.";
		document.getElementById("city").value = "";
		document.getElementById("region_code").value = "";
		document.getElementById("country_desc").value = "";
		document.getElementById("country_code").value = "";
	} else {
		divAddress = document.getElementById("ajax_address_data");
		divAddress.style.display = "none";
		document.getElementById("city").value = oCity;
		document.getElementById("region_code").value = oRegionCode;
		document.getElementById("country_desc").value = oCountryName;
		document.getElementById("country_code").value = oCountryCode;
	}
}

function successPostalCodesInv(o){
	var root = o.responseXML.documentElement;
	var oCity = root.getElementsByTagName('city')[0].firstChild.nodeValue;
	var oRegionCode = root.getElementsByTagName('regionCode')[0].firstChild.nodeValue;
	var oCountryCode = root.getElementsByTagName('countryCode')[0].firstChild.nodeValue;
	var oCountryName = root.getElementsByTagName('countryName')[0].firstChild.nodeValue;

	if (oCity == "INVALID" || oRegionCode == "INVALID" || oCountryCode == "INVALID") {
		divAddress = document.getElementById("ajax_address_data");
		divAddress.style.display = "block";
		divAddress.innerHTML = "Invalid Zip/Postal Code. Please try again.";
		document.getElementById("inv_city").value = "";
		document.getElementById("inv_region_code").value = "";
		document.getElementById("inv_country_desc").value = "";
		document.getElementById("inv_country_code").value = "";
	} else {
		divAddress = document.getElementById("ajax_address_data");
		divAddress.style.display = "none";
		document.getElementById("inv_city").value = oCity;
		document.getElementById("inv_region_code").value = oRegionCode;
		document.getElementById("inv_country_desc").value = oCountryName;
		document.getElementById("inv_country_code").value = oCountryCode;
	}
}

/*
	Function finds postal code in
*/
function PostalQuery(CityName, StateName, CountryName, CountryCode, AlertField, ZipValue){
	var handlerFunction = "UpdatePostalCode";
	var postal_code_val = ZipValue;
	var qry = "";
	if (postal_code_val != "" && postal_code_val.length > 4){
		if (CityName != ""){
			if (qry != ""){
				qry += "&";
			}
			qry += "city=" + CityName;
		}
		if (StateName != ""){
			if (qry != ""){
				qry += "&";
			}
			qry += "state=" + StateName;
		}
		if (CountryName != ""){
			if (qry != ""){
				qry += "&";
			}
			qry += "country=" + CountryName;
		}
		if (CountryCode != ""){
			if (qry != ""){
				qry += "&";
			}
			qry += "countrycode=" + CountryCode;
		}
		if (AlertField != ""){
			if (qry != ""){
				qry += "&";
			}
			qry += "alertfield=" + AlertField;
		}
		queryURL = "postalcode/" + postal_code_val + "?" + qry;
		//method defined in site_tools.js
		queryAJAX(handlerFunction, queryURL);
	}
}

/*
	Success handler for the postalCodes Ajax query.
*/
function successUpdatePostalCode(o){
	var root = o.responseXML.documentElement;
	var oCity = root.getElementsByTagName('city')[0].firstChild.nodeValue;
	var oRegionCode = root.getElementsByTagName('regionCode')[0].firstChild.nodeValue;
	var oCountryCode = root.getElementsByTagName('countryCode')[0].firstChild.nodeValue;
	var oCountryName = root.getElementsByTagName('countryName')[0].firstChild.nodeValue;
	var qry_string = root.getElementsByTagName('queryString')[0].firstChild.nodeValue;
	var city_name = "";
	var state_name = "";
	var country_name = "";
	var country_code = "";

	if (qry_string != "INVALID"){
		var ar_qry = qry_string.split("&");
		for (var i=0; i < ar_qry.length;i++) {
			var ar_qry_str = ar_qry[i].split("=");
			switch (ar_qry_str[0]){
				case "city":
					city_name = ar_qry_str[1];
					break;
				case "state":
					state_name = ar_qry_str[1];
					break;
				case "country":
					country_name = ar_qry_str[1];
					break;
				case "countrycode":
					country_code = ar_qry_str[1];
					break;
				case "alertfield":
					alert_field = ar_qry_str[1];
					break;
			}
		}
	}

	if (oCity != "INVALID" && oRegionCode != "INVALID" && oCountryCode != "INVALID" && qry_string != "INVALID") {
		divAddress = document.getElementById(alert_field);
		divAddress.style.display = "none";
		document.getElementById(city_name).value = oCity;
		document.getElementById(state_name).value = oRegionCode;
		if (country_name != ""){
			document.getElementById(country_name).value = oCountryName;
		}
		if (country_code != ""){
			document.getElementById(country_code).value = oCountryCode;
		}
	}else{
		divAddress = document.getElementById(alert_field);
		divAddress.style.display = "block";
		divAddress.innerHTML = "Invalid Zip/Postal Code. Please try again.";
		if (city_name != "" && state_name != ""){
			document.getElementById(city_name).value = "";
			document.getElementById(state_name).value = "";
		}
		if (country_name != ""){
			document.getElementById(country_name).value = "";
		}
		if (country_code != ""){
			document.getElementById(country_code).value = oCountryCode;
		}
	}
}

/*
	Failure handler for the postalCodes Ajax query.
*/
function ajaxFailureHandler(o){
	//alert("The system is having some problems. Please check back at a later time.");
	setTimeout(alert("The system is having some problems. Please check back at a later time."), 200);
}

/*
	User Cancels adding new column
*/
function cancelAddNewColumn(){
	document.map_fields[document.new_column_form.map_new_col_to.value].selectedIndex = 0;
	document.new_column_form.map_new_col_to.value = "";
	document.new_column_form.new_column.value = "";
	document.new_column_form.col_data_type.selectedIndex = 0;
	hideLayer("addcolumn");
	//document.getElementById("addcolumn").style.visibility = "hidden";

	//disable all forms on the page
	for(i=0; i<document.map_fields.elements.length; i++) {
		document.map_fields.elements[i].disabled = false;
	}
}
/*
	Function to let user map uploaded list to fields
*/
function mapListFields(selectedField, selectedColumn, async, formats){
	var async = async === false ? false: true;
	var formats = formats || [];
	var mapcols = 1;

	if (selectedField != "ignore" && selectedField != "add_new") {
		for(i=0; i<document.map_fields.elements.length; i++) {
			if (document.map_fields.elements[i].name != selectedColumn && document.map_fields.elements[i].value == selectedField) {
				//alert("You have already mapped this field to another column, please make another selection.");
				Ext.Msg.alert("Invalid Selection", "You have already mapped this field to another column, please make other selection.");
				document.map_fields[selectedColumn].selectedIndex = 0;
				mapcols = 0;
			}
		}
	}

	if (mapcols == 1 && selectedField != "add_new") {
		if ( async ) {
			handlerFunction = "MapColumns";
			queryURL = "userlist/mapcols/" + selectedField + "/" + selectedColumn;
			queryAJAX(handlerFunction, queryURL);
		}
		else {
			if ( selectedField == 'ignore' ) {
				$('#pc_' + selectedColumn).hide();
				$("[@name=propercase_" + selectedColumn + "]").attr('checked', false);
			} else {
				var format = formats[selectedField];

				if ( (format == 'TEXT' || format == 'PROPERCASE' )
					&& selectedField != 'address1' && selectedField != 'address2'
					&& selectedField != 'city' && selectedField != 'state'
					&& selectedField != 'zip' && selectedField != 'country') {

					$('#pc_' + selectedColumn).show();
					if (format == 'PROPERCASE') {
						$("[@name=propercase_" + selectedColumn + "]").attr('checked', true);
					}
				}
			}
		}
	}

	//Add new column functionality
	if (selectedField == "add_new") {
		//disable all forms on the page
		for(i=0; i<document.map_fields.elements.length; i++) {
			document.map_fields.elements[i].disabled = true;
		}
		//activate the add new column layer
		showLayer("addcolumn", "no");
		//document.getElementById("addcolumn").style.visibility = "visible";
		document.new_column_form.map_new_col_to.value = selectedColumn;
	}
}

/*
	Success Handler for MapColumns
*/
function successMapColumns(o){
	var root = o.responseXML.documentElement;
	var oResult = root.getElementsByTagName('result')[0].firstChild.nodeValue;
	if (oResult != "SUCCESS") {
		//alert("There was an error mapping the field. Please try again later.");
		Ext.Msg.alert("Status", "There was an error mapping the field. Please try again later.");
	}
	else {
		var field = root.getElementsByTagName('field')[0].firstChild.nodeValue;
		var column = root.getElementsByTagName('column')[0].firstChild.nodeValue;

		if ( field == 'ignore' ) {
			$('#pc_' + column).hide();
			$("[@name=propercase_" + column + "]").attr('checked', false);
		} else {
			var format = root.getElementsByTagName('format')[0].firstChild.nodeValue;

			if ( (format == 'TEXT' || format == 'PROPERCASE' )
				&& field != 'address1' && field != 'address2'
				&& field != 'city' && field != 'state'
				&& field != 'zip' && field != 'country') {

				$('#pc_' + column).show();
				if (format == 'PROPERCASE') {
					$("[@name=propercase_" + column + "]").attr('checked', true);
				}
			}
		}
	}
}

/*
	Function gets all list columns in the current ListManager session
*/
function getListColumns(){
	var handlerFunction = "ListColumns";
	var queryURL = "userlist/listcols";
	queryAJAX(handlerFunction, queryURL);
}

/*
	Function gets all ProgramImages associated with the program id.
*/
function getTemplates(ProgramID){
	var handlerFunction = "ProgramImages";
	var queryURL = "programimages/" + ProgramID;
	queryAJAX(handlerFunction, queryURL);
}

/*
	Success handler for the ProgramImages Ajax query.
*/
function successProgramImages(o){
	var root = o.responseXML.documentElement;
	document.getElementById("ProgramTitle").innerHTML = root.getElementsByTagName("programName")[0].firstChild.nodeValue;
	document.getElementById("ProgramDescription").innerHTML = root.getElementsByTagName("programDescription")[0].firstChild.nodeValue;
	document.getElementById("master_account_id").value = root.getElementsByTagName("programMasterAccountID")[0].firstChild.nodeValue;
	var oSizes = root.getElementsByTagName("programSizes");
	var numberofSizes = oSizes.length;
	var oColumns = root.getElementsByTagName("column");
	var numberOfColumns = oColumns.length;
	var currentSize = root.getElementsByTagName("sizeTitle")[0].firstChild.nodeValue;
	var adPrice = "";
	var htmlString = "<div id='selecttemplatetop'></div><div id='selecttemplate'><table border='0' cellpadding='3' cellspacing='1'>";
	htmlString += "<tr><td class='sizebg'><strong>" + currentSize + "</strong></td></tr><tr>";
	var count = 0;
	for (x=0; x<numberOfColumns; x++){
		templateLabel = root.getElementsByTagName("templateLabel")[x].firstChild.nodeValue;
		templateType = root.getElementsByTagName("templateType")[x].firstChild.nodeValue;
		description = root.getElementsByTagName("description")[x].firstChild.nodeValue;
		fold = root.getElementsByTagName("fold")[x].firstChild.nodeValue;
		loadDocumentID = root.getElementsByTagName("loadDocumentID")[x].firstChild.nodeValue;
		layerID = root.getElementsByTagName("layerID")[x].firstChild.nodeValue;
		imageFile = root.getElementsByTagName("imageFile")[x].firstChild.nodeValue;
		thumbnailFile = root.getElementsByTagName("thumbnailFile")[x].firstChild.nodeValue;
		sizeID = root.getElementsByTagName("sizeID")[x].firstChild.nodeValue;
		sizeLabel = root.getElementsByTagName("sizeLabel")[x].firstChild.nodeValue;
		size = root.getElementsByTagName("size")[x].firstChild.nodeValue;
		uproduceID = root.getElementsByTagName("uproduceID")[x].firstChild.nodeValue;
		recommended = root.getElementsByTagName("recommended")[x].firstChild.nodeValue;
		pdfExists = root.getElementsByTagName("pdfExists")[x].firstChild.nodeValue;
		selectionLink = root.getElementsByTagName("selectionLink")[x].firstChild.nodeValue;
		if (currentSize != sizeLabel){
			currentSize = sizeLabel;
			NewSize = true;
			NewRow = true;
		}else{
			NewSize = false;
			NewRow = false;
		}
		if (NewSize){
			htmlString += "</tr><tr><td>&nbsp;</td></tr>";
			htmlString += "<tr><td class='sizebg'><strong>" + currentSize + "</strong></td>";
		}
		if (NewRow){
			count = 0;
			if (htmlString != ""){
				htmlString += "</tr><tr>";
			}
		}
		htmlString += "<td align='center'><div style='padding:3px 0;'><a alt='" + templateLabel + "' title='" + templateLabel + "'>";
		// Recommended Check
		if (templateLabel.length > 18){
			templateLabel = templateLabel.substr(0,15) + "...";
		}
		htmlString += templateLabel + "</a></div>";
		htmlString += "<div style='width:160px; border:1px solid #cccccc; height:168px; padding:5px 0;'>";
		htmlString += "<table border='0' cellpadding='0' cellspacing='0' height='100%'><tr><td align='center' valign='middle'>";
		htmlString += "<a href='javascript: doMagnify(&quot;" + selectionLink;
		htmlString += "&quot;);'><img src='/images/template_thumbnails/" + thumbnailFile + "' border='0' title='" + templateLabel;
		htmlString += "' alt='" + templateLabel + "' style='vertical-align:middle;'></a></td></tr>";
		if (recommended == "yes"){
			htmlString += "<tr><td align='center' valign='middle'><img src='/images/icon_recommend.gif' border='0' title='Recommended' ";
			htmlString += "alt='Recommended' style='vertical-align:middle;' height='18' width='116'></td></tr>";
		}else{
			htmlString += "<tr><td height='18'>&nbsp;</td></tr>";
		}
		htmlString += "</table></div>";
		htmlString += "<div style='margin-top: 3px; width: 160px; height: 80px;'>";
		htmlString += "<div style='padding:0 0 0 6px; text-align: left;'><img src='/images/icon_view_options.gif' align='absmiddle' border='0' alt=' ' />&nbsp;";
		htmlString += "<a class='utext' style='vertical-align:middle;font-size: 10px;color: #666666;' href='javascript: doMagnify(&quot;";
		htmlString += selectionLink + "&quot;);'>";
		htmlString += "View Template Options</a></div>";
		htmlString += "<div style='padding:0 0 0 6px; text-align: left;'><img src='/images/icon_view_pricing.gif' align='absmiddle' border='0' alt=' ' />&nbsp;";
		htmlString += "<a class='utext' style='vertical-align:middle;font-size: 10px;color: #666666;' href='javascript: doTemplateDetails(&quot;";
		htmlString += selectionLink + "&quot;)'>";
		htmlString += "View Pricing Details</a></div>";
		if (pdfExists == "yes"){
			htmlString += "<div style='padding:0 0 0 6px; text-align:left;'><img src='/images/icon_view_hires.gif' align='absmiddle' border='0' alt=' ' />&nbsp;";
			htmlString += "<a class='utext' style='vertical-align:middle;font-size: 10px;color: #666666;' href='javascript: doPDFPreview(&quot;";
			htmlString += selectionLink + "&quot;);'>";
			htmlString += "View Hi Res PDF</a></div>";
		}else{
			htmlString += "<div style='padding:2px 0; text-align:left;'>&nbsp;</div>";
		}
		htmlString += "<div style='padding:5px 0;'><input style='width:150px;cursor:pointer;' type='button' value='Select & Continue' name='" + layerID + "_" + sizeID;
		htmlString += "' onclick='javascript: doSelection(&quot;" + selectionLink + "&quot;, &quot;" + templateType + "&quot;);'>";
		htmlString += "</div></div></td>";
		switch (true){
			case (((count%3) == 0) || ((count%3) == 1)):
				//alert("left side or center");
				break;
			case ((count%3) == 2):
				if (htmlString != ""){
					htmlString += "</tr><tr>";
				}
				break;
		}
		count++;
	}
	htmlString += "</tr></table></div>";
	document.getElementById("template_images").innerHTML = htmlString;
	hideLayer("template_details");
}

/*
	Success Handler for getListColumns
*/
function successListColumns(o){
	var root = o.responseXML.documentElement;
	var oColumns = root.getElementsByTagName("column");
	var numberOfColumns = oColumns.length;
	var test_string = '';
	for (x=0; x<numberOfColumns; x++){
		test_string += '' + root.getElementsByTagName('field_name')[x].firstChild.nodeValue + '--';
	}
}
/**
 * hideLayer sets the css property visibility to hidden of the target element;
 * it does not set the property display to none.
 *
 * @param string zlayer - target element's id attribute
 * @param function callback - function to execute when blockUI has finished
 * removing all blockUI elements from the dom.
 *
 */
function hideLayer(zlayer) {
	if ($('.blockUI').length > 0) {
		$('html').unblock();
		$('#loading-indicator-wrap').hide();
	} else {
		$("#" + zlayer).css('visibility', 'hidden');
		$("#DivShim").css('visibility', 'hidden');
	}
}

function showLayer(zlayer, shift){
	var DivRef = document.getElementById(zlayer);

	DivRef.style.visibility = "visible";
	var divWidth = DivRef.offsetWidth;
	var divHeight = DivRef.offsetHeight;

   	var IfrRef = document.getElementById('DivShim');
   	if (shift != "no"){
   		if(typeof( window.pageYOffset) == "number") {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		}else if( document.body && ( document.body.scrollLeft || document.body.scrollTop )){
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		}else if( document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop )){
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}else{
			//IE7 standards compliant, I guess
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
	   	var posx = YAHOO.util.Dom.getViewportWidth();
		var posy = YAHOO.util.Dom.getViewportHeight();

		posx = ((Number(posx) - 325)/2) + scrOfX;
		posy = ((Number(posy) - 300)/2) + scrOfY;
   	}else{
		var posx = YAHOO.util.Dom.getX([zlayer]);
		var posy = YAHOO.util.Dom.getY([zlayer]);
   	}

	YAHOO.util.Dom.setStyle('DivShim', 'width', divWidth);
	YAHOO.util.Dom.setStyle('DivShim', 'height', divHeight);
	YAHOO.util.Dom.setX('DivShim', posx);
	YAHOO.util.Dom.setY('DivShim', posy);
	if (shift != "no"){
		YAHOO.util.Dom.setX(zlayer, posx);
		YAHOO.util.Dom.setY(zlayer, posy);
	}
	YAHOO.util.Dom.setStyle('DivShim', 'z-index', (DivRef.style.zIndex - 1));
	YAHOO.util.Dom.setStyle('DivShim', 'visibility', 'visible');

}
/*
	Lets the user escape data input in a list column or field
*/
function listViewEsc(evt){
	var key = document.all ? event.keyCode : document.layers ? evt.which : evt.keyCode;
    if (key == 27) {
		deactivateElement();
	}
}


/*
	Success handler for updating list data
*/
function successUpdateListData(o){
	var root = o.responseXML.documentElement;
	var oResult = root.getElementsByTagName('result')[0].firstChild.nodeValue;
	var oColUpdated = root.getElementsByTagName('colUpdated')[0].firstChild.nodeValue;
	var oRowUpdated = root.getElementsByTagName('rowUpdated')[0].firstChild.nodeValue;

	if (oResult != "SUCCESS") {
		alert("There was an error updating the data. Please try again later.");
		elementBox = document.getElementById(oColUpdated);
		elementBox.style.border = "0px";
		elementBox.style.background = editedBoxBG[oColUpdated];
		elementBox.style.padding = "2px";
		elementBox.value = origElementBoxValue;
	} else {
		elementBox = document.getElementById(oColUpdated);
		elementBox.style.border = "0px";
		elementBox.style.background = editedBoxBG[oColUpdated];
		elementBox.style.padding = "2px";
		elementRow = document.getElementById(oRowUpdated);

		//elementcass = document.getElementById(oRowUpdated + '+cass_message');
		//elementcassNav = elementcass.title;
		//elementcass.innerHTML = '<a href="/member_assets/lists/confirmaddress/' + oRowUpdated + '/' + elementcassNav + '">Confirm valid address?</a>';

		//for (x=0; x<document.list_view.elements.length; x++) {
			//if (testrow = document.list_view.elements[x].name.indexOf(oRowUpdated + '+')) {
				//document.list_view.elements[x].readonly = "";
				//formElement = document.getElementById(document.list_view.elements[x].name);
				//formElement.style.background = "#ffff99";
			//}
		//}
	}
}
/**
	The following vars are there to help with ajax functionality of updating
	list data.
**/

//store the original value of the editable text box.
var origElementBoxValue = "";
var elementBoxID;
var origElementBoxBackground;
var editedBoxBG = new Array();

/*
	Activate a form element so user can see it is editable
*/

function activateElement(elementID) {
	elementBoxID = elementID;
	elementBox = document.getElementById(elementID);
	origElementBoxBackground = elementBox.style.background;
	elementBox.style.border = "1px solid #666666";
	elementBox.style.background = "#EEEEEE";
	elementBox.style.padding = "1px";
	elementBox.readOnly = false;
	elementBox.hasLayout = true;
	elementBox.contentEditable = true;
	origElementBoxValue = elementBox.value;
}

/*
	De-activate a form element after user action of hitting
	the escape key or tabbing to the next element.
*/

function deactivateElement(resetElement){
	elementBox = document.getElementById(elementBoxID);
	elementBox.style.border = "0px";
	elementBox.style.background = origElementBoxBackground;
	elementBox.style.padding = "2px";

	//document.list-nav-links.focus();
	elementBox.readOnly = true;
	if (resetElement != 'keepnewvalue') {
		elementBox.value = origElementBoxValue;
	}
}

/*
	Check if data in the cell has changed. If it has do an
	ajax call to update the list data
*/
function checkListData() {
	elementBox = document.getElementById(elementBoxID);
	if(elementBox.value != origElementBoxValue) {
		//populate the editedBoxArray to reset box after ajax call
		editedBoxBG[elementBoxID] = origElementBoxBackground;

		//start doing ajax update. send value base64 encoded
		elementValue = elementBox.value.replace("/", "@@@");
		handlerFunction = "UpdateListData";
		queryURL = "userlist/update/" + elementBoxID + "/" + elementValue;
		//test = prompt("Testing..",queryURL);
		queryAJAX(handlerFunction, queryURL);
	} else {
		deactivateElement();
	}
}

/**
 * Performs a async call to update a reciepient field value if the cell
 * has changed
 *
 * @param  oid the encrypted order_id
 */
function checkRecipientField(oid) {
	elementBox = document.getElementById(elementBoxID);
	if(elementBox.value != origElementBoxValue) {
		//populate the editedBoxArray to reset box after ajax call
		editedBoxBG[elementBoxID] = origElementBoxBackground;

		//start doing ajax update
		elementValue = elementBox.value.replace('/', '@@@');
		var queryURL = '/admin/offline_ship_orders/recipients/' + oid + '/update/' + elementBoxID + '/' + elementValue;
		var callback = {
  			success: function(o) { successUpdateRecipientData(o);	},
  			failure: function(o) { ajaxFailureHandler(o); },
  			cache: false
		};
		YAHOO.util.Connect.asyncRequest('GET', queryURL, callback);

	} else {
		deactivateElement();
	}
}

function successUpdateRecipientData(o) {
	var result = 'FAILURE';
	if ( o.responseXML ) {
		var root = o.responseXML.documentElement;
		var result = root.getElementsByTagName('result')[0].firstChild.nodeValue;
		var element_id = root.getElementsByTagName('colUpdated')[0].firstChild.nodeValue;
		var row_number = root.getElementsByTagName('rowUpdated')[0].firstChild.nodeValue;
		var validated = root.getElementsByTagName('validated')[0].firstChild.nodeValue;
	}

	if (result != "SUCCESS") {
		alert("There was an error updating the data. Please try again later.");
		elementBox = document.getElementById(element_id);
		elementBox.style.border = "0px";
		elementBox.style.background = editedBoxBG[element_id];
		elementBox.style.padding = "2px";
		elementBox.value = origElementBoxValue;
	} else {
		elementBox = document.getElementById(element_id);
		elementBox.style.border = "0px";
		elementBox.style.background = editedBoxBG[element_id];
		elementBox.style.padding = "2px";

		if ( validated != 'TRUE' ) {
			elementRow = document.getElementById('row-' + row_number);
			elementRow.className = 'vcode-31';

			elementBtn = document.getElementById('btn-validate');
			elementBtn.disabled = false;
		}
	}
}


/*
	Limit Text area max input characters
*/
function limitTextAreaInput(maxAllowed, areaElement){
	if (areaElement.value.length > maxAllowed) {
		areaElement.value = areaElement.value.substring(0,maxAllowed);
		alert("The maximum amount of text has been reached.");
	}
}

/*
	Asset Library functions
*/
function selectImage(library_id, image_id){
	if (library_id != "" && image_id != ""){
		//do ajax call to get image details.
		handlerFunction = "ImageAssetDetails";
		queryURL = "asset_library/asset_details/" + library_id + "/" + image_id;
		//prompt('test', queryURL);
		queryAJAX(handlerFunction, queryURL);
	}
}

function successImageAssetDetails(o){
	var root = o.responseXML.documentElement;
	var asset_id = root.getElementsByTagName('asset_id')[0].firstChild.nodeValue;
	if (asset_id == "INVALID") {
		alert("The image data could not be retrieved. Please try again later.");
	} else {
		//start retrieving image details
		library_id = root.getElementsByTagName('library_id')[0].firstChild.nodeValue;
		is_editable = root.getElementsByTagName('is_editable')[0].firstChild.nodeValue;
		extension = root.getElementsByTagName('extension')[0].firstChild.nodeValue;
		mime_type = root.getElementsByTagName('mime_type')[0].firstChild.nodeValue;
		label = root.getElementsByTagName('label')[0].firstChild.nodeValue;
		description = root.getElementsByTagName('description')[0].firstChild.nodeValue;
		resolution_dpi = root.getElementsByTagName('resolution_dpi')[0].firstChild.nodeValue;
		pixel_width = root.getElementsByTagName('pixel_width')[0].firstChild.nodeValue;
		pixel_height = root.getElementsByTagName('pixel_height')[0].firstChild.nodeValue;
		resolution_level = root.getElementsByTagName('resolution_level')[0].firstChild.nodeValue;
		image_filename = root.getElementsByTagName('image_filename')[0].firstChild.nodeValue;
		thumb_filename = root.getElementsByTagName('thumb_filename')[0].firstChild.nodeValue;

		//create the html to populate the div tag to view image details.
		inner_html = "<div class='libraryheader'><p style='padding: 2px 3px 5px 15px;margin-top: 0px;'><strong>" + label + "</strong></p></div>";
		inner_html = inner_html + "<div style='margin-bottom: 25px; padding-left:15px;'><p style='margin-top: 15px; text-align: center;width: 150px; border: 1px solid #8C8C8C; background-color: #cccccc; padding: 3px;'><img src='/images/account/assets/" + thumb_filename + "'></p>";
		inner_html = inner_html + "<p><strong>Actions:</strong> ";
		inner_html = inner_html + "<blockquote><a href='/member_assets/imagelibrary/asset/download/" + library_id + "/" + asset_id + "' style='text-decoration:none;color:#144b9e;'><span style='padding: 1px 8px 1px 8px; background-color: #C9DAF4; border: 1px solid #144b9e;'>download</span></a>";
		if (is_editable == "TRUE") {
			inner_html = inner_html + "&nbsp;&nbsp;<a href='javascript: editSelectedImage();' style='text-decoration:none; color:#144b9e;'><span style='padding: 1px 16px 1px 16px;background-color: #C9DAF4; border: 1px solid #144b9e;'>edit</span></a>";
			inner_html = inner_html + "&nbsp;&nbsp;<a href='javascript: deleteSelectedImage();' style='text-decoration:none;color:#144b9e;'><span style='padding: 1px 12px 1px 12px; background-color: #C9DAF4; border: 1px solid #144b9e;'>delete</span></a>";
		}
		inner_html = inner_html + "</blockquote></p>";
		inner_html = inner_html + "<p><strong>Description:</strong> ";
		inner_html = inner_html + "<blockquote>" + description +  "</blockquote></p>";
		inner_html = inner_html + "<p><strong>Resolution:</strong>";
		if (extension == "jpg" || extension == "tif") {
			inner_html = inner_html + "<blockquote>" + resolution_dpi + "dpi - ";
			inner_html = inner_html + "(" + pixel_width + "x" + pixel_height +  ")</blockquote></p></div>";
		} else {
			inner_html = inner_html + " (" + resolution_level + ")</p></div>";
		}
		document.getElementById("image-detail").innerHTML = inner_html;
		document.editImage.asset_id.value = asset_id;
		document.editImage.label.value = label;
		document.editImage.description.value = description;
	}
}

var assetLibraryIDURL = "";
function deleteSelectedImage(){
	var asset_id = document.editImage.asset_id.value;
	var library_id = document.editImage.library_id.options[document.editImage.library_id.selectedIndex].value;
	assetLibraryIDURL = "/member_assets/imagelibrary/asset/delete/" + library_id + "/" + asset_id;
	if (asset_id != "" && library_id != ""){
		Ext.Msg.confirm("Delete Image?", "Are you sure you want to delete this image?", deleteSelectedImageClicked);
		/*if (confirm("Are you sure you want to delete this image?")) {
			document.location = "/member_assets/imagelibrary/asset/delete/" + library_id + "/" + asset_id;
		}*/
	}
}
function deleteSelectedImageClicked(id) {
	if (id == "yes") {
		document.location = assetLibraryIDURL;
	}
	assetLibraryIDURL = "";
}

function updateProfile(){
	var str = "";
	var val_str = "";
	for (var i = 0; i< document.edit_profile.length; i++){
		var field = document.edit_profile.elements[i];
		var field_value = document.getElementById(field.name).value;

		if (i < 5){
			if (val_str != ""){
				val_str = val_str + "&&&";
			}
			val_str = val_str + field.name + "=" + field_value;
		}else{
			if ((field.name.substr(0,3) != "req") && (field.name.substr(0,3) != "lab") &&
				(field.name.substr(0,3) != "frt")){
				req_field = "req_" + field.name;
				req_value = document.getElementById(req_field).value;
				lab_field = "lab_" + field.name;
				lab_value = document.getElementById(lab_field).value;

				//str = str + field.name + ": " + field_value + "\n";
				if ((field_value == "") && (req_value == "yes")){
					str = str + lab_value;
					str = str + " requires information to be entered.\n";
				}else{
					if (field_value != ""){
						val_str = val_str + "&&&" + field.name + "=" + field_value;
					}
				}
			}
		}
	}
	if (str != ""){
		Ext.Msg.alert("Profile", str.replace(/\n/g, "<br />"));
	}else{
		handlerFunction = "UpdateProfile";
		queryURL = "profiles/" + Base64.encode(val_str);
		queryAJAX(handlerFunction, queryURL);
		//prompt("", Base64.encode(val_str));
	}
}

function successUpdateProfile(o){
	var root = o.responseXML.documentElement;
	var oErrors = root.getElementsByTagName("errorsFound");
	var numberofErrors = oErrors.length;
	var oColumns = root.getElementsByTagName("column");
	var numberOfColumns = oColumns.length;

	if (root.getElementsByTagName("errorMessage")[0].firstChild.nodeValue == "None"){
		if (root.getElementsByTagName("locationID")[0].firstChild.nodeValue == "invalid"){
			str = "There was a problem saving the profile.\n";
			str = str + "Technical support has been notified.";
		}else{
			var new_drop_value = new Array();
			var new_drop_label = new Array();
			var new_drop_selected = new Array();
			loc_id = "";
			cur_loc_id = "";
			loc_id_selected = "";
			data_count = 0;
			prof_count = 0;
			drop_down_count = 0;
			new_drop_value[drop_down_count] = "#";
			new_drop_label[drop_down_count] = "Please select one";
			new_drop_selected[drop_down_count] = "";
			for (i=0; i<numberOfColumns; i++){
				loc_id = root.getElementsByTagName("locationID")[i].firstChild.nodeValue;
				attr_label = root.getElementsByTagName("attributeLabel")[i].firstChild.nodeValue;
				attr_name = root.getElementsByTagName("attributeName")[i].firstChild.nodeValue;
				attr_data = root.getElementsByTagName("attributeData")[i].firstChild.nodeValue;
				loc_selected = root.getElementsByTagName("locationSelected")[i].firstChild.nodeValue;
				pro_update_name = root.getElementsByTagName("profileName")[i].firstChild.nodeValue;
				if (cur_loc_id != loc_id){
					cur_loc_id = loc_id;
					data_count = 0;
					prof_count = 0;
					profile[loc_id] = attr_label + ": ";
					profile[loc_id] = profile[loc_id] + attr_data + "<br />\n";

					drop_down_count++;
					new_drop_value[drop_down_count] = loc_id;
					new_drop_label[drop_down_count] = attr_data;
					if (loc_selected == "yes"){
						loc_id_selected = loc_id;
						new_drop_selected[drop_down_count] = "selected";
					}else{
						new_drop_selected[drop_down_count] = "";
					}
				}else{
					data_count++;
					prof_count++;
					if (prof_count < 7){
						profile[loc_id] = profile[loc_id] + attr_label + ": ";
						profile[loc_id] = profile[loc_id] + attr_data + "<br />\n";
					}
					if (prof_count == 7){
						profile[loc_id] = profile[loc_id] + "<div style='text-align:right;'><a href='javascript: ";
						profile[loc_id] = profile[loc_id] + "doEditProfile(&quot;find&quot;, &quot;" + loc_id + "&quot;);' ";
						profile[loc_id] = profile[loc_id] + "style='font-weight:bold; color:#0099FF; text-decoration:none;'>...more</a></div>";
					}
				}
				profile_name[loc_id + "_" + data_count] = attr_name;
				profile_data[loc_id + "_" + data_count] = attr_data;
				profile_count[loc_id] = data_count;
			}

			for (i=1; i <= req_profiles; i++){
				cur_pro_name = "profile_" + i;
				cur_profile_field = Number(pro_update_name.substr(13,1));
				cur_sel = document.getElementById(cur_pro_name).value;
				selected_value = "";
				document.view_profile.elements[cur_pro_name].options.length = 0;
				for (a=0; a <= drop_down_count; a++){
					if (new_drop_label[a].length > 20){
						new_drop_label[a] = new_drop_label[a].substr(0,17) + "...";
					}
					document.view_profile.elements[cur_pro_name].options[a] = new Option(new_drop_label[a], new_drop_value[a]);
					if (new_drop_selected[a] == "selected" && loc_id_selected == new_drop_value[a] && cur_profile_field == i){
						selected_value = new_drop_value[a];
					}else{
						if (new_drop_value[a] == cur_sel && selected_value == ""){
							selected_value = new_drop_value[a];
						}
					}
				}
				document.view_profile.elements[cur_pro_name].value = selected_value;
			}
			doUpdateProfile(pro_update_name, loc_id_selected);
			timerID = setTimeout("doCloseProfile()", 350);
		}
	}else{
		str = "";
		for (i=0; i<numberofErrors; i++){
			str = str + root.getElementsByTagName("errorMessage")[i].firstChild.nodeValue + "\n";
		}
	}
	if (str != ""){
		alert(str);
	}
}

function getLibraryAssets(Asset_Field, LibraryID, CropSetting){
	img_count = Asset_Field.split("_");
	showProcessLayer("processing_screen");
	if (LibraryID != "#" && LibraryID != ""){
		handlerFunction = "GetImageAssets";
		queryURL = "asset_library/library_details/" + Asset_Field + "/" + LibraryID;
		queryAJAX(handlerFunction, queryURL);
	}else{
		document.cus_edits.elements[Asset_Field].options.length = 0;
		document.cus_edits.elements[Asset_Field].options[0] = new Option("Please select an Image Library", "#");
		hideLayer("processing_screen");
	}
	if (Asset_Field != ""){
		document.getElementById("image_" + img_count[2]).innerHTML = "";
		document.getElementById("image_title_" + img_count[2]).innerHTML = "";
	}
	if (CropSetting == "reload"){
		document.cus_edits.elements["asset_coords_" + img_count[2]].value = "";
		loadCroppedImage("asset_coords_" + img_count[2]);
		document.getElementById("ResolutionDPI_" + img_count[2]).innerHTML = "";
	}
	hideLayer("processing_screen");
}

function successGetImageAssets(o){
	var root = o.responseXML.documentElement;
	var updateField = root.getElementsByTagName("updateField")[0].firstChild.nodeValue;
	var oColumns = root.getElementsByTagName("column");
	var numberOfColumns = oColumns.length;

	if (updateField == "invalid"){
		str = "There was a problem retrieving the image library.\n";
		str = str + "Technical support has been notified.";
	}else{
		document.cus_edits.elements[updateField].options.length = 0;
		crop_loc = updateField.substr((updateField.length - 1), updateField.length);
		for (i=0; i<numberOfColumns; i++){
			new_opt_value = root.getElementsByTagName("assetID")[i].firstChild.nodeValue;
			new_opt_label = root.getElementsByTagName("label")[i].firstChild.nodeValue;
			if (new_opt_label.length > 45){
				new_opt_label = new_opt_label.substr(0,42) + "...";
			}
			image_label[new_opt_value] = root.getElementsByTagName("label")[i].firstChild.nodeValue;
			image_file[new_opt_value] = root.getElementsByTagName("imageFileName")[i].firstChild.nodeValue;
			image_thumb[new_opt_value] = root.getElementsByTagName("thumbFileName")[i].firstChild.nodeValue;
			enc_asset_id[new_opt_value] = root.getElementsByTagName("assetIDEnc")[i].firstChild.nodeValue;
			enc_lib_id[new_opt_value] = root.getElementsByTagName("libraryIDEnc")[i].firstChild.nodeValue;
			image_width[new_opt_value] = root.getElementsByTagName("pixelWidth")[i].firstChild.nodeValue;
			document.cus_edits.elements[updateField].options[i] = new Option(new_opt_label, new_opt_value);
		}
	}
	 hideLayer("processing_screen");
}

/**
 * Creates an overlay and shows a loading indicator (Known affectionately as the processing div)
 * Uses blockUI jQuery plugin
 */
function showProcessLayer(zlayer) {
	$(document).ready(function(){
		$.blockUI({ message: $('#loading-indicator-wrap').html() });
	});
}

function postNewImage(formName, ImgNo, EncCompID, encTemplateID){
	showProcessLayer("processing_screen");
	queryURL = "asset_library/add_image/" + ImgNo + "/" + EncCompID + "/" + encTemplateID;
	postAJAX(formName, queryURL, "FilePost");
	hideLayer("processing_screen");
}

function successUploadImageAssets(ImgNo, EncCompID, encTemplateID){
	hideLayer("processing_screen");
	showLayer("imagePane_" + ImgNo, "no");
	str = "";
	check_image_uploaded = "yes";
	document.cus_edits.elements["asset_name[" + ImgNo + "]"].value = "";
	document.cus_edits.elements["asset_description[" + ImgNo + "]"].value = "";
	document.cus_edits.elements["image_file[" + ImgNo + "]"].value = "";
	hideLayer("Image_Div_" + ImgNo);
	library_id = document.cus_edits.elements["library_id_" + ImgNo].value;
	/*$(document).ready(function() {
		timerID1 = setTimeout("getLibraryAssets('asset_id_" + ImgNo + "', '" + library_id + "')", 500);
		timerID2 = setTimeout("selectNewImage(" + ImgNo + ", '" + EncCompID + "', '" + encTemplateID + "')", 1000);
	});*/
	timerID1 = setTimeout("getLibraryAssets('asset_id_" + ImgNo + "', '" + library_id + "')", 500);
	timerID2 = setTimeout("selectNewImage(" + ImgNo + ", '" + EncCompID + "', '" + encTemplateID + "')", 1000);
	if (str != ""){
		alert(str);
	}
}

function postSaveCart(formName, queryURL){
	showProcessLayer("processing_screen");
	queryURL = "shop_cart/save_cart/" + queryURL;
	postAJAX(formName, queryURL, "FilePost");
}

function cartExpirationDate() {

	// Month array
	var months = new Array('January', 'February', 'March', 'April',
	'May', 'June', 'July', 'August', 'September', 'October',
	'November', 'December');

	// Create new date
	var futureDate = new Date();
	var daysToAdd = 2;
	var msPerDay = (24 * 60 * 60 * 1000);
	var expirationMS = futureDate.getTime() + (daysToAdd * msPerDay);

	// Set future date
	futureDate.setTime(expirationMS);

	// Create human readable output
	var month = futureDate.getMonth();
	var date = futureDate.getDate();
	var year = futureDate.getUTCFullYear();
	var expiration = months[month] + ' ' + date + ', ' + year + ' at 12:00 am EST - (midnight)';

	return expiration;
}

function successSaveCart(cartResult, cartItems){
	hideLayer("processing_screen");
	if (cartResult == "success"){
		document.getElementById("cart_items").innerHTML = String(cartItems);
		var successMessage = 'The Shopping Cart was successfully saved. <br /> Items within your cart will expire on ' + cartExpirationDate();
		$('#cart_alert_1').css({background: '#FFD700', display: 'block', textAlign: 'center'}).html(successMessage);
		$('#cart_alert_2').css({background: '#FFD700'}).html(successMessage);
		timerID0 = setTimeout("clearAlert()", 5000);
	}else{
		document.getElementById("cart_alert_1").innerHTML = "There was a problem saving the Shopping Cart.";
		document.getElementById("cart_alert_1").style.background = "#CC3300";
		document.getElementById("cart_alert_1").style.color = "#FFFFFF";
		document.getElementById("cart_alert_2").innerHTML = "There was a problem saving the Shopping Cart.";
		document.getElementById("cart_alert_2").style.background = "#CC3300";
		document.getElementById("cart_alert_2").style.color = "#FFFFFF";
		timerID0 = setTimeout("clearAlert()", 5000);
	}
}

function postVerifyBilling(formName){
	showProcessLayer("processing_screen");
	queryURL = "verify_billing";
	postAJAX(formName, queryURL, "FilePost");
}

function successVerifyBilling(billResult, billAlerts){
	if (billResult == "success"){
		billSuccess();
	}else{
		hideLayer("processing_screen");
		document.getElementById("cc_alerts").innerHTML = billAlerts;
	}
}

function clearAlert(){
	document.getElementById("cart_alert_1").innerHTML = "";
	document.getElementById("cart_alert_1").style.background = "#FFFFFF";
	document.getElementById("cart_alert_2").innerHTML = "";
	document.getElementById("cart_alert_2").style.background = "#FFFFFF";
}

function postTemplateCustomizations(ProfileNo, formName, ProfileCount, Type){
	qs1 = "";
	if (ProfileCount > 0){
		for (i=0; i< ProfileCount; i++){
			profile_value = document.view_profile.elements["profile_" + (i+1)].value;
			if (qs1 != ""){
				qs1 = qs1 + "_" + profile_value;
			}else{
				qs1 = qs1 + profile_value;
			}
		}
	}
	queryURL = "template_customizations/" + qs1 + "/" + Type;
	postAJAX(formName, queryURL, "FormPost");
}

function getNetworkDetails(AccountID){
	handlerFunction = "NetworkDetails";
	queryURL = "account_details/" + AccountID;
	queryAJAX(handlerFunction, queryURL);
}

function successNetworkDetails(o){
	var root = o.responseXML.documentElement;
	var oCompanyName = root.getElementsByTagName("companyName")[0].firstChild.nodeValue;
	var oFirstName = root.getElementsByTagName("firstName")[0].firstChild.nodeValue;
	var oLastName = root.getElementsByTagName("lastName")[0].firstChild.nodeValue;
	var oAddress1 = root.getElementsByTagName("address1")[0].firstChild.nodeValue;
	var oAddress2 = root.getElementsByTagName("address2")[0].firstChild.nodeValue;
	var oCity = root.getElementsByTagName("city")[0].firstChild.nodeValue;
	var oRegionCode = root.getElementsByTagName("regionCode")[0].firstChild.nodeValue;
	var oPostalCode = root.getElementsByTagName("postalCode")[0].firstChild.nodeValue;
	var oAreaCode = root.getElementsByTagName("areaCode")[0].firstChild.nodeValue;
	var oPhoneNumber = root.getElementsByTagName("phoneNumber")[0].firstChild.nodeValue;
	var oPhoneExt = root.getElementsByTagName("phoneExt")[0].firstChild.nodeValue;
	var oEmail = root.getElementsByTagName("email")[0].firstChild.nodeValue;

	document.getElementById("companyName").innerHTML = oCompanyName;
	document.getElementById("ownerName").innerHTML = oFirstName + " " + oLastName;
	document.getElementById("address1").innerHTML = oAddress1;
	document.getElementById("address2").innerHTML = oAddress2;
	document.getElementById("city").innerHTML = oCity;
	document.getElementById("regionCode").innerHTML = oRegionCode;
	document.getElementById("postalCode").innerHTML = oPostalCode;
	if (oPhoneExt != ""){
		phone_ext = " Ext. " + oPhoneExt;
	}else{
		phone_ext = "";
	}
	document.getElementById("phoneNumber").innerHTML = oAreaCode + "-" + oPhoneNumber.substr(0,3) + "-" + oPhoneNumber.substr(3,4) + phone_ext;
	document.getElementById("email").innerHTML = oEmail;
	showLayer("NetworkDetailsDiv", "yes");
}

/*
	Logout User after inactivity specified
*/
function autoLogout() {
	document.location = "/account/signout/timeout";
}

/*
	Open FEDEX tracking window
*/
function trackOrder(orderID){
	window.open("/member_account/orders/track/" + orderID, 'trackorder', 'width=700,height=500,scrollbars=yes,resizable=yes');
}

/*
	Highlight text input
*/
var currentlyActiveInputRef = false;
var currentlyActiveInputClassName = false;
function highlightActiveInput() {
	if(currentlyActiveInputRef) {
		currentlyActiveInputRef.className = currentlyActiveInputClassName;
	}
	currentlyActiveInputClassName = this.className;
	this.className = 'inputHighlighted';
	currentlyActiveInputRef = this;
}

function blurActiveInput() {
	this.className = currentlyActiveInputClassName;
}

function initInputHighlightScript() {
	var tags = ['INPUT','TEXTAREA'];
	for(tagCounter=0;tagCounter<tags.length;tagCounter++){
		var inputs = document.getElementsByTagName(tags[tagCounter]);
		for(var no=0;no<inputs.length;no++){
			if(inputs[no].className && inputs[no].className=='doNotHighlightThisInput')continue;
			if(inputs[no].className && inputs[no].className=='searchbox searchtext')continue;
			if(inputs[no].tagName.toLowerCase()=='textarea' || (inputs[no].tagName.toLowerCase()=='input' &&
			inputs[no].type.toLowerCase()=='text')){
		        inputs[no].onfocus = highlightActiveInput;
		        inputs[no].onblur = blurActiveInput;
			}
	    }
	}
}

function showFAQ(faqURL) {
	if (faqURL != "") {
		window.open(faqURL, 'faq', 'width=635,height=450,scrollbars=1,resizable=1, top=200, left=200');
	}

}

function VerifyDate(field1,field2,field3){
	if (field1 > 12 || field2 > 31){
		return false;
	}
	var Months = new Array(12);
		Months[1]="Jan";
		Months[2]="Feb";
		Months[3]="Mar";
		Months[4]="Apr";
		Months[5]="May";
		Months[6]="Jun";
		Months[7]="Jul";
		Months[8]="Aug";
		Months[9]="Sep";
		Months[10]="Oct";
		Months[11]="Nov";
		Months[12]="Dec";
	if (field1.substr(0,1) != 0){
		VrfyMonthStr = Months[field1];
	}else{
		VrfyMonthStr = Months[field1.substr(1,1)];
	}
	if (field2.substr(0,1) != 0){
		VrfyDayStr = field2;
	}else{
		VrfyDayStr = field2.substr(1,1);
	}
	VrfyYearStr = field3;
	VrfyDateStr = VrfyMonthStr + ' ' + VrfyDayStr + ' ' + VrfyYearStr;
	VrfyDate = new Date(VrfyDateStr);
	VrfyDate_string = VrfyDate.toGMTString();
	VrfyDate_array = VrfyDate_string.split(' ');
	if (VrfyDate_array[2] != VrfyMonthStr){
		return false;
	}else{
		return true;
	}
}

function showWorkflow(workflow_group) {
	var workflow = document.getElementById("workflow");

	if (workflow_group == "#") {
		workflow.style.display = "none";
	} else {
		workflow.style.display = "";
	}

	handlerFunction = "Workflow";
	queryURL = "workflows/" + workflow_group;
	queryAJAX(handlerFunction, queryURL);
}

function successWorkflow(o) {
	var root = o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oWorkflowTemp = root.getElementsByTagName("workflow")[0].firstChild.nodeValue;

	var workflow = document.getElementById("workflow");
	var wfTitle = document.getElementById("workflow_title");
	var postalGroup = document.getElementById("postal_group");
	var pgroupTitle = document.getElementById("postal_group_title");
	var postalCode = document.getElementById("postal_code");
	var pcodeTitle = document.getElementById("postal_code_title");

	var htmlString = "<select id='js_workflow' name='js_workflow' onChange=\"javascript:showPostalGroup(this.value);\"><option value='#'>Please select an option</option>";


	if (oWorkflowTemp == "INVALID") {
		workflow.style.display = "none";
		wfTitle.style.display = "none";
		postalGroup.style.display = "none";
		pgroupTitle.style.display = "none";
		postalCode.style.display = "none";
		pcodeTitle.style.display = "none";
	} else {
		workflow.style.display = "inline";
		wfTitle.style.display = "inline";
		for (i = 0; i < numOfDetailInfo; i++){
			oWorkflow = root.getElementsByTagName("workflow")[i].firstChild.nodeValue;
			htmlString += "<option label='" + oWorkflow + "' value='" + oWorkflow + "'>";
			htmlString += oWorkflow + "</option>";
		}

		workflow.innerHTML = htmlString;
		wfTitle.innerHTML = "<div style='text-align:right;background:#999999;height:18px;'><b>Workflow:</b></div>";
	}
}

function showPostalGroup(workflow) {
	var postalGroup = document.getElementById("postal_group");
	var pgroupTitle = document.getElementById("postal_group_title");
	var postalCode = document.getElementById("postal_code");
	var pcodeTitle = document.getElementById("postal_code_title");

	if (workflow == "#") {
		postalGroup.style.display = "none";
		pgroupTitle.style.display = "none";
		postalCode.style.display = "none";
		pcodeTitle.style.display = "none"
	} else {
		postalGroup.style.display = "";
		pgroupTitle.style.display = "";
		postalCode.style.display = "";
		pcodeTitle.style.display = "";
	}

	handlerFunction = "PostalGroup";
	queryURL = "postalgroups/" + workflow;
	queryAJAX(handlerFunction, queryURL);
}

function successPostalGroup(o) {
	var root= o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oPostalCodeTemp = root.getElementsByTagName("postal_group")[0].firstChild.nodeValue;
	var htmlString = "<select id='js_postal_group' name='js_postal_group'><option value='#'>Please select an option</option>";
	//var htmlString = "<select id='js_postal_group' name='js_postal_group' onChange=\"javascript:showPostalCode(this.value);\"><option value='#'>Please select an option</option>";

	var postalGroup = document.getElementById("postal_group");
	var pgroupTitle = document.getElementById("postal_group_title");
	var postalCode = document.getElementById("postal_code");
	var pcodeTitle = document.getElementById("postal_code_title");

	if (oPostalCodeTemp == "INVALID") {
		postalGroup.style.display = "none";
		pgroupTitle.style.display = "none";
		postalCode.style.display = "none";
		pcodeTitle.style.display = "none";
	} else {
		postalGroup.style.display = "inline";
		pgroupTitle.style.display = "inline";
		postalCode.style.display = "";
		pcodeTitle.style.display = "";
		for(i = 0; i < numOfDetailInfo; i++) {
			oPostalGroup = root.getElementsByTagName("postal_group")[i].firstChild.nodeValue;
			htmlString += "<option label='" + oPostalGroup + "' value='" + oPostalGroup + "'>";
			htmlString += oPostalGroup + "</option>";
		}

		postalGroup.innerHTML = htmlString;
		pgroupTitle.innerHTML = "<div style='text-align:left;background:#999999;height:18px;'><b>Postal Group:</b></div>";
		//pgroupTitle.innerHTML = "<div style='height:25;width:180;text-align:right;background-color:d0d0d0'><b>Postal Group:</b></div>";
	}
}

function showPostalCode(oPostalGroup) {
	var postalGroup = document.getElementById("postal_group");
	var pgroupTitle = document.getElementById("postal_group_title");
	var postalCode = document.getElementById("postal_code");
	var pcodeTitle = document.getElementById("postal_code_title");

	if (oPostalGroup == "#") {
		postalCode.style.display = "none";
		pcodeTitle.style.display = "none"
	} else {
		postalCode.style.display = "";
		pcodeTitle.style.display = "";
	}

	handlerFunction = "PostalCode";
	queryURL = "zipcode/" + oPostalGroup;
	queryAJAX(handlerFunction, queryURL);
}

function successPostalCode(o) {
	var root= o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oPostalGroupTemp = root.getElementsByTagName("postal_group")[0].firstChild.nodeValue;
	var htmlString  = "<textarea cols=50 rows=8 readonly='readonly' id='js_postal_code' name='js_postal_code'>";

	var postalGroup = document.getElementById("postal_group");
	var pgroupTitle = document.getElementById("postal_group_title");
	var postalCode = document.getElementById("postal_code");
	var pcodeTitle = document.getElementById("postal_code_title");

	if (numOfDetailInfo < 10) {
		multipleSize = 5;
	} else if (numOfDetailInfo >= 10 && numOfDetailInfo < 30) {
		multipleSize = 20;
	} else if (numOfDetailInfo >= 30 && numOfDetailInfo < 50) {
		multipleSize = 40;
	} else if (numOfDetailInfo >= 50 && numOfDetailInfo < 100) {
		multipleSize = 70;
	} else {
		multipleSize = 100;
	}

	if (oPostalGroupTemp == "INVALID") {
		postalCode.style.display = "none";
		pcodeTitle.style.display = "none";
	} else {
		postalCode.style.display = "";
		pcodeTitle.style.display = "";

		for(i = 0; i < numOfDetailInfo; i++) {
			oPostalCode = root.getElementsByTagName("postal_code")[i].firstChild.nodeValue;
			oCity		= root.getElementsByTagName("city")[i].firstChild.nodeValue;
			oState		= root.getElementsByTagName("region_code")[i].firstChild.nodeValue;
			oCountryCode= root.getElementsByTagName("country_code")[i].firstChild.nodeValue;
			htmlString += oPostalCode + "-" + oCity + "-" + oState + "-" + oCountryCode + "\n";
		}
		htmlString += "</textarea>";
		postalCode.innerHTML = htmlString;
		pcodeTitle.innerHTML = "<div style='text-align:left;background:#999999;height:18px;'><b>Postal Code:</b></div>";
		//pcodeTitle.innerHTML = "<div style='height:25;width:180;text-align:right;background-color:d0d0d0'><b>Postal Code:</b></div>";
	}

}

function showAccountUnderMaster(oMasterAccountID,searchString) {
	var accountID = document.getElementById("account_id");	
	var accountIDTitle = document.getElementById("account_id_title");	
	var accountAss = document.getElementById("account_assignment");
	
	if (oMasterAccountID == "#") {
		accountID.style.display = "none";
		accountIDTitle.style.display = "none";
		accountAss.style.display = "none";
	}
	/*
	else {
		accountID.style.display = "";
		accountIDTitle.style.display = "";
		accountAss.style.display = "";
	}
	*/
	

	handlerFunction = "AccountUnderMaster";
	if(searchString != ''){
		queryURL = "accountundermaster/" + oMasterAccountID +"/" + searchString;
	}else{
		queryURL = "accountundermaster/" + oMasterAccountID;
	}

	queryAJAX(handlerFunction, queryURL);
}

function successAccountUnderMaster(o) {
	var root= o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oAccountIDTemp = root.getElementsByTagName("account_id")[0].firstChild.nodeValue;
	var htmlString  = "<select id='account_ids[]' name='account_ids[]' size='5' multiple='multiple'>";

	var accountID = document.getElementById("account_id");
	var accountIDTitle = document.getElementById("account_id_title");
	var accountAss = document.getElementById("account_assignment");
	
	if (oAccountIDTemp == "INVALID") {
		accountID.style.display = "none";
		accountIDTitle.style.display = "none";
		accountAss.style.display = "none";
	} else if (oAccountIDTemp == "EMPTY") {
		accountID.style.display = "none";
		accountIDTitle.style.display = "none";
		accountAss.style.display = "none";
	} else {
		accountID.style.display = "";
		accountIDTitle.style.display = "";
		accountAss.style.display = "";

		for (i = 0; i < numOfDetailInfo; i++) {
			oAccountID = root.getElementsByTagName("account_id")[i].firstChild.nodeValue;
			if (root.getElementsByTagName("company_name")[i].hasChildNodes()) {
				oCompanyName = root.getElementsByTagName("company_name")[i].firstChild.nodeValue;
			} else {
				oCompanyName = "Not Applicable";
			}
			if (root.getElementsByTagName("full_name")[i].hasChildNodes()) {
				oFullName = root.getElementsByTagName("full_name")[i].firstChild.nodeValue;
			} else {
				oFullName = "Not Applicable";
			}

			htmlString += "<option value='" + oAccountID + "'>";
			htmlString += oFullName + ' - ' + oAccountID + ' - ' + oCompanyName + ' - ' + "</option>";
		}

		htmlString += "</select>";
		accountID.innerHTML = htmlString;
		//accountIDTitle.innerHTML = "<div style='text-align:left;background:#999999;height:18px;'><b>Account ID*:</b></div>";	
		
	}

}

function toggleBilling(o) {
	if (o == "invoice") {
		// DISABLE CREDIT CAR INFORMATION FIELDSET ELEMENTS
		var inputBillInfo = document.getElementById("billing_information").getElementsByTagName("input");
		for (var i = 0; i < inputBillInfo.length; i++) {
			inputBillInfo[i].disabled = true;
		}
		var selectBillInfo = document.getElementById("billing_information").getElementsByTagName("select");
		for (var i = 0; i < selectBillInfo.length; i++) {
			selectBillInfo[i].disabled = true;
		}

		var inputBillContact = document.getElementById("billing_contact_details").getElementsByTagName("input");
		for (var i = 0; i < inputBillContact.length; i++) {
			inputBillContact[i].disabled = true;
		}
		var selectBillContact = document.getElementById("billing_information").getElementsByTagName("select");
		for (var i = 0; i < selectBillContact.length; i++) {
			selectBillContact[i].disabled = true;
		}

		// ENABLE NEW BILLING COMPANY FIELDSET ELEMENTS
		var inputNewBillComp = document.getElementById("new_billing_company").getElementsByTagName("input");
		for (var i = 0; i < inputNewBillComp.length; i++) {
			inputNewBillComp[i].disabled = false;
		}
	} else if (o == "credit_card") {
		// DISABLE NEW BILLING COMPANY FIELDSET ELEMENTS
		var inputNewBillComp = document.getElementById("new_billing_company").getElementsByTagName("input");
		for (var i = 0; i < inputNewBillComp.length; i++) {
			inputNewBillComp[i].disabled = true;
		}

		// ENABLE NEW CREDIT CARD INFORMATION FIELDSET ELEMENTS
		var inputBillInfo = document.getElementById("billing_information").getElementsByTagName("input");
		for (var i = 0; i < inputBillInfo.length; i++) {
			inputBillInfo[i].disabled = false;
		}

		var selectBillInfo = document.getElementById("billing_information").getElementsByTagName("select");
		for (var i = 0; i < selectBillInfo.length; i++) {
			selectBillInfo[i].disabled = false;
		}

		var inputBillContact = document.getElementById("billing_contact_details").getElementsByTagName("input");
		for (var i = 0; i < inputBillContact.length; i++) {
			inputBillContact[i].disabled = false;
		}

		var selectBillContact = document.getElementById("billing_information").getElementsByTagName("select");
		for (var i = 0; i < selectBillContact.length; i++) {
			selectBillContact[i].disabled = false;
		}

	} else {
	}
}

function showBillingPref(oBillingPref) {
	var billing_information = document.getElementById("billing_information");
	var billing_contact_details = document.getElementById("billing_contact_details");
	var billing_companies = document.getElementById("billing_companies");
	var billing_company = document.getElementById("billing_company");
	var new_billing_company = document.getElementById("new_billing_company");

	if (oBillingPref == "invoice") {
		billing_information.style.display = "none";
		billing_contact_details.style.display = "none";
		billing_companies.style.display = "block";
		billing_company.style.display = "block";
		new_billing_company.style.display = "none";

		toggleBilling(oBillingPref);

		handlerFunction = "BillingPref";
		queryURL = "billing_companies/" + oBillingPref;
		queryAJAX(handlerFunction, queryURL);
	} else {
		billing_information.style.display = "";
		billing_contact_details.style.display = "";
		billing_companies.style.display = "none";
		new_billing_company.style.display = "none";
		toggleBilling(oBillingPref);
		document.getElementById("inv_company_id").value = "";
		document.getElementById("inv_company_name").value = "";
		document.getElementById("inv_first_name").value = "";
		document.getElementById("inv_last_name").value = "";
		document.getElementById("inv_address1").value = "";
		document.getElementById("inv_address2").value = "";
		document.getElementById("inv_postal_code").value = "";
		document.getElementById("inv_city").value = "";
		document.getElementById("inv_region_code").value = "";
		document.getElementById("inv_country_code").value = "";
	}
}

function successBillingPref(o) {
	var root = o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oCompanyIDTemp = root.getElementsByTagName("company_id")[0].firstChild.nodeValue;
	var billingCompany = document.getElementById("billing_company");
	var billingCompanies = document.getElementById("billing_companies");
	var htmlString = "<select id='js_company' name='js_company' onChange='showBillingCompany(this.value);'>";

	if (oCompanyIDTemp == "INVALID") {
	} else {
		billingCompany.style.display = "block";
		billingCompanies.style.display = "block";

		htmlString += "<option value='#'>Please select one...</option>";
		htmlString += "<option value='##'>Company not listed</option>";
		for(i = 0; i < numOfDetailInfo; i++) {
			oCompanyID = root.getElementsByTagName("company_id")[i].firstChild.nodeValue;
			oCompanyName = root.getElementsByTagName("company_name")[i].firstChild.nodeValue;

			oFirstName = root.getElementsByTagName("first_name")[i].firstChild.nodeValue;
			oLastName = root.getElementsByTagName("last_name")[i].firstChild.nodeValue;
			oAddress1 = root.getElementsByTagName("address1")[i].firstChild.nodeValue;
			if (root.getElementsByTagName("address2")[i].hasChildNodes()) {
				oAddress2 = root.getElementsByTagName("address2")[i].firstChild.nodeValue;
			}
			/*
			oCity = root.getElementsByTagName("city")[i].firstChild.nodeValue;
			oState = root.getElementsByTagName("state")[i].firstChild.nodeValue;
			oPostalCode = root.getElementsByTagName("postal_code")[i].firstChild.nodeValue;
			oCountry = root.getElementsByTagName("country")[i].firstChild.nodeValue;
			oPhoneAreaCode = root.getElementsByTagName("phone_area_code")[i].firstChild.nodeValue;
			oPhoneNumber = root.getElementsByTagName("phone_number")[i].firstChild.nodeValue;
			oFaxAreaCode = root.getElementsByTagName("fax_area_code")[i].firstChild.nodeValue;
			oFaxPhoneNumber = root.getElementsByTagName("fax_phone_number")[i].firstChild.nodeValue;
			oAddress = oAddress1 + oAddress2 + oCity + oState + oPostalCode;
			*/

			htmlString += "<option value='" + oCompanyID + "'>" + oCompanyName +  "</option>";
		}
		htmlString += "</select>";
		billingCompany.innerHTML = htmlString;
	}
}

function showBillingCompany(oCompanyID) {
	var new_billing_company = document.getElementById("new_billing_company");

	if (oCompanyID == "#") {
		new_billing_company.style.display = "none";
		alert("Please select Billing Company!");
	} else if (oCompanyID == "##") {
		new_billing_company.style.display = "";
		document.getElementById("inv_company_id").value = "";
		document.getElementById("inv_company_name").value = "";
		document.getElementById("inv_first_name").value = "";
		document.getElementById("inv_last_name").value = "";
		document.getElementById("inv_address1").value = "";
		document.getElementById("inv_address2").value = "";
		document.getElementById("inv_postal_code").value = "";
		document.getElementById("inv_city").value = "";
		document.getElementById("inv_region_code").value = "";
		document.getElementById("inv_country_code").value = "";
		document.getElementById("inv_phone_area_code").value = "";
		document.getElementById("inv_phone_number").value = "";
		document.getElementById("inv_phone_ext").value = "";
		document.getElementById("inv_fax_area_code").value = "";
		document.getElementById("inv_fax_phone_number").value = "";
	} else {
		new_billing_company.style.display = "";
		handlerFunction = "BillingCompany";
		queryURL = "billing_companies/" + oCompanyID;
		queryAJAX(handlerFunction, queryURL);
	}
}

function successBillingCompany(o) {
	var root = o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oCompanyIDTemp = root.getElementsByTagName("company_id")[0].firstChild.nodeValue;

	var oCompanyID = root.getElementsByTagName("company_id")[0].firstChild.nodeValue;
	var oCompanyName = root.getElementsByTagName("company_name")[0].firstChild.nodeValue;
	var oFirstName = root.getElementsByTagName("first_name")[0].firstChild.nodeValue;
	var oLastName = root.getElementsByTagName("last_name")[0].firstChild.nodeValue;
	var oAddress1 = root.getElementsByTagName("address1")[0].firstChild.nodeValue;
	if (root.getElementsByTagName("address2")[0].hasChildNodes()) {
		var oAddress2 = root.getElementsByTagName("address2")[0].firstChild.nodeValue;
	}
	var oCity = root.getElementsByTagName("city")[0].firstChild.nodeValue;
	var oState = root.getElementsByTagName("state")[0].firstChild.nodeValue;
	var oPostalCode = root.getElementsByTagName("postal_code")[0].firstChild.nodeValue;
	var oCountry = root.getElementsByTagName("country")[0].firstChild.nodeValue;
	var oPhoneAreaCode = root.getElementsByTagName("phone_area_code")[0].firstChild.nodeValue;
	var oPhoneNumber = root.getElementsByTagName("phone_number")[0].firstChild.nodeValue;
	if (root.getElementsByTagName("phone_ext")[0].hasChildNodes()) {
		var oPhoneExt = root.getElementsByTagName("phone_ext")[0].firstChild.nodeValue;
	} else {
		var oPhoneExt = " ";
	}
	if (root.getElementsByTagName("fax_area_code")[0].hasChildNodes()) {
		var oFaxAreaCode = root.getElementsByTagName("fax_area_code")[0].firstChild.nodeValue;
	} else {
		var oFaxAreaCode = " ";
	}
	var oFaxPhoneNumber = root.getElementsByTagName("fax_phone_number")[0].firstChild.nodeValue;
	//var oAddress = oAddress1 + oAddress2 + oCity + oState + oPostalCode;
	if (oCompanyIDTemp == "INVALID") {
		// Do error handling here.
	} else {
		document.getElementById("inv_company_id").value = oCompanyID;
		document.getElementById("inv_company_name").value = oCompanyName;
		document.getElementById("inv_first_name").value = oFirstName;
		document.getElementById("inv_last_name").value = oLastName;
		document.getElementById("inv_address1").value = oAddress1;
		document.getElementById("inv_address2").value = oAddress2;
		document.getElementById("inv_postal_code").value = oPostalCode;
		document.getElementById("inv_city").value = oCity;
		document.getElementById("inv_region_code").value = oState;
		document.getElementById("inv_country_code").value = oCountry;

		if (oPhoneAreaCode != "" || oPhoneAreaCode != NULL) {
			document.getElementById("inv_phone_area_code").value = oPhoneAreaCode;
		}
		if (oPhoneNumber != "" || oPhoneNumber != NULL) {
			document.getElementById("inv_phone_number").value = oPhoneNumber;
		}
		if (oPhoneExt != "" || oPhoneExt != NULL) {
			document.getElementById("inv_phone_ext").value = oPhoneExt;
		}
		if (oFaxAreaCode != "" || oFaxAreaCode != NULL) {
			document.getElementById("inv_fax_area_code").value = oFaxAreaCode;
		}
		if (oFaxPhoneNumber != "" || oFaxPhoneNumber != NULL) {
			document.getElementById("inv_fax_phone_number").value = oFaxPhoneNumber;
		}
	}
}

function successJobStatus(o) {
	var root = o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oResult = root.getElementsByTagName("result")[0].firstChild.nodeValue;

	if (oResult == "SUCCESS") {
		document.getElementById("attention").value = oResult + " updating the record.";
	} else if (oResult == "FAILED") {
		document.getElementById("attention").value = oResult + " updating the record.";
	} else if (oResult == "INVALID") {
		document.getElementById("attention").value = oResult + " updating the record.";
	} else {
		document.getElementById("attention").value = "Error Encountered";
	}
}

function successChargeStatus(o) {
	var root = o.responseXML.documentElement;
	var oDetailInfo = root.getElementsByTagName("detail_information");
	var numOfDetailInfo = oDetailInfo.length;
	var oResult = root.getElementsByTagName("result")[0].firstChild.nodeValue;

	if (oResult == "SUCCESS" || oResult == "FAILED" || oResult == "INVALID") {
		document.getElementById("attention").innerHTML = oResult + " updating the record.";
		showLayer("attention", "yes");
		timerID0 = setTimeout(clearMsg, 5000);
	} else {
		document.getElementById("attention").innerHTML = "There was a problem updating your record (" + oResult + ")";
		showLayer("attention", "yes");
		timerID0 = setTimeout(clearMsg, 5000);
	}
}

function clearMsg(){
	document.getElementById("attention").style.visibility = "hidden";
	document.getElementById("attention").innerHTML = "";
}

/*
	Hides hovering context menu
*/
function HideContextMenu(mlayer){
    var obj = document.layers ? document.layers[mlayer] :
	document.getElementById ?  document.getElementById(mlayer).style : document.all[mlayer].style;
	obj.visibility = document.layers ? (0 ? "show" : "hide") : (0 ? "visible" : "hidden");
}

/*
	Shows hovering context menu
	Usage Example:
	<a href="#" onmousemove="ShowContextMenu(event,TextWithinDiv,Layer); return true" onmouseout="HideContextMenu(Layer); return true">Link</a>
*/
function ShowContextMenu(mevent,mtxt,mlayer){
	//newH = document.body.scrollTop;
	if(typeof( window.pageYOffset) == "number") {
		//Netscape compliant
		newH = window.pageYOffset;
	}else if( document.body && ( document.body.scrollLeft || document.body.scrollTop )){
		//DOM compliant
		newH = document.body.scrollTop;
	}else if( document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop )){
		//IE6 standards compliant mode
		newH = document.documentElement.scrollTop;
	}else{
		//IE7 standards compliant, I guess
		newH = document.documentElement.scrollTop;
	}
	newX = mevent.clientX + 15;
	newY = mevent.clientY + 15 + newH;

	document.getElementById(mlayer).style.top = newY + "px";
	document.getElementById(mlayer).style.left = newX + "px";
	document.getElementById(mlayer).innerHTML = mtxt;
	var obj = document.layers ? document.layers[mlayer] :
		document.getElementById ?  document.getElementById(mlayer).style : document.all[mlayer].style;
	obj.visibility = document.layers ? (1 ? "show" : "hide") : (1 ? "visible" : "hidden");
}

/*
	Function gets a template's pricing details.
*/
function getTemplateDetails(selLink){
	var handlerFunction = "TemplateDetails";
	var queryURL = "templatedetails/" + selLink;
	queryAJAX(handlerFunction, queryURL);
}

function successTemplateDetails(o){
	var root = o.responseXML.documentElement;
	var oColumns = root.getElementsByTagName("column");
	var numberOfColumns = oColumns.length;
	var tier1Label = root.getElementsByTagName("tier1Label")[0].firstChild.nodeValue;
	var tier2Label = root.getElementsByTagName("tier2Label")[0].firstChild.nodeValue;
	var pricingType = root.getElementsByTagName("pricingType")[0].firstChild.nodeValue;
	var htmlString = "<div style='padding:5px 5px; border:1px solid #669933; background-color:White;'>";
	htmlString += "<table border='0' cellpadding='0' cellspacing='0' width='236'>";
	htmlString += "<tr><td colspan='3' style='text-align:right; font-size:10px;'><a href='javascript: hideLayer(&quot;";
	htmlString += "template_details&quot;);'>close</a></td></tr>";
	htmlString += "<tr><td colspan='3' style='text-align:center; font-size:10px; font-weight:bold; padding:4px 0;'>Price Per Piece</td></tr>";
	htmlString += "<tr><td nowrap='nowrap' width='100' style='font-size:11px; font-weight:bold; color:#333333; padding-bottom:2px;' align='left'>Quantity</td>";
	htmlString += "<td width='73' style='font-size:10px; font-weight:bold; color:#333333; padding-bottom:2px;'>" + tier1Label + "</td>";
	htmlString += "<td width='63' style='font-size:10px; font-weight:bold; color:#333333; padding-bottom:2px;'>" + tier2Label + "</td></tr>";
	htmlString += "<tr><td colspan='3' style='height:1px; background-color: #b3984b;'></td></tr>";
	htmlString += "<tr><td colspan='3' height='1' style='font-size: 11px;color: #333333;'></td></tr>";
	var bgcolor = "";
	var showMinInfo = true;
	for (x=0; x<numberOfColumns; x++){
		basePriceID = root.getElementsByTagName("basePriceID")[x].firstChild.nodeValue;
		encBasePriceID = root.getElementsByTagName("encBasePriceID")[x].firstChild.nodeValue;
		minQuantity = root.getElementsByTagName("minQuantity")[x].firstChild.nodeValue;
		maxQuantity = root.getElementsByTagName("maxQuantity")[x].firstChild.nodeValue;
		vDataMaxQty = root.getElementsByTagName("vDataMaxQty")[x].firstChild.nodeValue;
		tier1Price = root.getElementsByTagName("tier1Price")[x].firstChild.nodeValue;
		tier2Price = root.getElementsByTagName("tier2Price")[x].firstChild.nodeValue;
		tier1WorkflowName = root.getElementsByTagName("tier1WorkflowName")[x].firstChild.nodeValue;
		tier2WorkflowName = root.getElementsByTagName("tier2WorkflowName")[x].firstChild.nodeValue;
		if (x%2 == 0){
			bgcolor = "#DFDFDF";
		}else{
			bgcolor = "#FFFFFF";
		}
		htmlString += "<tr bgcolor='" + bgcolor + "'>";
		htmlString += "<td nowrap='nowrap' align='left' height='18' style='padding-left: 5px;font-size: 11px;color: #333333;'>";
		if (minQuantity != maxQuantity){
			if (pricingType != "INCREMENTAL"){
				htmlString += minQuantity + " - ";
			}
		}
		htmlString += maxQuantity;
		if ((x+1) == numberOfColumns){
			htmlString += "+";
		}
		htmlString += "</td>";
		htmlString += "<td height='18' style='font-size:11px; color:#333333;'>$" + Number(tier1Price).toFixed(2) + "</td>";
		htmlString += "<td height='18' style='font-size:11px; color:#333333;'>";
		if (tier2Price == 0){
			htmlString += "NA";
			showMinInfo = false;
		}else{
			htmlString += "$" + Number(tier2Price).toFixed(2);
			showMinInfo = true;
		}
		htmlString += "</td></tr>";
	}
	htmlString += "<tr><td colspan='3' height='1' style='font-size: 11px;color: #333333;'></td></tr>";
	htmlString += "<tr><td colspan='3' style='height:1px; background-color: #b3984b;'></td></tr>";
	if (vDataMaxQty != 0 && showMinInfo){
		htmlString += "<tr><td colspan='3' style='text-align:center;'><br />";
		htmlString += tier2Label + "<br /> minumum is " + vDataMaxQty + "</td></tr>";
	}
	htmlString += "<tr><td colspan='3'>&nbsp;</td></tr>";
	htmlString += "</table></div>";
	document.getElementById("template_details").innerHTML = htmlString;
}

function pauseScript(millis) {
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < millis);
}

function checkFormat(strFormat, strString, fldName){
	var handlerFunction = "FormatCheck";
	var queryURL = "format_check/" + strFormat + "/" + strString + "/" + fldName;
	queryAJAX(handlerFunction, queryURL);
}

function successFormatCheck(o){
	var root = o.responseXML.documentElement;
	var oColumns = root.getElementsByTagName("column");
	var numberOfColumns = oColumns.length;
	var formatField = root.getElementsByTagName("formatField")[0].firstChild.nodeValue;
	var encString = root.getElementsByTagName("encString")[0].firstChild.nodeValue;
	var newString = Base64.decode(encString);
	document.getElementById(formatField).value = newString;
}


/// UTILITY FUNCTION
// Utility functions
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

/**
 * This function is used to disable if user press enter key.
 */
function preHandleEnter(a, b) {
	if(navigator.appName == "Netscape") {
		return handleEnter(a, b);
	}
	if(navigator.appName == "Microsoft Internet Explorer") {
		return noenter();
	}
	return true;
}

function noenter() {
	return !(window.event && window.event.keyCode == 13);
}

function stopRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

function handleEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++) {
			if (field == field.form.elements[i]) {
				break;
			}
		}
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	}
	else
	return true;
}

/**
 * This function is used to highlight user's selection
 */
function highlightSelection(divID, numbOfTmpl) {
	ar_divID = divID.split("_");
	selectedIndex = parseInt(ar_divID[1]);
	for (x = 1; x <= numbOfTmpl; x++) {
		if (x == selectedIndex) {
			document.getElementById("div_" + selectedIndex).className = "bgsearch-results";
		} else {
			document.getElementById("div_" + x).className = "bgwhite";
		}
	}
}

function setBackGroundColor(bColor, oName) {
	if (document.all) {
		var theStyle = eval('document.all.' + oName + '.style');
		theStyle.backgroundColor = bColor;
	}
}

/**
 * Function to display the message box via a javascript call.
 *
 * @param {var} messageData  - string message that should be displayed
 * @param {var} messageLevel - level of message, i.e., success, info, etc
 */
function showMessage(messageData, messageLevel) {
	if ( $("#messege_div").length > 0 ) {
		// set our content
		$('.messege_div_content').append('<li class="flash_notice_'+messageLevel+'">' + messageData + '</li>');
		// show the messaging div
		$("#messege_div").fadeIn(500);
		// allow closing of the message div via click of the close button
		$(".msg-close-button").bind('click', function(){ $("#messege_div").fadeOut(500); });
	}
	else if ($('#message_div_ul').length > 0 ){
			$('#message_div_label').html('Alert messages:');
			$('#message_div_ul').html('<li class="flash">' + messageData + '</li>');
	}
}

function getCRMLists(encAccountID, location) {
	showProcessLayer("processing_screen");
	var handlerFunction = "CRMLists";
	var queryURL = "all_crm_lists/" + encAccountID + "/" + location;
	queryAJAX(handlerFunction, queryURL);
}

function successCRMLists(o) {
	var root = o.responseXML.documentElement;
	var oCRMLists = root.getElementsByTagName("crm_list");
	var numberOfCRMLists = oCRMLists.length;
	var htmlString = "";

	var processValidated = true;

	if (numberOfCRMLists == 1) {
		listIDNoData = root.getElementsByTagName("list_id")[0].firstChild.nodeValue;
		listNameNoData = root.getElementsByTagName("list_id")[0].firstChild.nodeValue;
		listCountNoData = root.getElementsByTagName("list_id")[0].firstChild.nodeValue;

		if (listIDNoData == "INVALID" && listNameNoData == "INVALID" && listCountNoData == "INVALID") {
			processValidated = false;
		}
	}

	if (processValidated) {
		htmlString += '<div style="padding:5px 5px 5px 5px;">Please select a list from the drop down below:</div><br />';
		htmlString += '<div style="height: auto;width: auto;margin: 0 5px;padding:0px 5px 5px 5px;">';
		htmlString += "<select id='crm_existing_list' name='crm_existing_list'>";
		htmlString += '<option value="#">Select Existing List</option>';
		for (x = 0; x < numberOfCRMLists; x++) {
			listID = root.getElementsByTagName("list_id")[x].firstChild.nodeValue;
			listName = root.getElementsByTagName("list_name")[x].firstChild.nodeValue;
			if (listName.length > 35) {
				listName = listName.substr(0, 35) + "...";
			}
			listCount = root.getElementsByTagName("list_count")[x].firstChild.nodeValue;
			if (selectedListID != "" && selectedListID == listID && selectedListID != undefined) {
				htmlString += "<option value='" + listID + "' selected='selected'>" + listName +  " (#of records: " + listCount + ")</option>";
			} else {
				htmlString += "<option value='" + listID + "'>" + listName +  " (#of records: " + listCount + ")</option>";
			}
			//htmlString += "<option value='" + listID + "'>" + listName +  " #Count: " + listCount + "</option>";
		}

		htmlString += "</select></div>";
	} else {
		//document.getElementById("btn_use_this_list").style.visibility = "hidden";
		$('#btn_use_this_list').hide();
		htmlString += "<div style='color:red;text-align:center;padding:20px 0 20px 0;'><b>Currently, either you do not have a Contact Group available ";
		htmlString += "<br />or your Contacts are in the validation process.</b></div>";
		//htmlString += "<br />or your Contacts are in the process of CASS certification.</b></div>";
		//htmlString += "<div style='padding:0px 5px 20px 5px;'><b>Note</b>: CASS (Coding Accuracy Support System) enables the United States Postal Service ";
		//htmlString += "to evaluate the accuracy of software that cleans and matches addresses.</div>";
	}

	crmTab.set('content', htmlString);
	hideLayer("processing_screen");
}
/**
 * Initializes the toggle functionality for the need assistance link.
 * Detects and uses an iframe to cover select controls in IE6.
 */

function showContent(idNum){
	for (var i=0; i<12; i++) {
		document.getElementById("div" + i).style.display = "none";
	}
	document.getElementById("div" + idNum).style.display = "block";
}

/**
 * Sets all block level elements to have the same height as the tallest element.
 * Perfect for getting all divs in a layout to have same height.
 *
 * @param class string
 * return void
 */
var equalColumnHeights = function(id) {
	var col = $('.' + id);
	if ( col.length > 1 ) {
		var arrHeight = [];

		col.each(function(i) {
			arrHeight[i] = $(this).height();
		});

		arrHeight.sort();
		var height = arrHeight[arrHeight.length - 1];
		if ($.browser.msie && $.browser < 7) {
			col.css('height', height);
		} else {
			col.css('minHeight', height);
		}

	}
}



$().ready(function() {

	/*
	 * Handle need assistance functionality including
	 * addition and removal of iframe for ie6
	 */
	if ( $('#btn-need-assistance').length ) {
		$('#btn-need-assistance').bind('click', function(e) {
			e.preventDefault();
			// Check display of show-ma
			if ($('#show-ma').css('display') == 'none' ) {
				$('#show-ma').slideDown(500);
				// Use iframe to cover select controls
				if ($.browser.msie && $.browser.version < 7) {
					$('#show-ma-wrap').append('<iframe id="iframe-need-assistance" src="javascript: false;" frameborder="0"></iframe>');
					$('#iframe-need-assistance').css({
						height: '0',
						position: 'absolute',
						top: '3px',
						width: '250px',
						left: '476px',
						zIndex: '100',
						background: 'none'
					}).animate({ height: '150px'}, 400);
				}
			} else {
				$('#show-ma').slideUp(500);
				if ( $('#iframe-need-assistance').length > 0 ) {
					$('#iframe-need-assistance').slideUp(500, function() {
						$('#iframe-need-assistance').remove();
					});
				}
			}
		});
		$('#btn-close').bind('click', function(e) {
			e.preventDefault();
			$('#show-ma').slideUp(500);
			if ( $('#iframe-need-assistance').length > 0 ) {
				$('#iframe-need-assistance').slideUp(500, function() {
					$('#iframe-need-assistance').remove();
				});
			}
		});
	}

	/*
	 * By applying the show-tooltip class to any element with a title tag
	 * a tooltip is shown as well as a cursor change to help improve the
	 * interactive and targeting.
	 */
	if ( $('.show-tooltip').length > 0 ) {
		$('.show-tooltip').tooltip({
			track: true,
			top: 10,
			left: 35
		});
		$('.show-tooltip').css('cursor','help');
	}

});
