var baseUrl="";

$(function() {

	if (window.location.protocol=="https:") {
		baseUrl = "https://"+window.location.host+"/haggusandstookles/";
	}
	
	$("#disc_table").hide();
	$("#kindy_table").hide();
	
	$('#cloud a').tagcloud({
    size: {start: 14, end: 30, unit: "px"},
    color: {start: '#EF86B2', end: '#EF2C8F'}
	});
	
	$('#cloud').show();
	
	var dontSubmitMoreThanOnce=false;
	$("#coupon_code").keyup(function(e) {
		if (e.keyCode==13) {
			//console.log("before: "+dontSubmitMoreThanOnce);
			//if (dontSubmitMoreThanOnce==true) return;
			//console.log("after: "+dontSubmitMoreThanOnce);
			//dontSubmitMoreThanOnce=true;

			var cleanText=$("#coupon_code").val().replace(/\n/g, '');

			//Hack to stop hitting Enter on alert box from resending Ajax request
			if ($("#coupon_code").val()==cleanText)
			{
				//dontSubmitMoreThanOnce=false;
				return;
			}

			$("#coupon_code").val(cleanText);
			applyDiscount();
			//alert("do apply discount thing");
			return;
		}
	});


	$("#disc").click(function(e){
		if ($("#coupon_code").val()=="")
		{
			var gst = $("#totalprice").val() / 11;
			$("#finalTax").html("$"+gst.toFixed(2));
		}

		e.preventDefault();
		applyDiscount();
	});

	function applyDiscount() {
		$("#disc_table").hide();
		$("#kindy_table").hide();

		$.getJSON("https://secure4.ingenuity.net.au/gabbyglamour/app_disc.php?total_price="+$("#totalprice").val()+"&original_price="+$("#originalprice").val()+"&coupon_code="+$("#coupon_code").val()+"&finalTax="+$("#finalTax").html(),function(data){
		
		//dontSubmitMoreThanOnce=false;
		var errorMsg = data[0].result;
		if (errorMsg.length == 0)
		{
			var price = parseFloat(data[0].optionValue);
			var message = data[0].optionType;
			var discount = data[0].optionDiscount*1;
			var donation = data[0].optionDonationValue*1;
			var donationPercentage = data[0].optionDonation*1;
			var details = data[0].optionDetails;
			price += 1*$("#originalFreight").val();
			var tax = price / 11;
		
			if(message == "Donation")
			{
				$("#disc_table").hide();
				$("#kindy_text").html("Donation Coupon - " + donationPercentage + "% will be donated to: " + details);
				$("#kindy_price").html("$"+donation.toFixed(2));
				$("#kindy_table").show('slow');

				//var gst = $("#totalprice").val() / 11;
				//$("#finalTax").html("$"+gst.toFixed(2));
			}
			else if(message == "Discount")
			{
				$("#kindy_table").hide();
				$("#disc_text").html("Discount Coupon - " + details + "(" + discount + "%) - Total");
				$("#finalTax").html("$" + parseFloat(tax).toFixed(2));
				$("#totalLabelText").css("text-decoration", "line-through");
				$("#total_price").css("text-decoration", "line-through");
				$("#disc_price").html("$"+price.toFixed(2));
				$("#disc_table").show('slow');

				//var gst = price / 11;
				//$("#finalTax").html("$"+gst.toFixed(2));
			}
			else if(message == "Both")
			{
				
				$("#disc_text").html("Discount / Donation Coupon - " + details + "(" + discount + "%) - Total");
				$("#finalTax").html("$" + parseFloat(tax).toFixed(2));
				$("#totalLabelText").css("text-decoration", "line-through");
				$("#total_price").css("text-decoration", "line-through");
				
				$("#disc_price").html("$"+price.toFixed(2));
				$("#disc_table").show('slow');

				$("#kindy_text").html("Donation Coupon - " + donationPercentage + "% will be donated to: " + details);
				$("#kindy_price").html("$"+donation.toFixed(2));
				$("#kindy_table").show('slow');

				//var gst = price / 11;
				//$("#finalTax").html("$"+gst.toFixed(2));
			}
			else if(message == "Giftcard")
			{
				$("#gift_text").html("Gift Card - " + details + " - Total");
				$("#finalTax").html("$" + parseFloat(tax).toFixed(2));
				$("#totalLabelText").css("text-decoration", "line-through");
				$("#total_price").css("text-decoration", "line-through");
				$("#gift_price").html("$"+price.toFixed(2));
				$("#gift_table").show('slow');
			}
		} else
		{
			alert("Invalid Coupon: " + errorMsg);
		}
		});
		}
	
	$("#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 );
		});

	/*
	$(".addToCart").click(function(e) {
		e.preventDefault();

		$.get('ajax'+$(this).attr("href"),function(d) {
			if (d != "") alert(d);
			$("#cartDialog").fadeIn(200);
		});
	});
	*/

 
   $("#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(); 
		var giftname = $("input[name='giftwrap']:checked").attr("rel"); 

		var giftcard = $("input[name='giftcard']:checked").val(); 
		var gifttag = $("input[name='gifttag']:checked").val(); 
		var message = "Message:<br/>" + $("textarea[name='giftmessage']").val(); 

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

		if(special == "false")
	    {
			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) || !message)
	    {
			alert("Please select the Gift Wrap and Gift Tag 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;
	    }

		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="cart.php";
			});


  });

   //$("#AddToCart").click(AddToCart);
   //$("a.AddToCart").click(AddToCart);
   //function AddToCart(e) {
   
   $("#AddToCart").click(addToCart);
   $(".AddToCart").click(addToCart);
	
	$("input[type=radio]").click(function() {
		if ($(this).attr("name")=="paymethod") {
			if ($(this).val()=="Credit Card") $("#carddetails").show();
			else $("#carddetails").hide();
		} else if ($(this).attr("name")=="have_website") {
			if ($(this).val()=="1") $("#hiddenWebsite").show();
			else $("#hiddenWebsite").hide();
		} else if ($(this).attr("name")=="have_blog") {
			if ($(this).val()=="1") $("#hiddenBlog").show();
			else $("#hiddenBlog").hide();
		}
	});

	$("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").show("slow");
		$("#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").show("slow");
		$("#postal_address").val(""); 
		$("#postal_city").val("");
		$("#postal_state").val("");
		$("#postal_postcode").val("");
		$("#postal_country").val("Australia");
	});


	$("#yes_kids").focus(function(){
		$("#birthday1").show("slow");
	});
	$("#no_kids").focus(function(){
		$(".birthdays").hide("slow");
	});

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


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

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

	
	$('#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);
			}
		});
	});

	$("input[type=checkbox]").change(function() {
		if ($(this).attr("name")=="shippingbox" && $(this).attr("checked")==true) {
			$("#ship_street1").val($("#bill_street1").val());
			$("#ship_street2").val($("#bill_street2").val());
			$("#ship_suburb").val($("#bill_suburb").val());
			$("#ship_state").val($("#bill_state").val());
			$("#ship_postcode").val($("#bill_postcode").val());
			$("#ship_country").val($("#bill_country").val());
		}
	});

	// Date
	$(function()
	{
		var start = new Date();
		start.addDays(7);
		var end = new Date();
		end.addYears(2);
		$('.date-pick')
			.datePicker({startDate: start.asString(), endDate: end.asString(), createButton:false})
			.bind('click',
				function()
				{
					$(this).dpDisplay();
					this.blur();
					return false;
				}
			);
		// tl is the default so don't bother setting it's position
		$('#custom-offset').dpSetOffset(10, -800);
	});

	// Book Party
	$("#bookParty").click(function(e) {
	   e.preventDefault();
	   // Check that the terms and conditions are checked
	   if(!$("#terms").attr("checked")) {
			alert("You must accept the terms and conditions before proceeding");
			return;
	   }
		$.get('ajaxcart.php?action=add&prod_id='+$("#prod_id").val()+'&prodqty='+$("#prodqty").val(),function(d) {
		});
		$("#bookAPartForm").submit();
   });

	// Book Party Map
	$("area.capital").click(function(e) {
		// Prevent default
		e.preventDefault();
		var city = $(this).attr("href");
		
		// Get the regions for the selected city
		$.getJSON("regionFilterSelect.php",{ city: city}, function(j){
			var myOptions = '';
			for (var i = 0; i < j.length; i++) {
				try {
					myOptions += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
				} catch (exc) {
					//No one likes IE6
				}
			}
			if(j.length>1)
			{
				$("#noRegion").hide()
				$("#region").html(myOptions);
				$("tr.hiddenArea").show();
			}
			else{
				$("tr.hiddenArea").hide();
				$("#noRegion").show();
				var sorry = "<p>We are still looking for a salon in your area to do Gabby Glamour Parties.  Maybe you could suggest your local salon and we would be happy to contact them to arrange your party.  Please email us their details through our <a href='http://www.gabbyglamour.com/join-our-team/'>Join Our Team</a> page</p> <br /><p>Or you might want to consider doing a Gabby Glamour Party at home.  Please <a href=mailto:info@gabbyglamour.com>send us your details</a> and we will be happy to make contact with you.</p>";
				$("#noRegion").html(sorry);
			}
		});

		
	});

	$("#region").change(function(e){
		var region = $(this).val();
		var page = $('#page').val();
		// Region was clicked, so load hairdressers
		$.get("hairFilterSelect.php",{ region: region, page: page}, function(j){
			$('.hiddenHair').show();
			$("#hairdresserDetails").html(j);
		})
	});
		
	$("#eregion").click(function(e){
		var region = $(this).val();
		// Region was clicked, so load hairdressers
		$.getJSON("hairFilterSelect.php",{ region: region}, function(j){
			var myOptions = '';
			console.log($("#hairdressers").val());
			if ($("#region").val()==null)
			{
				// Use Hairdress details
				for (var i = 0; i < j.length; i++) {
					try {
						myOptions += '<li>' + j[i].optionDisplay + '</li><br />';
					} catch (exc) {
						//No one likes IE6
					}
				}
				$("#hairdresserDetails").html(myOptions);

			} else {
				for (var i = 0; i < j.length; i++) {
				console.log('for');
					try {
						myOptions += '<li style="list-style-type:none;"><input type="radio" name="hairdresser" value="' + j[i].optionValue + '" />' + j[i].optionDisplay + '</li><br />';
					} catch (exc) {
						//No one likes IE6
					}
				}
				$("#hairdresserDetails").html(myOptions);
				console.log(myOptions)
				}
			$("tr.hiddenHair").show();
		});
	});

	// Slideshow
	$(".pics").cycle({ 
		fx:    'fade', 
		speed:  2500
	 });
	 
	 // party Slideshow
	$("#partySlides").cycle({ 
		fx:    'fade', 
		speed:  2500,
		before: onBefore
	 });
	 
	function onBefore(){
		$("#partySlides_info").html($(this).attr('rel'));
	}


	function addToCart(e){
	e.preventDefault();
		
		var proceed = true;
		var href = 'http://www.gabbyglamour.com/ajax'+$(this).attr("href");
		   $("select.option_id").each(function (i) {
		   //console.log($(this).find("option:selected").text()+": "+$(this).val());
		   //console.log($(this).attr("rel")+": "+$(this).val());
		   if ($(this).val().length=="") {
			   alert($(this).attr("rel")+" is required");
			   
			   proceed = false;
			   return false;
		   }
			
			href += '&option_id='+$(this).val();
		   //$(this).attr("href", $(this).attr("href")+"&option_"+i+"="+$(this).val());
	   });
	   if (proceed){
		   href += "&prodqty="+$("#prodqty").val();
			$.get(href,function(d) {
				if (d != "") alert(d);
				$("#cartDialog").fadeIn('slow');

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

				//$.get("http://www.gabbyglamour.dev/calculateWeight.php", function(d) {
					//$("#weight").val(d);
					//displayPostageCost();
				//});

			});
			//$("#shopCartTable").load("http://www.gabbyglamour.dev/cartTable.php");

	   }
	}
	
		
});
