//COMMON ROUTINES

function detectJavascript() {
	var jstype="unknown";
	if(document.getElementById) jstype="DOM"; // DOM compliant script - can use document.getElementById 
	else if(document.layers) jstype="layers"; // JavaScript using layers 
	else jstype="MS"; // document.all Microsoft proprietary script 
	return jstype;
	}

function cloneObject(theobject,what) {
	for (i in what) {
	        if (typeof what[i] == 'object') {
			theobject[i] = new cloneObject(what[i]);
        		}
       	 	else theobject[i] = what[i];
    		}
	return theobject;
	}

//--www.howtocreate.co.uk
//This function can be called in two ways; to reference an item in the current document:
//MWJ_findObj( NameOrId )
//
//To reference an item in any other document in a frameset, you can choose how high in the frame structure to start. Remember that if using 'top', someone else may load your page in their frameset, and this will produce an error.
//MWJ_findObj( NameOrId, ReferenceToTopMostFrameToSearch )

function findObject( oName, oFrame, oDoc ) {
	if( !oDoc ) { if( oFrame ) { oDoc = oFrame.document; } else { oDoc = window.document; } }
	if( oDoc[oName] ) { return oDoc[oName]; } if( oDoc.all && oDoc.all[oName] ) { return oDoc.all[oName]; }
	if( oDoc.getElementById && oDoc.getElementById(oName) ) { return oDoc.getElementById(oName); }
	for( var x = 0; x < oDoc.forms.length; x++ ) { if( oDoc.forms[x][oName] ) { return oDoc.forms[x][oName]; } }
	for( var x = 0; x < oDoc.anchors.length; x++ ) { if( oDoc.anchors[x].name == oName ) { return oDoc.anchors[x]; } }
	for( var x = 0; document.layers && x < oDoc.layers.length; x++ ) {
		var theOb = MWJ_findObj( oName, null, oDoc.layers[x].document ); if( theOb ) { return theOb; } }
	if( !oFrame && window[oName] ) { return window[oName]; } if( oFrame && oFrame[oName] ) { return oFrame[oName]; }
	for( var x = 0; oFrame && oFrame.frames && x < oFrame.frames.length; x++ ) {
		var theOb = MWJ_findObj( oName, oFrame.frames[x], oFrame.frames[x].document ); if( theOb ) { return theOb; } }
	return null;
}

     
function getRefToDivNest( divID, oDoc ) {
	if( !oDoc ) { oDoc = document; }
	if( document.layers ) {
		if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
			for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
				y = getRefToDivNest(divID,oDoc.layers[x].document); }
			return y; } }
	if( document.getElementById ) { return document.getElementById(divID); }
	if( document.all ) { return document.all[divID]; }
	return document[divID];
}
function writeDiv(oString,oDiv,oFrame,oBGCol,oWidth,oHeight,oBorder,oRepeat) { 
	if(oRepeat) { oString = unescape(oString); }
	if( !oRepeat && typeof(oWidth) != 'undefined' && typeof(oHeight) != 'undefined'  && typeof(oBorder) != 'undefined' ) {
		oString = '<table border="'+oBorder+'" cellpadding="0" cellspacing="0"><tr><td height="'+
			oHeight+'" width="'+oWidth+'" valign="top">'+oString+'</td></tr></table>'; }
	var oContent = getRefToDivNest(oDiv); //create fake objects if needed
	if( !oContent ) { oContent = new Object(); } if( !window.frames ) { window.frames = new Object(); }
	if( typeof(oContent.innerHTML) != 'undefined' ) { oContent.innerHTML = oString; //DOM
		if( oContent.style ) { oContent.style.backgroundColor = oBGCol; } return; } //& Proprietary DOM
	if( oContent.document == document || !oContent.document ) { if( !window.frames.length ) { window.clearTimeout(winStatTim);
		rotString = '   -------  '+oString.replace(/<!--([^>]|[^-]>|[^-]->)*-->/g,' ').replace(/<[\/!]?[a-z]+\d*(\s+[a-z][a-z\-]*(=[^\s>"']*|="[^"]*"|='[^']*')?)*\s*(\s\/)?>/gi,' ').replace(/[^\S ]+/g,' ').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&nbsp;/g,' ').replace(/&quot;/g,'"').replace(/&amp;/g,'\t').replace(/&#?\w+;/g,' ').replace(/\t/g,'&').replace(/ +/g,' ');
		startrot(rotString.length); return; } //use status bar. Clears HTML ( clears script & CSS if in comments )
		if(!oRepeat) { window.clearTimeout(iframeHasNotLd[oFrame]); } //if they rewrite more than once before the iframe loads, only show the last one
		if(!window.frames[oFrame]) { //the iframe is unavailable until its content has loaded
			iframeHasNotLd[oFrame] = window.setTimeout('writeDiv(\''+oDiv+'\',\''+oFrame+'\',\''+escape(oString)+'\',\''+oBGCol+'\','+oWidth+','+oHeight+','+oBorder+',true)',100); return; }
		oContent = window.frames[oFrame].window; } //use iframe
	oContent.document.open(); //Separate contents syntax
	oContent.document.write('<html><head><title>Dynamic content</title></head><body bgcolor="'+oBGCol+'">'+oString+'</body></html>');
	oContent.document.close();        
}
function startrot(rotNum) {
	if( !rotString.replace(/\s/g,'').replace(/-------/,'') ) { rotString = ''; }
	window.status = rotString.substr(rotNum) + rotString.substr(0,rotNum);
	if( rotNum == rotString.length ) { rotNum = -1; }
	if(rotString) { winStatTim = window.setTimeout('startrot('+(rotNum+1)+')',60); }
}


function showDiv(divID_as_a_string,show_on) {
    //get a reference as above ...
    myReference = getRefToDiv(divID_as_a_string);
    if( !myReference ) {
        window.alert('Nothing works in this browser');
        return false; //don't go any further
        //return anything would work,
        //but I am using false to show failure
    }
    //now we have a reference to it
    if( myReference.style ) { //DOM & proprietary DOM
        if(show_on != 0) myReference.style.visibility = 'visible';
	else myReference.style.visibility = 'hidden';
    } else {
        if( myReference.visibility ) { //Netscape
            if(show_on != 0) myReference.visibility = 'show';
	    else myReference.visibility = 'hide'; 
        } else {
            window.alert('Nothing works in this browser');
            return false; //don't go any further
        }
    }
    return true;
}

//returns true if DIV tag is visible
function divVisible(divID_as_a_string) {
	var is_visible = false;
	//get a reference as above ...
    	myReference = getRefToDiv(divID_as_a_string);
    	if( !myReference ) {
        	window.alert('Nothing works in this browser');
        	return false; //don't go any further
        	//return anything would work,
        	//but I am using false to show failure
    		}
    	//now we have a reference to it
    	if( myReference.style ) { //DOM & proprietary DOM
        	if(myReference.style.visibility == 'visible') is_visible = true;
    	} else {
        if( myReference.visibility ) { //Netscape
            	if(myReference.visibility == 'show') is_visible = true;
        } else {
            	window.alert('Nothing works in this browser');
            	return false; //don't go any further
        	}
    	}
   	return is_visible;
}

function writeStyle(theobject,theproperty,thevalue) {
	if(document.all) theobject.style[theproperty] = thevalue;	//IE
	else if(document.layers) theobject[theproperty] = thevalue; 	//Navigator
	}

function returnQSPairs(searchstr) {
  	FORM_DATA = new Object();
  	separator = ','; // The token used to separate data from multi-select inputs
	query = '' + searchstr;
    	query = query.substring((query.indexOf('?')) + 1);
    // Keep everything after the question mark '?'.
   	if (query.length < 1) { return false; }  // Perhaps we got some bad data?
  	keypairs = new Object();
  	numKP = 1;
    	while (query.indexOf('&') > -1) {
    		keypairs[numKP] = query.substring(0,query.indexOf('&'));
    		query = query.substring((query.indexOf('&')) + 1);
    		numKP++;
   		}
  	keypairs[numKP] = query;
    // Store what's left in the query string as the final keypairs[] data.
  	for (i in keypairs) {
    		keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
          	keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      		while (keyValue.indexOf('+') > -1) {
      			keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
    			}
    		keyValue = unescape(keyValue);
     		if (FORM_DATA[keyName]) {
     	 		FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
    		} else {
      			FORM_DATA[keyName] = keyValue;
    			}
  		}
 	return FORM_DATA;
	}

//--important cookie saving and return add on function
function saveCookie(thecookiename,thevalue) {
	setCookie(thecookiename,thevalue);
	if(thecookiename == "ptstatus") ptstatus_temp = thevalue;
	if(thecookiename == "ptprices") ptprices_temp = thevalue;
	if(thecookiename == "delstatus") delstatus_temp = thevalue;	
	}

function returnCookie(thecookiename) {
	var read_status = readCookie(thecookiename);
	if((read_status == false) || (read_status == "false") || (read_status == null)) {	//if cookie has been deleted
		var thevalue = ptstatus_temp;  					// restore settings
		if(thecookiename == "ptprices") thevalue = ptprices_temp; 	// from appropriate
		if(thecookiename == "delstatus") thevalue = delstatus_temp;	// global temp var 
		saveCookie(thecookiename,thevalue); 
		read_status = readCookie(thecookiename);
		}
	return read_status;
	}

function recallPaperSizes(sname) {
	var sizearray = new Array("A0:841x1189","A1:594x841","A2:420x594","A3:297x420","A4:210x297","A5:148x210","A6:105x148","A7:74x105","13A4:99x210","23A4:198x210","SRA1:640x900","SRA2:450x640","SRA3:320x450","SRA4:225x320","SRA5:160x225","B1:700x1000","B2:500x700","ROY:520x640","DL:110x220","C6:114x162","C5:162x229","C4:229x324","C3:324x458","BCD4UP:55x85","BCD10UP:55x85");
	if(sname.indexOf("x") < 0) sname = getPropertyValue(sname,sizearray);
	thesizes = sname.split("x");
	var intsizes = new Array(parseInt(thesizes[0]),parseInt(thesizes[1]));
	return intsizes;
	}

function getPropertyValue(propertyname,the_array) {
	var the_info = new Array();
	for (var i=0; i<the_array.length; i++) {
		var broken_info = the_array[i].split(":");
		var the_property = broken_info[0];
		var the_value = unescape(broken_info[1]);
		the_info[the_property] = the_value;
		}
	return the_info[propertyname];
	}

function returnBandValue (the_curve,the_qty) {
	band_value = 0;
	if(the_curve.indexOf("-") >= 0) {
		the_pairs = the_curve.split(":");
		for(var p=0, pmax=the_pairs.length; p<pmax; p++) {
			current_pair = the_pairs[p];
			current_split = current_pair.split("-");	
			current_threshold_qty = current_split[0];
			current_value = current_split[1];
			if(the_qty >= current_threshold_qty) band_value = current_value;
			}
		}
	else band_value = parseFloat(the_curve); //allows for curve as single value
	return band_value;
	}

function returnCumulativeArea (the_curve,the_qty) {
	acc_value = 0;
	the_curve+=""; //convert to string
	if(the_curve.indexOf("-") >= 0) {
		prev_threshold_qty = 0;
		the_pairs = the_curve.split(":");
		num_of_pairs = the_pairs.length;
		var p=0;
		var rcondition = 0;
		while(rcondition < 1) {
			
			current_pair = the_pairs[p];
			current_split = current_pair.split("-");	
			current_threshold_qty = current_split[0];
			current_rate = current_split[1];
			//if snap qty specified else no snap supplied
			if(current_split[2]) current_snap_qty = current_split[2];
			else current_snap_qty = 1;
			if(current_threshold_qty == 0) acc_qty = 1;  //fixed 
			else if(the_qty <= current_threshold_qty) {
				acc_qty = the_qty - prev_threshold_qty;
				rcondition++;
				}
			else acc_qty = current_threshold_qty - prev_threshold_qty;
			acc_value += parseInt((acc_qty/current_snap_qty)+0.99) * current_rate;
			//alert("the_qty: "+the_qty+"acc_value: "+acc_value+"\nacc_qty: "+acc_qty+"\ncurrent_threshold_qty"+current_threshold_qty+"\ncurrent_snap_qty:"+current_snap_qty+"\nprev_threshold_qty:"+prev_threshold_qty);
			prev_threshold_qty = current_threshold_qty;
			p++;
			if(p >= num_of_pairs && rcondition==0) { acc_value=false; rcondition++; }
			}
		}
	else acc_value = parseInt(the_curve)*the_qty;
	return acc_value;
	}


//====================
//== TAX & CURRENCY ==
//====================

//Returns VAT amount - Rounding up
function returnVAT(the_value,the_taxcode) {
	return to2dp((the_value * taxArray[the_taxcode])+0.0001);
	}

//Calc nett function
function returnNettVAT(the_gross_value) {
	return to2dp((the_gross_value / 1.175));
	}

function returnGross(thevalue,thetaxcode) {
	thevalue = returnXRate(thevalue);
	thevalue = thevalue + returnVAT(thevalue,thetaxcode);
	return alterError(thevalue);
	}

function returnNet(thenetvalue) { //used by pt_price
	var thenewvalue = returnXRate(thenetvalue);
	return alterError(thenewvalue);
	}

function returnXRate(value) {	
	var currency = returnStatus("CUR");
	xrate = value / exchArray[currency];
	return xrate;	
	}

function returnXDesc(currency) {	
	return currArray[currency];	
	}
//============================
//== Pricing functions ==
//====== (c) Print Team ======
	
	
	//puts comma separator to integer value
	function toQty(the_value) {
	if(the_value > 999) {
		the_value+="";
		var val_len = the_value.length; 
		the_value = the_value.substring(0,val_len-3)+","+the_value.substring(val_len-3,val_len);
		}
	return the_value;
	} 	
	
	function toDisplay (the_value) {
		if(isNaN(the_value)) the_value = parseFloat(the_value);
		return the_value.toFixed(2);  //returns 2dp as a string 
		}		

	//-- rounds value to 2 d.p. keepinf as a float value
	function to2dp (the_value) {
		return parseFloat(toDisplay(the_value));
		}	

	//-- global Total handler -- used by pt_price only
	function applyPriceMode(totalvalue,codes)
	{
		//- If 'p' is present rounds up to integer
		if(codes.indexOf('p1') >= 0) newtotal = parseInt(totalvalue+0.99);
		else if(codes.indexOf('p2') >= 0) newtotal = alterFloat(totalvalue);  //-- puts total to 2 decimal places format
		else newtotal = alterFloat(totalvalue);
		return newtotal;
	}

	function applyTaxMode(totalvalue,showtax) {
		if(showtax != 0) newtotal = alterError(totalvalue * (1+taxArray[showtax]));
		return newtotal;
		}

	//rounds up values. Gives result as string
	function alterError(value) {
		value = parseFloat(value);
		if (value<=0.99) {
			newPounds = '0';
		} else {
			newPounds = parseInt(value);
		}
		newPence = (value+.0008 - newPounds)* 100;
		intPence = parseInt(newPence);
		rounddigit = parseInt((newPence - intPence)*10);
		if (rounddigit >= 5) newPence = intPence + 1;
		else newPence = intPence;

		if (newPence > 99) {	newPence = 0;
					newPounds++;
					}

		if (eval(newPence) <= 9) newPence='0'+newPence;
		newString = newPounds + '.' + newPence;
		return newString;
	}

	//gives result as Float
	function alterFloat(value) {
		var newval = alterError(value); // converts to 2 d.p. string
		return parseFloat(newval);
	}


//================================
//== Cookie Read/Write Routines ==
//================================

// general cookie setting function.
function setCookie(cookie_name,cookie_string)
{
var the_cookie = escape(cookie_string);
document.cookie = cookie_name+"="+the_cookie; //set cookie
}

// checks for a cookie on the machine before locating the particular cookie.
function readCookie(cookie_name)
{
	if (document.cookie == '')
		return false;
	else return unescape(getCookie(cookie_name));
}

function getCookie(name)
{
	// Declare variables
	var firstChar, lastChar;

	// get the entire cookie string. i.e. may contain several cookies
	var theBigCookie = document.cookie;

	// Grab just this cookie from theBigCookie string.
	// Find the start of 'name'.
	firstChar = theBigCookie.indexOf(name);

	// If you found it,
	if(firstChar != -1)
		{

		// Skip 'name' and '='.
		firstChar += name.length + 1;

		// Find the end of the value string (i.e. the next ';').
		lastChar = theBigCookie.indexOf(';', firstChar);

		if (lastChar == -1) lastChar = theBigCookie.length;

		// Return the value.
		return theBigCookie.substring(firstChar, lastChar);

	} else {
		// If there was no cookie, return false.
		return false;
		}
}


// general cookie return function.
function recallCookie(cookiename)
	{
		var the_info = new Array();
		var readinfo = readCookie(cookiename);

		if (readinfo != false) {
			var separated_values = readinfo.split("#");

			for (loop = 0; loop < separated_values.length; loop++)
				{
				var property_value = separated_values[loop];
				var broken_info = property_value.split(":");
				var the_property = broken_info[0];
				var the_value = unescape(broken_info[1]);
				the_info[the_property] = the_value;
				}
		}
		return the_info;
	}

function sndStatus(the_msg) {
	window.status = the_msg+"";	
	}
