/*************
/* Functions
/**************/

/**
 * Returns a single result from getElelmentsByClassName
*/
function getElementByClassName(class_name, element)
{
	var element = (element == null) ? document : element;
	var value = element.getElementsByClassName(class_name);
	return value[0];
}

/**
 * Returns an array with Width and Height of window
*/
function getWindowWidthHeight()
{
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winW = document.body.offsetWidth;
			winH = document.body.offsetHeight;
		}
	}

	return new Array(winW, winH);
}

/**
 * Add a product to the shopping cart
*/
function updateCart(el, event)
{
	var enterKey = 13;
	var tabKey   = 9; 
    var qty      = el.value;

	var parentEl = el.parentNode;
	var div = parentEl.parentNode;
    var scrollDiv = div.parentNode;

	id = div.id.substr(12);
	if (qty != '' && qty > 0 && (event.keyCode == enterKey || event.keyCode == tabKey || (event.keyCode == undefined || event.keyCode == 0)))
	{
        var blur = el.onblur;
        el.onblur = function() { return false; }
		new Ajax.Request('updateCart.php',
		{
			method: 'post',
			evalScripts: true,
			parameters: {id: id, qty: qty},
			onSuccess: function(transport) {
			  var response = transport.responseText || null;
			  $('cart-items').innerHTML		   = response;
			  response.evalScripts();
              el.onblur = blur;
			}
		 });
	}
	if (event.keyCode == enterKey || event.keyCode == tabKey) {
		return setFocusOnNextQty(scrollDiv, el);
	}

    return true;
}

/**
 * Add a product to the shopping cart
*/
function updateAddress(el)
{
	new Ajax.Request('updateAddress.php',
	{
		method: 'post',
		evalScripts: true,
		parameters: {ship_to: el.value}
	 });
}

/**
 * Remove a product to the shopping cart
*/
function deleteItemFromCart(id)
{
	new Ajax.Request('deleteItem.php',
    {
		method: 'post',
		evalScripts: true,
		parameters: {id: id},
		onSuccess: function(transport) {
		  var response = transport.responseText || null;
		  $('cart-items').innerHTML		   = response;
		  response.evalScripts();
		}
	  });
}

/**
 * Clear shopping cart
*/
function clearCart()
{
	new Ajax.Request('clearCart.php',
    {
		method: 'post',
		evalScripts: true,
		onSuccess: function(transport) {
		  var response = transport.responseText || null;
		  $('cart-items').innerHTML		   = response;
		  $('cart-summary').innerHTML = "Total Weight: 0 kgs<br />Total Cost: $0.00<br />";
		}
	  });

	  // Clear all checkboxes
	 $$('.cart-qty').each(function(item) {
		item.value = '';
	 });
}

/**
 * Return an index from a form element
*/
function getIndex(element)
{
    for (var i=0;i<document.forms[0].elements.length;i++)
        if (element == document.forms[0].elements[i])
            return i;
    return -1;
}

/**
 * Set focus on next qty field
*/
function setFocusOnNextQty(scrollDiv, input) 
{
    var qtys = scrollDiv.getElementsByTagName('input');

    for (var i=0;i<qtys.length;i++) {
        if (input == qtys[i]) {
            i = i + 1;
			if (qtys[i] != null) {
				qtys[i].focus();
				break;
			}
            else {
                scrollDiv.focus();
            }
		}
	}
    return false;
}

/**
 * Set the current cart position (store in a cookie)
*/
function setCartPosition() {  
	var intY =  parseInt($('cart').style.top.substr(0, $('cart').style.top.length - 2));
	document.cookie = "yPos=!~" + intY + "~!";  
}

/**
 * Get cart position from cookie
*/
function getCartPosition() {
	var strCook = document.cookie;
	var intS = strCook.indexOf("!~");  
	var intE = strCook.indexOf("~!");  
	var strPos = parseInt(strCook.substring(intS+2,intE));
	return strPos;
}


function checkOrder()
{
    // Give it a little time just to make sure everything has added to the cart
    setTimeout(function () { submitOrder(); }, 200);
}


/**
 * Submit order
*/
function submitOrder()
{
	var message = '';
	var shipping = null;

	$$('.shipping').each(function(item) {
		if (eval(item.checked) == true) {
			shipping = item.value;
		}
	});

	if ((shipping == null) || (shipping == 'other' && ($('shipping-other-val').value.replace(/^\s+|\s+$/g, '') == '' || $('shipping-other-val').value == "Please specify...")))
	{
		message = "- Shipping Method\n";
	}

	// Check shipping to
	if ($('ship-to').value == '') {
		message += "- Ship to Address\n";
	}
	// Check ordered by
	if ($('ordered-by').value == '') {
		message += "- Ordered by\n";
	}
	// Check order number
	if (document.getElementById('order-number') != null && $('order-number').value == '' && $('order-number').title == 'required') {
		message += "- Order number\n";
	}


	if (message != '')
	{
		alert("Please make sure the following fields are not blank: \n" + message);
		return false;
	}

	// Check to make sure they have products added
	if ($('cart-items').getElementsByClassName('row').length == 0)
	{
		alert('Please add some products to your cart before you continue.');
		return false;
	}
    
	$('order-form').onSubmit = '';
	$('order-form').submit();

	return true;
}

function addToCart(el)
{
	var parentEl = el.parentNode;
	var div = parentEl.parentNode;
	id = div.id.substr(12);
	var qty = div.getElementsByTagName('input');
	qty = qty[0].value;
	
	if (id > 0 && qty > 0)
	{
		new Ajax.Request('updateCart.php',
		{
			method: 'post',
			evalScripts: true,
			parameters: {id: id, qty: qty},
			onSuccess: function(transport) {
			  var response = transport.responseText || null;
			  $('cart-items').innerHTML		   = response;
			  response.evalScripts();
			}
		 });
	}
}

function clearQty(id)
{
	var qty = $('product-row-' + id).getElementsByTagName('input');
	qty[0].value = '';
}

function createCookie(name,value,days) {
    var date = new Date();
	if (days) {
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else {
		var expires = date.toGMTString();
	}
	document.cookie = name+"="+value+";"+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

overlayState = false;
function showBox()
{
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	$('overlay').style.height = ((arrayPageSize[1] - 1) + 'px');
	$('overlay').show();
    center('box');
    Effect.Appear('box');
    overlayState = true;

	selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
            selects[i].style.display = "none";
    }
}

function closeBox()
{
    Effect.Fade('box');
    overlayState = false;
    setTimeout(function () {
        $('overlay').style.display = 'none';
    }, 1000);
}

/**
 * Center a div on the screen
 */
function center(element){
    try{
        element = $(element);
    }catch(e){
        return;
    }
    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    } else if ( document.documentElement &&
             ( document.documentElement.clientWidth ||
               document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body &&
            ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    //element.style.position = 'absolute';

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ) {
        scrollY = document.documentElement.scrollTop;
    } else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    } else if ( window.pageYOffset ) {
        scrollY = window.pageYOffset;
    } else if ( window.scrollY ) {
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    element.style.left = setX + "px";
    $(element).setStyle({top: setY+'px'});
}

window.onresize = function(){
	if(overlayState == true){
	    center('box');
	}
}

window.onscroll = function(){
	if(overlayState == true){
	    center('box');
	}
}
