var baseUrl="";

function startList() {
	if (document.all && document.getElementById) {
		navRoot = document.getElementById("dmenu");
		for (i=0; i < navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}

$(function() {

	if (window.location.protocol=="https:") {
		baseUrl = "https://"+window.location.host+"/haggusandstookles/";
	}
	
	$("#hideCartDialog").click(function(e) {
		e.preventDefault();
		$("#cartDialog").fadeOut(200);

		//IE6 display bug workaround
		$("select").each(function() {
			$(this).show();
		});
	});
	
	$("#friend").click(function(e){
		e.preventDefault();
		window.open( $(this).attr('href'),width=350,height=250 );
	});

    $("input[name='giftwrap'], label.giftwrap").click(function(e) {
		$("input[name='xmasgifttag']").each( function() {
				this.checked = false;
		});	
		$("input[name='xmasgiftwrap']").each( function() {
				this.checked = false;
		});	
	});		
 
    $("input[name='giftcard'], label.giftcard").click(function(e) {
		$("input[name='gifttag']").each( function() {
				this.checked = false;
		});		
		$("input[name='xmasgifttag']").each( function() {
				this.checked = false;
		});	
		$("input[name='xmasgiftwrap']").each( function() {
				this.checked = false;
		});	
	});
	
    $("input[name='gifttag'], label.gifttag").click(function(e) {
		$("input[name='giftcard']").each( function() {
				this.checked = false;
		});		
		$("input[name='xmasgifttag']").each( function() {
				this.checked = false;
		});	
		$("input[name='xmasgiftwrap']").each( function() {
				this.checked = false;
		});	
	
	});	
	
	$("input[name='xmasgifttag'], label.xmasgifttag").click(function(e) {
		$("input[name='giftcard']").each( function() {
				this.checked = false;
		});		
		$("input[name='gifttag']").each( function() {
				this.checked = false;
		});		
		$("input[name='giftwrap']").each( function() {
				this.checked = false;
		});	
	
	});	
	$("input[name='xmasgiftwrap'], label.xmasgiftwrap").click(function(e) {
		$("input[name='giftcard']").each( function() {
				this.checked = false;
		});		
		$("input[name='gifttag']").each( function() {
				this.checked = false;
		});		
		$("input[name='giftwrap']").each( function() {
				this.checked = false;
		});	
	});	
 
   $("#giftwrapbutton").click(function(e) {

	   e.preventDefault();
		var prodid;
		var giftcardtype;
		var giftname;
		var message;
		var result;

		// get values
		var giftwrap = $("input[name='giftwrap']:checked").val(); 
		if (giftwrap == 0) {var giftwrap = undefined;}
		
		var xmasgiftwrap = $("input[name='xmasgiftwrap']:checked").val(); 
		if (xmasgiftwrap == 0) {var xmasgiftwrap = undefined;}

		if (xmasgiftwrap)
		{
			var giftname = $("input[name='xmasgiftwrap']:checked").attr("rel"); 
		} else
		{
			var giftname = $("input[name='giftwrap']:checked").attr("rel"); 
		}
		var giftcard = $("input[name='giftcard']:checked").val(); 
		if (giftcard == 0) {var giftcard = undefined;}

		var gifttag = $("input[name='gifttag']:checked").val(); 
		if (gifttag == 0) {var gifttag = undefined;}
		
		var xmasgifttag = $("input[name='xmasgifttag']:checked").val(); 
		if (xmasgifttag == 0) {var xmasgifttag = undefined;}
		
		var message = "Message:<br/>" + $("textarea[name='giftmessage']").val(); 

		var special = $("input[name='wholeorder']:checked").val(); 
		var specialmessage = $("textarea[name='giftspecial']").val(); 

		if(specialmessage != "")
	    {
			message += "<br/><br/>Special Instructions:<br/>" + specialmessage;
		}

				
		// they need to select a gift wrap option and a gift tag OR card to proceed
		if(  ((!giftwrap || (!giftcard && !gifttag)) && (!xmasgiftwrap || !xmasgifttag )))
	    {
			alert("Please select the Gift Wrap and Gift Tags or Card you would like to order and then type in a message"); //
			return false;
	    }
		else if(giftcard && gifttag)
	    {
			alert("Please select only one of either a Large Gift Card or Small Gift Card/Tag to go with your Gift Wrap.");

			//$("input[name='giftcard']").each( function() {
			//		this.checked = false;
			//});
			//$("input[name='gifttag']").each( function() {
			//		this.checked = false;
			//});
			return false;
	    } else if((giftcard || giftwrap || gifttag) && (xmasgiftwrap || xmasgifttag))
		{
			alert("Sorry, you can't mix and match xmas wrapping with normal gift wrapping");
			return false;
		}
		

		
		if (xmasgifttag)
		{
			prodid = '2859';
			giftname += " - " + $("input[name='xmasgifttag']:checked").attr("rel");			
		} else if (giftcard)
		{
			prodid = '2858';
			giftname += " - " + $("input[name='giftcard']:checked").attr("rel");
		}
		else
	    {
			prodid = '2857';
			giftname += " - " + $("input[name='gifttag']:checked").attr("rel");
	    }


		$.get("ajaxcart.php", { prod_id: prodid, action: "add", pdetails: giftname, pdesc: message},function(d) {
				$("#shopCartTable").load("cartTable.php");
				window.location.href="cart.php";
			});


  });

   $("#btnAddToCart2").click(function(e) {
	   var proceed = true;
	   e.preventDefault();
	   $("select.option_id").each(function (i) {
		   if ($(this).val().length=="") {
			   alert($(this).attr("rel")+" is required");
			   proceed = false;
			   return false;
		   }
		   $("#btnAddToCart2").attr("href", $("#btnAddToCart2").attr("href")+"&option_"+i+"="+$(this).val());
	    });

		if (proceed){
			if ($('.option_id').length != 0) {
				// product HAS options
				// get stock for product with option
				sendid = $('.option_id').val();
				ptype = "option";
			} else {
			// product has NO options
				sendid = $('#prodid').val();
				ptype = "nooption";
			}

			$.get("get-stock.php",{sendid: sendid, prodtype: ptype}, function(data){
				
				// OVERWRITE STOCK CONTROL FOR NOW!!
				//stock = "10000";
				stock = parseInt(data);
				

				prodqty = parseInt($('#prodqty').val());

				if(prodqty > stock)
				{
					notEnoughStock(stock, prodqty, sendid, ptype);
				}
				else
				{

					// add prod qty
					$("#btnAddToCart2").attr("href", $("#btnAddToCart2").attr("href")+"&prodqty="+$("#prodqty").val());				
					addToCart();

					// reset
					$("#btnAddToCart2").attr("href", $("#baseAddToCartHref").val());				
				}
			
			});		
		}
   });


   $("#newsletterSubscribe").click(function(e) {
		console.log((!$('#newsletterEmail').val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)));
		var proceed = true;
		var alertMessage = "<p>";
		e.preventDefault();
		
		if (!$('#newsletterEmail').val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
			alertMessage += "Error email not valid<br />";
		}
		if ($('#newsletterName').val() == "") {
			alertMessage += "Error please enter name<br />";
		}
		
		if ($('#captcha').val() != '5') {
			alertMessage += "Error incorrect answer to security question<br />";
		}
		
		if (alertMessage.length > 3) {
			alertMessage += '</p><p align="center"><a href=\'javascript:$("#newsletterDialog").fadeOut(200);\'>Close</a></p>';
			$("#newsletterDialog").html(alertMessage);
			$("#newsletterDialog").fadeIn(200);
			//alert(alertMessage);
			return false;
		} else
		{
			$.get('/newsletter-subscribe.php',{ajax: "1", email: $('#newsletterEmail').val(), name: $('#newsletterName').val()}, function(data) {
				$('.result').html(data);
				//alert("Data Loaded: " + data);
			});
			
			$("#newsletterDialog").html("<p>Thank you for joining our newsletter list, we look forward to talking to you soon.</p><p align='center'><a href=\"/\">Close</a></p>");
			$("#newsletterDialog").fadeIn(200);
		}

	});		


  function notEnoughStock(stock, prodqty, sendid, ptype){
	var optionuse;
	if(ptype == "option")
	  {
			optionuse = $('.option_id').val();
	  }
	  else
	  {
		  optionuse = "";
	  }
		$("#stockDialog").load("lowStockTable.php", { stock: stock, qty: prodqty, prodid: $('#prodid').val(), optionid: optionuse, ptype: ptype }, function() { 
			
			$("#hideStockDialog").click(attachHideLink);
			$('#backorderSubmit').click(attachSubmitLink);
			
		});

	$("#stockDialog").fadeIn(200);

   }

function attachSubmitLink (e){
	var data = decodeURIComponent($(".backorderForm").serialize());
	if ($("#backorder_email").val() != "") {
	$.post("backorder.php", data, function(){ 
		$('.backorderForm').html("<p>Thank you, your backorder has been lodged and you will be notified via email when more stock is available.</p>");
	});
	}
  return false;
}


	function attachHideLink (e){ 
		e.preventDefault();
		$("#stockDialog").fadeOut(200);

		//IE6 display bug workaround
		$("select").each(function() {
			$(this).show();
		});
	}

  function addToCart(){
		$.get('ajax'+$("#btnAddToCart2").attr("href"),function(d) {
			$("#cartDialog").fadeIn(200);

			//IE6 display bug workaround
			$("select").each(function() {
				$(this).hide();
			});
			$("#shopCartTable").load("cartTable.php");
		});
   }

	
	$("table.cart").find("td").each(function(i) {
		if ($(this).text().substring(0,1)=="$" || $(this).text().substring(0,2)=="-$") 
		{
			$(this).css("text-align", "right");
			$(this).css("font-size", "14px");
		}
	});

	$('input:checkbox').click(function () {
		if ($(this).attr("name")=="yesgiftwrap" && this.checked == true) {
			window.location="giftwrapping.php?cat_link=Gifts&sub_link=Gift-wrapping";
		}
	});


	$("#referral").change(function(){
		switch($("#referral").val()){
			case "friend":
				$("#moreinfo").show();
				$("#moreinfo").val("Please enter the person's name");
				break;
			case "online":
				$("#moreinfo").show();
				$("#moreinfo").val("Please enter the site");
				break;
			case "magazine":
				$("#moreinfo").show();
				$("#moreinfo").val("Please enter the magazine's name");
				break;
			case "kindergarten":
				$("#moreinfo").show();
				$("#moreinfo").val("Please enter the kindergarten's name");
				break;
			case "other":
				$("#moreinfo").show();
				$("#moreinfo").val("Where did you hear about us");
				break;
			default:
				$("#moreinfo").hide();
		}
	});

	$("#moreinfo").focus(function(){
		$("#moreinfo").val("");
	});

	$("#asabove").click(function(){
		$("#postal").slideDown(400);
		$("#postal_first_name").val($("#first_name").val()); 
		$("#postal_surname").val($("#surname").val()); 
		$("#postal_address").val($("#address").val()); 
		$("#postal_city").val($("#city").val());
		$("#postal_state").val($("#state").val());
		$("#postal_postcode").val($("#postcode").val());
		$("#postal_country").val($("#country").val());
	});
	$("#notasabove").click(function(){
		$("#postal").slideDown(400);
		$("#postal_first_name").val(""); 
		$("#postal_surname").val("");  
		$("#postal_address").val(""); 
		$("#postal_city").val("");
		$("#postal_state").val("");
		$("#postal_postcode").val("");
		//$("#postal_country").val("Australia");
	});

	/*

	$(".birthdaypicker").datepicker({ yearRange: '-18:+00', dateFormat: 'dd MM yy' });
	*/
	$(".birthdays").hide();

	$("#yes_kids").click(function(){
		$("#birthday1").slideDown(400);
	});
	$("#no_kids").click(function(){
		$(".birthdays").slideUp(400);
	});

	$(".birthdays a").click(function(e){
		e.preventDefault();
		var div = "#"+ $(this).attr("rel");
		$(div).slideDown(400);
	
	});


	$("#showspecial").hide();

	$("#yes_whole").focus(function(){
		$("#showspecial").hide("slow");
	});
	$("#no_whole").focus(function(){
		$("#showspecial").show("slow");
	});

	startList();
	
	$('#another_tip').hide();
	$("#tip_submit").click(function(){
		$.post("lodge_tips.php",
			{author: $('#author').val(), email: $('#email').val(), subject: $('#subject').val(), tip: $('#tip').val(), security_code: $('#security_code').val()},
			function(data){
				if(data == "<p>Incorrect security code, please try again</p>"){
					$('#response').html(data);
				}else{
					$('#response').html(data);
					$('#another_tip').show();
					$('#lodge_tip').hide();
				}
		})
	})

	$("#another_tip a").click(function(e){
		e.preventDefault();
		$('#lodge_tip').show();
		$('#another_tip').hide();
	});



	// Slide toggle sub menus in left hand menu
	$("#navlist").find("a").each(function() {
		$(this).click(function(e) {
			if ($(this).siblings(".subnavlist").length>0) {
				e.preventDefault();
				$(this).siblings(".subnavlist").slideToggle(1000);
			}
		});
	});

});
