/**
 * teclan Plugin functionality library.
 *
 * @version 1.0.0
 * @date 21/09/09
 * @author Lewis A MacKenzie
 * @copyright teclan 2009
 */

 
/***************************************************************/
/*********************** Common Functions **********************/
/***************************************************************/
/**
 * Shortcut for document.getElmementById()
 */
var $tb = function(id) {
  return document.getElementById(id);
};

/**
 * Returns all elements of type 'nodeType' with class 'className'.
 */
var $$tb = function(nodeType, className) {
  var ret = new Array();
  var arr = document.getElementsByTagName(nodeType.toUpperCase());
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].className) {
	  if (arr[i].className.split(" ").contains(className)) {
	    ret.push(arr[i]);
	  }
	}
  }
  return ret;
};

Array.prototype.contains = function (element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) {
      return true;
    }
  }
  return false;
};

/**
 * Checks if on the home page.
 */
function isHomePage() {
  var loc = window.location.toString();
  return loc.indexOf("acatalog") == -1;
}

/**
 * Checks for IE
 */
function isIE() {
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}


/***************************************************************/
/***************** Tab Switching Functionality *****************/
/***************************************************************/
function toggleTab(id) {
  if (!id) id = 1;
  var tabtitle = $tb("tab-title-bar");
  if (tabtitle) {
    var links = tabtitle.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
      if (links[i].name && links[i].name != ('tab' + id)) {
        var content = $tb("tabcontent" + (i+1));
        if (content) {
          content.style.display = "none";
	      links[i].className = "";
        }
      }
      else {
        links[i].className = "selected";
      }
    }
    var tbcont = $tb("tabcontent" + id);
    if (tbcont) tbcont.style.display = "block";
  }
}

function initTabs() { toggleTab(1); }
if (window.attachEvent) { window.attachEvent("onload", initTabs); } 
else { window.addEventListener("load", initTabs, false); }

function SwitchTab(index) {
  var titles = $tb('tab-titles');
  if (titles) {
    var titleLinks = titles.getElementsByTagName("A");
    for (var i = 0; i < titleLinks.length; i++) {
	  //set the title class
	  titleLinks[i].className = (i == index ? "sel" : "");
	  titleLinks[i].blur();
	  var tabContent = $tb('Section' + i);
	  if (tabContent) {
	    tabContent.className = (i == index ? "section-tab-content block" : "section-tab-content");
	  }
	}
  }
}


/***************************************************************/
/*************** Collapsible Cart Functionality ****************/
/***************************************************************/
function collapseCart(emptyLine) {
  var cart = $tb('collapsible-cart');
  if (!cart) return;
  
  if (cart.style.display && cart.style.display == "block") {
    cart.style.display = "none";
  }
  else {
    cart.innerHTML = getMiniCart(emptyLine);
	cart.innerHTML += '<div>' + $tb('cart-links').innerHTML + '</div>';
	cart.style.display = "block";
  }
}


/***************************************************************/
/******** Fully selectable section link functionality **********/
/***************************************************************/
function initClickableSections() {
  var sections = $$tb('DIV', 'tec-section');
  for (var i = 0; i < sections.length; i++) {
    stripWhitespace(sections[i]);
	
	sections[i].onmouseover = function() {
	  this.className += " ts-hov";
	};
	sections[i].onmouseout = function() {
	  this.className = this.className.replace(/ ts-hov/, "");
	};
	
	var link = searchForLink(sections[i]);
	if (link != null) {
	  sections[i].setAttribute("rel", link);
	  sections[i].onclick = function() {
	    this.className += " ts-hov";
	    window.location = this.getAttribute("rel");
	  };
	}
  }
}

/**
 * Removes excess whitespace from a node
 */
var notWhitespace = /\S/;
function stripWhitespace(node) {
  for (var i = 0; i < node.childNodes.length; i++) {
    var childNode = node.childNodes[i];
    if ((childNode.nodeType == 3) && (!notWhitespace.test(childNode.nodeValue))) {
      node.removeChild(node.childNodes[i]);
      i--;
    }
  }
}

/**
 * Searches a node for a link element and returns the href value if found.
 */
function searchForLink(node) {
  var links = node.getElementsByTagName('A');
  if (links.length > 0) {
    return links[0].href;
  }
  return null;
}

if (window.attachEvent) { 
  window.attachEvent("onload", initClickableSections); 
} 
else {  
  window.addEventListener("load", initClickableSections, false); 
}


/***************************************************************/
/**************** Image swapping functionality *****************/
/***************************************************************/
function swapImg(newImg) {
  var mimg = $tb('main-img');
  if (mimg) {
    mimg.src = newImg;
  }
}


/***************************************************************/
/************************ Drop Down Menu ***********************/
/***************************************************************/
var timeout	= 500;
var closeTimer = 0;
var menuParent = 0;
var menuItem = 0;

function tcOpen(id) {	
  tcCancelCloseTime();
  tcClose();
  menuParent = $tb('main-link' + id);
  menuItem = $tb('tc' + id);
  if (id == 6) {
    menuItem.style.left = "-15px";
  }
  if (id == 7) {
    menuItem.style.left = "-167px";
  }
  menuItem.style.display = 'block';
}

function tcClose() {
  if (menuItem) menuItem.style.display = 'none';
  if (menuParent) {
    menuParent.className = '';
  }
}

function tcCloseTime() {
  closeTimer = window.setTimeout(tcClose, timeout);
}

function tcCancelCloseTime() {
  if (closeTimer) {
    window.clearTimeout(closeTimer);
	closeTimer = null;
  }
  if (menuParent) {
    menuParent.className = 'sel';
  }
}

document.onclick = tcClose; 



/***************************************************************/
/**************************** Mini Cart ************************/
/***************************************************************/
function getMiniCart(){

var tableOpen="<table width='100%'>";
var itemLine="<tr><td valign='top'>VAR:QUANTITYx </td><td><a href='VAR:LINK'>VAR:TITLE...</a></td><td align='right' valign='top'>VAR:PRICE</td></tr>"
var shippingLine="<tr><td colspan='2'>Shipping</td><td align='right'>VAR:SHIPPING</td></tr>"
var vatLine="<tr><td colspan='2'>VAT</td><td align='right'>VAR:VAT</td></tr>"
var discountLine="<tr><td colspan='2'>Discounts</td><td align='right'>VAR:DISCOUNT</td></tr>"
var surchargeLine="<tr><td colspan='2'>Surcharges</td><td align='right'>VAR:SURCHARGE</td></tr>"
var totalLine="</table><table width='100%'><tr><td><b>Total</b></td><td align='right'><b>VAR:TOTAL</b></td></tr>"
var tableClose="</table>"
var emptyLine="No items in cart.";

var cookie=getCartItem(4);

if (!cookie){
	return emptyLine;
	}
var re=new Array();
var match=new Array();
var total=0;
var str;
re[1]=/cur=([^&]*)&!/g;
re[2]=/&!(.*)/g;
re[3]=/ss=(.*)cur=/i;
re[4]=/tx=(.*)sh=/i;
re[5]=/sh=(.*)ss=/i;
for (i=1;i<re.length;i++){
	match[i]=re[i].exec(cookie);
	match[i]=match[i][1];
	}
lines=match[2].split("&!");
store=new Array();
re[0]=/^(\d*)x/;
re[1]=/x([^>]*)>/;
re[2]=/>([^>]*)>/;
re[3]=/>([^>]*)$/;
str=tableOpen;
for (i=0;i<lines.length;i++){
	for (j=0;j<re.length-2;j++){
		detail=lines[i].match(re[j]);
		store[j]=detail[1];
		}
	str+=itemLine.replace("VAR:QUANTITY",store[0]).replace("VAR:LINK",match[3]+"?PRODREF="+store[1]+"&NOLOGIN=1").replace("VAR:TITLE",store[2]).replace("VAR:PRICE",match[1]+((store[3]*1).toFixed(2)));
	total+=(store[3]*1);
	}
if (match[5] > 0){
	str+=shippingLine.replace("VAR:SHIPPING",match[1]+(match[5]/100).toFixed(2));
	total=total+=(match[5]/100);
	}
if (match[4] > 0){
	str+=vatLine.replace("VAR:VAT",match[1]+(match[4]/100).toFixed(2));
	total=total+=(match[4]/100);
	}
gTotal=getCartItem(1);
var r=/&#(\d*);/gi;
var m=new Array();
var f=new Array();
while((m = r.exec(gTotal))!=null){
	f[f.length]=m[1];
	}
for (i=0;i<f.length;i++){
	gTotal=gTotal.replace("&#"+f[i]+";","");
	}
total=total.toFixed(2);
gTotal=(gTotal/100).toFixed(2);
if (total>gTotal){
	str=str+=discountLine.replace("VAR:DISCOUNT","-"+match[1]+(total-gTotal).toFixed(2));
	}
else if (total<gTotal){
	str=str+=surchargeLine.replace("VAR:SURCHARGE",match[1]+(gTotal-total).toFixed(2));
	}
str+=totalLine.replace("VAR:TOTAL",match[1]+(gTotal));
str+=tableClose;
return str;
}


/***************************************************************/
/**************************** Height Fix ***********************/
/***************************************************************/
function heightFix() {
  var toFix = $$tb('DIV', 'fh');
  var theHighest = 0;
  for (var i = 0; i < toFix.length; i++) {
    if (toFix[i].offsetHeight > theHighest) theHighest = toFix[i].offsetHeight;
  }
  for (var i = 0; i < toFix.length; i++) {
    toFix[i].style.height = theHighest + "px";
  }
}

if (window.attachEvent) { 
  window.attachEvent("onload", heightFix); 
} 
else {  
  window.addEventListener("load", heightFix, false); 
}

function searchResultsHeightFix() {
  var toFix = $$tb('DIV', 'teclan-search-result');
  var theHighest = 0;
  for (var i = 0; i < toFix.length; i++) {
    if (toFix[i].offsetHeight > theHighest) theHighest = toFix[i].offsetHeight;
  }
  for (var i = 0; i < toFix.length; i++) {
    toFix[i].style.height = theHighest + "px";
  }
}

/**
 * This document has been written for teclan's 'Free product add to cart' and minicart functionality.
 * teclan cannot support any modifications made to this file.
 *
 * @author Lewis MacKenzie, teclan, http://www.teclan.com/
 * @date   05/01/09
 */

//The HTTP request object
var request = null;

//attach the cart check function to the load event
if (window.attachEvent) { 
  window.attachEvent("onload", checkCart); 
} 
else {  
  window.addEventListener("load", checkCart, false); 
}

/**
 * Shortcut function.
 */
var $$ = function(id) {
  return document.getElementById(id);
};

/**
 * Adds a trim method to the String class. This will remove
 * leading and trailing white space.
 */
String.prototype.trim = function() { 
  return this.replace(/^\s+|\s+$/, '');
};

/**
 * Adds a method to the String class to check whether or not an instance 
 * is a valid email address.
 */
String.prototype.isValidEmailAddress = function() {
  return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(this);
}

/**
 * Checks if there are items in the shopping cart and shows the mini cart 
 * if necessary. If checkFree is true, it checks if the free product needs
 * to be added to or removed from cart.
 */
function checkCart() { 
  if (getCartItem(3) > 0 || window.location.href.toString().indexOf('file:') != -1) {
    var miniLink = $$('cartsummary');
	if (miniLink) {
	  miniLink.onclick = showCartSummary;
	  miniLink.style.cursor = 'pointer';
	}
	
	if (checkFreeProduct) {
	  getSessionData(1);
	}
  }
}

/**
 * Toggles the mini cart display in the shopping cart summary.
 */
function showCartSummary() {
  var mc = $$('minicart');
  var links = $$('cartlinks');
  if (mc && links) {
    if (mc.style.display == 'none') {
	  if (!mc.innerHTML || mc.innerHTML == "") {
	    $$('cartsummary').src = 'loading.gif';
		getSessionData(0);
	  }
	  else {
	    changeOpac(0, "minicart");
	    mc.style.display = 'block';
	    doOpacity("minicart", 0, 100, 800);
	  }
	}
	else {
	  mc.style.display = 'none';
	}
  }
}

function getSessionData(callType) {
  //Mozilla
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
  }
  //Microsoft
  else if (window.ActiveXObject) {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    if (!request) request = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (request) {
    request.onreadystatechange = callType == 0 ? handleMiniResponse : handleFreeProductResponse;
    try {
      request.open("POST", sessionScript, true);
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      request.send(callType == 0 ? "action=getSummary" : "action=checkFreeProduct");
    }
    catch (e) {
      alert(e);
    }
  }
  else {
    window.alert("Your browser does not support AJAX!");
  }
}

function handleMiniResponse() {
  if (request.readyState == 4) {
    if (request.status == 200) {
	  var mc = $$('minicart');
	  var links = $$('cartlinks');
	  mc.innerHTML = request.responseText;
	  mc.innerHTML += "<div align='center'>" + links.innerHTML + "</div>";
  	  changeOpac(0, "minicart");
      mc.style.display = 'block';
      doOpacity("minicart", 0, 100, 800);
	  $$('cartsummary').src = 'cartbg.gif';
    }
    else {
      window.alert("XMLHttpRequest failed!");
    }
  }
}

function handleFreeProductResponse() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      if (request.responseText.indexOf('OK') == -1 && request.responseText.indexOf('http://') != -1) {
	    window.location = request.responseText;
	  }
	}
  }
}

/**
 * Fades an element in or out.
 */
function doOpacity(id, opacStart, opacEnd, millisec) {
  var speed = Math.round(millisec / 100);
  var timer = 0;

  if (opacStart > opacEnd) {
    for(var i = opacStart; i >= opacEnd; i--) {
      setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
	  timer++;
    }
  } 
  else if (opacStart < opacEnd) {
    for (var i = opacStart; i <= opacEnd; i++) {
      setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
	  timer++;
    }
  }
}

/**
 * Cross-browser functionality to change the opacity of a given
 * element to the specified value.
 */
function changeOpac(opacity, id) {
  var object = $$(id).style; 
  object.opacity = (opacity / 100);
  object.MozOpacity = (opacity / 100);
  object.KhtmlOpacity = (opacity / 100);
  object.filter = "alpha(opacity=" + opacity + ")";
}

function checkImgUpload()
{
   var msg = "";
   if (!document.imgupload.ordernum.value || document.imgupload.ordernum.value == "") msg += "\nNo order number supplied.";
   if (!document.imgupload.imgfile.value || document.imgupload.imgfile.value == "") msg += "\nNo image file supplied.";
   if (msg != "")
   {
     window.alert("The following errors occurred:" + msg);
     return false;
   } 
   return true;
}

function checkMultiImgUpload()
{
   var msg = "";
   if (!document.multiupload.name.value || document.multiupload.name.value == "") msg += "\nNo name supplied.";
   if (!document.multiupload.email.value || document.multiupload.email.value == "") msg += "\nNo email address supplied.";
   if (!document.multiupload.phone.value || document.multiupload.phone.value == "") msg += "\nNo phone number supplied.";
   for (var i = 1; i <= document.multiupload.boxcount.value; i++)
   {
	  if (!document.getElementById("uploadbox" + i).value || document.getElementById("uploadbox" + i).value == "")
	  {
		 msg += "\nMissing image in upload box " + i + ".";  
	  }
   }
   if (msg != "")
   {
     window.alert("The following errors occurred:" + msg);
     return false;
   }
   document.getElementById('uploadmsg').style.display = "block";
   return true;
}

function sortPrompts(index) {
  var moi = document.getElementById('moi' + index);
  var oois = document.getElementsByName('oi' + index);
  var s = "";
  for (var i = 0; i < oois.length; i++) {
	if (oois[i].value != "") {
      s += oois[i].value + "; ";
	}
  }
  moi.value = s;
}