// JavaScript Document

function emptyIf(field,defaultValue)
{
		if (field.value == defaultValue)
		{
			field.value ="";	
		}
}
function defaultIfEmpty(field,defaultValue)
{
		if (field.value.length == 0)
		{
			field.value = defaultValue;	
		}
}

function pcalc()
{
	var pheight = new Number($('pheight').value);
	var pwidth = new Number($('pwidth').value);
	var pqty = new Number($('pqty').value);
	var pprice = $('shopprodlg-cart-price');
	var rate = parseFloat($('prate').value.replace(/[^0-9\.]+/g,""));
	var cart = $('shopprodlg-cart');
	var pmaxw = new Number($('pmaxw').value);

	var err = "";
	if (pheight != $('pheight').value
		|| $('pheight').value == 0)
	{
		err += "Please enter height in millimeters (mm)\n";

	}
	if (pwidth != $('pwidth').value
		|| $('pwidth').value == 0)
	{
		err += "Please enter width in millimeters (mm)\n";
	}
	if (pqty != $('pqty').value
	    || $('pqty').value.length == 0)
	{
		err += "Please enter quantity\n";
	}
	if (pmaxw > 0
		&& pwidth > pmaxw)
	{
		err += "Width must be less than the maximum of " + pmaxw.toString() + "mm";		
	}
	else
	{
		if (pwidth > 1200)
		{
			err += "Width must be less than the maximum of 1200 mm";	
		}
	}
	if (err.length > 0)
	{
		alert(err);
		return false;
	}
	
	
	// convert to 10cm units for pricing and shop cart
	// mm / 10 = cm
	// cm * 10 = mm / 100
	var pheight10cm = parseInt(pheight / 100);  
	
	// round up a unit if not whole units
	if (pheight10cm < (pheight / 100))
	{
		pheight10cm = pheight10cm + 1;
	}
	
	var __ProductLineId = 1;
	__ProductLineId = (new Date()).getTime().toString().substr(10);
	var c = readCookie("LineNo");
	if(c != null)
	{
		__ProductLineId = parseInt(c) + 1;
	}
	else
	{
		__ProductLineId = 1;
	}
	createCookie("LineNo", __ProductLineId, 1);
	
	
	// store customer size info
	var spec = $$('textarea.productTextarea')[0];
	if (spec != null)
	{
		spec.value = "Height: " + pheight.toString() + " mm " +
					 "Width: " + pwidth.toString() + " mm " +
					 "Qty: " + pqty.toString() + ".   " +
					 "Item: " + __ProductLineId.toString();
	}
				 
	// if over half width charge full width by doubling qty
	if (pwidth > 550)
	{
		pqty = pqty * 2;	
	}
	
	//if (pwidth < 550 && pwidth >= 250 )
	//{
//pqty = pqty / 2;	
	//}	
	
	//if (pwidth < 250)
	//{
	//	pqty = pqty / 4;	
	//}	
	

	// calculate total units
	var totalunits = pheight10cm * pqty;
	
	// min line item qty = 0.5 meter = 10 units
	if (totalunits < 10)
	{
		totalunits = 10;	
	}
	
	// add bleed space between heights for multi quantities
	if (pqty > 1)
	{
		totalunits = totalunits + parseInt(pqty / 2); 
	}
	
	// if more than one piece and total units close to a meter, make it a meter
	if (pqty > 1)
	{
		if(totalunits > 15
		&& totalunits < 20)
		{
			totalunits = 20;	
		}
	}

	
	// calculate price with gst 
	var val = (totalunits * rate * 1.1); // 10cm units
	
	// show cart
	$('shopprodlg-cart-usecalc').hide();
	cart.show();
	$('shopprodlg-cart-add').show().focus();
	
	// update price
	pprice.update("$" + val.toFixed(2));

	var qty = $$('input.productTextInput')[0];
	
	qty.value = totalunits;

}

function AddToCart2(a,b,c,d,e)
{
	
		// store quantity for sheet items
		var spec = $$('textarea.productTextarea')[0];
		if (spec != null)
		{
			if (spec.value == "")
			{
				spec.value = "Qty: " + $$('input.productTextInput')[0].value;
			}
		}
	
		// temp override alert messages while adding to cart
		var cartmsg = "";
		var curAlertFunc = window.alert;
		window.alert=function(msg){cartmsg = msg; };
		

		// add product option to cart
		AddToCart(a,b,c,d,e);
		
		// restore alert function
		window.alert=curAlertFunc;
		
		// re layout
		tiOnPageLoad()
		
		// show appropriate message
		if (cartmsg.indexOf('added') > 0)
		{
			alert('Item added to cart\n\nClick "View Cart" at the top of the page to checkout.');
		}
		else
		{
			if (cartmsg.length > 5)
			{
				alert(cartmsg);
			}
		}
}


function checkMinOrderVal()
{
		var invtotal = $('invtotal');
		if (invtotal != null)
		{
			var invtotalval = parseFloat(invtotal.innerHTML.toString().replace(/[^0-9\.]+/g,""));
			if (invtotalval < 29.70)
			{	
				$('minordererr').update("Minimum Order $29.70<br/>Please add more items to your cart.");
			}
		}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function tiOnPageLoad()
{
	
	// shopping cart is empty message when cart is cleared
	var cartempty = $$('a.cartLink');
	if (cartempty.length > 0)
	{
			cartempty[0].update("<p>&nbsp;</p><h1 class='white'> Your shopping Cart is Empty</h1><p>Please click here to go back, or use the menu's above to browse our catalogues</p>");
	}
	
	// shop cart summary layout
	var cartsum = $$('.cartSummaryItem');
	if (cartsum != null)
	{
		cartsum.each(function (item) {
							   		var itemtext = item.innerHTML;
									
									itemtext = itemtext.replace(/\d+ item\(s\), Total: (\$\d+.\d+)/i, "Total: $1" );	
									
							   		item.update(itemtext);
							   
							   } );
								   
								   
		// http://transformitimages2.businesscatalyst.com/OrderRetrievev2.aspx?CatalogueID=591
		// 2 item(s), Total: $59.60	
	}
	var cart = $('headshopcart');
	if (cart != null)
	{
		if (cart.innerHTML.indexOf("empty") == -1)
		{
			cart.addClassName('full');
			//cart.setStyle({ backgroundImage: '/images/transformit2-shopcartbg-full.jpg'} );
		}
	}
	$$('.cartSummaryLink').each(function (item) { item.update("View Cart / Checkout"); } );
	
	
	// hide empty catalogue descriptions
	var catDesc = $('shopCatalogueDesc')
	if (catDesc != null)
	{
		if (catDesc.innerHTML == "")
		{
			 catDesc.hide();
		}
		
	}
	
	// product large page changes
	if (window.location.toString().indexOf("/online-store/") > 0 )
	{
		
		// copy category
		$('shopprodlg-catname').update($('catalogueTitle').innerHTML);
		
		// configure product type
		var ptype = $('ptype').value;
		if (ptype == null)
		{
			// default
			ptype = "per sheet";	
		}
		
		if (ptype == "per meter"
			|| ptype == "per metre")
		{
			// show calulator
			
			// hide other details
			$('shopprodlg-attr').hide();
			$('shopprodlg-qty').hide();
			
			// hide price
			$('shopprodlg-cart-price').update("");
			
			// hide cart
			$('shopprodlg-cart-add').hide();
			//$('shopprodlg-cart').hide();
			
		} else
		{
			// hide calculator
			$('shopprodlg-calc').hide();
			
			$('shopprodlg-cart-usecalc').hide();
			
			// change title to "price per sheet"
			$('shopprodlg-cart-pricetitle').update("Price Per Sheet:");
		}
		
		
		// hide empty product options
		var popt = $('shopprodlg-related');
		if (popt != null)
		{
			if (popt.innerHTML.toString().indexOf("This product has no related products.") > 0)
			{
				popt.hide();	
			}
		}
		
		// hide sizing if not available
		var popts = $$('div.catProdAttributeTitle');
		if (popts.length == 0)
		{
			$('shopprodlg-attr').hide();
		}
		
		// hide catalogue description on product pages
		$('shopCatalogueDesc').hide();
		
		// change product grouping redraws
		/*
		var productGrouping = $$('select.productSelectInput');
		if (productGrouping != null)
		{
			productGrouping.each( function (item) {
												var oldonchange = item.onchange;
												item.onchange =  function() {
																	  reLayout();
																	  if (oldonchange) {
																		oldonchange();
																	  }
																	}
											
											});
				
		}
		*/
	}
}

function SetShipping(checked) {
	if (checked) {
		document.getElementById('ShippingAddress').value = document.getElementById('BillingAddress').value; 
		document.getElementById('ShippingCity').value = document.getElementById('BillingCity').value; 
		document.getElementById('ShippingState').value = document.getElementById('BillingState').value; 
		document.getElementById('ShippingZip').value = document.getElementById('BillingZip').value; 
		document.getElementById('ShippingCountry').value = document.getElementById('BillingCountry').value; 
	}
}

function DrawProduct2(a,b,c,d,e)
{
	reLayout();
	DrawProduct(a,b,c,d,e);	
}

function cartReLayout()
{
	checkMinOrderVal();
	// use a timer to give BC enough time to update the page
	new PeriodicalExecuter(function(pe) { tiOnPageLoad(); checkMinOrderVal(); }, 0.5) // 1 second
}

function reLayout()
{
	// use a timer to give BC enough time to update the page
	new PeriodicalExecuter(function(pe) { tiOnPageLoad();	pe.stop(); }, 0.2) // 1 second
}



// do page layout on page load
addLoadEvent(tiOnPageLoad);



/*** language overrides ****/
Oshoplang = { 

    RemoveError: 'ERROR: To remove or update quantities select the View Cart link.',    
    Added: ' Item added to cart\n\nClick "View Cart" at the top of the page to checkout.',
    OutOfStock: 'Either product is out of stock or choose a smaller quantity',
    PreOrder: ' item(s) pre-ordered and added to your cart.',
    MinLimit: 'ERROR: Quantity entered is too small, please enter a larger quantity.',
    MaxLimit: 'ERROR: Quantity entered is too large, please enter a smaller quantity.',
    InvalidQuantity: 'ERROR: Quantity entered is not valid.',
    CartEmpty: 'Your Shopping cart is empty.',
    CartUpdateSuccess: 'Shopping cart updated successfully.',
    InvalidShip: 'Please choose a valid shipping option before continuing.',
    ChooseState: 'ERROR: Please choose a destination state to calculate state tax.',
    EnterZip: 'ERROR: Please enter in your Zip/Postcode to calculate shipping costs for your order.',
    ChooseShip: 'ERROR: Please select a shipping charge for your order.',
    IncorrectGForm: 'ERROR: Your gift voucher form is not setup correctly. Please reset to original to restore.',
    EnterGName: 'ERROR: Please enter a name for the recipient of your gift voucher.',
    InvalidGEmail: 'ERROR: Please enter a valid email address for the recipient of your gift voucher.',
    EnterGMessage: 'ERROR: Please enter a personal message for the recipient of your gift voucher.',
    ChooseAttribute: 'Please choose your Sizing and Finishing options before adding to cart.'


}

