// all that
// jquery action
// get called
// from here

$(document).ready(function(){
	$(".giftMessageArea").hide();
	$(".giftwrapCheck").each(function(){
		var currentId = $(this).attr("id");	
		if(currentId.indexOf("_on")>0) {
			currentId = currentId.slice(currentId.indexOf("_")+1, currentId.indexOf("_", currentId.indexOf("_")+1));
			$(this).attr("checked") != true ? $("#giftMessage_"+currentId).hide() : $("#giftMessage_"+currentId).show();
		}	
	});
	$(".giftwrapCheck").click(function(){
		var currentId = $(this).attr("id");		
		currentId = currentId.slice(currentId.indexOf("_")+1, currentId.indexOf("_", currentId.indexOf("_")+1));
		$(this).val() == 0 ? $("#giftMessage_"+currentId).hide('slow') : $("#giftMessage_"+currentId).show('slow');
	});
	
	$("input[name='giftwrapQuestion']").attr("checked") != true ? $("#allGiftwrap").hide() : $("#allGiftwrap").show();
	$("input[name='giftwrapQuestion']").click(function(){
		$(this).val() != true ? $("#allGiftwrap").hide('slow') : $("#allGiftwrap").show('slow');
	})
	
	$('input#search').example('search');
	
	// **************************
	// order view selector
	
	$("#orderSelector").change(function () {
		var urlSplit = location.href.split('/');
		var orderSeg = urlSplit.exists("order");
		if(!orderSeg) {
			finalUrl = appendToUrl('/order/'+$("#orderSelector").val(), location.href);
		} else {
			finalUrl = changeURLSegment($("#orderSelector").val(), orderSeg-1, urlSplit);
		}
	    location.href = finalUrl;
	});

	function appendToUrl(val, url) {
		if(url.charAt(url.length-1)=="/") {
			url = url.substring(0,url.length-1);
		}
		return url + val;
	}

	Array.prototype.exists = function(search){
	  for (var i=0; i<this.length; i++)
	    if (this[i] == search) return i;
	
	  return false;
	}

    function changeURLSegment(val, seg, urlSplit) {
		urlSplit[seg+2] = val;	// fiddle factor
		return urlSplit.join('/');
	}

	
	$("form#trolley #countryDropdown").bind("change", function(){
		$(".basRemove input").attr("disabled","disabled");
	  	updateTrolleyTotal();	
	});
	
	function updateTrolleyTotal() {
		$.ajax({
		  url: "/trolley/ajaxUpdate",
		  type: "POST",
		  async: false,
		  datatype: "json",
		  data: "countryId="+$("form#trolley #countryDropdown").val(),
		  cache: false,
		  success: function(data){
				var data2 = eval("(" + data + ")");
				if(data2['itemcount']=="0") {
					window.location="/trolley";
				} else {
					$("#postageDisplay").html(data2['postage']);
					$("#totalDisplay").html(data2['total']);
					$(".basRemove input").attr("disabled","");
					$("#postMethod").html(data2['postMethod']);
				}							
		  }
		});
	}
	
	
});