/*
	Objects to support client side javascript
	active scripting moved from javaScript.jsp
	jbaun 1/13/2005
	
	Note that some methods have very short names because
	this code is included in downloads.
*/
    var newPDFWindow = "";
    function MM_openBrWindowPDF(theURL) { //v2.0
      //check to see if window already exits
      if (!newPDFWindow || newPDFWindow.closed) {
      	newPDFWindow = window.open(theURL, "", "menubar,scrollbars,resizable,alwaysRaised=yes")
      	newPDFWindow.focus()
      }
      else {
      	//window already exits so bring it forward
      	newPDFWindow.focus()
      }
    }
    var newBigWindow = ""
    function MM_openBrWindow(theURL, newHEIGHT, newWIDTH) {
      //check to see if window already exits
      if (!newBigWindow || newBigWindow.closed) {
      	if (!newHEIGHT)
      	{
      		newHEIGHT=480;
      	}
      	if (!newWIDTH)
      	{
      		newWIDTH=640;
      	}
      	newBigWindow = window.open(theURL, "", "HEIGHT=" + newHEIGHT + ",WIDTH=" +newWIDTH +",screenX=0,screenY=100,left=0,top=100,menubar,toolbar,scrollbars,location,resizable")
      	newBigWindow.focus()
      }
      else {
      	//window already exits so bring it forward
      	newBigWindow.focus()
      }
    }
	function openPleaseWaitWindow()
	{ }
	function closePleaseWaitWindow()
	{ }
	
    function populateDDLB(field, section, stateValue) {
	  field.value=stateValue;
	  section.setState(stateValue);
    }
	
	function selectDDLBMember(member, section){
		member.onChange();
	}

	function doesElementExist(elementId){
		return document.all[elementId] != null;
	}


	function MM_swapImgRestore() { 
	  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}

	function pviiClassNew(obj, new_style) {
	    obj.className = new_style;
	}
	
	function MM_findObj(n, d) {
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && document.getElementById) x=document.getElementById(n); return x;
	}
	
	function MM_swapImage() { 
	  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}

	var numDeleted = 0;
	function deleteLine(section, lineID, entryLineSize){
		var i,thisForm;
		var thisForm = document.forms[Page.currentPage.formName];
		if (++numDeleted == entryLineSize){
			document.all["entryLinesForm.isLastItemDeleted"].value = 'true';
			thisForm.submit();	
			return true;			
		}
		else setState(section, "notrash");
		thisForm.elements["entryLinesForm.entryLine[" + lineID + "].deleted"].value="true";
	}	

	var numLineItemsDeleted = 0;
	function deleteLineItem(adjustWeight, adjustPrice, lineID, numLineItems){
		var thisForm = document.forms[Page.currentPage.formName];
		thisForm.elements["ULF.UL(" +lineID+ ").deleteButton"].value = "clicked";
		if (++numLineItemsDeleted == numLineItems){
			document.getElementById('ULF.isLastItemDeleted').value = 'true';
			thisForm.submit();	
			return true;
		}
		else {
			setState(page.getSection("dl"+lineID+".trash"), "notrash")
			setState(page.getSection("dlshipping"+lineID+".trash"), "notrash")
			setState(page.getSection("dlpartvar"+lineID+".trash"), "notrash")
			setState(page.getSection("dldisclaimer"+lineID+".trash"), "notrash")
			errorSection = document.getElementById("dlerrors" + lineID);
			if ( errorSection ) {
				errorSection.style.display = 'none';
			}
		}
		if (adjustWeight) {recalcWeight(thisForm, lineID)};
		if (adjustPrice) {recalcPrice(thisForm, lineID)};
	}	
	
	var units ="";
	var weightFormat = 0;
	function recalcWeight(thisForm, lineID) {
		var cartCode = document.getElementById('lineCartCode'+lineID).value;
		var topWeight = 'cartWeightTop';
		var botWeight = 'cartWeightBottom';
		var topUnits = 'cartUnitsTop';
		var botUnits = 'cartUnitsBottom';
		if(splitcarts == "true" && cartCode != null && trim(cartCode) !=""){
			topWeight = topWeight + cartCode;
			botWeight = botWeight + cartCode;
			topUnits = topUnits + cartCode;
			botUnits = botUnits + cartCode;
		}
		var cartWeight = getNumeric(document.getElementById(topWeight).innerHTML);
		var lineWeight = 0;
		if (units == "") {  
			// only need to separate unit of measure after first item deleted
			units = getCharacters(document.getElementById(topWeight).innerHTML);
			document.getElementById(topUnits).innerHTML = units; 
			document.getElementById(botUnits).innerHTML = units; 
		}
		try { 
			// if no lineWeight, then it will get partWeight * quantity
			lineWeight = document.getElementById('lineWeight'+lineID).innerHTML; 
		} catch (e) { 
			var quantity = parseFloat(thisForm.elements["ULF.UL(" +lineID+ ").quantity"].value); 
			var partWeight = parseFloat(document.getElementById('partWeight'+lineID).innerHTML); 
			lineWeight = partWeight * quantity;
		} 
		if (weightFormat == 0) weightFormat = getDecimalFormat(cartWeight);
		var adjustedWeight = addCommas((parseFloat(cartWeight) - lineWeight).toFixed(weightFormat));
		document.getElementById(topWeight).innerHTML = adjustedWeight;
		document.getElementById(botWeight).innerHTML = adjustedWeight;
	}		

	var currency = "";
	var priceFormat = 0;
	function recalcPrice(thisForm, lineID) {
		var cartCode = document.getElementById('lineCartCode'+lineID).value;
		var topCur = 'cartCurrencyTop';
		var botCur = 'cartCurrencyBottom';
		var topPrice = 'cartPriceTop';
		var botPrice = 'cartPriceBottom';
		if(splitcarts == "true" && cartCode != null && trim(cartCode) !=""){
			topCur = topCur + cartCode;
			botCur = botCur + cartCode;
			topPrice = topPrice + cartCode;
			botPrice = botPrice + cartCode;
		}
		if (currency == "") {
			// only need to separate currency display after first item deleted
			currency = getCharacters(document.getElementById(topPrice).innerHTML);
			if (currency != 'N/A' && currency != 'N/D' && currency != 'S/O') {
			document.getElementById(topCur).innerHTML = currency; 
			document.getElementById(botCur).innerHTML = currency; 
			}
		}
		var cartPrice = getNumeric(document.getElementById(topPrice).innerHTML); 
		if (priceFormat == 0) priceFormat = getDecimalFormat(cartPrice);
		if (cartPrice != 0) { 
			var linePrice = getNumeric(document.getElementById('extPrice'+lineID).innerHTML);
			var adjustedPrice = addCommas((cartPrice - linePrice).toFixed(priceFormat));
			document.getElementById(topPrice).innerHTML = adjustedPrice;
			document.getElementById(botPrice).innerHTML = adjustedPrice;
		}
	}
	var numSREntryDeleted = 0;
	function deleteSREntryLine(section, lineID, srLineSize){
		var i,thisForm;
		var thisForm = document.forms[Page.currentPage.formName];
		thisForm.elements["scheduledReleasesForm.scheduledRelease[" + lineID + "].deleted"].value="true";
		if (++numSREntryDeleted == srLineSize){	
			document.all["scheduledReleasesForm.isLastItemDeleted"].value = 'true';
			thisForm.submit();			
		}
		else setState(section, "notrash");
	}
	
	function deleteSR(fieldName, section){ 
		section.setState("notrash");
		var thisForm = document.forms[Page.currentPage.formName];	
		thisForm.elements[fieldName].value='true';
	}

	function setState(thisSection, state){
		if (thisSection != null) { 
			thisSection.setState(state); 
		} 
	}

/*------------------------------------------------------------------*/
/*
    ColinxFetchQueue provides a way to execute functions sequentially
    and without having them step on one another if their actions can fire
    async and modify the same elements on the page
*/
	function ColinxFetchQueue() { };
    ColinxFetchQueue.queue = { };
    /*
        adds a function to the queue for the given key

        removeIntermediate - if this is true, all functions waiting in the queue between
        the 1st one and the one being added will be removed; otherwise, func is just
        added to the end of the list

        func must accept one argument which is a callback to let the queue know when the function is done

        Example Usage:
        ColinxFetchQueue.addToQueue("key",true,function(done_callback) {
            alert('hello world!');
            done_callback();
        });
    */
    ColinxFetchQueue.addToQueue = function(/*string*/key,/*boolean*/removeIntermediate,/*function*/func) {
        if(ColinxFetchQueue.queue[key] == null) {
            ColinxFetchQueue.queue[key] = [];
        }
        var q = ColinxFetchQueue.queue[key];

        var fetch = {
          "running": false,
          "go": function() {
              this.running = true;
              func(this.done);
          },
          "done": function() {
                q.splice(0,1);
                if(q.length > 0) {
                    q[0].go();
                }
          }
        };
        q.push(fetch);
        if(removeIntermediate) {
            q.splice(1,q.length - 2);
        }
        var firstFetcher = q[0];
        if (!firstFetcher.running) {
            firstFetcher.go();
        }
    };
/*------------------------------------------------------------------*/
    /**
     *   Note: this function can only work if dojo is
     *           also included on the page
     **/
     function countryChanged(fetchurl,selected_country,form) {
         ColinxFetchQueue.addToQueue(form + ".fetchState",true,function(done_callback) {
         	 var dateForUrl = new Date();
             var stateSection = dojo.byId(form + '.stateSection');
             var selectedState = dojo.byId(form + '.state').value;
             stateSection.innerHTML = '<img src="/images/ajax-loader.gif">';
             var params = {
                 country: selected_country,
                 formName: form,
                 x: dateForUrl.getTime()
             };

             /* fetch states for country */
             dojo.io.bind({
                 url:fetchurl,
                 content: params,
                 load:function(type, html){
                     stateSection.innerHTML = html;
                     dojo.byId(form + '.state').value = selectedState;

                     var scriptFrag = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
                     var scripts = html.match(scriptFrag,'img');
                     for(var i=0;i < scripts.length;i++) {
                         eval((scripts[i].match(scriptFrag,'im')|| ['', ''])[1]);
                     }
                     doCountryChange();
                     done_callback();
                 },
                 error:function(type, error) {
                     alert('error fetching states data: ' + error.toJSONString());
                 },
                 mimetype: "text/plain"
             });
         });
 	}
 	
     /**
      *   Note: this function can only work if dojo is
      *           also included on the page
      **/
      function countryChangedWithStateEdit(fetchurl,selected_country,form,state) {
          ColinxFetchQueue.addToQueue(form + ".fetchState",true,function(done_callback) {
              var stateSection = dojo.byId(form + '.stateSection');
              var selectedState = dojo.byId(form + '.state').value;
              var dateForUrl = new Date();
              stateSection.innerHTML = '<img src="/images/ajax-loader.gif">';
              var params = {
                  country: selected_country,
                  formName: form,
                  x: dateForUrl.getTime()
              };

              /* fetch states for country */
              dojo.io.bind({
                  url:fetchurl,
                  content: params,
                  load:function(type, html){
                      stateSection.innerHTML = html;
                      var scriptFrag = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
                      var scripts = html.match(scriptFrag,'img');
                      for(var i=0;i < scripts.length;i++) {
                          eval((scripts[i].match(scriptFrag,'im')|| ['', ''])[1]);
                      }
                      doCountryChange();
                      setStatePostCountryChange(state);
                      done_callback();
                  },
                  error:function(type, error) {
                      alert('error fetching states data: ' + error.toJSONString());
                  },
                  mimetype: "text/plain"
              });
          });
  	}
  	
	function toggleDisplay(bool,classNm) {
		var i = 1;
		while (document.getElementById(classNm+i) !=null && 
				document.getElementById(classNm+i) !='undefined'){
			var obj = document.getElementById(classNm+i);
			if (bool == 'false') {
				obj.style.visibility = 'hidden';
			} else {
				obj.style.visibility = 'visible';
			}
			i++;
		}
	}
	
	function handleEnterSubmit(e) {
		if (e.keyCode == 13 && document.getElementById("submittedViaEnter")) {
			document.getElementById("submittedViaEnter").value = "true";
		}
	}
	
	function getCharacters (input) {
		var filteredValues = "1234567890., ";     // numbers are stripped out
		var returnString = "";
		for (var i = 0; i < input.length; i++) { 
			var c = input.charAt(i);
			if (filteredValues.indexOf(c) == -1) returnString += c;
		} 
		return returnString;
	}
	
	function getNumeric (input) {
		var allowedValues = "1234567890."; 
		var i;
		var returnString = "";
		for (i = 0; i < input.length; i++) { 
			var c = input.charAt(i);
			if (allowedValues.indexOf(c) != -1) returnString += c;
		} 
		return returnString;
	}
	
	function addCommas(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}	
	
	function getDecimalFormat (input) {
		var decimal = input.indexOf("."); 
		var nbrDecimals = 0;
		if (decimal > -1) {
			var start = decimal+1;
			var afterDecimal = input.substring(start,input.length);
			nbrDecimals = getNumeric(afterDecimal).length;
		} 
		return nbrDecimals;
	}	
	
	function trim(str){
		return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	}
	
	function changeStyle(elementName,strClassName) {
		try {
			document.getElementById(elementName).className = strClassName;
			} catch(e) {
			}
	}
	
	function fetchDiagnosticResult(diagUrl) {
		diagnosticsRecursionCounter++;
		var dateForUrl = new Date();
		var params = {
			x: dateForUrl.getTime()
		};
		dojo.io.bind({
			url:diagUrl,
			content: params,
			load:function(type, json){
				bigJsonObj = eval('(' + json + ')');
				for(var bla in bigJsonObj){
					if(bla != 'toJSONString' && bla != 'diagnostic0' && 'diagn' == bla.substring(0,5)){
						var subd = bigJsonObj[bla];
						if(subd.executed == true){
							if(subd.success){
								var el = dojo.byId(subd.id);
								if ( el ) {
									dojo.byId(el).className = 'success';
								}
							}
							else{
								var el = dojo.byId(subd.id);
								if ( el ) {
									el.className = 'failure';
								}
								var elFailure = dojo.byId(subd.id + 'Error');
								if ( elFailure ) {
									elFailure.style.display="block";
								}
							}
						}
					}
				}
				if(bigJsonObj.diagnostic0.executed == false  && diagnosticsRecursionCounter < 20000){
					setTimeout("fetchDiagnosticResult('"+diagUrl+"')", 500);
				}	
			},				
			error:function(type, error) {
				alert('error fetching diagnostic data: ' + error.toJSONString());
			},
			mimetype: "text/plain"	
		});	
	}
	
	var clientStatus = new Array();
	function processClientSideDiagnostics(){
		var i = 1;
		var current = "diag" + i;
		var browser=navigator.appName;
		while (dojo.byId(current)){

			if(browser=="Microsoft Internet Explorer"){
				dojo.byId(current).className = "clientSideBlank";
				dojo.byId('infoWrap' + current).className = 'infoHidden';
				dojo.byId(current + 'Frame').innerHTML = "<iframe id=\""+current+"ifrm\" height=\"200\" ></iframe>"; //style=\"position:absolute; top:-999px\"
				clientStatus[current]='complete';
				var theURL = dojo.byId(current).getElementsByTagName('h3')[0].innerHTML;
				var url = "https://" + theURL;
				dojo.byId(current+"ifrm").src = url;
			}
			else{
				clientStatus[current] = 'running';
				dojo.byId(current).className = "running";
				dojo.byId(current + 'Frame').innerHTML = "<iframe id=\""+current+"ifrm\" style=\"position:absolute; top:-999px\"  onload=\" return setSuccess(\'" + current + "\');\"></iframe>"; //
				var theURL = dojo.byId(current).getElementsByTagName('h3')[0].innerHTML;
				var url = "https://" + theURL;
				
				checkURLforConnection(url, current);
			}
			i++;
			current = "diag" + i;
		}
	};
	
	function setSuccess(location) {
		var browser=navigator.appName;
		dojo.byId(location).className =  "success";
		clientStatus[location] = 'success';
	};
	
	function checkURLforConnection(dURL, location) {
		dojo.byId(location+"ifrm").src = dURL;
		setTimeout("setLocationFail('" + location + "')", 15000);
	};
	
	function setLocationFail(location){
		if(clientStatus[location] != 'running'){
		}
		else{
			var browser=navigator.appName;
			if(browser=="Microsoft Internet Explorer"){
				dojo.byId(location).className = "success";
			}else{
				dojo.byId(location).className = "failure";
				dojo.byId('diag0Error').style.display = 'block';
			}

		}
	};
	
	function countSelectedPandA(id) {
		if(dojo.byId(id).checked){
			if(currentIndex >= limit){
				showProductListPopup();
				dojo.byId(id).checked = false;
			}else{
				currentIndex = currentIndex + 1;
			}
		}else{
			currentIndex = currentIndex - 1;
		}
	}
	
	function resetIndex(num) {
		alert("num:" + num);
		currentIndex = 0;
		return true;
	}
	
	function showProductListPopup() {
		dojo.event.topic.publish(ColinxEvents.dialog.openDialog,{widgetId:'productListPopup'});
	}	
	
