// JSON

if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapeable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapeable.lastIndex=0;return escapeable.test(string)?'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
return'\\u'+('0000'+
(+(a.charCodeAt(0))).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value,rep);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
return{stringify:function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});},parse:function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+
(+(a.charCodeAt(0))).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');}};}();}

// Bernhard van Woerden: qcode.co.uk


// Set Globals
var today = new Date();
var ie4 = (document.all)? true:false;

// Check for old order if help cookie not set
checkOldOrder();
// If this is a new order add a catalogue;
if ( getCookie('order_key') == '' ) {	
  setProduct('TLCAT',1,1);
}
// Check if customer_key set in url
if ( urlGet(document.location.href,'customer_key') != null ) {
	var customer_key = urlGet(document.location.href,'customer_key');
	setCookie('customer_key',customer_key,30);
}
// Tracking
checkReferrer();
tradeDoubler();

function getCookie(name) {
  var pairs = document.cookie.split("; ");
  for (var i=0; i < pairs.length; i++) {
    pair = pairs[i].split("="); 
    if (pair[0] == name || pair[0] == escape(name) ) { 
      return unescape(pair[1]); 
    } 
  }
  return null; // if no match return null
}

function setCookie(name, value, days) {
  var newCookie = new String();
  var deliminator = new String("; ");
  var expiry = new Date(today.getTime() + days * 24 * 60 * 60 * 1000); // plus days
  newCookie = escape(name) + "=" + escape(value) + deliminator + "path=/";
  if (days) {
    newCookie += deliminator + "expires=" + expiry.toGMTString();
  }
  document.cookie = newCookie;
  if (getCookie(name)==value) {
    return true;
  } else {
    return false;
  }
}

function deleteCookie(name) {
	setCookie(name,null,-1); // Set cookie expiry yesterday
	if (getCookie(name)) {
		return false;
	} else {
		return true;
	}
}

function getProduct(name) {
	var name_values = new Array();
	var product_cookie = new String();
	product_cookie = getCookie('products');
	if (product_cookie) {
		name_values = product_cookie.split("%");//split on first delimiter
	}
	for (var i=0; i < name_values.length; i++) {
      		pair = name_values[i].split("~"); // break into name and value
      		if (pair[0] == name){ // if name matches
		     	return pair[1]; // return value
		}    		
	}
	return null; // if no match return null
}

function resetProduct(name,qty) {
	var products = new Array();
	var quantities = new Array();
	var product_cookie = getCookie('products');
	var name_values = product_cookie.split("%");//split on first delimiter
	for (var i=0; i < name_values.length; i++) {
      		pair = name_values[i].split("~"); // break into name and value
			products[i]=pair[0]; //
			if (pair[0] ==name) {
				quantities[i]=qty;
			} else {
				quantities[i]=pair[1];
			} 
	}    		
	
	for (i=0;i<products.length;i++) {
		name_values[i] = products[i] + "~" + quantities[i];
	}
	product_cookie = name_values.join("%");
	return setCookie('products',product_cookie,30);				
}

function deleteProduct(name) {
	var counter=0;
	var pair;
	var products = new Array();
	var quantities = new Array();
	var new_name_values = new Array();
	var product_cookie = getCookie('products');
	var name_values = product_cookie.split("%");//split on first delimiter
	for (var i=0; i < name_values.length; i++) {
      		pair = name_values[i].split("~"); // break into name and value
			if (pair[0]!=name) {
				products[counter]=pair[0];// push-but this is JS1.1
				quantities[counter]=pair[1];
				counter++;
			} 
	}    		
	
	for (i=0;i<products.length;i++) {
		new_name_values[i] = products[i] + "~" + quantities[i];
	}
	product_cookie = new_name_values.join("%");
	if (product_cookie) {
		return setCookie('products',product_cookie,30);
	} else {
		return deleteCookie('products');
	}
}

function setProduct(name,qty) {
  var bol; 
  if (getProduct(name)) { //another qty is already set for this product
    bol=resetProduct(name,qty);
  } else if (getCookie('products')) { // other products exist
    var product_cookie = getCookie('products') + "%" + name + "~" + qty;
    bol = setCookie('products',product_cookie,30);
  } else {
    bol = setCookie('products',name + "~" + qty,30);// first product to be set
  }
  return bol;
}

function countProducts() {
  var myString = '';
  if (getCookie('products')) {
    myString = getCookie('products');
  }
  var myArray = new Array();
  myArray = myString.split("~");
  if (myArray) {
    // Exclude TLCAT
    if ( getProduct('TLCAT') ) {
      return myArray.length - 2;
    } else {
      return myArray.length -1;
    }
  } else {
    return 0;
  }
}

function enter_addtoorder(productID,Qty,selling_unit,e) {
  if (!e) {
    e = window.event; 
  }
  if (e && e.keyCode == 13) { // return key pressed
    addtoorder(productID,Qty,selling_unit);
    return false;
  }
}

function leapto(form) {
  var myindex=form.dest.selectedIndex;
  var mylink = form.dest.options[myindex].value;
  if (mylink != '') {
    window.location=mylink;
  }
  form.dest.selectedIndex=0;
}

function jumpto(oSelect) {
  var myindex=oSelect.selectedIndex;
  var mylink=oSelect.options[myindex].getAttribute('value');
  if (mylink!=null && mylink != '') {
    window.location=mylink;
  }
}

function checkOrder() { // Checks product cookie for items already ordered
  // Fill in items already on order
  for (var j=0; j< document.forms.length;j++) {
    var myform = document.forms[j];
    for (var i=0; i< myform.elements.length; i++) {
      var myfield = myform.elements[i];
      if (myfield.type == 'text') {
	var webcode = myfield.name;
	if (getProduct(webcode)) {
	  myfield.value = getProduct(webcode); // Fill in the qty ordered
	  show_tick(webcode);	
	}
      }
    }
  }
  // reset dropdowns
  var selects = document.body.getElementsByTagName('SELECT');
  for(var i=0;i<selects.length;i++) {
    var oSelect = selects[i];
    setOptionValue(oSelect,'');
  }
}

function checkOldOrder() {
  //if saved order exists and we have not shown help
  var message;
  var count = countProducts();
  if (count == 1) {
    message = "You have 1 product in your basket saved from your last visit.";
  } else {
    message = "You have " + count + " products in your basket saved from your last visit.";
  }
  if (count > 0 && ! getCookie('help') ) {
    if (setCookie('help','done')) {
      alert(message);
    } else {
      return false;
    }
  }
}

function check_missing(form) {
  if (getCookie('help')){
    return true;
  }
  if ( window.event ) {
    if (!form.contains(event.toElement)) {
      // mouse leave
      for (var i=0; i< form.elements.length; i++) {
	var myfield = form.elements[i];
	if (myfield.type == 'text') {
	  var webcode = myfield.name;
	  var qty = myfield.value;
	  if (qty != "" && ! isNaN(qty) && ! getProduct(webcode)) {
	    var message ="After entering a quantity, please click the OK button or press Return to add the product to your order.";
	    message +="\nIf you do not do so the product will not be added to your order.";
	    message += "\n\nFor your convienience, this message will not be shown again.";
	    alert(message);
	    setCookie('help','done');
	  }
	}
      }
    }
  }
}

function addtoorder(productID,Qty,selling_unit) {
  if (Qty == null || Qty == "" || Qty == 0) {
    if (getProduct(productID)) {
      deleteProduct(productID);
      untick(productID);
      checkOrder();
      return true;
    } else {
      alert("Please enter a quantity for this product ! ");
      return false;
    }
  }
  if ((Qty % selling_unit) == 0 ) {
    if ( setProduct(productID,Qty) ) {
      show_tick(productID);
      checkOrder();
      if ( ! getCookie('help') ) {
		alert('You can always check your order by clicking "View Your Order" at the top of the page.');
		setCookie('help','done');
      }
      return true;
    } else {
	  // Failed to add product
	  alert('I tried to write a cookie in order to store your shopping basket but your browser refused.\nYou may need to change your browser settings to allow this site to write cookies.\nIf you need further help please contact sales@tlc-direct.co.uk stating which browser and version you are using.');
      return false;
    }
  } else {
    alert ("Sorry, this product is only sold in multiples of " + selling_unit);
    return false;
  }
  alert ("Invalid Call, Please Contact the Systems Administrator");
}

function updateOrder(productID,Qty,selling_unit) {
  // legacy API
  return addtoorder(productID,Qty,selling_unit);
}

function show_tick (productID) {
  for ( var i = 0;i<document.images.length;i++) {
    var img = document.images[i];
    if ( img.name == productID || img.name == 'tick' + productID ) {
      if ( typeof(tick) !="undefined" ) {
	img.src = tick.src;
      }
    }
  }
}
function untick (productID) {
  for ( var i = 0;i<document.images.length;i++) {
    var img = document.images[i];
    if ( img.name == productID || img.name == 'tick' + productID  ) {
      if ( typeof(blank)!="undefined" ) {
	img.src = blank.src;
      }
    }
  }
}

function popUpLink(url,width,height) {
  winOptions = "WIDTH=" + width + ",HEIGHT=" + height + ",scrollbars,resizable";
  newWindow = window.open(url,"new_window",winOptions);
  newWindow.focus();
  return false;
}

function checkReferrer() {
  var source = trackingSource();
  var media  = trackingMedia();
  var kw = trackingKeyword();
  var domain = referralDomain();
  var term   = referralSearchTerms();

  if ( source || domain ) {
      var now = new Date();
      var datetime = now.getUTCFullYear() + '-' + parseInt(now.getUTCMonth()+1) + '-' + now.getUTCDate() + ' ' + now.getUTCHours() + ':' +  now.getUTCMinutes() + ':' + now.getUTCSeconds();
      if (getCookie("tracking_history")) {	
	  var tracking_history = JSON.parse(getCookie("tracking_history"));
      } else {
	  var tracking_history = new Array();
      }
      var track = new Object();
      track.datetime=datetime;
      if (source) {track.source=source}
      if (kw) {track.kw=kw}
      if (media) {track.media=media}
      if (domain) {track.domain=domain}
      if (term) {track.term=term}

      while ( tracking_history.length>10 || JSON.stringify(tracking_history).length>2000 ) {
	  tracking_history.shift();
      }
      tracking_history.push(track);
      setCookie("tracking_history",JSON.stringify(tracking_history),365);
  }
}

function check_empty(textfield) {
  var productID = textfield.name;
  var qty = textfield.value;
  if (qty=="" || qty=='null' || qty==0) {
    deleteProduct(productID);
    untick(productID);
  }
}

function getOptionValue(dropdown) {
  var myindex=dropdown.selectedIndex;
  return dropdown.options[myindex].value;
}

function setOptionValue(dropdown,value) {
  for(var i=0;i<dropdown.options.length;i++) {
    if ( dropdown.options[i].value == value ) {
      dropdown.selectedIndex = i;
      break;
    }
  }
}
 
function getRadioValue(radio_name,form) {
  for(var i=0;i<form.elements.length;i++) {
    var elmt = form.elements[i];
    if (elmt.name == radio_name && elmt.checked) {
      return elmt.value;
    }
  }
  return null;
}

function setRadioValue(radio_name,form,value) {
  for(var i=0;i<form.elements.length;i++) {
    var elmt = form.elements[i];
    if (elmt.name == radio_name && elmt.value == value ) {
      elmt.checked = true;
      return true;
    }
  }
  return false;
}

function urlSet(url,name,value) {
	var list = new Array();
	var a = new Array();
	var b = new Array();
	var c = new Array();
	var re = /([^\?]+)\??(.*)/;
	re.exec(url);
	var path = RegExp.$1;
	var queryString = RegExp.$2;
	if ( queryString != "" ) {
		var a = queryString.split('&');
	}
	for (var i=0;i<a.length;i++) {
		b = a[i].split('=');
		var n = unescape(b[0]);
		var v = unescape(b[1]);
		c[n]=v;
	}
	c[name] = value;
	for (key in c) {
		list.push(escape(key) + "=" + escape(c[key]));
	}
	
	url = path + "?" + list.join("&");
	return url;
}

function urlGet(url,name) {
  var a = new Array();
  var b = new Array();
  var c = new Array();
  var re = /([^\?]+)\??(.*)/;
  re.exec(url);
  var path = RegExp.$1;
  var queryString = RegExp.$2;
  if ( queryString != "" ) {
    var a = queryString.split('&');
  }
  for (var i=0;i<a.length;i++) {
    b = a[i].split('=');
    var n = unescape(b[0]);
    if ( n == name ) {
      var v = unescape(b[1]);
      v = v.replace(/\+/g," ");
      return v;
    }
  }
  return null;
}

function trackingKeyword() {
    var url = document.location.href;
    var varnames = ['kw','utm_term','OVRAW'];
    for (i=0;i<varnames.length;i++) {
	if ( urlGet(url,varnames[i]) != null ) {
	    return urlGet(url,varnames[i]);
	}
    }
    return null;
}

function trackingSource() {
    var url = document.location.href;
    var varnames = ['utm_source','source'];
    for (i=0;i<varnames.length;i++) {
	if ( urlGet(url,varnames[i]) != null ) {
	    return urlGet(url,varnames[i]);
	}
    }
    return null;
}
       
function trackingMedia() {
  var url =  document.referrer;
  var varnames = ['utm_media','media'];
  for (i=0;i<varnames.length;i++) {
    if ( urlGet(url,varnames[i]) != null ) {
      return urlGet(url,varnames[i]);
    }
  }
  return null;
}

function referralSearchTerms() {
    var url =  document.referrer;
    var varnames = ['q','query','qry','qt','ask','search','keyword','word','p',];
    for (i=0;i<varnames.length;i++) {
	if ( urlGet(url,varnames[i]) != null ) {
	    return urlGet(url,varnames[i]);
	}
    }
    return null;
}

function referralDomain() {
  var url =  document.referrer;
  var re = /([^:]+):\/\/([^:\/]+)(:(\d+))?([^\?]*)([\?](.*))?/;
  if (re.exec(url)) {
    var domain = RegExp.$2;
    if ( domain != document.location.hostname ) {
      return domain;
    }
  }
  return null;
}

function tradeDoubler() {
   var url = document.location.href;
   if ( urlGet(url,'tduid') != null ) {
     setCookie('TRADEDOUBLER',urlGet(url,'tduid'),365);
   }
}
