var loadImg;
//preload loader img
if (document.images) {
    loadImg = new Image();
    loadImg.src = "/images/site/loader.gif";
}
function setLoadingImg() {
	document.getElementById('preview').setAttribute('src', loadImg.src);
	document.getElementById('preview').setAttribute('style', "padding: 62px 0 0 62px");
}
function unsetLoadingImg() {
	document.getElementById('preview').removeAttribute('style');
}
function encodeMyHtml(str) {
//from: http://www.yuki-onna.co.uk/html/encode.html
	var encodedHtml = escape(str);
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	encodedHtml = encodedHtml.replace(/\+/g,"%2B");
	//encodedHtml = encodedHtml.replace(/+/g,"%20");
	return encodedHtml;
}
function decodeMyHtml(str) {
	var encodedHtml = unescape(str);
	encodedHtml = encodedHtml.replace(/\+/g," ");
	encodedHtml = encodedHtml.replace(/%2F/g,"\\");
	encodedHtml = encodedHtml.replace(/%3F/g,"?");
	encodedHtml = encodedHtml.replace(/%3D/g,"=");
	encodedHtml = encodedHtml.replace(/%26/g,"&");
	encodedHtml = encodedHtml.replace(/%40/g,"@");
	encodedHtml = encodedHtml.replace(/%2B/g,"+");
	return encodedHtml;
}
var timeint = 500;
var timeout;
function reloadimg(event) {
	//alert(event.keyCode + " " + event.charCode);
	//skip left and right arrow keys
	if (event.keyCode != 37 && event.keyCode != 39) {
		clearTimeout(timeout);
		timeout = setTimeout('newimg()', timeint);
	}
}
// Updates the image
function newimg() {
	//get current image
	var img = document.getElementById('preview'),
		productType = img.src.match(/&?product=(hoodie|tshirt|vneck)/),
		//get text from input field and set product type
		txt = document.getElementById('txt').value;
	//display loading img
	setLoadingImg();
	//set eventHandler for when new image is loaded
	img.onload = function() { unsetLoadingImg(); this.onload=null; };
	productType = (productType==null) ? "" : productType[0];
	//update image
	img.setAttribute('src', "backend/makeimage.php?str=" + encodeMyHtml(txt) + productType);
	img.setAttribute('alt', "I Heart "  + encodeMyHtml(txt) + " Top");
	//Ali?
	if ((T = document.getElementById('google_notif'))) {
		document.getElementById('google_notif').style.display = "none";
	}
	document.getElementById('instructions').style.display = "block";
	//update links and hash in URL
	document.getElementById('linkto').value = 'http://www.ihearttops.com/i-heart/' + encodeMyHtml(txt).replace(/ /g,"+");
	document.getElementById('purchase').href = "http://www.ihearttops.com/actions/add_tobasket.php?str=" + encodeMyHtml(txt).replace(/ /g,"+") + productType;
	document.location = '#' + encodeMyHtml(txt).replace(/ /g,"+");
}
// Removes all children from an element
function removeAllChildren(elem) {
	if (elem && elem.hasChildNodes()) {
		while (elem.childNodes.length >= 1) {
			elem.removeChild(elem.firstChild);
		}
	}
}
// Updates picture to reflect any anchor links
function checkURL() {
	var url = String(document.location);
	if (url.indexOf('#') > 0) {
		var preview = document.getElementById('preview'),
			msg = url.substr(url.indexOf('#')+1),
			productType = preview.src.match(/&?product=(hoodie|tshirt|vneck)/);	
		setLoadingImg();
		preview.onload = function() { unsetLoadingImg();  this.onload=null; };
		//document.getElementById('preview').setAttribute('src', loadImg.src);
		productType = (productType==null) ? "": productType[0];
		document.getElementById('input').getElementsByTagName('input')[0].value = decodeMyHtml(msg);
		document.getElementById('preview').setAttribute('src', "backend/makeimage.php?str=" + msg + productType);
		document.getElementById('linkto').value = 'http://www.ihearttops.com/i-heart/' + encodeMyHtml(msg).replace(/ /g,"+");
		//document.getElementById('input').getElementsByTagName('a')[0].href = "#" + msg;
		document.getElementById('purchase').href = "http://www.ihearttops.com/actions/add_tobasket.php?str=" + msg + productType;
	}
}
// Updates postage
function updatePostage() {
	var country = document.getElementById('loc');
	country = country.options[country.selectedIndex].value;
	var nextday = document.getElementById('nextday').checked.toString();
	document.location = 'basket.php?postage=' + country + '&nextday=' + nextday;
}
// Updates product sizes
function updateSize(size, index) {
	document.location = 'basket.php?changesize=' + size + '&index=' + index;
}

function twoDigits(p) {
	p = p.toString();
	var index = p.indexOf(".");
	if (p.substr(index) == ".5") {
		return p + "0";
	} else if (index < 0) {
		return p + ".00";
	} else {
		return p;
	}	
}

function SelectAll(id){
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

function changeProduct(elem) {
	//get current img and relevant attributes
	var preview = document.getElementById('preview'),
		previewLink = preview.src.replace(/&?product=(hoodie|tshirt|vneck)/, "");
	//set loading img and event handler to remove styling when new image is ready
	setLoadingImg();
	preview.onload = function() { unsetLoadingImg();  this.onload=null; };
	//variables for changing price and buynow link
	var newImg = elem.src,
		currentProduct = document.getElementById('pic').style.backgroundImage,
		itemPrice = document.getElementById('itemprice'),
		purchaseBtn = document.getElementById('purchase'),
		purchaseLink = purchaseBtn.href.replace(/&?product=(hoodie|tshirt|vneck)/, ""),
		// filter URLs by last / to last _
		newType = newImg.substring(newImg.lastIndexOf('/')+1, newImg.lastIndexOf('_')),
		currentType = currentProduct.substring(currentProduct.lastIndexOf('/')+1, currentProduct.lastIndexOf('_'));
	//change this image that has just been clicked on
	elem.src = newImg.replace(newType, currentType);
	switch (currentType) {
		case 'vneck': elem.title="Woman's fitted T-Shirt"; break;
		case 'tshirt': elem.title="T-shirt"; break;
		case 'hoodie': elem.title="Hoodie"; break;
	}
	//update buynow link and preview image - important to keep & in single char quotes
	switch (newType) {
		case 'hoodie':
			if (itemPrice !== null) itemPrice.innerHTML = "19.00";
			purchaseBtn.setAttribute('href', purchaseLink+"&product=hoodie");
			preview.setAttribute('src', previewLink+"&product=hoodie");
			break;
		case 'tshirt':
			if (itemPrice !== null) itemPrice.innerHTML = "15.00";
			purchaseBtn.setAttribute('href',purchaseLink+"&product=tshirt");
			preview.setAttribute('src', previewLink+"&product=tshirt");
			break;
		case 'vneck':
			if (itemPrice !== null) itemPrice.innerHTML = "15.00";
			purchaseBtn.setAttribute('href',purchaseLink+"&product=vneck");
			preview.setAttribute('src', previewLink+"&product=vneck");
			break;
	}
	//swap main product image around
	document.getElementById('pic').style.backgroundImage = currentProduct.replace(currentType, newType);
	return false;
}

