// JavaScript Document
var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}
function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}
function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)){
    dispmessage = String.fromCharCode(nbsp);    
  }else{
    dispmessage = message;
  }

  var elem = document.getElementById(fld);
  //dispmessage.blink();
  elem.firstChild.nodeValue = dispmessage;
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}
function swap_towel(colour_index,img_name,color_menuID,path){
	var colour_menu=document.getElementById(color_menuID);
	document[img_name].width="150";
	document[img_name].length="150";
	document[img_name].border="1px";
	document[img_name].src =path+colour_menu.options[colour_index].title+'.jpg';
}
function swap_colour(img_name,color_menuID,mat){
	colour=document.getElementById(color_menuID).value;
	if(matches=colour.match(/^(.+)\s+(-out of stock-|#oos#)/i)){
		colour=matches[1];
	}
	[img_name].border="1px";
	document[img_name].src ='../../images/pix/table_linen/Colour_Scans/'+mat+'_'+colour+'.jpg';
}
function swap_colour2(colour_index,img_name,color_menuID,mat,path){
	var colour_menu=document.getElementById(color_menuID);
	document[img_name].width="150";
	document[img_name].length="150";
	document[img_name].border="1px";
	document[img_name].src =path+'/'+mat+'_'+colour_menu.options[colour_index].value+'.jpg';
}
function standinaIMG_swapper(img_name,standina){
	document[img_name].border="1px";
	document[img_name].src ='pix/Table%20linen/Standina/'+standina+'.jpg';
}
function quant_discount(quant,hprice_id,dprice_id,oprice,sprice){
	hprice=document.getElementById(hprice_id);
	dprice=document.getElementById(dprice_id);
	
	if(quant>=50){
		hprice.value=sprice;
		dprice.innerHTML='&pound;'+sprice;
	}else{
		hprice.value=oprice;
		dprice.innerHTML='&pound;'+oprice;
	}
}
function login(showhide){
  if(showhide == "show"){
	  document.getElementById('popupbox').style.visibility="visible"; /* If the function is called with the variable 'show', show the login box */
  }else if(showhide == "hide"){
	  document.getElementById('popupbox').style.visibility="hidden"; /* If the function is called with the variable 'hide', hide the login box */
  }
}

function do_u_understand(){
	if(confirm('Your logo will be printed:\n\n+ As is including any background.\n+As a rectangular patch, not just the lettering.\n+Logo background will not match fabric colour.\n\nPlease read the description of our printing method.\n\nPress OK to continue or Cancel to stay on this page.')){
		return true;
	}else{
		return false;
	}
}
function hireChevron(X,colourRate,deposit){
		document.getElementsByName(X+'thresholdprice1')[0].value=(document.getElementsByName(X+'thresholdpriceorig1')[0].value*colourRate*(deposit+1)).toFixed(2);
		document.getElementsByName(X+'thresholdprice2')[0].value=(document.getElementsByName(X+'thresholdpriceorig2')[0].value*colourRate*(deposit+1)).toFixed(2);
		document.getElementById(X+'depositInfo').value='Hire price &pound;'+(document.getElementsByName(X+'thresholdpriceorig2')[0].value*colourRate).toFixed(2)+' plus '+(deposit*100)+'% refundable deposit &pound;'+(document.getElementsByName(X+'thresholdpriceorig2')[0].value*colourRate*deposit).toFixed(2);
		document.getElementById(X+'pricecol1').innerHTML=(document.getElementsByName(X+'thresholdpriceorig1')[0].value*colourRate).toFixed(2);
		document.getElementById(X+'pricecol2').innerHTML=(document.getElementsByName(X+'thresholdpriceorig2')[0].value*colourRate).toFixed(2);
}
function chevron(X,colourRate){
		document.getElementsByName(X+'thresholdprice1')[0].value=document.getElementsByName(X+'thresholdpriceorig1')[0].value*colourRate;
		document.getElementsByName(X+'thresholdprice2')[0].value=document.getElementsByName(X+'thresholdpriceorig2')[0].value*colourRate;
		document.getElementById(X+'pricecol1').innerHTML=(document.getElementsByName(X+'thresholdpriceorig1')[0].value*colourRate).toFixed(2);
		document.getElementById(X+'pricecol2').innerHTML=(document.getElementsByName(X+'thresholdpriceorig2')[0].value*colourRate).toFixed(2);
}
function macrame_price(length,width,tag,rate){
	price = (length*width*rate).toFixed(2);
	document.getElementById("price_td"+tag).innerHTML=price;
	document.getElementById(tag+"price").value=price;
}
// curvy corners =>  overlock only!
function nobinding(patternID,bindingID,X,rate){
	//var corner_menu=document.getElementById(corner_id);
	var binding_menu=document.getElementById(X+bindingID);
	var pattern=document.getElementById(patternID+X).value;
	binding_menu.options.length=0;
	if(pattern.match(/^pvc clear/i)){
		binding_menu.options[0]=new Option('No Binding','No Binding', false, false);
		binding_menu.options[1]=new Option('Binding','Binding', false, false);
	}else{
		binding_menu.options[0]=new Option('No Binding','No Binding', false, false);
		binding_menu.options[1]=new Option('Binding','Binding', false, false);
	}
	chevron(X,rate);
}
// curvy corners =>  overlock only!
function checkFinish(corner,finish_id,finish_txt,X,shapeFinishTxt,id){
	var finishes = finish_txt.split(",");
	var RoundFinishes = shapeFinishTxt.split(",");
	var finish_menu=document.getElementById(finish_id);
	finish_menu.options.length=0;
	if(corner.match(/^Curvy|Round/i)){
		var count=0;
		for(var i=1;i<RoundFinishes.length;i=i+2){
			finish_menu.options[count]=new Option(RoundFinishes[i],RoundFinishes[i], false, false);
			count++;
		}
	}else{
		var count=0;
		for(var i=0;i<finishes.length;i=i+3){
			finish_menu.options[count]=new Option(finishes[i],finishes[i], false, false);
			count++;
		}
	}
	checkJoin(document.getElementById('color_menuID'+X).value,X,document.getElementById(id+'_defaultWidth').value,'itemname4');
	chevron(X,calCurrentRate(Array(document.getElementById(finish_id).value,id+'_rate_'+document.getElementById('color_menuID'+X).value)));
}
////////////////////////////////////////////////////////////////////////
// THIS FUNCTION WILL FIND THE INDEX OF A VALUE
Array.prototype.findIndex = function(value){
  var ctr = "";
  for (var i=0; i < this.length; i++) {
	// use === to check for Matches. ie., identical (===), ;
	if (this[i] == value) {
	  return i;
	}
  }
  return ctr;
};
// THIS FUNCTION FINDS THE SMALLEST VALUE IN ARRAY
Array.prototype.max = function() {
var max = this[0];
var len = this.length;
for (var i = 1; i < len; i++) if ((this[i]*1) > max) max = this[i]*1;
return max;
}
// THIS FUNCTION FINDS THE HIGHEST VALUE IN ARRAY
Array.prototype.min = function() {
var min = this[0];
var len = this.length;
for (var i = 1; i < len; i++) if ((this[i]*1) < min) min = this[i]*1;
return min;
}
/////////////////////////////////////////////////////////////////////////
function checkJoin(id,X,default_width,itemname){
	id=id.replace(/\s/g, '');
	var size=document.getElementById(X+'popular').value;
	
	var currentFinishWaste = 0; // default finish waste is set to zero
	// check whether finish rates exist e.g. hire pages do not have finish values
	var currentFinish = (document.getElementById(X+"Finish"))?document.getElementById(X+"Finish").value:1;
	
	if(document.getElementById(currentFinish+"Waste")){ // retrieve finish fabric consumption if available
		currentFinishWaste=(document.getElementById(currentFinish+"Waste").value)*2; // multiply by 2 for both finish on both sides
	}
	var colour_width; var hidden_join;
	if(document.getElementById(id)){
		var nums=document.getElementById(id).value.split(";");
		colour_width = (nums.max()*1)-currentFinishWaste; // substract finish waste
	}else{
		colour_width = (default_width*1)-currentFinishWaste; // substract finish waste
	}
	var joinTxt=""; var joinFlag=false;
	if(matches=size.match(/^(\d+)x(\d+)$/i)){
		matches.splice(0,1);
		if(matches.min()>colour_width){
			var num = calcJoin(matches.min(),colour_width);
			var joinWidth = calcJoinWidth(matches.min(),colour_width);
			//if(joinWidth<20){joinWidthTxt=" ("+joinWidth+"cm)";}else{joinWidthTxt="";}
			if(num==1){joinTxt=" Join";}else{joinTxt=" Joins";}
			hidden_join=num+joinTxt; joinFlag=true;
			document.getElementById(X+"join").innerHTML = num+joinTxt;
			document.getElementById(X+"joininfo").style.visibility="visible";
		}else{
			hidden_join=""; joinFlag=false;
			document.getElementById(X+"join").innerHTML = "&nbsp;";
			document.getElementById(X+"joininfo").style.visibility="hidden";
		}
	}
	if(matches=size.match(/^(\d+)$/i)){
		matches.splice(0,1);
		if(matches.min()>colour_width){
			var num = calcJoin(matches.min(),colour_width);
			var joinWidth = calcJoinWidth(matches.min(),colour_width);
			//if(joinWidth<20){joinWidthTxt=" ("+joinWidth+"cm)";}else{joinWidthTxt="";}
			if(num==1){joinTxt=" Join";}else{joinTxt=" Joins";}
			hidden_join=num+joinTxt; joinFlag=true;
			document.getElementById(X+"join").innerHTML = num+joinTxt;
			document.getElementById(X+"joininfo").style.visibility="visible";
		}else{
			hidden_join=""; joinFlag=false;
			document.getElementById(X+"join").innerHTML = "&nbsp;";
			document.getElementById(X+"joininfo").style.visibility="hidden";
		}
	}
	document.getElementById(X+itemname).value=hidden_join;
	// IF CALCULATOR AND FABRIC NON-JOINABLE E.G. POLYCOTTON
	if(document.getElementById("isJoinable") && joinFlag){
		if(document.getElementById("isJoinable").value==2){ // non-joinable flag as per product_inf
		  document.getElementById("Basket").disabled=true;
		  document.getElementById("Basket").value="This Product Cannot be Added to Basket";
		  document.getElementById("finishWasteAlert").style.display="table-cell";
		}
	}else if(document.getElementById("Basket")){
		document.getElementById("Basket").disabled=false;
		document.getElementById("Basket").value="Add to Basket";
		(document.getElementById("finishWasteAlert"))?document.getElementById("finishWasteAlert").style.display="none":"";
	}
}
function calCurrentRate(arr){
	var val=1;
	for(var i=0;i<arr.length;i++){
		if(matches=arr[i].match(/^(.+)\s+(-out of stock-|#oos#)/i)){
			arr[i]=matches[1];
		}
		arr[i]=arr[i].replace(/\s/g, '');
		val *= document.getElementById(arr[i]).value;
	}
	return val;
}
function calcJoinWidth(dim,maxi){
	return (dim-(maxi*Math.floor(dim/maxi)));
}
function calcJoin(dim,maxi){
	if((dim%maxi)>0){
		num=Math.floor(dim/maxi);
	}else{
		num=Math.floor(dim/maxi)-1;
	}
	return num;
}

