$(function () {
  $.boss = $.boss || {};

  $.extend($.boss, {
    alphaNum : function (string) {
      return string.replace(/[^a-zA-Z 0-9]+/g, "").replace(/ /gi,"").toLowerCase();  // temp fix for bug #39
    }
  });

  /* Preload Mid sized images */
  var images = [];
  $("div.product div.right div.bot li a").each(function () {
    images.push($(this).attr("href"));
  });
  $.preload(images);
  
  $("div.product div.right div.bot li a").click(function () {
    var img = $(this).attr("href"), large = $(this).attr("class").split("large:")[1].split(" ")[0],
    alt = $(this).find("img").attr("alt"), optRef;
    $("div.product div.BossImage a").empty();
    $("dl.cart option").each(function () {
      var opt = $.boss.alphaNum( $(this).text() ), cur = $.boss.alphaNum( img.split("/")[3].split(".")[0] );
      if (cur.indexOf(opt) > 0) {
        optRef = $(this);
        $(this).parent().highlightFade().val( $(this).val() )
		$("#productcode .current").html($(this).attr("id"));
      }
    });
	
	if (typeof optRef  == "undefined")  $("#productcode .current").html( $("#productcode .default").html() );
	
    $("div.product div.BossImage a").attr("href", large).append("<img alt=\"\" src=\"" + img + "\" />");
    
    /* Aroma dough */
   if ( $("#BossProduct-93").length ) {
     $("#variation").empty().append("<h5>" + optRef.text() + "</h5><p>" + alt + "</p>");
   }   
    return false;
  });

  $("select").each(function () {
    if ($(this).attr("name").indexOf("attSelect") > 0) {
      $(this).unbind("change").change(function () {
        var anchor = $("div.right div.bot li a[href*='" + $.boss.alphaNum( $(this).find(":selected").text() ) + "']");
        
        if (anchor.length == 0) var img = "/store/images/noimage.png", large = "/store/images/noimage-big.png";
        else  var img = anchor.attr("href"), large = anchor.attr("class").split("large:")[1].split(" ")[0];        
        $("div.product div.BossImage a").empty().attr("href", large).append("<img alt=\"\" src=\"" + img + "\" />");
		
        $("#productcode .current").html( $(this).find(":selected").attr("id") );
		
        if ( $("#BossProduct-93").length ) {
          var alt = anchor.find("img").attr("alt"), title = $(this).find(":selected").text();
          $("#variation").empty().append("<h5>" + title + "</h5><p>" + alt + "</p>");
        }
      });
    }
  });




  /*
    Ajax Cart.
  ---------------------------------- */
  $("dl.cart input.BossButton[type=submit]").click(function () {
    var that = this, params = $("#BossProductForm").serialize();
    /* Disable Form elements and notify user of progress */
    $(that).val("Please wait.").addClass("loading");
    $("select, input ",$("#BossProductForm")).attr("disabled", "true");
    $("div.cartinfo").hide();

    $.ajax({
      url : "/cart.html",
      data : params,
      type: "POST",
      success : function (data) {
        /* Gather some useful data. */
        data = data.split("<div id=\"CartInfo\" style=\"display:none;\">")[1].split("</div>")[0];
        var total = data.split("<span class=\"totalPrice\">")[1].split("</span>")[0], count = data.split("<span class=\"productCount\">")[1].split("</span>")[0];      
        var item = parseInt(count) == 1? "item" : "items";
        var output = "<p>You currently have <em>" + count + "</em> " + item + " in your cart with a total price of " + total + " (not including shipping). To manage your cart click <a href=\"/cart.html\">here</a>.</p>";
        $("div.cartinfo").empty().append(output).fadeIn();
        $(that).val("Add to cart").removeClass("loading");
        $("select, input ",$("#BossProductForm")).removeAttr("disabled");
      },
      error : function () {
        $("div.cartinfo").empty().append("An Error Has Occured, Please ensure you are connected to the internet. if the problem persists please contact the site owner.").fadeIn();
        $(that).val("Add to cart").removeClass("loading");
        $("select, input ",$("#BossProductForm")).removeAttr("disabled");
      }
    });
    return false;
  });



/*
  Refund Form
*/

$("form.ReturnForm").validate();
         
$("#removeitem").click(function () {
  $("dl.returnitem:last").remove();
  if ($("dl.returnitem").length == 1) $(this).attr("disabled", "disabled");
});

 $("#additem").click(function () {
          $("#removeitem").removeAttr("disabled");
          var id = "item" + ( $("dl.returnitem").length + 1 );
          var item = $("<dl class=\"returnitem\" id=\"" + id +"\"></dl>");
          /* Build new item */
          item.append("<dt><label for=\"" + id + "-code\">Item Code :</label></dt>");
          item.append("<dd><em>*</em><input type=\"text\" class=\"required\" name=\""+ id +"-Code\" id=\""+ id + "-code\"></dd>");
          item.append("<dt><label for=\"" + id + "-name\">Name :</label></dt>");
          item.append("<dd><em>*</em><input type=\"text\" class=\"required\" name=\"" + id + "-Name\" id=\"" + id + "-name\"></dd>");
          item.append("<dt><label for=\""+ id + "-qty\">Quantity :</label></dt>");
          item.append("<dd><em>*</em><input type=\"text\" class=\"required\" name=\"" + id + "-Quantity\" id=\"" + id + "-qty\"></dd>");
          item.append("<dt><label for=\"" + id + "-reason\">Reason for Return :</label></dt>");
          var select = $("<select name=\"" + id + "-Reason-for-Return\" id=\"" + id + "-reason\" class=\"required\"></select>");
          select.append("<option value=\"\">Please select</option><option>Broken on Arrival</option><option>Broken in use</option>");
          select.append("<option>Fault developed in use </option><option>Not wanted/change of mind</option><option>Not as expected</option>");
          select.append("<option>Not as pictured and/or described</option><option>Not of sufficient quality</option>");
          select.append("<option>Delivered too late, no longer required</option><option>Other</option>");
          var dd =$("<dd><em>*</em></dd>").append(select);
          item.append(dd);
          item.append("<dt><label for=\""+ id +"-problem\">Describe the problem:</label></dt>");
          item.append("<dd><em>*</em><input type=\"text\" class=\"required\" name=\""+id+"-problem\" id=\"" + id + "-problem\"></dd>");
          item.append("<dt><label>Prefered action :</label></dt>");
          dd = "<dd><input type=\"radio\" checked=\"checked\" value=\"Replace\" name=\""+ id +"-Action\" id=\""+ id +"-action-replace\">";
          dd += "<label for=\""+ id +"-action-replace\">Replace</label><input type=\"radio\" value=\"Refund\" name=\""+id+"-Action\" id=\""+id+"-action-refund\">";
          dd += "<label for=\""+ id +"-action-refund\">Refund</label></dd>";
          item.append(dd); 
          /* insert 'item' after the last item */
          $("dl.returnitem:last").after(item);
        });
 
 
   /* Featured Gallery */
  
  $.getJSON("/gallery/49/json/FeaturedProducts.html", function (data) {

    $.each(data.items, function ( index ) {
      $("#FeaturedGallery .images").append("<img src=\"" + this.url +"\" alt=\"" + this.caption + "\"  id=\"image" + (index + 1) +"\"/>");
      $("#FeaturedGallery").append("<a  rel=\"image" + (index + 1) + "\" href=\"/category/22/Products.html\" title=\"" + this.caption +"\">" + (index + 1) + "</a>")
    });
    
    $("#FeaturedGallery .images img:first").addClass("current");
    $("#FeaturedGallery a:last").css({borderRight : "none"});
    
    $("#FeaturedGallery > a").click(function () {
      $("#FeaturedGallery .images img.current").removeClass("current");
      $("#" + $(this).attr("rel")).addClass("current");
      return false;  
    });
    
    $("#FeaturedGallery .images img").click(function () {
      window.location = $("a[rel=" + this.id + "]",this.parentNode.parentNode).attr("href");
    });

	 window.slideShow = function () {
    var gallery = $("#FeaturedGallery"), 
        current = $("img.current" , gallery),
        imageCount = gallery.find("img").length,
        index = parseInt(current.attr("id").replace("image", ""));

    current.removeClass("current");
    $("img[id=image" + (index < imageCount ? (index + 1) : 1) + "]", gallery).addClass("current");
    clearTimeout(slideTimer);
    window.slideTimer = setTimeout(slideShow, 5000);    
	}

	if ($("#FeaturedGallery").length > 0) window.slideTimer = setTimeout(slideShow, 5000);

  });

});