/*
 * Delvaux App script
 *
 * Copyright (c) 2009 Mr. Henry
 * Author: brecht@mrhenry.be
 *
 */

/* Shadowbox */
Shadowbox.init({ skipSetup: true, enableKeys: false, players: ["html"]});

/* Initialize */
$(document).ready(function() {
  // Subnavigations
  var currentSubNav = null;
  $(".hasSubNavs").droppy();
  
  // Accordions
  if($(".isAccordion").length > 0){
    $(".isAccordion").accordion({
      autoHeight: false,
      collapsible:true,
      active:0
    });
  }
  if($(".isAccordion2").length > 0){
    $(".isAccordion2").accordion({
      autoHeight: false,
      collapsible:true,
      active:false
    });
    if($("#tab_id").val()!=-1){
      $(".isAccordion2").accordion( 'activate' , Number($("#tab_id").val()) );
    }
  }
  
  // CheckBoxes
  $(".checkThis").checkThis();
  
  // Select filters
  $(".selectFilter").selectThis();
  
  // Cart calculation
  $(".reCalculate").calculateThis();
  
  // Product detail
  if($("#productDetail").length > 0){
    // Productdetail zoom
    var options = {
      zoomWidth: 388,
      zoomHeight: 404,
      showEffect:'fadein',
      fadeinSpeed: 'slow',
      hideEffect:'fadeout',
      fadeoutSpeed: 'slow',
        xOffset: 90,
        yOffset: 0,
        position: "right",
      title :false
    };
  
    // Productdetail image switch
    initZoom($(".thumbs:first-child a").attr("rel"),options,true);
    
    $(".thumbs a").each(function(){
      $(this).attr("href","javascript:;");
    });
    $(".thumbs a").click(function(){      
      var img = $(this).attr("rel");
      $(".imgZoom").fadeOut("fast",function(){
        initZoom(img,options,false);
      });
    });
  }
  
  // Tips
  $(".tipThis").tipThis(false);
  
  // Togglers
  $(".toggleThis").toggleThis();
  
  // Addresses & shipping costs
  $("#addresses, #billing_address_country").change(function(){
    if($(this).val()==""){
      window.location = $("#add_address_path").val();
    }else{
      var a = $(this).parent().parent().parent().parent().find("tbody tr:first .quantity input.reCalculate").reCalculate();
    }
  });
  $("#exclusive_shipping_costs").click(function(){
    var a = $(this).parent().parent().parent().parent().find("tbody tr:first .quantity input.reCalculate").reCalculate();
  });
  
  // Conditions check
  $("#conditions").enableMyButton();
  $(".shadowMe").each(function(){
    $(this).attr("href","javascript:;");
  });
  $(".shadowMe").click(function(){
    var target = $(this).attr("rel");
    var content = $("#"+target).html();
    var s_width = 500;
    var s_height = 500;
    if($(this).hasClass("order_cart")){
      s_width = 700;
      s_height = 480;
    }
    Shadowbox.open({
      content:    content,
      player:     "html",
      height:     s_height,
      width:      s_width,
      options:    {
        displayNav: true,
        overlayColor: '#ffffff'
      }
    });
  });
  
  // Validation
  // Registration form
  $("#subscribe_newsletter").validate({
    rules: {
      "newsletter[email]": { required: true, email: true, minlength: 6 },
      "newsletter[name]": { required: true }
    },
    messages: {
      "newsletter[email]": {
        required: "Please provide an email",
        email: "Email not valid",
        minlength: "Please provide an email"
      },
      "newsletter[name]": {
        required: "Please enter your name"
      }
    }
  });
  $("#update_email").validate({
    rules: {
      "email[email]": { required: true, email: true, minlength: 6 },
      "email[confirm_email]": { required: true,minlength: 6,equalTo: "#email_email" }
    },
    messages: {
      "email[email]": {
        required: "Please provide an email",
        email: "Please enter a valid email address",
        minlength: "Your email must consist of at least 6 characters"
      },
      "email[confirm_email]": {
        required: "Please confirm your email",
        email: "Please enter a valid email address",
        minlength: "Your email must consist of at least 6 characters",
        equalTo: "Please enter the same email as above"
      }
    }    
  });
  $("#update_password").validate({
    rules: {
      "password[current_password]": { required: true },
      "password[new_password]": { required: true,minlength: 8 },
      "password[confirm_new_password]": { required: true,minlength: 8,equalTo: "#password_new_password" }
    },
    messages: {
      "password[current_password]": {
        required: "Please provide a password"
      },
      "password[new_password]": {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long"
      },
      "password[confirm_new_password]": {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long",
        equalTo: "Please enter the same password as above"
      }
    }    
  });
  
  $(".reset_password").validate({
    rules: {
      "user[password]": { required: true,minlength: 8 },
      "user[password_confirmation]": { required: true,minlength: 8,equalTo: "#user_password" }
    },
    messages: {
      "user[password]": {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long"
      },
      "user[password_confirmation]": {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long",
        equalTo: "Please enter the same password as above"
      }
    }    
  });

  $("#add_shipping_address").validate({
    rules: {
      "shipping_address[country]": { required: true },
      "shipping_address[line_1]": { required: true },
      "shipping_address[locality]": { required: true },
      "shipping_address[postal_code]": { required: true }   
    },
    messages: {
      "shipping_address[country]": {
        required: "Please provide a country"
      },
      "shipping_address[line_1]": {
        required: "Please provide an address"
      },
      "shipping_address[locality]": {
        required: "Please enter your city"
      },
      "shipping_address[postal_code]": {
        required: "Please provide a postal code"
      }
    }    
  });
  $("#edit_billing_address").validate({
    rules: {
      "billing_address[country]": { required: true },
      "billing_address[line_1]": { required: true },
      "billing_address[locality]": { required: true },
      "billing_address[postal_code]": { required: true }   
    },
    messages: {
      "billing_address[country]": {
        required: "Please provide a country"
      },
      "billing_address[line_1]": {
        required: "Please provide an address"
      },
      "billing_address[locality]": {
        required: "Please enter your city"
      },
      "billing_address[postal_code]": {
        required: "Please provide a postal code"
      }
    }    
  });
  
  $("#new_lalala_users_user").validate({
    rules: {
      "lalala_users_user[login]": { required: true, email: true, minlength: 6 },
      "lalala_users_user[password]": { required: true,minlength: 8 },
      "lalala_users_user[password_confirmation]": { required: true,minlength: 8,equalTo: "#lalala_users_user_password" },
      "lalala_shop_client_profile[first_name]": { required: true },
      "lalala_shop_client_profile[last_name]": { required: true },
      "lalala_shop_client_profile[country]": { required: true },
      "lalala_addresses_address[line_1]": { required: true },
      "lalala_addresses_address[locality]": { required: true },
      "lalala_addresses_address[postal_code]": { required: true },
      "lalala_shop_client_profile[phone_number]": { required: true }      
    },
    messages: {
      "lalala_users_user[login]": {
        required: "Please enter an email address",
        email: "Please enter a valid email address",
        minlength: "Your username must consist of at least 6 characters"
      },
      "lalala_users_user[password]": {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long"
      },
      "lalala_users_user[password_confirmation]": {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long",
        equalTo: "Please enter the same password as above"
      },
      "lalala_shop_client_profile[first_name]": {
        required: "Please enter your first name"
      },
      "lalala_shop_client_profile[last_name]": {
        required: "Please enter your last name"
      },
      "lalala_shop_client_profile[country]": {
        required: "Please provide a country"
      },
      "lalala_addresses_address[line_1]": {
        required: "Please provide an address"
      },
      "lalala_addresses_address[locality]": {
        required: "Please enter your city"
      },
      "lalala_addresses_address[postal_code]": {
        required: "Please provide a postal code"
      },
      "lalala_shop_client_profile[phone_number]": {
        required: "Please provide a phone number"
      }
    }    
  });
  // Login form
  $("#new_user_session").validate({
    rules: {
      "user_session[login]": { required: true, email: true, minlength: 6 },
      "user_session[password]": { required: true }        
    },
    messages: {
      "user_session[login]": {
        required: "Please enter an email address",
        email: "Please enter a valid email address",
        minlength: "Your username must consist of at least 6 characters"
      },
      "user_session[password]": {
        required: "Please provide a password"
      }
    }
  });
  
  // Grid equal item heights
  $(".grid").equalHeightThis();
});

function initZoom(imgId,options,initial){
  var imgHtm = getImgHtml(imgId);
  $("#img").html("");
  $("#img").append(imgHtm);
  if(initial){$(".imgZoom").show();}else{$(".imgZoom").fadeIn("slow");}
  $(".imgZoom").jqzoom(options);
}
function getImgHtml(img){
  var imgBig = $("#"+img).attr("href");
  var imgTitle = $("#"+img).attr("title");
  var imgNormal = $("#"+img).children("img").attr("src");
  var imgHtm = "<a href='"+imgBig+"' title='"+imgTitle+"' class='imgZoom' style='display:none;'><img src='"+imgNormal+"' alt='"+imgTitle+"' title='"+imgTitle+"' /></a>";
  return imgHtm;
}

jQuery.fn.equalHeightThis = function(){
  var highest = 0;
  $(this).children("li").each(function(){
    if($(this).height()>highest){
      highest = $(this).height();
    }
  });
  $(this).children("li").css("height",highest+"px");
};

jQuery.fn.calculateThis = function(){
  $(this).click(function(){
    if($(this).attr("rel")!==undefined){
      var sender = $("#"+$(this).attr("rel"));
      sender.reCalculate();
    }
  });
  $(this).change(function(){
    $(this).reCalculate();
  });
};

jQuery.fn.reCalculate = function(){

  // selectors
  var cell = $(this).parent();
  var row  = cell.parent();
  var grid = row.parent();
  
  // values
  var unitPrice  = Number(row.children(".unitPrice").find(".value").html().replace(",","."));
  var unitWeight = Number(row.children(".unitPrice").find(".unit-weight").html().replace(",","."));
  var quantity   = Math.floor(Number($(this).val().replace(",",".")));
  
  // reset this value
  $(this).val(quantity);
  if(quantity<1 || isNaN(quantity)){
    quantity = 1;
    $(this).val("1");
  }
  
  // totals
  var subTotal       = Math.round((unitPrice*quantity)*100)/100;
  var subTotalWeight = Math.round((unitWeight*quantity)*1000)/1000;
  var total         = 0;
  var totalWeight   = 0;
  var totalQuantity = 0;
  
  // set subTotal
  row.children(".price").find(".value").html(subTotal);
  row.children(".price").find(".total-weight").html(subTotalWeight);
  
  // personalized prices
  // check if this rows is updated
  var p_check = row.find(".personalize input[type='checkbox']");
  if(p_check.attr("checked") && !p_check.hasClass("disabled")){
    // get personalized unit price
    var p_unit_price = grid.find(".personalize .price").val();
    var p_total_price = Number(p_unit_price)*quantity;
    row.find(".price .additional_price").html(p_total_price);
    row.find(".price .additional").fadeIn("slow");
  }else if(!p_check.hasClass("disabled")){

      row.find(".price .additional").hide();
      row.find(".price .additional_price").html("");
  }
  
  grid.find(".price .total-weight").each(function(){
    totalWeight += Number($(this).html());
  });
  
  // shipping costs
  var address_id = 0;
  var shipping_cost = 0;
  $("#addresses option:selected").each(function(){
    address_id = $(this).val();
  });
  $("#billing_address_country option:selected").each(function(){
    address_id = $(this).val();
  });
  
  if ((!address_id) || (address_id == '-')) {
    address_id = 'BE';
  }
  
  if($("#exclusive_shipping").length>0){
    var country_code = $("#addresses :selected").text().substring($("#addresses :selected").text().length-2);
    if(country_code=="BE"){
      $("#exclusive_shipping").show();
    }else{
      $("#exclusive_shipping").hide();
    }
  }
  
  shipping_cost = 0;
  
  
  for (var i in document.shipping_costs[address_id]) {
    var price_point = document.shipping_costs[address_id][i];
    if ((totalWeight >= price_point[0][0]) && (totalWeight < price_point[0][1])) {
      shipping_cost = price_point[1];
    }
  }
  if (shipping_cost == 0) {
    var l = document.shipping_costs[address_id].length;
    shipping_cost = document.shipping_costs[address_id][l-1][1];
  }
  
  //shipping_cost = ($("#exclusive_shipping_costs").attr("checked")) ? 85 : shipping_cost;

  grid.parent().find(".shipping_costs .value").html(shipping_cost);
  
  // update total
  grid.find(".price .value").each(function(){
    total += Number($(this).html());
  });
  grid.find(".additional_price").each(function(){
    if($(this).html()!="&nbsp;" && $(this).html()!=null && $(this).html()!=""){
      total += Number($(this).html());
    }
  });
  
  // reset topper
  grid.find(".quantity").children("input").each(function(){
    totalQuantity += Number($(this).val());
  });
  
  //total = Math.round(total*100)/100;
  //var vat_prc = Number(grid.find("tfoot .vat .percent"))/100;
  //var vat = (total*0.21);
  
  var total_br = total + Number(shipping_cost);
  
  total_br = Math.round(total_br*100)/100;
  total = Math.round(total*100)/100;
  //vat = Math.round(vat*100)/100;

  grid.parent().find("tfoot .total_excl .value").html(total);
  grid.parent().find("tfoot .total .value").html(total_br);
  //grid.parent().find("tfoot .vat .value").html(vat);
  $("#topper .last .price").html(total_br);
  $("#topper .last .quantity").html(totalQuantity);
};
  
jQuery.fn.selectThis = function(){
  $(this).change(function(){
    if($(this).val()!=null && $(this).val()!=""){
      window.location = $(this).val();
    }else{
      
    }
  });
};
jQuery.fn.checkThis = function() {
  $(this).each(function(){
    // vars
    var id = $(this).attr("id");
    var txt = $("label[for="+id+"]").html();
    var sClass = "";
    if($(this).hasClass("checkBox_checked")){
      sClass = " checkBox_checked";
      if($(this).hasClass("disabled")){
        txt = $(this).parent().children(".description").html();
      }
    }else{
      sClass = " checkBox_unchecked";
    }
    if($(this).hasClass("small")){
      sClass += " small";
    }
    if($(this).hasClass("tip")){
      sClass += " tip";
    }
    // hide
    $(this).hide();
    $("label[for="+id+"]").hide();
    
    // replace
    if(!$(this).hasClass("disabled")){
      $(this).parent().append("<a href=\"javascript:;\" id=\"sender_"+id+"\" rel=\""+id+"\" class=\"checkBox"+sClass+"\"><span>"+txt+"</span></a>");
      
      $("#sender_"+id).tipThis(txt);
        
      $(this).parent().children("a").click(function(){
        var target = $(this).attr("rel");
        var miniForm = "<div id='sBoxTemp' class='clearfix'>";
        miniForm += "<input type='hidden' id='hd_target' name='hd_target' value='"+$(this).attr("rel")+"' />";
        miniForm += "<input type='hidden' id='hd_sender' name='hd_sender' value='"+$(this).attr("id")+"' />";
        miniForm += $(this).parent().children(".miniForm").html()+"</div>";
        if($(this).hasClass("checkBox_unchecked")){
          sHeight = 560;
          sWidth = 350;
          if($(this).hasClass("small")){
            sHeight = 370;
          }
          if($(this).hasClass("wide")){
            sHeight = 500;
          }
          Shadowbox.open({
            content:    miniForm,
            player:     "html",
            height:     sHeight,
            width:      sWidth,
            options:    {
            displayNav: true,
            overlayColor: '#ffffff',
            onClose: function(args){ }
            }
          });
        }else{
          $(this).removeClass("checkBox_checked");
          $(this).addClass("checkBox_unchecked");
          $("#"+target).attr("checked",false);
          $(this).parent().parent().children(".quantity").children("input").reCalculate();
        }
    });
    }else{
       $(this).parent().append("<span href=\"#\" id=\"sender_"+id+"\" class=\"checkBox checkBox_disabled"+sClass+"\"><span>"+txt+"</span></span>");
       $("#sender_"+id).tipThis(txt);
    }
    
  });
  
  $(".personalize_options li input").live("click",function(){
    if($(this).attr("checked")){
       $("#sBoxTemp .img_personalized").hide();
      switch($(this).attr("class")){
        case "checkbox checkbox_1":
          $("#sBoxTemp #img_personalized_1").show();
        break;
        case "checkbox checkbox_2":
          $("#sBoxTemp #img_personalized_2").show();
        break;
        case "checkbox checkbox_3":
          $("#sBoxTemp #img_personalized_3").show();
        break;
      }
    }
  });
  
  $(".miniFormAction").live("click",function(){
    var hasTextFields = false;
    var textEmpty = true;
    var target = null;
    var sender = null;
    
    $("#sBoxTemp").find("input").each(function(){
      var id = $(this).attr("id");
      var type = $(this).attr("type");

      switch(type){
        case "text":
          hasTextFields = true;
          var val = $(this).val();
          $("#"+id).val(val);
          if(val!="" && val!=null){
            textEmpty = false;
          }
        break;
        case "radio":
          var val = $(this).attr("checked");
          $("#"+id).attr("checked",val);
        break;
        case "checkbox":
          var val = $(this).attr("checked");
          $("#"+id).attr("checked",val);
        break;
        case "hidden":
          if($("#"+id).attr("id")=="hd_sender"){
            sender = $("#"+id).val();
            
          }else if($("#"+id).attr("id")=="hd_target"){
            target = $("#"+id).val();
          }
        break;
      }      
    });

    $("#sBoxTemp").find("textarea").each(function(){
      hasTextFields = true;
      var id = $(this).attr("id");
      var val = $(this).val();
      $("#"+id).val(val);
      if(val!="" && val!=null){
        textEmpty = false;
      }
    });
    
    if(!hasTextFields || !textEmpty){
      $("#"+sender).removeClass("checkBox_unchecked");
      $("#"+sender).addClass("checkBox_checked");
      $("#"+target).attr("checked",true);
      $("#"+sender).parent().parent().find(".quantity input").reCalculate();
      Shadowbox.close();
    }else{
      $("#sBoxTemp").find(".error").show();
    }
  });
};

jQuery.fn.tipThis = function(contentHtml){
  $(this).each(function(){
    var tipTarget = false;
    var tipDelay = 140;
    if($(this).hasClass("mouseTip")){
      tipTarget = 'mouse';
      tipDelay = 40;
    }
    $(this).children("img").removeAttr("title");
    $(this).qtip({
       content: { text: contentHtml },
       show: { when: { event: 'mouseover' }, delay: tipDelay, effect: {type:'fade',length:500} },
       hide: 'mouseout',
       style: { name: 'delvaux', tip: true },
       position: {adjust:{ screen:true},target: tipTarget}
    });
  });
};

jQuery.fn.toggleThis = function(){
  $(this).each(function(){
    var target = $(this).attr("rel");
    $(this).attr("href","javascript:;");
    $(this).toggle(
      function(){
        $("#"+target).fadeIn("slow");
      },
      function(){
        $("#"+target).fadeOut("fast");
      }    
    );
  });
};

jQuery.fn.enableMyButton = function(){
  $(this).click(function(){
    var target = $(this).parent().parent().find("input[type='submit']");
    if($(this).attr("checked")){
      target.attr("disabled",false);
      target.removeClass("buttonDisabled");
    }else{
      target.attr("disabled",true);
      target.addClass("buttonDisabled");
    }
  });
};

jQuery.fn.qtip.styles.delvaux = {
   border: {
       width: 3,
       radius: 0,
       color: '#ccc'
    },
    title: {
       background: '#fff',
       color: '#A27D35'
    },
    background: '#fff',
    color: '#999',
    width: {
      max: 350
    },
    classes: { tooltip: 'qtip-delvaux' }
};