/**
 * This document has been written for Michael Abakhan Ltd t/a Abakhan-Online.
 * @author Lewis MacKenzie, teclan, http://www.teclan.com
 * @date   17/11/08
 */

/**
 * 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);
}

/**
 * Replaces the main product image with that specified in the argument.
 */
function swapThumb(source) {
  var mainimg = $('main-img');
  if (mainimg) {
    mainimg.src = source;  
  }
  var enlarge = $('enlarge-main');
  if (enlarge) {
    enlarge.href = source;  
  }
}

/**
 * Sets up the email a friend link and opens default email client.
 */
function emailAFriend(productName) {
  var script = "I thought you might be interested in " + productName + ".\n\nYou can view it at the following URL\n\n" + window.location;
  var subject = encodeURI(productName + " from Abakhan");
  window.location.href = 'mailto:?subject=' + subject + '&body=' + encodeURI(script);
}

/**
 * Formats the displayed product price on the basis of the quantity and value entered.
 */
function formatPrice(quantity, value) {
  if (quantity == "") {
    return;  
  }
  if (isNaN(quantity)) {
    window.alert("Please enter an integer value.");
	return;
  }
  var pf = $('priceformat');
  if (pf) {
	var val = parseInt(quantity) * value * 1.15;
	val = Math.round(val)/100;
    pf.innerHTML = '£' + val;
  }
}

/**
 * Toggles the mini cart display in the shopping cart summary.
 */
function showMiniCart() {
  var mc = $('minicart');
  var links = $('cartlinks');
  if (mc && links) {
    if (mc.style.display == 'none') {
	  if (!mc.innerHTML || mc.innerHTML == "") {
	    mc.innerHTML = getMiniCart();
	    mc.innerHTML += "<div align='center'>" + links.innerHTML + "</div>";
	  }
	  links.style.display = 'none';
	  changeOpac(0, "minicart");
	  mc.style.display = 'block';
	  doOpacity("minicart", 0, 100, 800);
	}
	else {
	  mc.style.display = 'none';
	  links.style.display = 'block'
	}
  }
}

/**
 * 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 + ")";
}

/**
 * Sets the sample product reference cookie then bounces to the sample product page.
 */
function requestSample(sampleRef) {
  setCookie("sampleRef", sampleRef, false);
  window.location = "Request_a_Sample.html";
}

/**
 * Checks the email addresses added in the checkout invoice field.
 */
function checkInvoiceEmail() {
  var e1 = $('email1');
  var e2 = $('email2');
  if (e1 && e2) {
	//first check that both fields are supplied
	if (e1.value.trim() == '') {
      window.alert("Please enter your email address and then repeat it in the next field.");
	  e1.focus();
	  return false;
    }
	if (e2.value.trim() == '') {
	  window.alert("Please repeat your email address.");
	  e2.focus();
	  return false;
    }
	
	//check email address is actually valid
	if (!e1.value.trim().isValidEmailAddress()) {
	  window.alert("The email address you have supplied is invalid - it must match 'name@domain.com'.");
	  e1.focus();
	  e1.select();
	  return false;
	}
	
	//now check that both match
    if (e1.value.trim() != e2.value.trim()) {
	  window.alert("The email addresses you supplied do not match.");
	  e2.focus();
	  e2.select();
	  return false;
	}
	
	return true;
  }
}

/**
 * Searches for empty links with the 'rel' attribute and sets them up as 
 * mailto anchors.
 */
function checkELinks() {
  var links = document.getElementsByTagName("A");
  for (var i = 0; i < links.length; i++) {
	var rel = links[i].getAttribute("rel");
    if (rel && links[i].innerHTML == '') {
	  rel += "@abakhan-fabrics.co.uk";
	  links[i].href = "mailto:" + rel;
	  links[i].innerHTML = rel;
	}
  }
}

if (window.attachEvent) { 
  window.attachEvent("onload", checkELinks); 
} 
else {  
  window.addEventListener("load", checkELinks, false); 
}


/***********************************************************************
*
* getMiniCart		-	fetches cart content summary
*
* Returns:		-	HTML string for summary display
*
* Graham Bradley 2007
* Comments & bug reports to web@gbradley.co.uk
*
* To make editing the output HTML easier, output code has been split into
* nine 'template' strings.
*
*	tableOpen	-	the opening table code
*	itemLine	-	repeated for each item in the cart
*	shippingLine	-	for displaying shipping charges (if any)
*	vatLine		-	for displaying VAT on items & shipping (if any)
*	discountLine	-	for displaying discount total (if any)
*	surchargeLine	-	for displaying surcharge total (if any)
*	totalLine	-	for displaying the cart total
*	tableClose	-	the closing table code
*	emptyLine	-	displayed when cart is empty
*
* Within these templates, you can use variables to insert values into
* the summary, similar to variables in Actinic:
*
*	VAR:QUANTITY	-	The quantity of item in cart
*	VAR:TITLE	-	Abbreviated name of item
*	VAR:LINK	-	URL of item via the cgi-bin
*	VAR:PRICE	-	Formatted price of item
*	VAR:SHIPPING	-	Total of shipping applied
*	VAR:VAT		-	Total VAT on cart items & shipping
*	VAR:DISCOUNT	-	Total of discounts applied
*	VAR:SURCHARGE	-	Total of surcharges applied
*	VAR:TOTAL	-	Grand total
*
* Variables can only be used in the templates in which they are found.	
*
************************************************************************/

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;
}