var pageLoaded = false;
var currentField = null;
function parseBoolean(string){
    if (string == "true" || string == "t" || string == "y" || string == "yes" || string == "1" || string == 1){
            return true;
    } else if (string == "false" || string == " f" || string == "n" || string == "no" || string == "0" || string == 0){
            return false;
    }       
    return null;
}           
function validDate(d){
  	if (!/^\d{2}\/\d{2}\/\d{4}$/.test(d) && ! /^\d{4}-\d{2}-\d{2}$/.test(d)) { return false; }
  	if (d.indexOf("-")>=0){
		var parts = d.split("-");
		var day = new Date(parts[0],parts[1]-1,parts[2]);
		if (day.getDate() != parts[2] || day.getMonth() != parts[1]-1) {
			return false;
		}
	} else {
		var parts = d.split("\/");
		var day = new Date(parts[2],parts[0]-1,parts[1]);
		if (day.getDate() != parts[1] || day.getMonth() != parts[0]-1) {
			return false;
		}
	}
  	return true;
};
function validateDate(fieldName, label){
	var d = document.getElementById(fieldName);
	if (d.length==0){
		return true;
	}
	if (!validDate(d.value)){
		alert('Field Validation Error: ' + label + '\nYou must enter a date in the format mm/dd/yyyy or yyyy-mm-dd');
		return false;
	}
	return true;
}
function cleanDate(date){
	if (date=='1100'){
		date='01/01/1900';
		return date;
	}
	if (date.indexOf("\/")<0 &&  date.length==6){
		date=date.substring(0,2) + "/" + date.substring(2,4) + "/20" + date.substring(4,6);
	}
	if (date.indexOf("\/")==2 && date.length==8){
		var pieces = date.split("/");
		date = pieces[0] + "/" + pieces[1] + "/20" + pieces[2];
	}
	if (date.indexOf('t')>=0){
		var today = new Date()
		var mm = today.getMonth() + 1;
		var dd = today.getDate();
		var yy = today.getFullYear();
		if (mm<10) mm="0" + mm;
		if (dd<10) dd="0" + dd;
		date = mm + "/" + dd + "/" + yy;
	}
	if (date.indexOf('+')>=0){
		var dte;
		if (date=='+'){
			dte = new Date()
		} else {
			info = date.replace("+","").split("\/");
			dte = new Date(info[2],info[0],info[1]);
			dte.setDate(dte.getDate()+1);
		}
		var mm = dte.getMonth();
		var dd = dte.getDate();
		var yy = dte.getFullYear();
		if (mm<10) mm="0" + mm;
		if (dd<10) dd="0" + dd;
		date = mm + "/" + dd + "/" + yy;
	}
	if (date.indexOf('-')>=0){
		var dte;
		if (date=='-'){
			dte = new Date()
		} else {
			info = date.replace("-","").split("\/");
			dte = new Date(info[2],info[0],info[1]);
			dte.setDate(dte.getDate()-1);
		}
		var mm = dte.getMonth();
		var dd = dte.getDate();
		var yy = dte.getFullYear();
		if (mm<10) mm="0" + mm;
		if (dd<10) dd="0" + dd;
		date = mm + "/" + dd + "/" + yy;
	}	
	return date;
}
function dateCheck(f, p){
	var d = document.getElementById(fieldName);
	d.value = cleanDate(d.value);

}
function previewOpen(drk, p, w, irk, trk){
	var dv = document.getElementById('displayProof_' + drk);
	if (p>1){
		var iWidth = 0;
		var iHeight = 0;
		for (x=1; x<=p; x++){
			var pi = (x<100 ? (x<10 ? '00' + x : '0' + x) : x);
			if (document.getElementById('img_' + drk + '_' + pi)){
				var i = document.getElementById('img_' + drk + '_' + pi);
				if (w=='preview'){
					i.src="viewer?which=preview&itemRecKey=" + irk + "&templateRecKey=" + trk;
				} else {
					i.src="viewer?which=proof&detailRecKey=" + drk + "&pageInc=" + pi;
				}
				iWidth = i.width+10;
				iHeight = ((i.height+20)*p);
			}
		}
		if (iWidth>0){
			dv.style.width=iWidth;
		}
		if (iHeight>0){
			dv.style.height=iHeight;
		}
	} else {
		if (document.getElementById('img_' + drk)){		
			var i = document.getElementById('img_' + drk);
			if (w=='preview'){
				i.src="viewer?which=preview&itemRecKey=" + irk + "&templateRecKey=" + trk;
			} else {
				i.src="viewer?which=proof&detailRecKey=" + drk;
			}
			dv.style.width=i.width;
			dv.style.height=i.height;
		}
	}
    window.setTimeout("doPageResizeApproval(" + parseInt(dv.style.width) +"," + parseInt(dv.style.height) + ")", 500);
	//doPageResize();
}
function doDivResize(drk,p){
	var preHeight = 0;
	var postHeight = 0;
	var preWidth = 0;
	var postWidth = 0;
	var dv = document.getElementById('displayProof_' + drk);
	preHeight = parseInt(dv.style.height);
	postWidth = parseInt(dv.style.width);
	if (p>1){
		var i = document.getElementById('img_' + drk + '_001');
		dv.style.width=i.width+10;
		dv.style.height=((i.height+20)*p);
	} else {
		var i = document.getElementById('img_' + drk);
		dv.style.width=i.width;
		dv.style.height=i.height;
	}
	postHeight = parseInt(dv.style.height);
	postWidth = parseInt(dv.style.width);
	if (preHeight==0){
	} else if (postHeight>preHeight){
		doPageResizeApproval();
	} else if (preHeight<postHeight){
		doPageResizeApproval();
	} else {
	}
}
function doPageResizeApproval(mWidth, mHeight){
	var h=xHeight('content',0);
	if (parseInt(mHeight)>h) h = parseInt(mHeight);
	var w=xWidth('content',0);
	if (parseInt(mWidth)>w) w = parseInt(mWidth);
	var pre=h;
	if (h<500) h=500;
	var currW=874;
	var deltaW=(w-currW)+25;
	if (document.getElementById("footer")){
		var foot = document.getElementById("footer");
		foot.style.width=w+deltaW;
		foot.style.top=h+xHeight('vertnavbar',0);
		foot.style.left=0;
	}
	if (document.getElementById("vertnavbar")){
		document.getElementById("vertnavbar").style.width=w+deltaW+xWidth('summary',0)-4;
	}
	if (document.getElementById("summary")){
		var summary = document.getElementById("summary");
		summary.style.left=w+deltaW;
		summary.style.height=h+32;
	}
}
function previewClose(drk,p){
	if (document.getElementById('previewDivWidth')){
		var dv = document.getElementById('displayProof_' + drk);
		dv.style.width=document.getElementById('previewDivWidth').value;
		dv.style.height=document.getElementById('previewDivHeight').value;
		doPageResizeApproval(dv.style.width, dv.style.height);		
	} else {
		if (p>1){
			for (x=1; x<=p; x++){
				var pi = (x<100 ? (x<10 ? '00' + x : '0' + x) : x);
				if (document.getElementById('img_' + drk + '_' + pi)){
					var i = document.getElementById('img_' + drk + '_' + pi);
					i.src='/img/1x1.gif';
				}
			}
		} else {
			if (document.getElementById('img_' + drk)){
				var i = document.getElementById('img_' + drk);
				i.src='/img/1x1.gif';
			}
		}
		var dv = document.getElementById('displayProof_' + drk);
		dv.style.width='555px';
		dv.style.height='1px';
	}
}
var imgWidth = 0;
function doPageResize(){
	//test to see if there is a customer-specific page re-size function
	// if there is, call it in place of the standard page re-size
	try{
		var test = customerPageResize;
		if ((typeof test) == "function"){
			customerPageResize();
			return
		}
	} catch (err){
	}
	
	try{
		if ((typeof pageName) == "undefined"){
			pageName = "";
		}
	} catch (err){
		pageName = "";
	}
	
	if (pageName == "itemInfoResize"){
		doItemInfoPageResize();
		return;
	}
	if (pageName == "Checkout"){
		doItemBrowseCheckoutPageResize();
		return;
	}
	if (pageName == "Item Browse"){
		doItemBrowseCheckoutPageResize();
		return;
	}
	doStandardPageResize();
}
function doItemInfoPageResize(){
/*  need to add handling for if the image is on the left  */
	var contentHeight=xHeight('content');

	var pW = xWidth('view_proof');
	var w=xWidth('content');
	var currW= parseInt(xWidth('content'));
	if (pW>0){
		deltaW=(pW-(currW-w)) + 5;
	} else {
		deltaW=(w-currW)+5;
	}
	var pre=contentHeight;
	var headerHeight=0;
	var hw=0;
	if (document.getElementById("imprintHeader")){
		headerHeight = xHeight("imprintHeader");
		hw = xWidth("imprintHeader");
	}
	if (document.getElementById("proofDiv")){
		var pDiv = document.getElementById("proofDiv");
		if (parseInt(xOffsetLeft(pDiv))<proofDivLeft){
			pDiv.style.left=proofDivLeft;
		}
		if (parseInt(xTop(pDiv))!=proofDivTop){
			pDiv.style.top=proofDivTop;
		}
		var tw = parseInt(xWidth('proofDiv'));
		var lw = parseInt(xOffsetLeft("proofDiv"));
		var tmpW = (currW-lw) + tw;
		if (tmpW>currW){
			currW = (currW-lw) + tw;
			deltaW = 0;
		} else {
			deltaW = 50;
		}
		var proofHeight = xHeight('proofDiv');
		var imprintHeight = xHeight("imprintBlockDiv");
		if (imprintHeight>proofHeight){
			if ((imprintHeight+headerHeight)>contentHeight){
				contentHeight = imprintHeight + headerHeight + 120;
			}
		} else {
			if ((proofHeight+headerHeight)>contentHeight){
				contentHeight = proofHeight + headerHeight + 120;
			}
		}
	}
	if (deltaW<0) deltaW=0;
	if (contentHeight<500) contentHeight=500;
	if (document.getElementById("footer")){
		document.getElementById("footer").style.width=currW+deltaW;
		document.getElementById("footer").style.top=contentHeight+xHeight('vertnavbar');
	}
	if (document.getElementById("vertnavbar")){
		document.getElementById("vertnavbar").style.width=currW+deltaW+xWidth('summary')-4;
	}
	if (document.getElementById("summary")){
		document.getElementById("summary").style.left=currW+deltaW;
		document.getElementById("summary").style.height=contentHeight+32;
	}
}
function getcss( selector, property ) {
    var i, r, s=document.styleSheets && document.styleSheets[0];
    if(s) {
            r = s.rules ? s.rules : s.cssRules;
            if(r) {
                    i = r.length;
                    while (i--) {
                            if(r[i].selectorText.toLowerCase() === selector.toLowerCase()) {
                                    return ( r[i].style[property] );
                            }
                    }
            }
    }
    return null;
}

function doItemBrowseCheckoutPageResize(iw){
	var iw = xWidth('img_' + iw);
	if (iw>imgWidth) imgWidth=iw;
	var contentHeight=parseInt(xHeight('content'));
	var contentTop=parseInt(xOffsetTop('content'));
	var w=parseInt(xWidth('content'));
	var hh=0;
	var hw=0;
	var deltaW = 0;
	var paddingHeight = xIE4Up ? 0 : -4;
	var footerHeight = xIE4Up ? 30 : 32;
	var deltaPadding = 5;
	
	if (document.getElementById("imprintHeader")){
		hh = xHeight("imprintHeader");
		hw = xWidth("imprintHeader");
	}
	if (document.getElementById("proofDiv")){
		var tw = xWidth('proofDiv');
		if ((tw+420)>w) w=tw + 420;
		var th = xHeight('proofDiv');
		if ((th+hh)>h) h=th + hh + 120;
	}

	var currW = parseInt(xPageX('summary'));
    try{
        if ((typeof imageBaseWidth) == "undefined") {
                imageBaseWidth = parseInt(getcss(".imageBaseWidth", "width"));
        }
        if (imageBaseWidth == null || isNaN(imageBaseWidth) ){
                imageBaseWidth = 600;
        }
	} catch (err){
	        imageBaseWidth = 600;
	}
	
	window.status = contentHeight;
	var imgDelta = (imgWidth-imageBaseWidth);

	if (imgDelta<0) imgDelta=0;
	
	var deltaW=(w-currW)+deltaPadding+imgDelta;
	if (deltaW<0) deltaW = 0;

	if (contentHeight<500) contentHeight=500;
	if (document.getElementById("footer")){
		document.getElementById("footer").style.width=currW+deltaW;
		
		var fTop = parseInt(document.getElementById("footer").style.top);
		if ((contentHeight + contentTop) > fTop){
			document.getElementById("footer").style.top = contentHeight+contentTop;
		} else {
			var backgroundHeight = xHeight("background");
			if (backgroundHeight>contentHeight){
				document.getElementById("footer").style.top=backgroundHeight + contentTop;
			} else {
				document.getElementById("footer").style.top = contentHeight + contentTop;
			}
		}
	}

	if (document.getElementById("vertnavbar")){
		document.getElementById("vertnavbar").style.width=currW+deltaW+xWidth('summary')+paddingHeight;
	}
	if (document.getElementById("summary")){
		document.getElementById("summary").style.left=currW+deltaW;
		document.getElementById("summary").style.height=contentHeight+footerHeight;
	}
}
function doStandardPageResize(){
	var contentHeight = xHeight('content');
	var contentTop=parseInt(xOffsetTop('content'));
	var w=parseInt(xWidth('content'));
	var headerHeight=0;
	var hw=0;
	var pW = xWidth('view_proof');
	pW = 0;
	var currW = parseInt(xPageX('summary'));
	var deltaW = 0;
	var paddingHeight = xIE4Up ? 0 : -4;
	var footerHeight = xIE4Up ? 30 : 32;
	var deltaPadding = 5;
	if (pW>0){
		deltaW=(pW-(currW-w)) + deltaPadding;
	} else {
		deltaW=(w-currW) + deltaPadding;
	}
	if (document.getElementById("imprintHeader")){
		headerHeight = xHeight("imprintHeader");
		hw = xWidth("imprintHeader");
	}
	if (document.getElementById("proofDiv")){

		var pDiv = document.getElementById("proofDiv");
		if (parseInt(xOffsetLeft(pDiv))<proofDivLeft){
			pDiv.style.left=proofDivLeft;
		}
		if (parseInt(xTop(pDiv))!=proofDivTop){
			pDiv.style.top=proofDivTop;
		}
		var proofWidth = xWidth('proofDiv');
		var leftProof = parseInt(xOffsetLeft("proofDiv"));
		var leftImprint = parseInt(xOffsetLeft("imprintBlockDiv"));
		var imprintWidth = parseInt(xWidth("imprintBlockDiv"));
		if (leftProof>leftImprint){
			var tmpW = (leftProof + proofWidth);

			if (tmpW>currW){
				currW = tmpW;
			}
			deltaW = 0;
		} else {
			var tmpW = proofWidth + imprintWidth;
			if (tmpW>currW){
				currW = proofWidth + imprintWidth + 20;
			}
			deltaW = 0;
		}

		var proofHeight = xHeight('proofDiv');
		var imprintHeight = xHeight("imprintBlockDiv");
		if (imprintHeight>proofHeight){
			if ((imprintHeight+headerHeight)>contentHeight){
				contentHeight = imprintHeight + headerHeight + 120;
			}
		} else {
			if ((proofHeight+headerHeight)>contentHeight){
				contentHeight = proofHeight + headerHeight + 120;
			}
		}
	}
	if (document.getElementById("resultsTable")){
		var tw = xWidth('resultsTable');
		if (tw>currW){
			currW = tw;
			deltaW = 0;
		}
	}

	var pre=contentHeight;
	
	if (deltaW<0) deltaW=0;
	
	if (contentHeight<500) contentHeight=500;

	if (document.getElementById("footer")){
		var backgroundHeight = xHeight("background");
		var fTop = parseInt(document.getElementById("footer").style.top);
		
		document.getElementById("footer").style.width = currW+deltaW;
		
		if (backgroundHeight>contentHeight){
			document.getElementById("footer").style.top=backgroundHeight + contentTop;
		} else if ((contentHeight + contentTop) > fTop){
			document.getElementById("footer").style.top = contentHeight+contentTop;
		} else {
			var backgroundHeight = xHeight("background");
			if (backgroundHeight>contentHeight){
				document.getElementById("footer").style.top=backgroundHeight + contentTop;
			} else {
				document.getElementById("footer").style.top = contentHeight + contentTop;
			}
		}
	}
	if (document.getElementById("vertnavbar")){
		document.getElementById("vertnavbar").style.width=currW+deltaW+xWidth('summary')+paddingHeight;
	}
	if (document.getElementById("summary")){
		document.getElementById("summary").style.left=currW+deltaW;
		document.getElementById("summary").style.height=contentHeight+footerHeight;
	}
}
/*  This page resize should deal with the imprint information being on the right instead of the left */
function doAgnosticPageResize(){
	var h=xHeight('content');
	var w=xWidth('content');
	var hh=0;
	var hw=0;
	var pW = xWidth('view_proof');
	pW = 0;
	var currW = xWidth('content');
	var deltaW = 0;
	if (pW>0){
		deltaW=(pW-(currW-w)) + 5;
	} else {
		deltaW=(w-currW)+5;
	}
	if (document.getElementById("imprintHeader")){
		hh = xHeight("imprintHeader");
		hw = xWidth("imprintHeader");
	}
	if (document.getElementById("proofDiv")){
		var pDiv = document.getElementById("proofDiv");
		if (parseInt(xOffsetLeft(pDiv))<proofDivLeft){
			pDiv.style.left=proofDivLeft;
		}
		if (parseInt(xTop(pDiv))!=proofDivTop){
			pDiv.style.top=proofDivTop;
		}

		var proofWidth = xWidth('proofDiv');
		var leftProof = parseInt(xOffsetLeft("proofDiv"));
		var leftImprint = parseInt(xOffsetLeft("imprintBlockDiv"));
		var imprintWidth = parseInt(xWidth("imprintBlockDiv"));
		if (leftProof>leftImprint){
			var tmpW = (currW-leftProof) + proofWidth;
			if (tmpW>currW){
				currW = (currW-leftProof) + proofWidth;
				deltaW = 0;
			} else {
				deltaW = 50;
			}
		} else {
			var tmpW = proofWidth + imprintWidth;
			if (tmpW>currW){
				currW = leftProof + proofWidth;
				deltaW = 0;
			} else {
				deltaW = 50;
			}
		}
		var th = xHeight('proofDiv');
		if ((th+hh)>h) h=th + hh + 120;
	}
	if (document.getElementById("resultsTable")){
		var tw = xWidth('resultsTable');
		if (tw>currW){
			currW = tw;
			deltaW = 0;
		}
	}

	var pre=h;
	if (deltaW<0) deltaW=0;
	if (h<500) h=500;

	if (document.getElementById("footer")){
		document.getElementById("footer").style.width=currW + deltaW;
		document.getElementById("footer").style.top=h+xHeight('vertnavbar');
	}
	if (document.getElementById("vertnavbar")){
		document.getElementById("vertnavbar").style.width=currW+deltaW+xWidth('summary')-4;
	}
	if (document.getElementById("summary")){
		document.getElementById("summary").style.left=currW+deltaW;
		document.getElementById("summary").style.height=h+32;
	}
}

function checkIntlChar(chr, pos){
	try{
		var test = checkImprintStatus;
		if ((typeof test) == "function"){
			checkImprintStatus(currentField.id);
		}
	} catch (err){
	}	
	if (! document.getElementById('displayIntlHints')) return;
	if (! document.getElementById('displayIntlHints').checked) return;
	if (currentField.value=='') return;
	//check to see if the most recent char has intl equiv
	var test = document.getElementById("testText");
	var dl = document.getElementById("displayList");
	if (dl.style.display != "none") dl.style.display = "none";
	var str = "";

	var l = "";
	if (chr==""){
		l = currentField.value.substring(currentField.value.length-1);
		pos = currentField.value.length-1;
	} else {
		l = chr;
	}
	
	test.innerHTML=currentField.value.substring(0, pos);
	for (x=0; x<intlChars.length; x++){
		if (intlChars[x].rootLetter.toLowerCase() == l.toLowerCase()){
			str += "<a class=display href=\"javascript:selectIntlChar('" + x + "','" + currentField.id + "', " + pos + ");\">" + intlChars[x].htmlCode + "</a><br>";
		}
	}
	if (str != ""){
		try{
			if (itemDisplay && itemDisplay.debug == true){
				itemDisplay.appendDebug("currentField: " + currentField.id + "; " + xPageY(currentField.id) + "<br>\n");
			}
		} catch (err){}
		dl.style.top = xPageY(currentField.id)+xHeight(currentField.id);
		dl.style.left = xPageX(currentField.id) + xWidth("testText");
		dl.innerHTML = str;
		dl.style.visibility="visible";
		dl.style.display = "inline";
		dl.style.display = "block";
	}
}
function selectIntlChar(x, id, pos){
	var f = document.getElementById(id);
	if (pos==f.value.length-1){
		f.value = f.value.substring(0, pos) + intlChars[x].display;
	} else {
		var s = f.value;
		f.value = s.substring(0, pos) + intlChars[x].display + s.substring(pos+1);
	}
	var dl = document.getElementById("displayList");
	dl.style.display = "none";
	f.focus();
}
function closeDisplay(){
	document.getElementById("displayList").style.display="none";
}
function replaceSelected(){
	closeDisplay();
	var str = "";
	var startInt = -1;
	var endInt = -1;
	if (document.getSelection) {
		startInt = currentField.selectionStart;
		endInt = currentField.selectionEnd;
		str = currentField.value.substring(startInt, endInt);
	} else if (document.selection && document.selection.createRange) {
		startInt = Math.abs(document.selection.createRange().moveStart("character", -1000000));
		endInt = Math.abs(document.selection.createRange().moveEnd("character", -1000000));
		str = document.selection.createRange().text;
	}
	if (str.length==1){
		checkIntlChar(str, startInt);
	}
}
function hideProofDiv(){
	if (document.getElementById("proofDiv")){
		var m = document.getElementById("proofDiv");
		m.style.display = "none";
	}
	if (document.getElementById("view_proof")){
		m = document.getElementById("view_proof");
		m.style.display = "none";
	}
}
function closeMessage(){
	if (document.getElementById("message")){
		var m = document.getElementById("message");
		m.style.display = "none";
	}
	if (document.getElementById("proofDiv")){
		var m = document.getElementById("proofDiv");
		m.style.display = "inline";
		if (document.getElementById("view_proof")){
			m = document.getElementById("view_proof");
			frames['view_proof'].setProofStr();
			frames['view_proof'].resizeFrame();
			m.style.display = "inline";
			doPageResize();
		}
	}
}
function uploadResizeFrame(){
	var proofWidth = xWidth('proofDiv');
	var leftProof = parseInt(xOffsetLeft("proofDiv"));
	var leftImprint = parseInt(xOffsetLeft("imprintBlockDiv"));
	var imprintWidth = parseInt(xWidth("imprintBlockDiv"));
	var topProof = parseInt(xHeight("topProofNotice"));
	var bottomProof = parseInt(xHeight("bottomProofNotice"));
	if (leftProof<leftImprint){
		resizeUploadAgnosticFrame();
	} else {
		var contentWidth = xWidth("content");
		var imgToLoad = document.getElementById('imgToLoad');
		var imgToLoadHeight = 0;
		if (! imgToLoad){
			imgToLoadHeight = xHeight('imgToLoadBackground');
			imgToLoad = document.getElementById('imgToLoadBackground');
		} else {
			imgToLoadHeight = xHeight('imgToLoad');
		} 
		if (imgToLoad){
			if (imgToLoad.width<100){
//				document.getElementById('view_proof').width=400;
//				document.getElementById('view_proof').style.width=400;
//				document.getElementById('view_proof').height=imgToLoad.style.height+topProof+bottomProof+20;
//				document.getElementById('view_proof').style.height=imgToLoad.style.height+topProof+bottomProof+20;
				document.getElementById('proofDiv').style.width=imgToLoad.width+20;
				document.getElementById('proofDiv').style.height=imgToLoad.height+topProof+bottomProof+20;
				document.getElementById('proofDiv').style.height=imgToLoad.style.height+topProof+bottomProof+20;

			} else {
				if (pageName=='itemProofResize'){
//					document.getElementById('view_proof').width=imgToLoad.width+0;
//					document.getElementById('view_proof').style.width=imgToLoad.width+20;
//					document.getElementById('view_proof').height=imgToLoad.height+topProof+bottomProof+20;
//					document.getElementById('view_proof').style.height=imgToLoad.height+topProof+bottomProof+20;
				} else {
					if (imgToLoad.width<580){
//						document.getElementById('view_proof').width=imgToLoad.width+20;
//						document.getElementById('view_proof').style.width=imgToLoad.width+20;
//						document.getElementById('view_proof').height=imgToLoad.height+topProof+bottomProof+20;
//						document.getElementById('view_proof').style.height=imgToLoad.height+topProof+bottomProof+20;

						document.getElementById('proofDiv').style.width=imgToLoad.width+20;
						document.getElementById('proofDiv').height=imgToLoad.height+topProof+bottomProof+20;
						document.getElementById('proofDiv').style.height=imgToLoad.height+topProof+bottomProof+20;
					} else {
//						document.getElementById('view_proof').width=550;
//						document.getElementById('view_proof').style.width=550;
//
//						document.getElementById('view_proof').scrolling='yes';
						document.getElementById('proofDiv').style.width=imgToLoad.width+20;
						document.getElementById('proofDiv').style.height=imgToLoad.height+topProof+bottomProof+20;
						document.getElementById('proofDiv').style.height=imgToLoad.style.height+topProof+bottomProof+20;
						
						if (imgToLoad){
//							document.getElementById('view_proof').height=imgToLoad.height+topProof+bottomProof+20;
//							document.getElementById('view_proof').style.height=imgToLoad.height+topProof+bottomProof+20;
						}
					}
				}
			}
			if (imgToLoadHeight>300){
				document.getElementById('footer').style.top=imgToLoadHeight+200;
				if (document.getElementById('summary')){
					document.getElementById('summary').style.height=imgToLoadHeight+200;
				}
			}
		}
	}
	
}
function resizeFrame() {
	var proofWidth = parent.xWidth('proofDiv');
	var leftProof = parseInt(parent.xOffsetLeft("proofDiv"));
	var leftImprint = parseInt(parent.xOffsetLeft("imprintBlockDiv"));
	var imprintWidth = parseInt(parent.xWidth("imprintBlockDiv"));
	var topProof = parseInt(xHeight("topProofNotice"));
	var bottomProof = parseInt(xHeight("bottomProofNotice"));
    if (document.getElementById('imgToLoad')){
        if (document.getElementById("bottomProofNotice")){
                var imgHeight = xHeight('imgToLoad');
                document.getElementById("bottomProofNotice").style.top = imgHeight + 10;
        }
    } else if (document.getElementById("backgroundImage")){
        if (document.getElementById("bottomProofNotice")){
                var imgHeight = xHeight('backgroundImage');
                document.getElementById("bottomProofNotice").style.top = imgHeight + 10;
        }
    }
    
	if (leftProof<leftImprint){
		resizeAgnosticFrame();
	} else {
		var contentWidth = parent.xWidth("content");
		var imgToLoad = document.getElementById('imgToLoad');
		var imgToLoadHeight = 0;
		if (! imgToLoad){
			imgToLoadHeight = xHeight('imgToLoadBackground');
			imgToLoad = document.getElementById('imgToLoadBackground');
		} else {
			imgToLoadHeight = xHeight('imgToLoad');
		} 
		if (imgToLoad){
			if (pageName=='itemProofResize'){
				parent.document.getElementById('view_proof').width=imgToLoad.width+0;
				parent.document.getElementById('view_proof').style.width=imgToLoad.width+20;
				parent.document.getElementById('view_proof').height=imgToLoad.height+topProof+bottomProof+20;
				parent.document.getElementById('view_proof').style.height=imgToLoad.height+topProof+bottomProof+20;
			} else if (imgToLoad.width<100){
				parent.document.getElementById('view_proof').width=400;
				parent.document.getElementById('view_proof').style.width=400;
				parent.document.getElementById('view_proof').height=imgToLoad.style.height+topProof+bottomProof+20;
				parent.document.getElementById('view_proof').style.height=imgToLoad.style.height+topProof+bottomProof+20;
				parent.document.getElementById('proofDiv').style.width=imgToLoad.width+20;
				parent.document.getElementById('proofDiv').style.height=imgToLoad.height+topProof+bottomProof+20;
				parent.document.getElementById('proofDiv').style.height=imgToLoad.style.height+topProof+bottomProof+20;

			} else {
				 if (imgToLoad.width<580){
					parent.document.getElementById('view_proof').width=imgToLoad.width+20;
					parent.document.getElementById('view_proof').style.width=imgToLoad.width+20;
					parent.document.getElementById('view_proof').height=imgToLoad.height+topProof+bottomProof+20;
					parent.document.getElementById('view_proof').style.height=imgToLoad.height+topProof+bottomProof+20;

					parent.document.getElementById('proofDiv').style.width=imgToLoad.width+20;
					parent.document.getElementById('proofDiv').height=imgToLoad.height+topProof+bottomProof+20;
					parent.document.getElementById('proofDiv').style.height=imgToLoad.height+topProof+bottomProof+20;
				} else {
					parent.document.getElementById('view_proof').width=550;
					parent.document.getElementById('view_proof').style.width=550;

					parent.document.getElementById('view_proof').scrolling='yes';
					parent.document.getElementById('proofDiv').style.width=550;
					parent.document.getElementById('view_proof').height=imgToLoad.height+topProof+bottomProof+20;
					parent.document.getElementById('view_proof').style.height=imgToLoad.height+topProof+bottomProof+20;
				}
			}
			if (imgToLoadHeight>300){
				parent.document.getElementById('footer').style.top=imgToLoadHeight+200;
				if (parent.document.getElementById('summary')){
					parent.document.getElementById('summary').style.height=imgToLoadHeight+200;
				}
			}
		}
	}
}
function resizeUploadAgnosticFrame(){
	var imgToLoad = document.getElementById('imgToLoad');
	var imgToLoadHeight = 0;
	if (! imgToLoad){
		imgToLoadHeight = xHeight('imgToLoadBackground');
		imgToLoad = document.getElementById('imgToLoadBackground');
	} else {
		imgToLoadHeight = xHeight('imgToLoad');
	} 

	if (imgToLoad){
		if (document.getElementById('imgToLoad').width<100){
		} else {
			document.getElementById('proofDiv').style.width=document.getElementById('imgToLoad').width+20;
			document.getElementById('proofDiv').style.height=document.getElementById('imgToLoad').height+80;
		}
		if (xHeight('imgToLoad')>300){
			document.getElementById('footer').style.top=xHeight('imgToLoad',0)+200;
			if (document.getElementById('summary')){
				document.getElementById('summary').style.height=xHeight('imgToLoad',0)+200;
			}
		}
		var proofWidth = xWidth('proofDiv');
		var leftProof = parseInt(xOffsetLeft("proofDiv"));
		var leftImprint = parseInt(xOffsetLeft("imprintBlockDiv"));
		var imprintWidth = parseInt(xWidth("imprintBlockDiv"));
		if (leftProof<leftImprint && (proofWidth+leftProof+5)>leftImprint){
			document.getElementById("imprintBlockDiv").style.left = proofWidth + leftProof + 5;
		}
	}
}
function resizeAgnosticFrame() {

	if (imgToLoad){
		if (document.getElementById('imgToLoad').width<100){
			parent.document.getElementById('view_proof').width=400;
			parent.document.getElementById('view_proof').style.width=400;
			parent.document.getElementById('view_proof').height=200;;
		} else {
			parent.document.getElementById('view_proof').width=document.getElementById('imgToLoad').width+0;
			parent.document.getElementById('view_proof').style.width=document.getElementById('imgToLoad').width+20;
			parent.document.getElementById('view_proof').height=document.getElementById('imgToLoad').height+60;
			parent.document.getElementById('view_proof').style.height=document.getElementById('imgToLoad').height+60;
			parent.document.getElementById('proofDiv').style.width=document.getElementById('imgToLoad').width+20;
			parent.document.getElementById('proofDiv').style.height=document.getElementById('imgToLoad').height+80;
		}
		if (xHeight('imgToLoad')>300){
			parent.document.getElementById('footer').style.top=xHeight('imgToLoad',0)+200;
			if (parent.document.getElementById('summary')){
				parent.document.getElementById('summary').style.height=xHeight('imgToLoad',0)+200;
			}
		}
		var proofWidth = parent.xWidth('proofDiv');
		var leftProof = parseInt(parent.xOffsetLeft("proofDiv"));
		var leftImprint = parseInt(parent.xOffsetLeft("imprintBlockDiv"));
		var imprintWidth = parseInt(parent.xWidth("imprintBlockDiv"));
		if (leftProof<leftImprint && (proofWidth+leftProof+5)>leftImprint){
			parent.document.getElementById("imprintBlockDiv").style.left = proofWidth + leftProof + 5;
		}
	}
}

function setProofStr(){
	if (proofImages.length>0){
		for (x=0; x<proofImages.length; x++){
			if (x==0){
				pageLinks = "<br>Page:";
			}
			pageLinks += "  <a href=\"javascript:loadProofImage('" + x + "');\">" + proofImages[x].label + "</a>  |"
		}
		if (document.getElementById('imgToLoad')){
			if (document.getElementById('imgToLoad').height>650){
				document.getElementById("bottomProofNotice").innerHTML=proofStr + pageLinks;
				document.getElementById("topProofNotice").innerHTML=proofStr + pageLinks;
			} else {
				document.getElementById("bottomProofNotice").innerHTML=proofStr + pageLinks;
			}
		} else {
			if (typeof(proofStr) != "undefined") document.getElementById("bottomProofNotice").innerHTML=proofStr + pageLinks;
		}
		if (document.getElementById('imgToLoad').getAttribute("loadedImage") == null) {
			loadProofImage(0);
		}
	} else {
		if (document.getElementById('imgToLoad')){
			if (document.getElementById('imgToLoad').height>650){
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr;
				}
				if (document.getElementById('topProofNotice')){
					document.getElementById("topProofNotice").innerHTML=proofStr;
				}
			} else {
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr;
				}
			}
		} else {
			if (typeof(proofStr) != "undefined") document.getElementById("bottomProofNotice").innerHTML=proofStr;
		}
	}
}
function setUploadProofStr(){
	if (proofImages.length>0){
		for (x=0; x<proofImages.length; x++){
			if (x==0){
				pageLinks = "<br>Page:";
			}
			if (proofImages[x].proofComplete=="true"){
				pageLinks += "  <a href=\"javascript:loadProofImage('" + x + "');\">" + proofImages[x].label + "</a>  |";
			} else {
				pageLinks += " " + proofImages[x].label + "  |";
			}
		}
		if (document.getElementById('imgToLoad')){
			if (document.getElementById('imgToLoad').height>650){
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr + pageLinks;
				}
				if (document.getElementById('topProofNotice')){
					if (document.getElementById("topProofNotice").getAttribute("containsStatus")!="true"){
						document.getElementById("topProofNotice").innerHTML=proofStr + pageLinks;
					}
				}
			} else {
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr + pageLinks;
				}
			}
		} else {
			if (typeof(proofStr) != "undefined"){
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr + pageLinks;
				}
			}
		}
		if (document.getElementById('imgToLoad').getAttribute("loadedImage")=="none"){
			loadProofImage(0);
		}
	} else {
		if (document.getElementById('imgToLoad')){
			if (document.getElementById('imgToLoad').height>650){
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr;
				}
				if (document.getElementById('topProofNotice')){
					if (document.getElementById("topProofNotice").getAttribute("containsStatus")!="true"){
						document.getElementById("topProofNotice").innerHTML=proofStr;
					}
				}
			} else {
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr;
				}
			}
		} else {
			if (typeof(proofStr) != "undefined"){
				if (document.getElementById('bottomProofNotice')){
					document.getElementById("bottomProofNotice").innerHTML=proofStr;
				}
			}
		}
	}
}

function fixPNGForOldIE(src) {
//       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
//	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
//	   var imgTitle = (myImage.title) ? "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' ";
//	   var imgStyle = "display:inline-block;" + myImage.style.cssText;
//	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
//                  + " style=\"" + "width:" + myImage.width 
//                  + "px; height:" + myImage.height 
//                  + "px;" + imgStyle + ";"
 //                 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
  //                + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
	   var foreGround = document.getElementById('foregroundImage');
	   var strNewHTML = "<span style=\"display:inline-block;width:500px;height:388px;" +
                  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" +
                 "(src=\'" + src + "\', sizingMethod='scale');\"></span>";
	   foreGround.innerHTML = strNewHTML;
//    }
}

function proofImage(l, d, o, i, u, p, b){
	this.label = l;
	this.detRecKey = d;
	this.orderRecKey = o;
	this.itemRecKey = i;
	this.url = u;
	this.pageInc = p;
	this.background = b;
}
function uploadProofImage(l, d, o, i, u, p, c){
	this.label = l;
	this.detRecKey = d;
	this.orderRecKey = o;
	this.itemRecKey = i;
	this.url = u;
	this.pageInc = p;
	this.proofComplete = c;
}

function displayImage(x){
	var img = document.getElementById(x);
	//img.style.visibility="visible";
}
var pngArVersion = null;
var pngVersion = 8;
if (navigator.appVersion.indexOf("MSIE")>0){
	pngArVersion = navigator.appVersion.split("MSIE");
	if (pngArVersion.length>1){
		pngVersion = parseFloat(pngArVersion[1]);
		if (pngVersion == NaN){
			pngVersion = 8;
		}
	}
	
}
var proofImages = new Array();
function loadProofImage(x){
	if (proofImages[x].background==null || proofImages[x].background==''){
		var img = document.getElementById('imgToLoad');
		img.setAttribute("loadedImage", x);
		img.src = proofImages[x].url;
	} else {
		var img = document.getElementById('imgToLoadBackground');
		img.setAttribute("loadedImage", x);
		//img.style.visibility="hidden";
		var now = new Date();
		img.src = proofImages[x].background + "?13hvp" + now.getTime();
		
    	if ((pngVersion >= 5.5) && (pngVersion < 7) && (document.body.filters)) {
    		fixPNGForOldIE(proofImages[x].url);
    	} else {
			img = document.getElementById('imgToLoad');
			img.setAttribute("loadedImage", x);
		//	img.style.visibility="hidden";
			img.src = proofImages[x].url;
		}
	}
}
function savedAddress(rk, attn, addr1, addr2, addr3, city, state, zip, country, tel, fax, county, ro){
	this.recKey = rk;
	this.attn = attn;
	this.addr1 = addr1;
	this.addr2 = addr2;
	this.addr3 = addr3;
	this.city = city;
	this.state = state;
	this.zip = zip;
	this.country = country;
	this.tel = tel;
	this.fax = fax;
	this.county = county;
	this.readOnly = ro;
}
function doGetBillTo(recKey){
	if (recKey==''){
		document.frmMe.txtBillToType.style.color='black';
		document.frmMe.txtBillToType.value  = "";

		document.frmMe.txtBillToName.style.color='black';
		document.frmMe.txtBillToName.value  = "";

		document.frmMe.txtBillToCompany.style.color='black';
		document.frmMe.txtBillToCompany.value = "";

		document.frmMe.txtBillToStreet1.style.color='black';
		document.frmMe.txtBillToStreet1.value = "";

		document.frmMe.txtBillToStreet2.style.color='black';
		document.frmMe.txtBillToStreet2.value = "";

		document.frmMe.txtBillToCity.style.color='black';
		document.frmMe.txtBillToCity.value = "";

		document.frmMe.txtBillToState.style.color='black';
		document.frmMe.txtBillToState.value = "";

		document.frmMe.txtBillToZip.style.color='black';
		document.frmMe.txtBillToZip.value = "";

		document.frmMe.txtBillToCountry.style.color='black';
		document.frmMe.txtBillToCountry.value = "";

		document.frmMe.txtBillToTel.style.color='black';
		document.frmMe.txtBillToTel.value = "";

		document.frmMe.txtBillToFax.style.color='black';
		document.frmMe.txtBillToFax.value = "";

		document.frmMe.txtBillToType.readOnly = false;
		document.frmMe.txtBillToName.readOnly = false;
		document.frmMe.txtBillToCompany.readOnly = false;
		document.frmMe.txtBillToStreet1.readOnly = false;
		document.frmMe.txtBillToStreet2.readOnly = false;
		document.frmMe.txtBillToCity.readOnly = false;
		document.frmMe.txtBillToState.readOnly = false;
		document.frmMe.txtBillToZip.readOnly = false;
		document.frmMe.txtBillToCountry.readOnly = false;
		document.frmMe.txtBillToTel.readOnly = false;
		document.frmMe.txtBillToFax.readOnly = false;
		return;
	}
	for (bx=0; bx<BillAddrs.length; bx++){
		if (BillAddrs[bx].recKey==recKey){
			document.frmMe.txtBillToType.value  = BillAddrs[bx].recKey;

			document.frmMe.txtBillToName.value  = BillAddrs[bx].attn;

			document.frmMe.txtBillToCompany.value = BillAddrs[bx].addr1;

			document.frmMe.txtBillToStreet1.value = BillAddrs[bx].addr2;

			document.frmMe.txtBillToStreet2.value = BillAddrs[bx].addr3;

			document.frmMe.txtBillToCity.value = BillAddrs[bx].city;

			document.frmMe.txtBillToState.value = BillAddrs[bx].state;

			document.frmMe.txtBillToZip.value = BillAddrs[bx].zip;

			document.frmMe.txtBillToCountry.value = BillAddrs[bx].country;

			document.frmMe.txtBillToTel.value = BillAddrs[bx].tel;

			document.frmMe.txtBillToFax.value = BillAddrs[bx].fax;
			if (BillAddrs[bx].readOnly==true || BillAddrs[bx].readOnly=='true'){
				document.frmMe.txtBillToName.style.color='#cccccc';
				document.frmMe.txtBillToName.readOnly = true;

				document.frmMe.txtBillToCompany.style.color='#cccccc';
				document.frmMe.txtBillToCompany.readOnly = true;

				document.frmMe.txtBillToStreet1.style.color='#cccccc';
				document.frmMe.txtBillToStreet1.readOnly = true;

				document.frmMe.txtBillToStreet2.style.color='#cccccc';
				document.frmMe.txtBillToStreet2.readOnly = true;

				document.frmMe.txtBillToCity.style.color='#cccccc';
				document.frmMe.txtBillToCity.readOnly = true;

				document.frmMe.txtBillToState.style.color='#cccccc';
				document.frmMe.txtBillToState.readOnly = true;

				document.frmMe.txtBillToZip.style.color='#cccccc';
				document.frmMe.txtBillToZip.readOnly = true;

				document.frmMe.txtBillToCountry.style.color='#cccccc';
				document.frmMe.txtBillToCountry.readOnly = true;

				document.frmMe.txtBillToTel.style.color='#cccccc';
				document.frmMe.txtBillToTel.readOnly = true;

				document.frmMe.txtBillToFax.style.color='#cccccc';
				document.frmMe.txtBillToFax.readOnly = true;
			}
			return;
		}
	}
}
	function setUpFade(fadeDiv) {
	  if (document.getElementById('errorbar')) {
	    elName = 'errorbar';
	  } else if (document.getElementById('successbar')) {
	    elName = 'successbar';
	  } else if (fadeDiv!=''){
	    elName = fadeDiv;
	  } else {
	  	return;
	  }
	  fader(elName,2000,50,2500);
	}
	function unFader(elName,start,steps,time) {
	  setOpacity(elName,1); // To prevent flicker in Firefox
	                          // The first time the opacity is set
	                          // the element flickers in Firefox
	  fadeStep = 100/steps;
	  timeStep = time/steps;
	  opacity = 1;
	  time = start + 100;
	  while (opacity <100) {
	    window.setTimeout("setOpacity('"+elName+"',"+opacity+")",time);
	    opacity += fadeStep;
	    time += timeStep;
	  }
	}

	// Fades an element
	// elName - id of the element
	// start - time in ms when the fading should start
	// steps - number of fading steps
	// time - the length of the fade in ms
	function fader(elName,start,steps,time) {
	  setOpacity(elName,100); // To prevent flicker in Firefox
	                          // The first time the opacity is set
	                          // the element flickers in Firefox
	  fadeStep = 100/steps;
	  timeStep = time/steps;
	  opacity = 100;
	  time = start + 100;
	  while (opacity >=0) {
	    window.setTimeout("setOpacity('"+elName+"',"+opacity+")",time);
	    opacity -= fadeStep;
	    time += timeStep;
	  }
	  if (opacity<=0){
		  if (document.getElementById(elName)){
			  var e = document.getElementById(elName);
				e.style.zIndex=0;
				e.zIndex=0;
				e.style.display='none';
		  }
	  }
	}
	function setOpacity(elName,opacity) {
	  opacity = (opacity == 100)?99:opacity;
	  if (document.getElementById(elName)){
		  el = document.getElementById(elName);
		  // IE
		  el.style.filter = "alpha(opacity:"+opacity+")";
		  // Safari < 1.2, Konqueror
		  el.style.KHTMLOpacity = opacity/100;
		  // Old Mozilla
		  el.style.MozOpacity = opacity/100;
		  // Safari >= 1.2, Firefox and Mozilla, CSS3
		  el.style.opacity = opacity/100;
	  }
	}

	function hideSelectBoxes(w) {
		try{
		 	var svn=document.getElementsByTagName("SELECT");
			for (a=0;a<svn.length;a++){
				if (svn[a].parentElement){
					var p = svn[a].parentElement;
					if (p.id == w || w=='all'){
						if (svn[a].style.display!="none"){
							svn[a].markedHidden = svn[a].style.display;
							svn[a].style.display="none";
						}
					}
				} else {
					if (svn[a].style.display!="none"){
						svn[a].markedHidden = svn[a].style.display;
						svn[a].style.display="none";
					}
				}
			}
		} catch (err){
			alert('hsb: ' + err);
		}
	}

	function displaySelectBoxes(w) {
		try{
		 	var svn=document.getElementsByTagName("SELECT");
			for (a=0;a<svn.length;a++){
				if (svn[a].parentElement){
					var p = svn[a].parentElement;
					if (p.id == w || w=='all'){
						try{
							if (svn[a].markedHidden!="undefined"){
								svn[a].style.display=svn[a].markedHidden;
							}
						} catch (e){
						}
					}
				} else {
					if (svn[a].markedHidden!="undefined"){
						svn[a].style.display=svn[a].markedHidden;
					}
				}
				svn[a].markedHidden = "undefined";
			}
		} catch (err){
			alert('hsb: ' + err);
		}
	}
	function formatNumber(id, format){
		var field = document.getElementById(id);
		if (field.value!=''){
			if (format=="FORMAT_CURRENCY_NODEC"){
				field.value = doNumberFormat(field.value, "$", false);
			} else {
				field.value = doNumberFormat(field.value, "", true);
			}
		}
	}
	function doNumberFormat(num,prefix,includeDec){
	
	   prefix = prefix || '';
	   num = unformatNumber(num);
	   num += '';

	   var splitStr = num.split('.');
	   var splitLeft = splitStr[0];
	   var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
	   var regx = /(\d+)(\d{3})/;
	   while (regx.test(splitLeft)) {
	      splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
	   }
	   if (includeDec){
		   return prefix + splitLeft + splitRight;
	   } else {
		   return prefix + splitLeft;
	   }
	}

	function unformatNumber(num) {
	   return num.replace(/([^0-9\.\-])/g,'')*1;
	}
	function showMessageDiv(which){
		showMessageDiv(which, 999998);
	}
	function showMessageDiv(which, displayZIndex){
		if (displayZIndex == null || parseInt(displayZIndex) == NaN){
			displayZIndex = "999998";
		}
		gPopupMask = document.getElementById("masker");
		gPopupContainer = document.getElementById(which);

		// calculate where to place the window on screen
		var fullHeight = document.body.clientHeight;
		var fullWidth =  document.body.clientWidth;		
	
		var theBody = document.getElementsByTagName("BODY")[0];
		theBody.style.overflow = "hidden";
		
		var scTop = parseInt(theBody.scrollTop,10);
		var scLeft = parseInt(theBody.scrollLeft,10);

		gPopupMask.style.top = scTop + "px";
		gPopupMask.style.left = scLeft + "px";

		setMaskSize();
//		var left = xPageX(which)
//		var top = xPageY(which);
//		document.getElementById("popupMessageDiv").style.left = left;
//		document.getElementById("popupMessageDiv").style.top = top;
//		document.getElementById("popupMessageDiv").style.display = 'block';
//		document.getElementById("popupMessageDiv").style.zIndex=999999;
//		document.location="#" + which;
		hideSelectBoxes('all');
		gPopupMask.style.display = "block";
		gPopupContainer.style.display = "block";
		gPopupMask.style.zIndex = displayZIndex;
		gPopupContainer.style.zIndex = (parseInt(displayZIndex) + 1);
		if (which=="popupMessageWrapperDiv"){
			document.getElementById('popupMessageWrapperDiv').style.height = xHeight('popupMessageDiv') + 50;
		}
		var height = xHeight(which);
		var width = xWidth(which);
		if (width == null || isNaN(width)) {
			width = gPopupContainer.offsetWidth;
		}
		if (height == null) {
			height = gPopupContainer.offsetHeight;
		}

		if (width==0 || height==0){
			gPopupContainer.style.top = scTop + 10;
			gPopupContainer.style.left =  scLeft + 10;
			
		} else {
//			gPopupContainer.style.top = scTop + 10;
//			gPopupContainer.style.left =  scLeft + 10;

			var scCenterTop = fullHeight/2;
			gPopupContainer.style.top = scTop + parseInt(scCenterTop - (height/2));
//			
			var scCenterWidth = fullWidth/2;
			gPopupContainer.style.left =  parseInt(scCenterWidth - (width/2));
//			alert("centered:\n" + height + " x " + width + "\n" + scCenterTop + " x " + scCenterWidth + "\n" + parseInt(scCenterTop - (height/2)) + " x " + parseInt(scCenterWidth - (width/2)));
			
		}
		
	}
	function setMaskSize() {
		var theBody = document.getElementsByTagName("BODY")[0];

		var fullHeight = xClientHeight();
		var fullWidth =  xClientWidth();

		// Determine what's bigger, scrollHeight or fullHeight / width
		if (fullHeight > theBody.scrollHeight) {
			popHeight = fullHeight;
		} else {
			popHeight = theBody.scrollHeight
		}
		var gPopupMask = document.getElementById("masker");
		gPopupMask.style.height = popHeight + "px";
		gPopupMask.style.width = theBody.scrollWidth + "px";
		setOpacity("masker",30);
	}
	function hideMessageDiv(){
		var cDiv = "popupMessageWrapperDiv";
		var theBody = document.getElementsByTagName("BODY")[0];
		theBody.style.overflow = "";
		var gPopupMask = document.getElementById("masker");
		var gPopupContainer = document.getElementById(cDiv);
		gPopupMask.style.display = "none";
		gPopupContainer.style.display = "none";
		
		displaySelectBoxes('all');
		
	}
	function hideMessageDiv(postFunction){
		var cDiv = "popupMessageWrapperDiv";
		var theBody = document.getElementsByTagName("BODY")[0];
		theBody.style.overflow = "";
		var gPopupMask = document.getElementById("masker");
		var gPopupContainer = document.getElementById(cDiv);
		gPopupMask.style.display = "none";
		gPopupContainer.style.display = "none";
		
		displaySelectBoxes('all');
		try{
			eval(unFEscape(postFunction));
		} catch (err){}
	}

	function markErrors(){
		if (typeof strMsgArray == 'undefined'){
			return;
		}
		
		if (strMsgArray.length>0){
			
			for (x=0; x<strMsgArray.length; x++){
				var pieces = strMsgArray[x].split("::");
				var fields = pieces[0].split(",");
				for (y=0; y<fields.length; y++){
					if (document.getElementById(fields[y])){
						var element = document.getElementById(fields[y]);
						var className = element.className;
						if (className.indexOf('Error')<0){
							className += "Error";
							element.className = className;
						}
						if (y==0){
							if (document.getElementById(fields[0] + "Error")){
								element = document.getElementById(fields[0] + "Error")
								element.innerHTML = pieces[1];
								element.style.display="block";
							}
						}
					}
				}
			}
		}
	}
	function clearErrors(){
		var obj = document.getElementById("frmMe");
//		if (!obj) obj = document;
		if (obj==null) return;
		var types = "input,select,textarea".split(",");
		for (x=0; x< types.length; x++){
			var tags = obj.getElementsByTagName(types[x]);
			for (var j=0;j<tags.length;j++) {
				var className = tags[j].className;
				if (className.indexOf('Error')>=0){
					className = className.replace("Error","");
					tags[j].className = className;
				}
				if (document.getElementById(tags[j].id + "Error")){
					var element = document.getElementById(tags[j].id + "Error");
					element.innerHTML = "";
					element.style.display="none";
				}
			}
		}
		
	}
	function showPopupMessage(strMessage){
		showPopupMessageWithLabel("", strMessage);
	}
	function showPopupMessageWithLabel(label, strMessage){
		clearErrors();
		if (label!=""){
			document.getElementById('popupMessageLabelDiv').innerHTML = label;
		} else {
			document.getElementById('popupMessageLabelDiv').innerHTML = "WARNING";
		}
		document.getElementById('popupMessageDiv').innerHTML = strMessage + "<br><br><a href=\"javascript:hideMessageDiv();\">Close Message</a>";
		showMessageDiv("popupMessageWrapperDiv");
		markErrors();
	}
	
	function showPopupMessageWithCloseFunction(strMessage, closeFunction){
		showPopupMessageWithLabelAndCloseFunction("", strMessage, closeFunction);
	}
	function showPopupMessageWithLabelAndCloseFunction(label, strMessage, closeFunction){
		clearErrors();
		if (label!=""){
			document.getElementById('popupMessageLabelDiv').innerHTML = label;
		} else {
			document.getElementById('popupMessageLabelDiv').innerHTML = "WARNING";
		}
		document.getElementById('popupMessageDiv').innerHTML = strMessage + "<br><br><a href=\"javascript:hideMessageDiv('" + fEscape(closeFunction) + "');\">Close Message</a>";
		showMessageDiv("popupMessageWrapperDiv");
		markErrors();
	}
	
	function confirmWithPopupMessage(strMessage, continueFunction){
		confirmWithPopupMessageWithLabel("", strMessage, continueFunction);
	}
	function confirmWithPopupMessageWithLabel(label, strMessage, continueFunction){
		clearErrors();
		if (label!=""){
			document.getElementById('popupMessageLabelDiv').innerHTML = label;
		} else {
			document.getElementById('popupMessageLabelDiv').innerHTML = "WARNING";
		}
		document.getElementById('popupMessageDiv').innerHTML = strMessage +
			"<br><br><a href=\"javascript:" + continueFunction + ";\">Continue</a>" +
			// Ticket 2090: Need to be able to reenable the checkout button if we have issues
			"<br><br><a href=\"javascript:hideMessageDiv();reEnableCheckoutButtons();\" >Close Message and Return</a>";
		showMessageDiv("popupMessageWrapperDiv");
		markErrors();
	}
	
	// Ticket 2090: Reenable the checkout buttons if they exists
	function reEnableCheckoutButtons() { 
		if ( document.getElementById("completeOrderButton") ) {
			document.getElementById("completeOrderButton").disabled = false;
		}
		
		if ( document.getElementById("cancelOrderButton") ) {
			document.getElementById("cancelOrderButton").disabled = false;
		}
		
		if ( document.getElementById("saveOrderButton") ) {
			document.getElementById("saveOrderButton").disabled = false;
		}
	}
	
	var validationComplete = false;
	function doValidation(destination, which){
		validationComplete = false;

		var xmlhttp = new XMLHttpRequest();  
		xmlhttp.open("GET", destination, true);  
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200){
					parseResponse(xmlhttp.responseXML, which);
				} else {
				}
			}
		}		
		xmlhttp.send(null);  
	}
	function parseResponse(responseXML, which){
		var text = "";
		var responseType = responseXML.getElementsByTagName('responseType')[0].childNodes[0].data;
		if (responseType == "success"){
			validationComplete = true;
			return;
		} else {
			for (x=0; x< responseXML.getElementsByTagName('responseErrorMessage')[0].childNodes.length; x++){
				text += responseXML.getElementsByTagName('responseErrorMessage')[0].childNodes[x].data;
			}
			strMsg += text + '<br>\\n';
			strMsgArray[strMsgArray.length]=which + '::' + text;
			validationComplete = true;
			return;
		}
	}
	function addJavascript(jsname,pos) {
		var th = document.getElementsByTagName(pos)[0];
		var s = document.createElement('script');
		s.setAttribute('type','text/javascript');
		s.setAttribute('src',jsname);
		th.appendChild(s);
	}
	try{
		var jsonTest = jsonParse;
		if ((typeof jsonTest) == "function") {
		} else {
			addJavascript("/js/json_sans_eval.js", "head");
		}
	} catch (err){
		addJavascript("/js/json_sans_eval.js", "head");
	}

	function acceptCarrierAddressChange( addressChangeString){
		var addressChange = jsonParse(decodeURI(addressChangeString));
		try{
			if (addressChange.street1){
				document.getElementById("txtAddr2").value = addressChange.street1;
			}
			if (addressChange.street2){
				document.getElementById("txtAddr3").value = addressChange.street2;
			}
			if (addressChange.city){
				document.getElementById("txtCity").value = addressChange.city;
			}
			if (addressChange.state){
				document.getElementById("cboState").value = addressChange.state;
			}
			if (addressChange.zip){
				document.getElementById("txtZip").value = addressChange.zip;
			}
			if (addressChange.country){
				document.getElementById("txtCountry").value = addressChange.country;
			}
			if (addressChange.tel){
				document.getElementById("txtShipToTel").value = addressChange.tel;
			}
			hideMessageDiv();
		} catch (err){
			
		}
	}
	
	function acceptCarrierAddressChanges( addressChangeString, recKey){
		var addressChange = jsonParse(decodeURI(addressChangeString));
		try{		
			if ( recKey == 0 ) {  // order
					if (addressChange.street1){
						document.getElementById("shipToAddr2").value = addressChange.street1;
					}
					if (addressChange.street2){
						document.getElementById("shipToAddr3").value = addressChange.street2;
					}
					if (addressChange.city){
						document.getElementById("shipToCity").value = addressChange.city;
					}
					if (addressChange.state){
						document.getElementById("shipToState").value = addressChange.state;
					}
					if (addressChange.zip){
						document.getElementById("shipToZip").value = addressChange.zip;
					}
					if (addressChange.country){
						document.getElementById("shipToCountry").value = addressChange.country;
					}
					if (addressChange.tel){
						document.getElementById("shipToTel").value = addressChange.tel;
					}
				} else { // if detail line
					if (addressChange.street1){
						document.getElementById("shipToAddr2" + recKey).value = addressChange.street1;
					}
					if (addressChange.street2){
						document.getElementById("shipToAddr3" + recKey).value = addressChange.street2;
					}
					if (addressChange.city){
						document.getElementById("shipToCity" + recKey).value = addressChange.city;
					}
					if (addressChange.state){
						document.getElementById("shipToState" + recKey).value = addressChange.state;
					}
					if (addressChange.zip){
						document.getElementById("shipToZip" + recKey).value = addressChange.zip;
					}
					if (addressChange.country){
						document.getElementById("shipToCountry" + recKey).value = addressChange.country;
					}
					if (addressChange.tel){
						document.getElementById("shipToTel" + recKey).value = addressChange.tel;
					}
				}
			//hideMessageDiv();
			cancelMessage('');
		} catch (err){
			alert('Error in acceptCarrierAddressChanges');
		}
	}
	
	function isArray(testObject) {   
	    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
	}
	function randomString(len) {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = len;
		var randomstring = "";
		for (var i=0; i<string_length ; i++){
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	}
    function fEscape(txt){
        var localTxt = txt;
        localTxt = localTxt.replace(/'/g, "##Q##");
        localTxt = localTxt.replace(/"/g,"##DQ##");
        return localTxt;
    }
    function unFEscape(txt){
        var localTxt = txt;
        localTxt = localTxt.replace(/##Q##/g, "'");
        localTxt = localTxt.replace(/##DQ##/g,"\"");
        return localTxt;
    }
	
	function escapeForSubmission(txt){
//		var localTxt = escape(txt);
		var localTxt = txt;
		localTxt = localTxt.replace(/%/g, "%25");
		localTxt = localTxt.replace(/\//g,"%2F");
		localTxt = localTxt.replace(/\?/g,"%3F");
		localTxt = localTxt.replace(/=/g,"%3D");
		localTxt = localTxt.replace(/&/g,"%26");
		localTxt = localTxt.replace(/@/g,"%40");
		localTxt = localTxt.replace(/\+/g, "%2B");
		return localTxt;
		//return txt;
	}
	function setCursor(which){
		document.body.style.cursor = which;
	}

	// Ticket 1903: Add a check for bad international characters
function checkForBadInternationalCharacters(fieldID) {
	// This is the regular expression to get all non-regular characters (not on english keyboard) 
	var regEx = /[^0-9a-zA-Z,&lt; \.&gt; \/\?\\&#39; " ;:\]\}\[\{=+-_~'`!@#$%\^&amp;\*()\$|\\]/;
	
	// Check if field exists
	if ( document.getElementById(fieldID) ) {
		// get the value from the field
		var testString = document.getElementById('txtImprint_1').value;
		
		// find the first matchin character
		var matchingChar = testString.search(regEx);
		var badChars = '';
		
		// While there are more non-regular characters, check them
		while ( matchingChar != -1  ) {
			var found = false;
			
			// Check if the intlChars array exist
			if ( intlChars != null ) {
				// Go through and see if the character matches any in the special characters list.
				for ( var charWalker = 0 ; charWalker <  intlChars.length ; charWalker++ ) {
					if ( testString.charAt(matchingChar) == intlChars[charWalker].display ) {
						found = true;
						charWalker = intlChars.length;
					}
				}
			}
			
			// If the character isn't found, add it to the bad character list.
			if ( !found ) {
				if ( badChars == '' ) {
					badChars = testString.charAt(matchingChar);
				} else {
					badChars += ', ' + testString.charAt(matchingChar);
				}
			}
			
			// If we are at the last character, stop looking
			if ( matchingChar == (testString.length - 1) ) {
				matchingChar = -1;
			} else {
				// Find the next bad character past the last one
				testString = testString.substring(matchingChar + 1);
				
				matchingChar = testString.search(regEx);
			}
		}
		
		return badChars;
	}
	
	return 'Bad imprint field: ' + fieldID;
}

// Ticket 1911: Have a function to set up international shipments for the users
function checkCountry(countryElementID, stateElementID, zipElementID) {
	var countryID = 'txtCountry';
	var stateID = 'cboState';
	var zipID = 'txtZip';
	
	if ( countryElementID != null && countryElementID != '' ) {
		countryID = countryElementID;
		// Ticket 1983: If we are checking a bill to country, default the state and zip to the bill to state/zips
		if ( countryElementID.toLowerCase().indexOf("bill") >= 0) {
			stateID = "txtBillToState";
			zipID = 'txtBillToZip';
		}
	}
	
	if ( stateElementID != null && stateElementID != '' ) {
		stateID = stateElementID;
	}
	
	if ( zipElementID != null && zipElementID != '' ) {
		zipID = zipElementID;
	}
	
	var country = document.getElementById(countryID).value;
	
	if ( country != 'US' && country != 'CA' && country != 'PR' && ( !document.getElementById(stateID).options[0].selected || document.getElementById(zipID).value != '00000' ) ) {
		var blankStateAndZip = confirm('This country has no state or zip, would you like us to blank your state and zip?');
		
		if ( blankStateAndZip )  {
			document.getElementById(stateID).options[0].selected = true;
			document.getElementById(zipID).value = '00000';
			checkCounty();
		}
	}
}
function parseTimeFromSeconds(seconds){
	var txt = "";
	//if we're under a minute, return seconds
	if (seconds<60){
		txt = seconds + " second";
		if (seconds>1){
			txt += "s";
		}
	//if more than a minute, but less than an hour 
	} else if (seconds > 60 && seconds < (60*60)){
		var minutes = parseInt(seconds/60);
		var secs = seconds - (minutes * 60);
		txt = minutes + " minute";
		if (minutes>1){
			txt += "s";
		}
		if (secs>0){
			txt += ", " + secs + " second";
			if (secs>1){
				txt += "s";
			}
		}
	// if more than an hour...	
	} else {
		var hours = parseInt(seconds/60/60);
		var minutes = parseInt((seconds - (hours * 60 * 60)) / 60);
		var secs = seconds - (hours * 60 * 60) - (minutes * 60)
		txt = hours + " hour";
		if (hours>1){
			txt+="s";
		}
		if (minutes>0){
			txt += ", " + minutes + " minute";
			if (minutes>1){
				txt += "s";
			}
		} 
		if (secs>0){
			txt += ", " + secs + " second";
			if (secs>1){
				txt += "s";
			}
		}
	}
	return txt;
}
function clearTimers(timer){
	if (typeOf(timer) == "array"){
		for(var k in timer){
			if (isDefined(timer[k]) && timer[k]!=null){
				clearTimeout(timer[k]);
				timer[k] = null;
			}
		}
	} else {
		if (isDefined(timer) && timer != null){
			clearTimeout(timer);
			timer = null;
		}
	}
}
function isDefined(someVariable){
	try{
		if ((typeof someVariable) == "undefined") {
			return false;
		}
		if (someVariable == null){
			return false;
		}
		return true;
	} catch (err){
		return false;
	}
}
function stopTimeout(id){
	if (isDefined(timers[id]) && timers[id]!=null){
		clearTimeout(timers[id]);
		timers[id]=null;
	}
}
function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length')) &&
                    typeof value.splice === 'function') {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}
function setRealDimensions(){
	this.parentObject.realWidth = this.width;
	this.parentObject.realHeight = this.height;
}
var newImage = null;
function toggleStockCheckImage(){
	//str.append("<div id=\"stockCheckImageDiv\"><img id=\"stockCheckImage\" onclick=\"javascript:toggleStockCheckImage()\" src=\"viewer?which=doStockCheckPDF&detailRecKey=").append(d.recKey).append("&fp=true\" /></div><br>");
	if (document.getElementById("stockCheckImage")){
		var image = document.getElementById("stockCheckImage");
		if (typeof(image.realWidth) != "undefined"){
			if (image.width != image.realWidth){
				image.width=image.realWidth;
				image.style.width=image.realWidth;
			} else {
				image.width = document.getElementById("stockCheckImageDiv").style.width;
				image.style.width=document.getElementById("stockCheckImageDiv").style.width;
			}
		} else {
			if (newImage == null){
				newImage = new Image();
				newImage.parentObject = image;
				newImage.src = image.src;
				newImage.onload = setRealDimensions;
				if (newImage.width != 0){
					newImage.parentObject.realWidth = newImage.width;
					newImage.parentObject.realHeight = newImage.height;
					setTimeout(toggleStockCheckImage, 1000);
				} else {
					setTimeout(toggleStockCheckImage, 1000);
				}
			}
		}
	}
}

/**
 * Returns whether or not the updates to the implemention customer are valid or not
 * @returns {Boolean}
 */
function validateImpCustomer(){
	var f = document.editForm;
	var alertStr = '';
	if (document.getElementById("completed")){
		if (f.completed.checked && (f.status.value<6 || f.status.value==9)){
			alertStr += "Completed checked, status must be Moved Live, Sent to Prod or Completed (Not Moved Live)\n";
		}
		if ((f.status.value==6 || f.status.value==7 || f.status.value==8) && !f.completed.checked){
			alertStr += "If you are selecting Moved Live, Sent to Prod or Completed (Not Moved Live), you should also check complete.\n";
		}
	}

	if ( $('[name="accountNumber"]').length > 0 && $('[name="accountNumber"]').val() != "" ) {
		validatePaceCode($('[name="accountNumber"]').val(), alertStr );
		return false;
	}

	if (alertStr == ''){
		f.submit();
	} else {
		alert(alertStr);
		return false;
	}
}

/**
 * Fixes the accont code
 */
function fixAccountCode(){
	var uid = document.editForm.accountCode.value;
	uid = uid.toLowerCase();
	uid = uid.replace(' ','');
	uid = uid.replace('-','');
	uid = uid.replace('\'','');
	uid = uid.replace('\"','');
	document.editForm.accountCode.value=uid;
}

/**
 * Makes sure the paceCode is a valid pace code
 * @param paceCode - The Pace Code to verify
 * @param alertStr - The current alert string
 */
function validatePaceCode(paceCode, alertStr) {
	this.orderDetailsLoaded = false;
	var destination = "implementation";
	var postData = "which=validatePaceCode&paceCode=" + paceCode;
	
	$.ajax(
		{ 
			conentType: 'application/x-www-form-urlencoded',
			type: "POST",
			url: destination, 
			data: postData,
			success: function(xml){ parseValidatePaceCodeResponse(xml, alertStr); }
		}
	);
}

/**
 * Figures out if the Pace code is valid or not and then alers any errors there may be or submits if there are none
 * @param responseXML - The XML from implementation servlet
 * @param alertStr - The current alert string
 * @returns {Boolean}
 */
function parseValidatePaceCodeResponse(responseXML, alertStr) {
	var responseType = responseXML.getElementsByTagName('responseType')[0].childNodes[0].data;

	if (responseType == "success"){
		var found = responseXML.getElementsByTagName('responseMessage')[0].childNodes[1].childNodes[0].nodeValue;
		
		if ( found != "true") {
			alertStr += "Pace Code not found";
		}
	} else {
		alertStr += "Error checking pace code: " + responseXML.getElementsByTagName('responseMessage').childNodes[0].childNodes[1].childNodes[0].nodeValue + "\n";		
	}
	
	if (alertStr == ''){
		document.editForm.submit();
	} else {
		alert(alertStr);
		return false;
	}
}

/**
 * Validates if the current changes to a DOL customer
 * @returns {Boolean}
 */
function validateDOLCustomer(){
	var f = document.editForm;
	var alertStr = '';
	
	if ( $('[name="paceCustCode"]').length > 0 && $('[name="paceCustCode"]').val() != "" ) {
		validatePaceCode($('[name="paceCustCode"]').val(), alertStr );
		return false;
	}

	if (alertStr == ''){
		f.submit();
	} else {
		alert(alertStr);
		return false;
	}
}

function loadServlet(url, target){
	if (url == null || url == undefined || url == "" ){
		return;
	}
	if (target == null || target == "" || target == 'null'){
		if ($("#dialogDiv").length==0){
			$('body').append("<div id=\"dialogDiv\" style=\"display: none;text-align: left; padding-left: 20px; padding-right: 20px;\"></div>");
		} else {
			$("#dialogDiv").dialog('destroy');
		}
		$("#dialogDiv").attr("title", "Loading page").html("loading....");
		$("#dialogDiv").dialog({
			modal: true,
			height: 200,
			width: 500
		});
		
		document.location = url;
	} else {
		if (target == "_newWindow"){
			target += randomString(6);
			var h = $(window).height();
			var w = $(window).width();
			window.open(url, target, "height=" + h + ",width=" + w);
		} else {
			target += randomString(6);
			window.open(url, target, "");
		}
		closeContextMenu();		
	}
}
function showSubMenuInternal(id){
	jQuery("li#" + id).addClass("menuHighlight");
	var offset = jQuery("li#" + id).offset();
	var t = offset.top + jQuery("li#" + id).height()+3;
	var l = offset.left;
	jQuery("ul#" + id + "SubMenuUl").css({top: t, left: l}).fadeIn("fast");
	
}

function hideSubMenuInternal(id){
	if (jQuery("ul#" + id + "SubMenuUl").hasClass('activeSubMenu')){
		return;
	}
	if (jQuery("li#" + id).hasClass("activeMenu")){
		return;
	}
	jQuery("li#" + id).removeClass("menuHighlight");
	jQuery("ul#" + id + "SubMenuUl").hide();
}
//function setMenuHover(){
//}

//Note: the session is really 30 minutes long, but we allow for
//only 25 here to ensure the session isn't timed out
var SESSION_LENGTH = (1000 * 60 * 25);
function checkSessionForSubmission(successFunction, forceUrl){
	onLoginSuccess = null;
	//var pageLoadDate = $("input[name=pageLoadDate]").val();
	//check to see how long it has been since the page was loaded... if it is more than 30 minutes, load a page to get the session updated, then
	var pld = new Date(pageLoadDate);
	var cd = new Date();
	if (cd.getTime() - pld.getTime() > SESSION_LENGTH){
		if ($("#dialogDiv").length==0){
			$('body').append("<div id=\"dialogDiv\" style=\"text-align: left; padding-left: 20px; padding-right: 20px;\"></div>");
		} else {
			$("#dialogDiv").dialog('destroy');
		}
		$("#dialogDiv").attr("title", "Checking aged session").html("Checking the status of your session...");
		$("#dialogDiv").dialog({
			modal: true,
			height: 300,
			width: 600,
			buttons: {
			}
		});

		//we need to reload
		//show a dialog telling end-user we are re-validating session
		//hit a page the will revalidate teh session
		
		$.ajax({
			url: isDefined(forceUrl) ? forceUrl : "entry",
			dataType: "html",
			data: "which=sessionCheck",
			success: function(html, textStatus, httpResult){
				if (html.indexOf("Session.Success")>=0){
					//go ahead and submit the form now
					$("#dialogDiv").dialog('close');
					successFunction();
				} else {
					$("#dialogDiv").dialog('destroy');
					$("#dialogDiv").attr("title", "Session Invalid").html("Sorry, your session is no longer valid.<br><br>If you click the <b>Login</b> button below, a pop-window will open to allow you to re-login.  When you successfully login, your submission will be sent automatically.<br><br>You can click <b>Close</b> to deal with this problem manually.");
					$("#dialogDiv").dialog({
						modal: true,
						height: 300,
						width: 600,
						buttons: {
							Login: function(){
								onLoginSuccess = successFunction;
								window.open("https://auth.duplionline.com:8443/cas/login?service=http%3A%2F%2Fproxy.duplionline.com%3A8080%2ForderAdmin%2Fservlet%2Fentry%3Fwhich%3DsessionRefresh", "_sessionRefresh", "width=600,height=650,status=no,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no"); $("#dialogDiv").dialog('close');},
							Close: function(){$("#dialogDiv").dialog('close');} 
						}
					});
					
				}
			}
		});
		
	} else {
		//submit the data.  otherwise, go ahead and submit the data
		successFunction();
	}
}
var onLoginSuccess = null;
function loginSuccess(){
	if ($("#dialogDiv").length==0){
		$('body').append("<div id=\"dialogDiv\" style=\"display: none;text-align: left; padding-left: 20px; padding-right: 20px;\"></div>");
	} else {
		$("#dialogDiv").dialog('destroy');
	}
	$("#dialogDiv").attr("title", "Loading page").html("submitting....");
	$("#dialogDiv").dialog({
		modal: true,
		height: 200,
		width: 500
	});
	
	onLoginSuccess();
}
function delayedAjax(options){
	if (! isDefined(options.error)){
		options.error = function(){};
	}
	if (! isDefined(options.type)){
		options.type = "GET";
	}

	jQuery.ajax({
		type: options.type,
		url: options.url,
		data: options.data,
		dataType: options.dataType,
		success: options.success,
		error: options.error
	});
}

function getLabelElement(elementID, isGrandchild) {
	var child = $("#" + elementID);
	var parent = child.parent();
	var grandParent = parent.parent();
	var label = null;
	
	if  ( !isGrandchild ) {
		grandParent = parent;
		parent = child;
	}

	for ( var childWalker = 1 ; childWalker < grandParent.contents().length ; childWalker++ ) {
		var current = grandParent.contents()[childWalker];
		if ( current === parent[0] ) {//.find(child).length > 0 ) {
			label = grandParent.contents()[childWalker - 1];
			childWalker = grandParent.contents().length
		}
	}
	
	return label;
}
function getFormattedToday(){
	var today = new Date()
	var mm = today.getMonth() + 1;
	var dd = today.getDate();
	var yy = today.getFullYear();
	if (mm<10) mm="0" + mm;
	if (dd<10) dd="0" + dd;
	return (mm + "/" + dd + "/" + yy);

}
function defineEnterFunction(id, functionName) {
	$('#' + id).keyup(function(e) {
		if(e.keyCode == 13) {
			eval(functionName + "()");
		}
	});
}

function findIndex(array, value) {
	var index = $.inArray(value, array);
	
	if ( index <= -1 ) {
		for (i in array) {
			if ( array[i] == value ) {
				index = i;
				break;
			}
		}
	}
	
	return index;
}

function isNumeric(n){
	if (isNaN(n*1)){
		return false;
	} else {
		return true;
	}
}

var Base64 = {
		// private property
		_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 +
			Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
			Base64._keyStr.charAt(enc3) + Base64._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 = Base64._keyStr.indexOf(input.charAt(i++));
		enc2 = Base64._keyStr.indexOf(input.charAt(i++));
		enc3 = Base64._keyStr.indexOf(input.charAt(i++));
		enc4 = Base64._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;

},

// private 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;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
	var string = "";
	var i = 0;
	var c = c1 = 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;
}
}

//function to display tooltip/info based on section/etc
function displayTooltip(id, toolTipName, message){
	if (! isDefined(toolTips[toolTipName])){
		return;
	}
	if ($("div.toolTip").length==0){
		$("body").append("<div class=toolTip></div>");
	}
	var toolTip = toolTips[toolTipName];
	if ( isDefined(message) && message.length > 0 ) {
		$("div.toolTip").html(message);
	} else {
		$("div.toolTip").html(toolTip.message);
	}
	var offset = $(toolTip.objectType + "[name='" + id + "']").offset();
	$("div.toolTip").css({
		top: toolTip.top >= 0 ? toolTip.top : (offset.top + toolTip.offsetY),
		left: toolTip.left >= 0 ? toolTip.left : (offset.left + toolTip.offsetX)
	});
	$("div.toolTip").show();
}
function hideTooltip(){
	$("div.toolTip").hide();
}
