// jCart v1.3
// http://conceptlogic.com/jcart/

$(document).ready(function(){

	var JCART = (function() {

		// This script sends Ajax requests to config-loader.php and relay.php using the path below
		// We assume these files are in the 'jcart' directory, one level above this script
		// Edit as needed if using a different directory structure
		var path = 'includes',
			container = $('#basketItemsWrap'),
			token = $('[name=jcartToken]').val(),
			tip = $('#jcart-tooltip');

		var config = (function() {
			var config = null;
			$.ajax({
				url: path + '/config-loader.php',
				data: {
					"ajax": "true"
				},
				dataType: 'json',
				async: false,
				success: function(response) {
					config = response;
				},
				error: function() {
					alert('Ajax error: Edit the path in jcart.js to fix. (e1.1)');
				}
			});
			return config;
		}());

		var setup = (function() {

			// Remove the update and empty buttons since they're only used when javascript is disabled
			$('#jcart-buttons').remove();

			// Default settings for Ajax requests
			$.ajaxSetup({
				type: 'POST',
				url: path + '/relay.php',
				success: function(response) {
					// Refresh the cart display after a successful Ajax request
					container.html(response);
					$('#jcart-buttons').remove();
				},
				// See: http://www.maheshchari.com/jquery-ajax-error-handling/
				error: function(x, e) {
					var s = x.status, 
						m = 'Ajax error: ' ; 
					if (s === 0) {
						m += 'Check your network connection.';
					}
					if (s === 404 || s === 500) {
						m += s;
					}
					if (e === 'parsererror' || e === 'timeout') {
						m += e;
					}
					alert(m);
				}
			});
		}());

		// Check hidden input value
		// Sent via Ajax request to jcart.php which decides whether to display the cart checkout button or the PayPal checkout button based on its value
		// We normally check against request uri but Ajax update sets value to relay.php

		// If this is not the checkout the hidden input doesn't exist and no value is set
		var isCheckout = $('#jcart-is-checkout').val();

		function add(form) {
			// Input values for use in Ajax post
			var itemQty = form.find('[name=' + config.item.qty + ']'),
			    itemAdd = form.find('[name=' + config.item.add + ']');

                        if ($("#slidingTopContent").is(":visible")) {
        			// Add the item and refresh cart display
        			$.ajax({
        				data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
        				success: function(response) {

        					// Momentarily display tooltip over the add-to-cart button
        					if (itemQty.val() > 0 && tip.css('display') === 'none') {
        						tip.fadeIn('100').delay('400').fadeOut('100');
        					}

        					container.html(response);
        					$('#jcart-buttons').remove();
        				}
        			});
                        } else {
                            $("#slidingTopContent").slideToggle("slow", function(){

				$("#slidingTopFooterLeft").html('<img src="images/arrow-up.png" alt="Hide Basket" /> <a href="aaa.htm" onclick="return false;" id="slidingTopTrigger">Hide Basket</a>');
				$("#notificationsLoader").html('<img src="images/loader.gif">');

        			// Add the item and refresh cart display
        			$.ajax({
        				data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
        				success: function(response) {
        
        					// Momentarily display tooltip over the add-to-cart button
        					if (itemQty.val() > 0 && tip.css('display') === 'none') {
        						tip.fadeIn('100').delay('400').fadeOut('100');
        					}
        
        					container.html(response);
        					$('#jcart-buttons').remove();
        				}
        			});
        
				$("#slidingTopTrigger").fadeTo(4000, 1, function(){
					$("#slidingTopContent").delay(4000).slideToggle("slow", function(){
						$("#slidingTopFooterLeft").html('<img src="images/arrow-down.png" alt="Show Basket" /> <a href="aaa.htm" onclick="return false;" id="slidingTopTrigger">Show Basket</a>');
					});

				});
                             });
                        }

		}

		function update(input) {
			// The id of the item to update
			var updateId = input.parent().find('[name="jcartItemId[]"]').val();
			var updateSize = input.parent().find('[name="jcartItemSize[]"]').val();
			var updatePattern = input.parent().find('[name="jcartItemPattern[]"]').val();

			// The new quantity
			var newQty = input.val();

			// As long as the visitor has entered a quantity
			if (newQty) {

				// Update the cart one second after keyup
				var updateTimer = window.setTimeout(function() {

					// Update the item and refresh cart display
					$.ajax({
						data: {
							"jcartUpdate": 1, // Only the name in this pair is used in jcart.php, but IE chokes on empty values
							"itemId": updateId,
							"itemSize": updateSize,
							"itemPattern": updatePattern,
							"itemQty": newQty,
							"jcartIsCheckout": isCheckout,
							"jcartToken": token
						}
					});
				}, 1000);
			}

			// If the visitor presses another key before the timer has expired, clear the timer and start over
			// If the timer expires before the visitor presses another key, update the item
			input.keydown(function(e){
				if (e.which !== 9) {
					window.clearTimeout(updateTimer);
				}	
			});
		}

		function remove(link) {
			// Get the query string of the link that was clicked
			var queryString = link.attr('href');
			queryString = queryString.split('=');

			// The id of the item to remove
			var removeId = queryString[1];

			// Remove the item and refresh cart display
			$.ajax({
				type: 'GET',
				data: {
					"jcartRemove": removeId,
					"jcartIsCheckout": isCheckout
				}
			});
		}

		// Add an item to the cart
		$('.jcart').submit(function(e) {
                        if ($("#my-item-qty").val()=='') {
                          $("#my-item-qty").val('1');
                        }

			add($(this));
			e.preventDefault();
		});

		// Prevent enter key from submitting the cart
		container.keydown(function(e) {
			if(e.which === 13) {
				e.preventDefault();
			}
		});

		// Update an item in the cart
		container.delegate('[name="jcartItemQty[]"]', 'keyup', function(){
			update($(this));
		});

		// Remove an item from the cart
		container.delegate('.jcart-remove', 'click', function(e){
			remove($(this));
			e.preventDefault();
		});

	}()); // End JCART namespace

        	$(".ppdSizes").live('click',  function() {
          $("div.ppdSizes").css("border" , "solid .1em #3c3c3c");
          $(this).css("border", "solid white 1px");
            var text = $(this).text();
            $("#my-item-size").val(text);

            if ($("#my-item-size").val()!="" && $("#my-item-pattern").val()!="") {
               $("#my-add-button").attr("value","Add to Cart");
               $("#my-add-button").removeAttr("disabled");
            }
            temp = $("#productID").val();
            $("#my-item-id").val(temp);
        });

	$(".ppdPrints").live('click',  function() {
          $("div.image44").find("img").fadeTo('fast', .4);
          $(this).fadeTo('fast', 1);

          var text = $(this).attr('id');
          text = text.substr(10);
          pID = text.substr(0,text.indexOf('-'));
          pattern = text.substr(text.indexOf('-')+1);
          $("#ppdSize").html("<p>Sizes Available:</p>" + patternSizeValues[pID]);
          $(".ppdSizes:eq(0)").css("border", "solid white 1px");

          $("#my-item-patternID").val(pID);
          $("#my-item-pattern").val(pattern);

          if ($("#my-item-size").val()!="" && $("#my-item-pattern").val()!="") {
             $("#my-add-button").attr("value","Add to Cart");
             $("#my-add-button").removeAttr("disabled");    ;
          }
          temp = $("#productID").val();
          $("#my-item-id").val(temp);
        });

	$("#slidingTopTrigger").live("click", function(event) {
      	$("#slidingTopContent").slideToggle("slow", function(){
			if ($("#slidingTopContent").is(":visible")) {
				$("#slidingTopFooterLeft").html('<img src="images/arrow-up.png" alt="Hide Basket" /> <a href="no-js.htm" onclick="return false;" id="slidingTopTrigger">Hide Basket</a>');
                                $("#slidingTopFooterLeft").css('margin', '15px 0 0 20px');
			} else {
				$("#slidingTopFooterLeft").html('<img src="images/arrow-down.png" alt="Show Basket" /> <a href="no-js.htm" onclick="return false;" id="slidingTopTrigger">Show Basket</a>');
			}
		});
    });
	


	$("#basketItemsWrap li img").live("click", function(event) {
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 			= productIDValSplitter[1];
	
		$.ajax({
		type: "POST",
		url: "inc/functions.php",
		data: { productID: productIDVal, action: "deleteFromBasket"},
		success: function(theResponse) {
			
			$("#productID_" + productIDVal).hide("slow",  function() {
				$(this).remove();
			});
		
		
		}
					
		});  	
		
	});

}); // End the document ready function
