$(document).ready(function() {
  // Obscure Emails
  $('span.email').each(function(i) {
    var address = $(this).text();
    address = address.replace("| [at] |", "@");
    var atitle = $(this).attr("title").split("//");
    stext = atitle[0].replace("| [at] |", "@");
    stitle = (atitle.length == 1) ? atitle[0].replace("| [at] |", "@") : atitle[1].replace("| [at] |", "@");
    
    $(this).after("<a href=\"mailto:"+address+"\" title=\""+stitle+"\">"+stext+"</a>");
    $(this).remove();
  });
  
  $("#csvclub h5 a").click(function() {
    toggleFade("#csvModal");
    return false;
  });
  $("#csvModal .close").click(function() {
    toggleFade("#csvModal");
    return false;
  });
  $("li.purchase a").click(function() {
    toggleFade("#purchaseModal");
    return false;
  });
  $("#purchaseModal .close").click(function() {
    toggleFade("#purchaseModal");
    return false;
  });
  
  // Empty the cart without modal
  $(".fc_empty_cart").click(function() {
    $.getJSON('https://edenhall.foxycart.com/cart?output=json&cart=empty&callback=?' + fc_AddSession(), function(data) {
      fc_json = data;
      if ($("#purchase #productForm").length > 0) {
        $("input.quantity").val(0).parent("td").parent("tr").removeClass("selected");;
        gatherPrices();
      }
      fc_UpdateCart("edenhall.foxycart.com");
    });
    return false;
  });
  
  jQuery("#purchaseModal #productForm").submit(function(){
    MyFoxyData = jQuery(this).serialize(false);
    MyFoxyID = jQuery(this).attr('id');
    // if they defined fc_PreProcess(), let them process the form data before we pass it along
    if (typeof(fc_PreProcess) == 'function') { 
      if (!fc_PreProcess(MyFoxyData, MyFoxyID)) {
        return false;
      }
    }  
    if( $(".jaxxy").length == 0) {
      $('<p class="jaxxy" style="display:none;">Adding to cart</p>').insertAfter($(this).find('input#submit'));
    }
    toggleFade(".jaxxy");
    $.getJSON('https://edenhall.foxycart.com/cart?' + MyFoxyData + '&output=json&callback=?' + fc_AddSession(), function(data){
      fc_json = data;
      fc_UpdateCart("edenhall.foxycart.com");
      if( $(".jaxxy").length ) {
        $(".jaxxy").addClass("success").html("Added successfully. <a href=\"/purchase\">Click to view your cart</a>");
        $(".jaxxy").animate({ opacity: 1.0 },5000).fadeOut(500, function() { $(this).remove(); });
      }
    });
    return false;
  });
  
  jQuery("#csvModal #csvForm").submit(function(){
    var showError = false;
    if ($(this).find("#csvName").val() == "") {
      $(this).find("#csvName").addClass("error").siblings("label").addClass("error");
      showError = true;
    } else {
      $(this).find("#csvName").removeClass("error").siblings("label").removeClass("error");
    }
    if ($(this).find("#csvEmail").val() == "" || !(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test( $(this).find("#csvEmail").val() ))) {
      $(this).find("#csvEmail").addClass("error").siblings("label").addClass("error");
      showError = true;
    } else {
      $(this).find("#csvEmail").removeClass("error").siblings("label").removeClass("error");
    }
    if (showError) {
      $("#csvModal p#error").show();
      return false;
    } else {
      $("#csvModal p#error").hide();
      var dataString = 'CSVName='+ $(this).find("#csvName").val() + '&CSVEmail=' + $(this).find("#csvEmail").val();
      $.ajax({
        type: "POST",
        url: "process_csv.asp",
        data: dataString,
        success: function(data) {
          $("#csvModal h3").text("Thanks!").after("<p>"+data+"</p>");
          $("#csvForm").hide();
        }
      });
      return false;
      //return true;
    }
  });
  
  jQuery("#fc_update_cart").click(function(){
    MyFoxyData = jQuery("#productForm").serialize(false);
    MyFoxyData = MyFoxyData.replace("cart=checkout&","");
    MyFoxyID = jQuery("#productForm").attr('id');
    // if they defined fc_PreProcess(), let them process the form data before we pass it along
    if (typeof(fc_PreProcess) == 'function') { 
      if (!fc_PreProcess(MyFoxyData, MyFoxyID)) {
        return false;
      }
    }  
    if( $(".jaxxy").length == 0) {
      $('<p class="jaxxy" style="display:none;">Updating cart</p>').insertAfter($(this));
    }
    toggleFade(".jaxxy");
    $.getJSON('https://edenhall.foxycart.com/cart?' + MyFoxyData + '&output=json&callback=?' + fc_AddSession(), function(data){
      fc_json = data;
      fc_UpdateCart("edenhall.foxycart.com");
      if( $(".jaxxy").length ) {
        $(".jaxxy").addClass("success").html("Cart updated. Feel free to continue to browse the site.");
        $(".jaxxy").animate({ opacity: 1.0 },5000).fadeOut(500, function() { $(this).remove(); });
      }
    });
    return false;
  });
  
  PAUSEACTION = false;
  
  $("#mapIn").click(function() {
    var currentMap = $("#maps").children("img:visible:first");
    if ($(currentMap).attr("id") != "map_4" && !PAUSEACTION) {
      PAUSEACTION = true;
      alterGoogleMaps($(currentMap).next("img").attr("id"));
      $(currentMap).next("img").show();
      $(currentMap).fadeOut("slow", function() {PAUSEACTION = false;});
      if ($(currentMap).next("img").attr("id") == "map_4") {
        $("#mapIn").fadeOut("slow");
      } else {
        if ($("#mapOut").is(":hidden")) {
          $("#mapOut").fadeIn("slow");
        }
      }
    }
    return false;
  });
  
  $("#mapOut").click(function() {
    var currentMap = $("#maps").children("img:visible:first");
    if ($(currentMap).attr("id") != "map_1" && !PAUSEACTION) {
      PAUSEACTION = true;
      alterGoogleMaps($(currentMap).prev("img").attr("id"));
      $(currentMap).prev("img").fadeIn("slow",function() {
        $(currentMap).hide();
        PAUSEACTION = false;
      });
      if ($(currentMap).prev("img").attr("id") == "map_1") {
        $("#mapOut").fadeOut("slow");
      } else {
        if ($("#mapIn").is(":hidden")) {
          $("#mapIn").fadeIn("slow");
        }
      }
    }
    return false;
  });
  
  alterGoogleMaps("map_1");
  
});

$(window).load(function() {
  if( $("#vineyard.map").length > 0) {
    $("#mapLoading").fadeOut("slow");
    $("#mapHolder #actions .right").fadeIn("slow");
    $("#mapHolder #maps #map_1").fadeIn("slow");
  }
});


function alterGoogleMaps(level) {
  if (level == "map_3") {
    $("#googleMapsLink").attr("href","http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Taste+Eden+Valley,+Angaston,+South+Australia,+Australia&sll=-34.674017,139.065928&sspn=0.026153,0.055747&g=-34.679124,139.063089&ie=UTF8&hq=Taste+Eden+Valley,&hnear=Angaston+South+Australia,+Australia&ll=-34.500686,139.04785&spn=0.006331,0.013937&t=h&z=17&iwloc=A").text("View our Cellar Door in Google Maps");
  } else {
    $("#googleMapsLink").attr("href","http://maps.google.com/maps?q=-34.679124,139.063089&num=1&t=h&sll=-34.66357,139.065757&sspn=0.026156,0.055747&ie=UTF8&ll=-34.674017,139.065928&spn=0.026153,0.055747&z=15").text("View the Avon Brae Vineyards in Google Maps");
  }
}

function toggleFade(element) {
  if ($(element).is(":visible")) {
    $(element).fadeOut("slow");
  } else {
    $(element).fadeIn("slow");
  }
}

$(document).ready(function(){
	
	// bind the recalc function to the quantity fields
  $("input[name*=quantity]").bind("keyup", update);
	
	// get all the prices and put them in a nice hash
	gatherPrices();
	
});

function fc_BuildFoxyCart() {
  if ($("#purchase #productForm").length > 0) {
    // Pull in the JSON object
		if (fc_json.products.length > 0) {
		  for (var i in fc_json.products) {
		    var theId = $("input[value='" + fc_json.products[i].name + "']").attr('name');
		    theId = theId.split(':',1);
		    $("#quantity_"+theId).attr('value',fc_json.products[i].quantity);
		    $("#quantity_"+theId).parent("td").parent("tr").addClass("selected");
		    update.apply($("#quantity_"+theId)[0]);
		  }
		  //$("#fc_total_cost").html("$"+fc_CurrencyFormatted(fc_json.total_price))
		}
	}
	// Google Analytics
	var pageTracker = _gat._getTracker();
	$.getJSON('https://' + FoxyDomain + '/cart?cart=view' + fc_AddSession() + '&h:ga=' + escape(pageTracker._getLinkerUrl('', true)) + '&output=json&callback=?', function(data){});
}

function gatherPrices() {
  
  itemPrices = {};
  itemTotals = {};
  totalUnits = 0;
  totalCost = 0;
  
  // update shipping if the postcode exists
 // checkPostcode();
  // loop through each product, and save to hash
  $("input[name*=quantity]").each(function(){
    name = getInt(this.name);
    itemPrices[name] = {};
    itemTotals[name] = {};
    
    itemPrices[name]["bottle"] = parseInt($(this).nextAll("input[name*=price]").val());
    //itemPrices[this.id]["case"] = $("."+this.id+"_case").parseNumber();
    update.apply(this);
  });
}

function update(target) {
  var item;
  // logic to see if this is direct or from key binding
  if (this.id == undefined) {
    item = target;
  } else {
    item = this;
  }
  
  var units;
  if (item.value == "") {
    units = 0;
  } else {
    sNum = item.value;
    if (!isNaN(parseInt(sNum))) {
      if (sNum.toString().indexOf('.')!=-1 || parseInt(parseInt(sNum)) !== Number(sNum)) {
        $(item).val(parseInt(sNum));
      }
      units = parseInt(sNum);
    } else {
      units = 0;
      $(item).val(0);
    }
  }
  
  if (units > 0) {
		$(item).parent("td").parent("tr").addClass("selected");
  } else {
		$(item).parent("td").parent("tr").removeClass("selected");
  }
  
  // calculations
  var result = itemPrices[getInt(item.name)]["bottle"] * units;
  itemTotals[getInt(item.name)]["cost"] = result;
  itemTotals[getInt(item.name)]["unit"] = units;
  
  $("#total_"+getInt(item.name)).text(formatCurrency(itemTotals[getInt(item.name)]["cost"]));
  total();
}

function total() {
  if ($("#purchase #productForm").length > 0) {
    totalCost = 0;
    totalUnits = 0;
    for(var i in itemTotals) {
      totalCost += itemTotals[i]["cost"];
      totalUnits += itemTotals[i]["unit"];
    }
    
    $("#fc_total_products").text(totalUnits);
    $("#fc_total_cost").text(formatCurrency(totalCost));
  }
}

function formatCurrency(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + "$" + s;
	return s;
}

function getInt(string) {
  return string.split(':',1);
}
