$(document).ready(function(){
	var DocumentHeight = $(document).height();
	
	$("<div id='modalLayer'></div>").css({"height":DocumentHeight+"px","opacity":0.7}).insertAfter("#outerwrapper").hide();
	
});

$(function() {
	$("#optional").hide();
	$("a#readMore").click(function(){

		$("#optional").slideDown("slow");
		return false;
	});
	
	$("a#close").click(function(){
		$("#optional").slideUp("slow");
		return false;
	});
});

$(function(){
	$("form#addToCart").ajaxForm({
		
        dataType: 'json',
    	url: 'http://www.protectivetextile.co.uk/ajax/add_to_cart.php',
        success:addToCart  
        
	});
});

function addToCart(data)
{
	if (data.type == "cart")
	{ 
		$("#cartContainer").load("http://www.protectivetextile.co.uk/ajax/cart_data.php",function(){
			showMessage('<p>Your product has been added to your cart</p>',1);
		});
		
	}
	else if (data.type == "favourites")
	{
		$("#favsContainer").load("http://www.protectivetextile.co.uk/ajax/favs_data.php",function(){
			showMessage('<p>Your product has been added to your favourites list</p>',1);
		});
	}
	else {
		
		
		var message = '<p class="emphasis">There are errors with the submission of your request</p>';
		for (var key in data) 
		{
			if (key == 'repeat')
			{
				message = "<p>"+data[key]+"</p>";
			}
			else
			{
				message = message + "<p>"+data[key]+"</p>";
			}
		}
		showMessage(message,0);
	}
}


function showMessage(message,success)
{
	if (success == 0)
	{
		timedelay = 3000;
	}
	else
	{
		timedelay = 1500;
	}
	
	var Message = $("<div class='message'>"+message+"</div>");
	Message.insertAfter("#wrapper").hide();
	
	$("#modalLayer").bgiframe().show();
	Message.center().
	hide().
	fadeIn("slow").
	animate({opacity: 0.0}, timedelay,function(){
		($(this).remove());
		($("#modalLayer").fadeOut("slow"));
	});
	
};

$(document).ready(function(){
	$("input.btn").hover(function(){
		$(this).addClass("hover");
	},
	function() {
		$(this).removeClass("hover");	
	});
});

$(document).ready(function(){
	$("input.btn").focus(function(){
		$(this).addClass("hover");
	});
});

$(function(){
	$("a#shippingestimatebutton").click(function(){
		var Value = $("input#shippingestimate").val();
		if (Value == "")
		{
			$(".shippingcost").html("Please enter your postcode").fadeIn("slow");
		}
		else
		{
			$(".shippingcost").load("http://www.protectivetextile.co.uk/ajax/shippingEstimate.php",{'postcode':Value})
		}
		return false;
	});
});

$(document).ready(function(){
	$('#imageGallery').cycle({
   	fx:    'fade', 
    speed:2500,
    timeout: 4000,
     pause:   1,
    before: onBefore,
    after: onAfter
    });   
});

function onBefore() { 
    $(".gallerytext").fadeOut("slow");
} 
function onAfter() { 
   var altext = $(this).attr("alt");
  // $("<div class='gallerytext'>"+altext+"</div>").prependTo("#imageGallery").hide().fadeIn("slow");
  $("<div class='gallerytext'>"+altext+"</div>").prependTo("#imageGallery").hide().effect("slide",{direction:"left"},1000);
 
}

$(document).ready(function() { 
    $('ul.sf-menu').superfish({ 
    
    delay:       500,                            // one second delay on mouseout 
    animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
    speed:       'fast',                          // faster animation speed 
    autoArrows:  false,                      // disable generation of arrow mark-up 
    dropShadows: false   // disable drop shadows 
}); 
}); 

$(document).ready(function(){
	$("form:not(.search) input:not(:submit),textarea ").focus(function(){
		$(this).addClass("inputFocus");
	}).
	blur(function(){
		$(this).removeClass("inputFocus");
	}).
	keyup(function(){
		$(this).removeClass("inputFocus");
	});
});

$(document).ready(function(){
	var Errors = $(".errors");
	Errors.hide();
	Errors.slideDown("slow");
});

$(document).ready(function() 
{$(".trigger").tooltip({ 
    position:['center','right'],
    offset: [0,100], 
    effect: 'fade',
    opacity: 0.9, 
    tip: '.tooltip' 
});
});

/*----------------------------------------------------------
for product listings 
------------------------------------------------------------*/

var fnGetPrice = function(o_select){ 
        $(o_select).parents('div').find('select').each(function()
        {
            if (this.value.length == 0){return false;}
        });
        	
        var v_url = 'http://www.protectivetextile.co.uk/ajax/getOptionPrices.php'; 
        var rowID = $(o_select).parents('tr').attr('id');
        rowID = rowID.replace(/item_/,"");
    	var v_qrystr = 'type=listing&'+'p_id=' + rowID +'&';
    	    
        $(o_select).parents('tr').find('select.do').each(function()
        {
			v_qrystr = v_qrystr  + $(this).attr('name') + '=' + $(this).val() + '&';
		});

		$.ajax({
  			type: "GET", 
  	 		url: v_url,
  			data: v_qrystr,
 	  		success: function(msg)
 	  		{
    			$("td.price_"+rowID).html(msg);
   
 	  		}
		});		
}
$(document).ready(function(){
	 $('tr.productListing').each(function(v_index){                           
		$(this).find('select.do').change(function(){
			fnGetPrice(this);
		});    
	 });
});
/*----------------------------------------------------------
for product detail page
------------------------------------------------------------*/
$(function(){
   	$(".productWrapper select.do").not(":first").attr("disabled", "disabled");
   	var num = $(".productWrapper select.do").size() -1 ;
   	
   	var prodID = $(".productWrapper").attr("id");
   	if (prodID)
   	{
   		prodID = prodID.replace("item_","");
   	}
	$(".productWrapper select.do").each(function(index){
		var newIndex = index + 1;
		
		$(this).change(function(){
			
		var v_qrystr = "";
   		var v_qrystr = "prodID="+prodID+"&";
   						
		$("select."+newIndex).removeAttr("disabled");
			
		var styleID = $(this).prev("p").attr("id");
		styleID = styleID.replace("styleID_","");
				
		var nextStyleID = $("select."+newIndex).attr("name");
				
		v_qrystr = v_qrystr + $(this).attr('name') + '=' + $(this).val() + '&';
		v_qrystr = v_qrystr + 'nextStyleID['+prodID+']='+nextStyleID+'&'+$(this).attr('name') + '=' + $(this).val() + '&';
				
		$.ajax({
			type: "GET", 
  	 		url: 'http://www.protectivetextile.co.uk/ajax/getOptionValues.php',
  	 		data: v_qrystr,
  	 		success:function(msg)
  	 			{
  	 				$("select."+newIndex).html(msg);
  	 			}
				
			});
		});	
	});
});

var fdGetPrice = function(o_select)
{
	var v_url = 'http://www.protectivetextile.co.uk/ajax/getOptionPrices.php'; 
	var rowID = $(o_select).parents('.productWrapper').attr('id');   
    rowID = rowID.replace(/item_/,"");
    var v_qrystrPrice = 'type=detail&'+'p_id=' + rowID +'&';
    $(o_select).parents('.productWrapper').find('select.do').each(function() {
			v_qrystrPrice = v_qrystrPrice  + $(this).attr('name') + '=' + $(this).val() + '&';
	});
	$.ajax({
  		type: "GET", 
  	 	url: v_url,
  		data: v_qrystrPrice,
 	  	success: function(msg)
 	  	{
    		$("div.price_"+rowID).html(msg);
 	  	}
	});	
}


$(function() {
	
	$('.productWrapper select.do').live("change",function(){
	 	 fdGetPrice(this);
	 });
});	


/*----------------------------------------------------------*/

$(document).ready(function(){
	$("fieldset").each(function(){
		var heading = $("legend",this).remove().text();
		$("<h3></h3>").text(heading).prependTo(this);
	});
});

/*----------------------------------------------------------*/


$(document).ready(function() {
   	$('#sameAsBilling').click(function() {
    if ($("#sameAsBilling").is(":checked")) 
    {
   		$(".billingtext").text("Deselect");
    	$('#shipping_fields input').each(function(i) { 
   		$(this).val( $('#billing_fields input').eq(i).val() );
    	});
 		var bcounty = $("select#billing_county").val();
    	$("select#shipping_county").val(bcounty);                    
    } 
    else 
    {
  	 
  	 	$(".billingtext").text("Same as billing");
    	$('#shipping_fields input').each(function(i) { 
     	$(this).val(""); 
    	});
    	$("select#shipping_county").val("");
    }
    });
});


$(document).ready(function() {
	$("select.deliveryCost").change(function() {
		if ((this).value == '')
		{
			$('.revisedTotals').load('ajax/getDeliveryCost.php',{'value':(this).value},function() {
				$("td.delCost").text("");
			});
		}
		else
		{
			$('.revisedTotals').load('ajax/getDeliveryCost.php',{'value':(this).value});
		}
	});
});

$(document).ready(function() {
	$("table.orderItems, table.addressBook, table.cart").each(function() {
		$("tr:last",this).css({"border":"none"});
	});
});

/*
$(document).ready(function(){
	var required = $("<p class='req'><span class=\"req\">*</span> required</p>");
	required.insertAfter($("form :submit"));
	$("form.createOrder p.req, , form.addressBook p.req, form.search p.req, form.cart p.req, form.detailPage p.req, form.itemListing p.req").remove();
});
*/

$(document).ready(function(){
	$("#billing_fields label").each(function(){
		var Original = $(this).text();
		var New = Original.replace(/Billing/,"");
		var Match = /[*]/.test(New);
		if (Match)
		{
			New = New.replace(/[*]/,"");
			$(this).text(New);
			$(this).append("<span class=\"req\">*</span>");
		}
		else 
		{
			$(this).text(New);
		}
	
	});
});

$(document).ready(function(){
	$("#shipping_fields label").each(function(){
		var Original = $(this).text();
		var New = Original.replace(/Shipping/,"");
		var Match = /[*]/.test(New);
		if (Match)
		{
			New = New.replace(/[*]/,"");
			$(this).text(New);
			$(this).append("<span class=\"req\">*</span>");
		}
		else
		{
			$(this).text(New);
		}
	});
});

$(document).ready(function(){
	function throwalert(message)
	{
		var Message = $("<div class='inlinemessage'>"+message+"</div>");
		Message.insertAfter("#wrapper").hide();			
		$("#modalLayer").bgiframe().show();
		Message.center().
		hide().
		fadeIn("slow").
		animate({opacity: 0.0}, 1500,function(){
			($(this).remove());
			($("#modalLayer").fadeOut("slow"));
		});	
		
	}
	
	$("form.createOrder :submit").click(function() {
		if ($("select.deliveryCost").val() == '')
		{

			throwalert("Can you enter your delivery method please");
			return false;
		}
		if ($("select.paymentMethod").val() == '')
		{
			throwalert("Can you enter your payment method please");
			return false;
		}
		if ($("select#termsAndConditions").val() == '')
		{
			throwalert("Please let us know if you accept our terms and conditions");
			return false;
		}
		return true;
	});
});

// this for terms and conditions, delivery etc

$(function(){
	$(".showContent").colorbox({
		opacity:0.7,
		width:"800px", 
		height:"70%"});
});

// this for viewing orders and print address

$(function(){
	$(".printSummary").colorbox({
		opacity:0.7,
		width:"820px", 
		height:"160%"});
});

/*
$(function(){
	$("a.print").live("click",function (){
		$(".orderSummary").print();
		return false;
	});
});
*/

$(document).ready(function(){
	$("table.information tr:last td").css({"padding":"10px 0 10px 0"})
});

$(document).ready(edit_order_init);
function edit_order_init()
{
	$("a.editOrder").click(edit_order);
}
function edit_order()
{
	var id  = getUrlVars(this.href)["id"];
	$.getJSON('http://www.protectivetextile.co.uk/ajax/editOrder.php?ajax=true&id='+id,returntocart);
	return false;
}
function returntocart()
{
	location.href="http://www.protectivetextile.co.uk/cart.html";
}



$(document).ready(delete_order_init);
function delete_order_init()
{
	$("a.deleteOrder").click(delete_order);
}
function delete_order()
{
	var id  = getUrlVars(this.href)["id"];
	var user_id = getUrlVars(this.href)["user_id"];		
	this.id = 'delete_link_'+id;
	$.getJSON('http://www.protectivetextile.co.uk/ajax/deleteOrder.php?ajax=true&id='+id+'&user_id='+user_id,remove_row);
	return false;
}
function remove_row(data)
{	
	if(data.empty == "1")
	{
		$("table").remove()
		$("p.ordersmessage").text("You have yet to place any orders with us");
	}
	else
	{
		$("#delete_link_"+data.id)
		.closest("tr")
		.remove()
		$("table tr:last").css({"border-bottom":"1px solid #bd0b0f"});
	}
}


$(document).ready(delete_address_init);
function delete_address_init()
{
	$("a.deleteAddress").click(delete_address);
}
function delete_address()
{
	var id = getUrlVars(this.href)["delete"];
	var user_id = getUrlVars(this.href)["user_id"];		
	this.id = 'delete_link_'+id;
		$.getJSON('http://www.protectivetextile.co.uk/ajax/deleteAddress.php?ajax=true&id='+id+'&user_id='+user_id,remove_address);
	return false;
}
function remove_address(data)
{
	if (data.empty == "0")
	{
		var form = $("form.addressBook");
		$("table").remove()
		$("input.selectAsMainAddress").remove()
		$("<p>You have no delivery addresses set up - please add one now</p>").prependTo(form);
	}
	if (data.empty == "1")
	{
		$("#delete_link_"+data.id)
		.closest("tr")
		.remove()
		$("table tr:last").css({"border-bottom":"1px solid #bd0b0f"});
		
		if (data.priority == "1")
		{
		 if ($("form.addressBook input").not(":checked")) 
		 {
		 	$("form.addressBook input:first").attr("checked","checked");
		 }
		}
	}
}

function getUrlVars(url)
{
 
	var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

$(document).ready(function() {
	$("a.clearSearchFilters").click(function(){	$(".searchContainer").load("http://www.protectivetextile.co.uk/ajax/clearSearchFilters.php",function(){
			$(this).fadeIn("slow");
		});
		return false;
	});
});

$(document).ready(function(){
	$(".giftMessage").hide();
	$("a.showGiftMessage").click(function(){
		var target = $(this);
		target.next("div").slideDown("slow");
		return false;
		});
		
		$("a.cancelGiftMessage").click(function(){
			var targetCancel = $(this);
			targetCancel.parents(".giftMessage").slideUp("slow");
			return false;
		});
		
	});
	
$(document).ready(function(){
	$("a[rel='imageGallery']").colorbox({
		opacity:0.7
	});
});

$(document).ready(function() {
  $('#loading').ajaxStart(function() {
    $(this).show();
  }).ajaxStop(function() {
    $(this).hide();
  });
});


    
