// Javascript functions used in the Kencart software

// search tip to make the hint disappear automatically
function searchTip()
{
	var defaultText = "Looking for something? Search here!";
	if ($('search_box').value == defaultText) {
		$('search_box').value = "";
	}
	else if ($('search_box').value == "") {
		$('search_box').value = defaultText;
	}
}


// make a popup window for viewing images
function image_popup(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, 'Image', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=450,left = 112,top = 84');");
}

// used to toggle the shopping list feature on and off on the show_cart page
function toggleLayer(whichLayer) {
	if (document.getElementById) {
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;
		style2.display = style2.display=="none" ? "block":"none";
	}
}

// alert the user if he is trying to buy more than we have in stock
function showStockWarning()
{
	return confirm('Your order includes some product quantities which are not currently avaiable in stock.\n '
		+ 'If you proceed with the order, these products will be put on a back-order and dispatched\n when they come back into stock.'
		+ ' See our Shipping Policy for more information.\n\n'
		+ 'Press \'OK\' to proceed, or \'Cancel\' to amend your order');
}

// display the update cart button dynamically when a quantity is changed in the 
// shopping cart.
function showUpdateCartButton()
{
	if (document.getElementById('update_cart_row').style.display == 'none')
	{
		Effect.BlindDown('update_cart_row');
		//Effect.Pulsate('update_cart_row', { pulses: 1, duration: 1 });
		// disable the checkout button until the cart is updated.
		Effect.BlindUp('go_to_checkout_row');
		return false;
	}
}

// function to add a cool slide effect to the shipping info page
function toggle_shipping_layer(show_me)
{
	var divs = new Array();
	divs[0] = "info_mainland";
	divs[1] = "info_highlands";
	divs[2] = "info_channel";
	divs[3] = "info_eec";
	divs[4] = "info_world";
		
	var i;
	
	for (i in divs)
	{
		if (i==0 || i==1 || i==2 || i==3 || i==4)
		{
			if(document.getElementById(divs[i]).style.display != "none")
			{
				Effect.BlindUp(divs[i], {duration: 0.5});
			}
			if (divs[i] == show_me)
				Effect.toggle(show_me, 'Blind', {duration: 0.5}); 
		}
	}
}

// toggle the checkbox effect on the wishlist page
function wl_toggle_select(wl_id)
{
	if ($('select_text_'+wl_id).innerHTML == "Click to select")
	{
		new Effect.Morph("wl_item_box_"+wl_id, {
						style: 'color: #000; background-color:#FFFFBA; border: 1px solid #F5F531;',
						duration: 0.5});
		$('checkbox'+wl_id).checked = true;
		$('select_text_'+wl_id).update("Selected");
	}
	else
	{
		new Effect.Morph("wl_item_box_"+wl_id, {
						style: 'color: #A3A365; background-color:#F5F5DA; border: 1px solid #ccc;',
						duration: 0.5});
		$('checkbox'+wl_id).checked = false;
		$('select_text_'+wl_id).update("Click to select");
	}
}

// select all on the wishlist page
function wl_checkAll() {
	var form = $('wl_select_form');
	var inputs = form.getInputs('checkbox');
	var wl_id = 0;
	inputs.each(function (elem) {
		elem.checked = true;
		new Effect.Morph("wl_item_box_"+wl_id, {
						style: 'color: #000; background-color:#FFFFBA; border: 1px solid #F5F531;',
						duration: 0.5});
		$('select_text_'+wl_id).update("Selected");
		wl_id++;
	});
}

// deselect all on the wishlist page
function wl_checkNone() {
	var form = $('wl_select_form');
	var inputs = form.getInputs('checkbox');
	var wl_id = 0;
	inputs.each(function (elem) {
		elem.checked = false;
		new Effect.Morph("wl_item_box_"+wl_id, {
						style: 'color: #A3A365; background-color:#F5F5DA; border: 1px solid #ccc;',
						duration: 0.5});
		$('select_text_'+wl_id).update("Click to select");
		wl_id++;
	});
}

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
	}
}

// popup cart functions /////////////////////////////////////////////////////////////////////

document.observe('dom:loaded', function() {
    $('header_cart_tooltip')
        .observe('mouseenter', function() {
            Effect.Appear('shopping_cart_box', { duration: 0.5 });
            $('header_cart_tooltip').down('h3').style.color = '#EF1C1C';
        })
        .observe('mouseleave', function() {
            Effect.Fade('shopping_cart_box', { duration: 0.2 });
            $('header_cart_tooltip').down('h3').style.color = '#C11A1A';
        })
    $('header_wishlist_tooltip')
        .observe('mouseenter', function() {
            Effect.Appear('wishlist_box', { duration: 0.5 });
            $('header_wishlist_tooltip').down('h3').style.color = '#B8B84B';
        })
        .observe('mouseleave', function() {
            Effect.Fade('wishlist_box', { duration: 0.2 });
            $('header_wishlist_tooltip').down('h3').style.color = '#777777';
        })
});

Effect.fadeInOut = function(el, message) {
	
	$(el+'_notice').insert(message);
	$(el+'_notice').setStyle({ display:'block'});
	new Effect.Appear(el, { duration: 0.5, queue: { scope: 'wl_cart_popup', position: 'end' }});
	new Effect.Fade(el, {duration: 0.2, queue: { scope: 'wl_cart_popup', position: 'end' }, delay: 1.5}); 	

	window.setTimeout(function() {$(el+'_notice').remove(); }, 2300);
}

Event.observe(window, 'load', function() {
	// When items are added to the cart or wishlist, display the popups briefly
    var query = document.location.search;
    
    if (query.match(/cart_added/) != null) {
    	var matches = query.match(/cart_added=([0-9]{1,3})/);
    	
    	if (query.match(/op_error/) != null) 
    		Effect.fadeInOut('shopping_cart_box', "Please select an option!");
    	else if (matches[1] == 0)
    		Effect.fadeInOut('shopping_cart_box', "Please enter a quantity!");
    	else if(matches[1] == 1)
    		Effect.fadeInOut('shopping_cart_box', "Product added to cart!");
    	else
    		Effect.fadeInOut('shopping_cart_box', "Products added to cart!");
    }
    else if (query.match(/wl_added/) != null) {
    	var matches = query.match(/wl_added=([0-9]{1})/);
    	
    	if (query.match(/op_error/) != null) 
    		Effect.fadeInOut('wishlist_box', "Please select an option!");
    	else if (matches[1] == 0)
    		Effect.fadeInOut('wishlist_box', "Please enter a quantity!");
    	else if (matches[1] > 0)
    		Effect.fadeInOut('wishlist_box', "Products added to wishlist!");
    }
});


var cartReq = getXmlHttpRequestObject();

function updateItem(item_id, qty)
{
  if (item_id == 'x' && qty == 'x')
  	var url = "show_cart_popup.php";
  else
	var url = "show_cart_popup.php?action=update&"+item_id+"="+qty;
	
	// Open a connection to the server
  cartReq.open("GET", url, true);

  // Setup a function for the server to run when it\'s done
  cartReq.onreadystatechange = updateCart;

  // Send the request
  cartReq.send(null);
  
  if (item_id != 'x' && qty != 'x')
  	wishlistToCart('x', '');

}

function updateCart()
{
	if (cartReq.readyState == 4) {
    var response = cartReq.responseText;
    document.getElementById("header_cart_table").innerHTML = response;
    var total_price;
    document.getElementById("total_price_popup").innerHTML = document.getElementById("total_price").innerHTML;
    document.getElementById("total_price_header").innerHTML = document.getElementById("total_price").innerHTML;
	var total_items = document.getElementById("total_items").innerHTML;
    var items_text = (total_items == 1) ? "item" : "items";
	document.getElementById("total_items_header").innerHTML = total_items+' '+items_text;
	}

}

///////////////////// popup wishlist functions ////////////////////////////////////

var wlReq = getXmlHttpRequestObject();

function wishlistToCart(prod_id, options)
{
  if (prod_id == 'x')
  	var url = "wishlist_popup.php";
  else
	var url = "wishlist_popup.php?action=add&prod_id="+prod_id;
	
  if (options != '')
  	url += "&options=" + options;
	
	// Open a connection to the server
  wlReq.open("GET", url, true);

  // Setup a function for the server to run when it\'s done
  wlReq.onreadystatechange = updateWL;

  // Send the request
  wlReq.send(null);

}

function updateWL()
{
	if (wlReq.readyState == 4) {
    var response = wlReq.responseText;
    document.getElementById("header_wishlist_table").innerHTML = response;
    
    // now update the popup cart box
    updateItem('x', 'x');    
	}

}

/////////////////////// scrollbar stuff //////////////////////////////////

// scroll the element vertically based on its width and the slider maximum value
function scrollVertical(value, element, slider) {
	element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));
}

// scroll the element horizontally based on its width and the slider maximum value
function scrollHorizontal(value, element, slider) {
	element.scrollLeft = Math.round(value/slider.maximum*(element.scrollWidth-element.offsetWidth));
}

// disable vertical scrolling if text doesn't overflow the div
function toggleScrollBar(cart_items){
	//if (document.getElementById('header_cart_table').scrollHeight <= document.getElementById('header_cart_table').offsetHeight || cart_items <= 7) {
	if (cart_items <= 7){
		//alert(document.getElementById('header_cart_table').scrollHeight + '<= '+ document.getElementById('header_cart_table').offsetHeight +'= triggered');
		//alert(cart_items);
		slider1.setDisabled();
		document.getElementById('track1').hide();
		document.getElementById('header_cart_table').style.paddingRight = '15px';
	}
}

// disable vertical scrolling if text doesn't overflow the div
function toggleScrollBarWL(wl_items){
	//if (document.getElementById('header_cart_table').scrollHeight <= document.getElementById('header_cart_table').offsetHeight || cart_items <= 7) {
	if (wl_items <= 7){
		//alert(document.getElementById('header_cart_table').scrollHeight + '<= '+ document.getElementById('header_cart_table').offsetHeight +'= triggered');
		//alert(cart_items);
		slider2.setDisabled();
		document.getElementById('track2').hide();
		document.getElementById('header_wishlist_table').style.paddingRight = '15px';
	}
}

///////////////////////////////////  large item image info slider effect //////////////
document.observe('dom:loaded', function() {
$$('.item_box_large').each(function(element) {
   		element.observe('mouseenter', function() {
   			timedelay = setTimeout(function(){new Effect.Morph(element.down('div'), {style: 'top: 100px;', duration: 0.5})}, 500)
   		})
   		element.observe('mouseleave', function() {
   			clearTimeout(timedelay);
   			new Effect.Morph(this.down('div'), {style: 'top: 190px;', delay: 0.5, duration: 0.5})
   		});
   });
});

document.observe('dom:loaded', function() {
$$('.recommendation_box').each(function(element) {
		// add the display:none property dynamically via javascript
		element.down('span').setStyle({display: 'none'});
		
   		element.observe('mouseenter', function() {
   			timedelay = setTimeout(function(){new Effect.Appear(element.down('span'), {duration: 0.2})}, 100)
   		})
   		element.observe('mouseleave', function() {
   			clearTimeout(timedelay);
   			new Effect.Fade(this.down('span'), {duration: 0.1})
   		});
   });
});

////////////////////////////  experimental floating "add item" button////////
function float_buy_btn() {
	var window_top = document.viewport.getScrollOffsets()[1];
	var div_top = $('buy_btn_fixed-anchor').cumulativeOffset()[1];
	var table_bottom = $('buy_btn_fixed-end').cumulativeOffset()[1];
	//$('window_top').innerHTML = window_top;
	//$('div_top').innerHTML = div_top;
	//$('table_bottom').innerHTML = table_bottom;
	
	if (window_top > div_top)
	{
		if (window_top >= table_bottom)
		{
			// if it is the ci_colours page, we don't need to adjust the bottom position of
			// the buy_btn. On regular pages it needs to be adjusted upwards.
			if ($('colours_form')!=null)
				pos = table_bottom;
			else
				pos = table_bottom - 137;
				
			$('buy_btn').setStyle({top: pos+'px', position:'absolute'});
		}
		else
		{
			$('buy_btn').setStyle({top: '0px', position: 'fixed'});
			
		}
	}
	else
	{
		$('buy_btn').setStyle({top: '0px', position: 'relative'});
	}	
}
Event.observe(window, 'scroll', function() {
  float_buy_btn();
});
// hide the additional buy buttons
document.observe('dom:loaded', function() {
	$$('.buy_btn_no_js').each(function(element) {
   		element.hide();
	})
});

// review vote controls AJAX stuff //////////////////////////////////////////
document.observe('dom:loaded', function() {
	$$('.review_vote').each(function(element) {
        element.observe('click', function(event) {
            // first we should disable the links for the vote controls
            event.stop()

            var parent = element.up('.vote_controls');
            var review_id = element.readAttribute('data-review_id');
            var vote = element.readAttribute('data-review_yesno');

            new Effect.Fade(parent, {afterFinish: function(){
                new Ajax.Request('backgroundHelper.php', {
                    method: 'post',
                    parameters: {"action": "review_vote", "rID" : review_id,"yesno" : vote},
                    onSuccess: function(response){
                        parent.update('Thanks for the feedback!');
                        parent.appear({duration: 0.3});
                    }
                });
            }, duration: 0.3, to: 0.1});
        });
    });

    $$('.review_vote').observe('click', function(element) {
        /*// now do the AJAX stuff
        var review_id = element.readAttribute('data-review_id');
        var vote = element.readAttribute('data-review_yesno');

        new Ajax.Request('backgroundHelper.php', {
            method: 'post',
            postBody: {action: "review_vote", rID : review_id, yesno : vote},
            onSuccess: function(response){
                alert('yay!');
                element.up('.vote_controls').update('Thanks for the feedback!');
            },
            onFailure: function(response){
                alert('boo!');
            }
        });*/

    });
});

