/**
* This file allows you to over ride core events used by the shop.js
* and add any extra functions for the item detail page
*
* Standard methods to over ride are:
*
* onStockUpdated
* onBeforeAddItem
* onBeforeAmendItem
*
* Turboshop (c) Digivate 2007 - pAd Nov.
**/

var swatchChanged = false; // true if colour option has been selected
var swatchDelayTimeMS = 900; // 900ms before swatch is change onmouseover - just incase user does a onmouseout
var cancelSwatchHover = false;// true if user has done a onmouseout before swatchDelayTimeMS has passed


function haveAccessoriesToAdd() {
	var ret = true;

	try {
			var form = tsGetElementById('rangeaccessories');
			if (form!=null)
			{
				ret = false
				for(var i=0; i<form.elements.length; i++) {
					if (form.elements[i].name && form.elements[i].name.substr(0, 4)=='ass_') {
						if (form.elements[i].value != '0' && form.elements[i].value != '') {
							ret = true;
							break;
						}
					}
				}
			}
	}
	catch(e) {
	}

	return ret;

}

// main item methods used when accessories  add to cart is selected
function addMainAndAccessories(prcd, sku, qty) {
	if (tsGetElementById('hasAccessories1')==null) {
		if (qty==0) {
			alert("Please select a quantity and add or amend button");
			return;
		}

		if (qty>0) {
			tsGetElementById('mainitem_prcd').value =  prcd;
			tsGetElementById('mainitem_sku').value =  sku;
			tsGetElementById('mainitem_qty').value =  qty;
			if (tsGetElementById('linkeditem')!=null) {
				if (tsGetElementById('linkeditem').checked) {
					if (tsGetElementById('linkeditem').value.substr(0,6)=='LEAPRO')
					{
						if (numberOfLeatherProtectionItems+(parseInt(qty)*parseInt(numberOfSeats)) > 10)
						{
							alert('Leather protection can only be ordered for a maximum of 10 seating units, '+
							'your order has exceeded this limit.  If you wish to proceed with this order please '+
							'telephone our sales team on 01495 244226 who will help you with your order.');
					  		return;
						}
					}
					tsGetElementById('mainitem_linkeditem').value =  tsGetElementById('linkeditem').value;
				}
			}
		}

		tsGetElementById('rangeaccessories').submit();

	}
	else
	{
		var _haveAccessoriesToAdd = haveAccessoriesToAdd();
		if (tsGetElementById('noaccessories')!=null) {
			if (qty==0) {
				alert("Please select a quantity and continue to add your item to the basket");
				return;
			}
		}
		else if (!_haveAccessoriesToAdd && qty==0) {
			alert("Please select a quantity and continue to add your item to the basket");
			return;
		}
		else if (!_haveAccessoriesToAdd && qty>0)
		{
			if (!confirm('Would you like to buy this item without accessories?')) {
				alert('Please choose your accessories and try again');
				return;
			}
		} else if (_haveAccessoriesToAdd && qty==0) {
			if (!confirm('Would you like to buy accessories without a sofa?')) {
				alert('Please select a quantity for the sofa');
				return;
			}
		}

		if (qty>0) {
			tsGetElementById('mainitem_prcd').value =  prcd;
			tsGetElementById('mainitem_sku').value =  sku;
			tsGetElementById('mainitem_qty').value =  qty;
			if (tsGetElementById('linkeditem')!=null) {
				if (tsGetElementById('linkeditem').checked) {
					if (tsGetElementById('linkeditem').value.substr(0,6)=='LEAPRO')
					{
						if (numberOfLeatherProtectionItems+(parseInt(qty)*parseInt(numberOfSeats)) > 10)
						{
							alert('Leather protection can only be ordered for a maximum of 10 seating units, '+
							'your order has exceeded this limit.  If you wish to proceed with this order please '+
							'telephone our sales team on 01495 244226 who will help you with your order.');
							return;
						}
					}
					tsGetElementById('mainitem_linkeditem').value =  tsGetElementById('linkeditem').value;
				}
			}
		}

		tsGetElementById('rangeaccessories').submit();
	}
}


function amendMainAndAccessories(prcd, sku, qty){
	tsGetElementById('actfield').value =  'amenditems';

	if (qty>0)
	{
		tsGetElementById('mainitem_prcd').value =  prcd;
		tsGetElementById('mainitem_sku').value =  sku;
		tsGetElementById('mainitem_qty').value =  qty;
	}


	if (tsGetElementById('linkeditem')!=null)
	{
		if (tsGetElementById('linkeditem').checked)
		{
			if (tsGetElementById('linkeditem').value.substr(0,6)=='LEAPRO')
			{
				if (numberOfLeatherProtectionItems+(parseInt(qty)*parseInt(numberOfSeats)) > 10)
				{
					alert('Leather protection can only be ordered for a maximum of 10 seating units, '+
							'your order has exceeded this limit.  If you wish to proceed with this order please '+
							'telephone our sales team on 01495 244226 who will help you with your order.');
					return;
				}
			}
			tsGetElementById('mainitem_linkeditem').value =  tsGetElementById('linkeditem').value;
		}
	}

	tsGetElementById('rangeaccessories').submit();
}

function addAccessoriesAndMain(itemId){

	if (!haveAccessoriesToAdd()) {
		if (!confirm('Would you like to buy this item without accessories?')) {
			alert('Please choose your accessories and try again');
			return;
		}
	}

	var sku = '';
	var prcd = '';
	var itemSKU = getSelectedItemSkus(itemId);
	var qty = tsGetQty(itemId);

	if (g_ProductsList !=null && g_ProductsList['_'+itemId+itemSKU]!=null)
	{
		prcd = g_ProductsList['_'+itemId+itemSKU]['Product Code'];
		sku = g_ProductsList['_'+itemId+itemSKU]['SKU'];
	}

	tsGetElementById('mainitem_prcd').value =  prcd;
	tsGetElementById('mainitem_sku').value =  sku;
	tsGetElementById('mainitem_qty').value =  qty;

	if (tsGetElementById('linkeditem')!=null)
	{
		if (tsGetElementById('linkeditem').checked)
		{
			if (tsGetElementById('linkeditem').value.substr(0,6)=='LEAPRO')
			{
				if (numberOfLeatherProtectionItems+(parseInt(qty)*parseInt(numberOfSeats)) > 10)
				{
					alert('Leather protection can only be ordered for a maximum of 10 seating units, '+
							'your order has exceeded this limit.  If you wish to proceed with this order please '+
							'telephone our sales team on 01495 244226 who will help you with your order.');
			  		return;
				}
			}
			tsGetElementById('mainitem_extraitem').value =  tsGetElementById('linkeditem').value;
		}
	}

	tsGetElementById('rangeaccessories').submit();
}


/**
* Before an item is added to the basket by shop.js additem
* overrides shop.js method
**/
function onBeforeAddItem(prcd, sku, stockMessage, qty) {
	addMainAndAccessories(prcd, sku, qty);
	return false; // stop shop.js from adding this product we do this
}

/**
* Before an item is amended overrides shop.js method
**/
function onBeforeAmendItem(prcd, sku, stockMessage, qty) {
	amendMainAndAccessories(prcd, sku, qty);
	return false
}


/**
* Overrride shop.js method
* allows extra parameters to be sent to basket when b= is called by
* tsAddItem
* @return string
**/
function extraBasketInfo() {
	var ret = '';

	if (tsGetElementById('linkeditem')!=null)
	{
		if (tsGetElementById('linkeditem').checked)
		{
			ret = '&linkeditem='+escape(tsGetElementById('linkeditem').value);
		}
	}

	return ret;
}

/**
* Overrides shop.js method
* Allows you to add extra costs to unit total
**/
function getExtraCost() {
	var ret = 0.00;


	return ret;
}

//
// Change main image and price based on a given swatch (flag)
//
function changeSwatch(flag, itemId, prcd) {

	tsGetElementById('MainImage').src = rootdir+"imagshop/large/"+prcd.toLowerCase()+"_"+flag+".jpg";
	if (tsGetElementById('LargeImage')!=null)
	{
		tsGetElementById('LargeImage').style.background = '#FFF url(' + tsGetElementById('MainImage').src.replace(smallDir,largeDir) + ') 0 0 no-repeat';
		// = tsGetElementById('MainImage').src.replace(smallDir,largeDir); //reset zoom;
	}

	var colourOption = tsGetElementById('options_'+itemId+'_option0');
	if (colourOption!=null)
	{
		for(var i=0; i<colourOption.options.length; i++)
		{
			if (colourOption.options[i].value == '_'+flag.toUpperCase())
			{
				colourOption.selectedIndex = i;
				swatchChanged = true;
				break;
			}
		}
	}
	tsUpdateUnitPriceBox('options_'+itemId+'_option0');
}

var gcsFlag = '';
var gcsItemId = '';
var gcsPrcd = '';

// call changeSwatch after swatchDelayTimeMS of hover on the swatch, mean a user does not change colour by mistake when move mouse
// qiuckly over the swatch to get somewhere else like the top of the page
function changeSwatchDelay(flag, itemId, prcd){
	gcsFlag = flag;
	gcsItemId = itemId;
	gcsPrcd = prcd;
	cancelSwatchHover = false;
	setTimeout('callChangeSwatch()', swatchDelayTimeMS);

}
function callChangeSwatch(){
	if (!cancelSwatchHover) {
		changeSwatch(gcsFlag, gcsItemId, gcsPrcd);
		cancelChangeSwatch(); //stop build up of setTimeouts on callChangeSwatch()
	}
}

function cancelChangeSwatch(){
	cancelSwatchHover = true;
}

//
// set the correct colour picture based on selected colour option
//
function initSwatch() {
	var colourOption = tsGetElementById('options_'+random+'_option0');
	if (colourOption!=null && //document.location.href.indexOf('from=')==-1  &&
		colourOption.selectedIndex > -1)
	{
		//if (colourOption.selectedIndex==-1) colourOption.selectedIndex = 0;
		var flag = colourOption.options[colourOption.selectedIndex].value.toLowerCase();
		changeSwatch(flag.substr(1), random, prcd);
	}

}



/////////////
// Accessories item list  methods
//
function addAccessories() {
	if (haveAccessoriesToAdd())
	{
		tsGetElementById('rangeaccessories').submit();
	}
	else
	{
		alert('No accessories have been choosen. Please enter the quantity of each colour you want and then click add to cart.');
	}

}

function amendAccessories(){
	if (haveAccessoriesToAdd())
	{
		tsGetElementById('actfield').value =  'amenditems';
		tsGetElementById('rangeaccessories').submit();
	}
	else
	{
		alert('No accessories have been choosen. Please enter the quantity of each colour you want and then click add to cart.');
	}
}


/**
* Display info template in alax layer - enlarge image
**/
function customShopShowInfo(itemprcd) {

	var colour = '';
	var colourOption = tsGetElementById('options_'+random+'_option0');
	if ((swatchChanged || document.location.href.indexOf('/colour/')>-1) && colourOption.selectedIndex > -1)
	{
		var colourFlag = colourOption.options[colourOption.selectedIndex].value.toLowerCase();
		colour = '&tsp_colour='+colourFlag.substr(1);
	}
	tsQuery('j=shop&comd=displayproduct&t=iteminfo/large-external&p='+itemprcd+colour, 'enlargeImageArea', '');
	//tsLoadObjectsInHeader('index.php?j=comms&t=fabricrequest_javascript');
	show('enlargeImageArea');
}

///
// AJAX methods, uses ajax.js and scriptaculous libs
////

function showFabricChooser(itemprcd) {
	var colour = '';
	var colourOption = tsGetElementById('options_'+random+'_option0');
	if (colourOption!=null && colourOption.selectedIndex > -1)
	{
		var colourFlag = colourOption.options[colourOption.selectedIndex].value.toLowerCase();
		colour = '&tsp_colour='+colourFlag.substr(1);
	}
	tsQuery('j=comms&t=fabricrequest&tsp_itemprcd='+itemprcd+'&tsp_colour='+colour, 'contentarea', '');
	tsLoadObjectsInHeader('index.php?j=comms&t=fabricrequest_javascript');
	show('contentarea');
	hide('footer');
	hide('form1');
	hide('prodFurtherDetailsWrap');
}

function hideFabricChooser() {
	hide('contentarea');
	show('footer');
	show('form1');
  show('prodFurtherDetailsWrap');
}

function showCallBack() {
	tsQuery('j=comms&t=callback', 'contentarea4', '');
	tsLoadObjectsInHeader('index.php?j=comms&t=callback_javascript');
	show('contentarea4');
	hide('form1');
}

function hideCallBack() {
	hideBlind('contentarea4');
	show('form1');
}

function showPrintDetail(itemprcd, itemxt22_xtr, random) {
	var colour = '';
	var colourOption = tsGetElementById('options_'+random+'_option0');
	if (colourOption!=null && colourOption.selectedIndex > -1)
	{
		var colourFlag = colourOption.options[colourOption.selectedIndex].value.toLowerCase();
		colour = '&tsp_colour='+colourFlag.substr(1);
	}
	else
	{
		colour = '&tsp_colour='+itemxt22_xtr.toLowerCase();
	}

	tsQuery('j=shop&comd=displayproduct&p='+itemprcd+'&t=custom/shop/iteminfo/printproductdetails'+colour, 'contentarea3', '');
	showBlindAll('contentarea3');
}

function hidePrintDetail (div) {
	hide(div);
	show('headerwrap');
	show('footer');
	new Effect.BlindDown(document.getElementById('myCartCol'), {duration: 1});
	show('topNavMenuWrap');
	document.getElementById('prodDetailPageMain').style.display = 'block';
}


function fabicChooserChangeSwatch(prcd,flag) {
	tsGetElementById('sofaFabricMainImage').src = rootdir+"imagshop/fabrics/"+flag+".jpg";
}

function showProtection(protectionName) {
	var fn = protectionName.toLowerCase();
	fn = fn.replace(/ /, '');
	tsQuery('j=custom/shop/iteminfo/'+fn+'.htm', 'contentarea2', '');
	show('contentarea2');
}

function showLeatherProtection() {
	tsQuery('j=custom/shop/iteminfo/leatherprotection.htm', 'contentarea2', '');
	show('contentarea2');
}

function showCartLeatherProtection(code) {
	tsQuery('j=custom/shop/sections/basksum/leatherprotection2.htm&tsp_pointer='+code, 'lpcontentarea'+code, '');
	show('lpcontentarea'+code);
}


function showFamilyImageArea(code) {
	tsQuery('j=shop&comd=displayproduct&t=iteminfo/enlargefamilyimage.htm&p='+code, 'enlargeFamilyImageArea', '');
	show('enlargeFamilyImageArea');
	hide('familyImageDiv');
}


function hideFamilyImageArea() {
	hide('enlargeFamilyImageArea');
	show('familyImageDiv');
}

function mainImageOnError() {
	tsGetElementById('MainImage').src = rootdir+'imagshop/large/noimage.jpg';
}

function mainFabricImageOnError() {
	tsGetElementById('sofaFabricMainImage').src = rootdir+'imagshop/large/noimage.jpg';
}

function doLeatherProtectionLimit(obj, num) {

	if (!obj.checked && numberOfLeatherProtectionItems>0) {
		numberOfLeatherProtectionItems = numberOfLeatherProtectionItems-num;
	}

	if (obj.checked && numberOfLeatherProtectionItems+num > 10) {
		alert('You have reached the maximum Seat capacity for Leather Protection on this order, '+
			  'please contact sofasofa directly to add protection to the remaining order');
		obj.checked = false;

		return false;
	} else {

		if (numberOfLeatherProtectionItems+num>10) {

			num = 10-numberOfLeatherProtectionItems;
		}

		if (obj.checked)
			numberOfLeatherProtectionItems = numberOfLeatherProtectionItems+num;

		return true;
	}
}

function checkLeatherProtectionLimit(obj, linkedQty, prcd, seats) {
	if (prcd.substr(0,6)!='LEAPRO') {
		return true;
	}

	var num = 0;
	if (linkedQty!=null && linkedQty.selectedIndex>-1)
	if (seats<1) seats = 1;
		num = parseInt(linkedQty.options[linkedQty.selectedIndex].value)*parseInt(seats);

	if (num<1) {
		alert('Please select a quantity and then try and select leather protection again');
		obj.checked = false;
		return false;
	}
	doLeatherProtectionLimit(obj, num);
}

function checkAccLeatherProtectionLimit(obj, prcd) {
	if (prcd.substr(0,6)!='LEAPRO') {
		return true;
	}
	doLeatherProtectionLimit(obj, 1);
}


