var TOGGLE_PERIOD = 10000;

jQuery(document).ready(function(){
  jQuery("#products_filter_q").focus(function(){
    if (jQuery(this).val() == jQuery(this).attr("title")) {;jQuery(this).val("")};
  });
  jQuery("#products_filter_q").blur(function(){
    if (jQuery(this).val() == "") {jQuery(this).val(jQuery(this).attr("title"))};
  });
  jQuery(".top_basket").click(function(){
    window.location.href = jQuery(".top_basket a").attr("href"); 
  });
  
  jQuery("#header .top_basket .bck_wrapper").css({opacity: 0});
  
  jQuery("#header .top_basket").hover(function(){
    jQuery(this).find(".bck_wrapper").stop().animate({opacity: 1});
  }, function(){
    jQuery(this).find(".bck_wrapper").stop().animate({opacity: 0});
  });
  
  jQuery(".sidebar .big_back_button span").css({opacity: 0}).show();
  jQuery(".sidebar .big_back_button").hover(function(){
    jQuery(this).find("span").stop().animate({opacity: 1});
  }, function(){
    jQuery(this).find("span").stop().animate({opacity: 0});
  });
  
  
  jQuery(".slided_products").scrollable().navigator();
  
  jQuery(".fancy_ajax").live("mouseover",function(){
    if (!jQuery(this).data("init")) {
      jQuery(this).data("init", true);
      jQuery(".fancy_ajax").fancybox();
    }
  });
  
  jQuery("a.data_remote").live('click', function(){
    var ajax_options = {
      url: jQuery(this).attr("href"),
      type: "GET",
      beforeSend: function(xhr){
        jQuery.fancybox.showActivity();
        xhr.setRequestHeader('Accept', 'text/javascript');
      },
      complete: function(){jQuery.fancybox.hideActivity();}
    };
    if (jQuery(this).attr("data-confirm")) {
      if (confirm(jQuery(this).attr("data-confirm"))) {
        jQuery.ajax(ajax_options);
      };
    }else{
      jQuery.ajax(ajax_options);
    };
    return false;
  });
  
  jQuery("#web_user_is_company_true").add("#web_user_is_company_false").change(function(){
    checkIfCompany();
  });
  checkIfCompany();
  
//  jQuery("a.fancy_btn").fancybox({titleShow: false, padding: 5});
  jQuery(".big_branding").each(function(element){
    var parent = jQuery(this);
    
    if (jQuery(this).find("div.element").length > 1){
      toogleBrandingElement(parent.find("div.element:first").attr("id").split("_")[2], parent);
      parent.data("timerInterval", setInterval(function(){toogleSlowBrandingElement(null, parent);}, TOGGLE_PERIOD));
    }else{
      parent.find("div.nav").css({"display": "none"});
    };
    
    parent.find(".nav div").click(function(){
      if (parent.data("timerInterval")) {
        clearInterval(parent.data("timerInterval"));
      }
      toogleSlowBrandingElement(jQuery(this).attr("id").split("_")[3], parent);
      parent.data("timerInterval",setInterval(function(){toogleSlowBrandingElement(null, parent);}, TOGGLE_PERIOD));
    });
    
    parent.find(".product_phtoto_thumbs a").hover(function(){
      var src = jQuery(this).find("img").attr("src").replace("_icon","_normal");
      var thumbs = jQuery(this).parents(".product_phtoto_thumbs");
      var mainPhoto = jQuery(this).parents(".photos").find(".selected_photo img");
      mainPhoto.attr("src", src);
      thumbs.find("a img").removeClass("active");
      jQuery(this).find("img").addClass("active");
      if (parent.data("timerInterval")) {clearInterval(parent.data("timerInterval"))};
    }, function(){
      if (parent.data("timerInterval")) {clearInterval(parent.data("timerInterval"))};
      parent.data("timerInterval", setInterval(function(){toogleSlowBrandingElement(null, parent);}, TOGGLE_PERIOD));
    });
  });
  
  jQuery(".product_page .product_photo_thumbs a").hover(function(){
    var src = jQuery(this).find("img").attr("src").replace("_thumb","_normal");
    var thumbs = jQuery(this).parents(".product_photo_thumbs");
    var mainPhoto = jQuery(this).parents(".photos").find(".selected_photo img");
    mainPhoto.attr("src", src);
    thumbs.find("a img").removeClass("active");
    jQuery(this).find("img").addClass("active");
  });
  
  jQuery("#fancybox-inner .product_photo_thumbs a").live("hover", function(){
    var src = jQuery(this).find("img").attr("src").replace("_thumb","_max");
    var thumbs = jQuery(this).parents(".product_photo_thumbs");
    var mainPhoto = jQuery(this).parents(".photos").find(".selected_photo img");
    mainPhoto.attr("src", src);
    thumbs.find("a img").removeClass("active");
    jQuery(this).find("img").addClass("active");
  });
  
  jQuery(".filter .filter_all_prices").live("click", function(){
    checkPriceInSearch();
  });
  checkPriceInSearch();
  acceptOnlyDigits();
  prepareStep0();
  preapreSearch();
  
  jQuery("a.show_configurator").live("click", function(){
    resizeConfigurator();
    return false;
  });
  jQuery("a.hide_configurator").live("click", function(){
    jQuery(".configurator_wrapper").stop().animate({height: 150}).removeClass("configurator_open");
    return false;
  });
});

function resizeConfigurator() {
  return jQuery(".configurator_wrapper").addClass("configurator_open").stop().animate({height: (jQuery(".configurator_wrapper .core").height())});
}

function resizeFancybox() {
  $.fancybox.resize();
  setTimeout(function(){$.fancybox.resize();}, 1000);
}

function preapreSearch () {
  jQuery(".sidebar_search_form #products_filter_category_id").live("mouseover", function(){
    if (!jQuery(this).data('init')){
      jQuery(this).data('init', true);
      jQuery(this).change(function(){
        jQuery.fancybox.showActivity();
        jQuery("#advanced_search")
          .load("/wireframes/filter_category", jQuery(".sidebar_search_form").serialize(), function(){
            jQuery.fancybox.hideActivity();
          });
      });
    };
  });
}

function acceptOnlyDigits(){
  jQuery("input.only_digits").live("keydown",function(event){
    // Allow only backspace and delete
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || (event.keyCode >= 96 && event.keyCode <= 105)) {
      // let it happen, don't do anything
    }
    else {
      // Ensure that it is a number and stop the keypress
      if (event.keyCode < 48 || event.keyCode > 57 ) {
        event.preventDefault();
      }
    }
  });
}

function submitForm(form){
  jQuery.ajax({
    url: form.attr("action"),
    data : form.serialize(),
    type: "POST",
    beforeSend: function(xhr){
      jQuery.fancybox.showActivity();
      xhr.setRequestHeader('Accept', 'text/javascript');
    },
    complete: function(){jQuery.fancybox.hideActivity();}
  });
  return false;
}

jQuery.ajaxSetup({'beforeSend': function(xhr){xhr.setRequestHeader('Accept', 'text/javascript')}});

function checkIfCompany(){
  if (jQuery("#web_user_is_company_true").attr("checked")) {
    jQuery(".person_fields").hide();
    jQuery(".company_fields").show();
  }else{
    jQuery(".person_fields").show();
    jQuery(".company_fields").hide();
  };
}

function updateCart(quantity, price){
  jQuery("#basket .quantity").html("("+quantity+")");
  jQuery("#basket .value").html(price);
}

function toogleBrandingElement(nr, parent){
  var nnr = prepareNumberForToogleBranding(nr, parent);
  if ($.browser.msie) {
    parent.find(".branding_element_"+nnr).show();
    parent.find("div.element").not(".branding_element_"+nnr).hide();
  }else{
    parent.find(".branding_element_"+nnr).css({"opacity" :1}).show();
    parent.find("div.element").not(".branding_element_"+nnr).css({"opacity" :0}).hide();
  }
  
  parent.find(".nav div.branding_element_nav_"+nnr).addClass("active");
  parent.find(".nav div").not(".branding_element_nav_"+nnr).removeClass("active");
}



function toogleSlowBrandingElement(nr, parent){
  if ($.browser.msie) {
    toogleBrandingElement(nr, parent);  //problem z przeźroczystością przycisków
  }else{
    var nnr = prepareNumberForToogleBranding(nr, parent);
    parent.find(".branding_element_"+nnr).show().css({opacity: 0});
    parent.find(".branding_element_"+nnr).animate({opacity: 1});
    parent.find("div.element").not(".branding_element_"+nnr).animate({opacity: 0}, 300, function(){jQuery(this).hide()});

    parent.find(".nav div.branding_element_nav_"+nnr).addClass("active");
    parent.find(".nav div").not(".branding_element_nav_"+nnr).removeClass("active");
  };
}

function prepareNumberForToogleBranding(nr, parent){
  var nnr = nr;
  if(!nnr){
    var active = parent.find(".nav div.active");
    var next = null;
    if (active.prev().length > 0) {
      next = active.prev();
    }else{
      next = parent.find(".nav div:last");
    };
    nnr = next.attr("id").split("_")[3];
  }
  return nnr;
}

function checkPriceInSearch(){
  jQuery(".filter .prices input").attr("disabled", jQuery(".filter .filter_all_prices").attr("checked"));
}

function toggleTab(selector){
  if (selector) {
    jQuery(".fields_navigation a").removeClass("active_rounded_product_tab").not("#tab_trigger_"+selector);
    jQuery(".fields_navigation a#tab_trigger_"+selector).addClass("active_rounded_product_tab");
    
    jQuery(".product_tab").not("#product_tab_"+selector).hide();
    jQuery("#product_tab_"+selector).show();
  }else{
    jQuery(".fields_navigation a").removeClass("active_rounded_product_tab").not("#tab_trigger");
    jQuery(".fields_navigation a#tab_trigger").addClass("active_rounded_product_tab");
    jQuery(".product_tab").not("#basic_product_tab").hide();
    jQuery("#basic_product_tab").show();
  };
}

function prepareStep0(){
  jQuery("#product_table_with_shipment input").live("mouseover", function(){
    if (!jQuery(this).data('init')){
      jQuery(this).data('init', true);
      jQuery(this).change(function(){
        updateShopCartCosts();
      });
    };
  });
  
  jQuery("#product_table_with_shipment .cart_payment_summary .updatable select").live("mouseover", function(){
    if (!jQuery(this).data('init')){
      jQuery(this).data('init', true);
      jQuery(this).change(function(){
        jQuery.fancybox.showActivity();
        jQuery("#product_table_with_shipment")
          .load("/wireframes/update_shipment_category_in_cart", jQuery("#cart_products_form").serialize(), function(){
            updateShopCartCosts();
            jQuery.fancybox.hideActivity();
          });
      });
    };
  });
  setInterval("updateShopCartCosts();", 1000);
}

function updateShopCartCosts(){
  var totalCost = 0;
  var startCost = 0;
  startCost = parseFloat(jQuery("#cart_wrapper #start_cost").html())
  var shipmentCost = 0+startCost;
  jQuery("#cart_wrapper").find("table tr.product").each(function(){            
    var price = parseFloat(jQuery(this).find(".unit_price").html());
    var q = parseInt(jQuery(this).find("input").attr('value'));
    if (!q) {q = 0};
    var scost = parseFloat(jQuery(this).find(".shipment_cost_per_unit").html());
    jQuery(this).find(".all_products_price").html(""+sprintf("%.2f",price*q));
    jQuery(this).find(".shipment_cost").html(""+scost*q);
    shipmentCost += scost*q;
    totalCost += price*q
  });
  totalCost +=shipmentCost;
  jQuery("#cart_wrapper").find(".cart_payment_summary .shipment_cost .value").html(sprintf("%.2f",shipmentCost));
  jQuery("#total_price").html(sprintf("%.2f",totalCost));
}

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

var GOOGLEMAP = null;
function initializeGoogleMap(lat, lng, zoom,type){
  var latlng = new google.maps.LatLng(lat, lng);
  var myOptions = {
    zoom: zoom,
    center: latlng,
    mapTypeId: type
  };
  GOOGLEMAP = new google.maps.Map(document.getElementById("googlemap"), myOptions);
}


var MARKER = null;
function addMarker(lat, lng, body){
  var position = new google.maps.LatLng(lat, lng);
  
  var marker = new google.maps.Marker({
      map: GOOGLEMAP,
      position: position,
      clickable: (body ? true : false),
      draggable: (body ? false : true)
  });
  MARKER = marker;
  if (body!=null){
    if (body.length > 0) {
      var infoWindow = new google.maps.InfoWindow({
        content: body,
        position: position
      });
      google.maps.event.addListener(marker, 'click', function(){
        infoWindow.open(GOOGLEMAP, marker);
      });
    }
  }
}
