/**
 * @author Kamil Szafranek
 */
function c(data){
   console.log(data);
}


$(document).ready(function(){
	
   $(".request").click(function(){
      var type = $(this).attr('rel');
      $("#container").html('Czekaj...')
      $.post('/page/index/ajaxtest', {
	 'type' : type
      }, function(resp){
	 if (type == 'json'){
	    resp = eval('(' + resp + ')')
	    $("#container").html(resp.content)
	 }
	 else {
	    $("#container").html($('content', resp).text())
	 }
      });
      return false;
   })

   $("form .add_to_card, .list_add_to_cart").click(function(){
      var link = '/products/index/addToCartForm';
      var params = {};
      params['products_id'] = $(this).attr('itemid');
      $.post(link, params, function(data){
	 if(data.error == 0) {
	    d = $("<div />").attr('title', 'Wybierz ilość');
	    d.html(data.content);
	    var buttons = {
	       'Dodaj do koszyka' : function() {
		  var link = '/products/index/performAddToCart';
		  var params = {};
		  var params_array = [];
		  var params_ids = [];
		  $(".quantity_form").each(function(i, item){
		     params_array.push($(this).val());
		     params_ids.push($(this).attr('rel'))
		  })
		  params['quantity'] = params_array;
		  params['ids'] = params_ids;
		  $.post(link, params, function(data){

		     if(data.error == 1) {

			$(".add_to_cart_form .main_error")
			      .css('display', 'block')
			      .html(data.message);

			return false;
		     }
		     else {
			var sLink = '?options[]=' + params_ids.join('&options[]=');
			sLink += '&quantity[]=' + params_array.join('&quantity[]=')
			location.href = '/products/index/addToCard' + sLink;
		     }
		  }, 'json')
	       },
	       'Anuluj' : function() {
		  d.dialog('destroy')
		  d.remove();
	       }
	    };
	    d.simpleDialog({buttons : buttons});
	 }
      }, 'json')
   })
   $("body").delegate('.quantity_form', 'blur', updateAddToCart);
   function updateAddToCart(id) {
      var link = "/products/index/validateAddToCart";
      var params = {};
      params['option_id'] = $(this).attr('rel');
      var params_array = [];
      var params_ids = [];
      $(".quantity_form").each(function(i, item){
	 params_array.push($(this).val());
	 params_ids.push($(this).attr('rel'))
      })
      params['quantity'] = params_array;
      params['ids'] = params_ids;
      $.post(link, params, function(data){
	 if( data.error == 0 ) {
	 }
	 else {
	    $.each(data.errors, function(i, item){
	       if(item && item.quantity){
		  $(".add_to_cart_form .error[itemid='"+i+"']").html(item.quantity.message)
		  $(".add_to_cart_form .error[itemid='"+i+"']").css('display', 'block');
	       }
	       else {
		  $(".add_to_cart_form .error[itemid='"+i+"']").html('')
		  $(".add_to_cart_form .error[itemid='"+i+"']").css('display', 'none');
	       }
	    })
	 }
	 $(".price_summary").html(data.ammount);
      }, 'json')
   }
   //	$("form .add_to_card").click(function(){
   //		if ($('#quantity').css('display') == 'none'){
   //			$('#quantity').show();
   //		}
   //		else {
   //			if(parseInt($("#quantity").val()) > $("#max_quant").val() && $("#max_quant").val() != -1){
   //				$(".error").show();
   //			}
   //			else {
   //				$(this).parents('form').submit();
   //			}
   //		}
   //	})
   $(".search").click(function(){
      var link = $(this).attr('rel');
      if($("#search_value").val() != 'Wpisz szukaną frazę'){
	 link = decodeURI(link)
	 link = link.replace('%23VAR1%23', $("#search_value").val())
	 link = link.replace('%23VAR2%23', $("#categories_id").val())
	 location.href = link;
      }
   })
   $(".copy_form").click(function(){
      var elements = $(this).parents('form').find("input[type='text']");
      if(elements && elements.length > 0) {
	 $.each(elements, function(i, item){
	    if($(item).attr('name').indexOf('c_') == -1){
	       $("input[name='c_" + $(item).attr('name') + "']").val($(item).val())
	    }
	 })
			
      }
   })
   $("input[name='invoice']:checkbox").click(function(){
		
      if($(this).attr('checked')) {
	 $("#invoice_container").css('display','block')
      }
      else {
	 $("#invoice_container").css('display','none')
      }
   })
   $(".details_main_photo, .details_photo, .lightbox_a").lightBox();
	
	
//   $(".list_add_to_cart").click(function(){
//      if(!$(this).hasClass('not_active')&&!$(this).hasClass('active')) {
//	 $(this).next().css('display', 'none');
//	 $(this).prev().css('display', 'block');
//	 $(this).addClass('active')
//      }
//      else if($(this).hasClass('active')){
//	 var params = {};
//	 params['products_id'] = $(this).attr('rel');
//	 params['quantity'] = $("#prod_quant_"+$(this).attr('rel')).val();
//	 $.post('/products/index/checkquant', params, function(data) {
//	    if(data.error == 1){
//	       var d = $("<div />")
//	       .attr('title', 'Informacja')
//	       .html('<p>'+data.message+'</p>');
//	       d.dialog({
//		  modal: true,
//		  resizable: false,
//		  buttons : {
//		     'OK' : function() {
//			$(this).dialog('close');
//		     }
//		  }
//	       });
//	    }
//	    else {
//	       location.href = '/products/index/addToCard/product_id/'+params['products_id'] +'/quantity/'+params['quantity']
//	    }
//	 }, 'json')
//      }
//      else if($(this).hasClass('not_active')) {
//	 var d = $("<div />")
//	 .attr('title', 'Informacja')
//	 .html('<p>Produkt niedostępny.</p>');
//
//	 d.dialog({
//	    modal: true,
//	    resizable: false,
//	    buttons : {
//	       'OK' : function() {
//		  $(this).dialog('close');
//	       }
//	    }
//	 });
//      }
//      return false;
//   });
   $('.blue_box a.menu').menuHover();
   var t = null;
	
   $(".cart_input").keyup(function(){
      if(t) {
	 clearTimeout(t);
      }
      var rel = $(this).attr('rel')
      var val = $(this).val()
      t = setTimeout("updateCart("+rel+","+val+");", 1000);
   });
   $(".filter_form select").change(function(){
      $(this).parent().submit();
   })

   $(".forgot_pass").click(function(){
      var d = $("<div />");
      var buttons = {
	 'Wyślij hasło' : function(){
	    var link = "/orders/index/sendPassword";
	    var params = {
	       'email' : $("#forget_pass").val()
	    }
	    $.post(link, params, function(data){
	       if(data.error == 1) {
		  $(".error").html(data.message);
		  $(".error").fadeIn();
	       }
	       else {
		  d.html('Hasło zostało wysłane.');
		  buttons = {
		     'OK' : function(){
			d.dialog('close');
			d.remove();
		     }
		  }
		  d.dialog('option', 'buttons', buttons);
	       }

	    }, 'json')
	 }
      }
      var options = {
	 buttons : buttons

      };

      var html = '<div>'+
      '<p class="error" style="color: red;font-size: 9px;display: none;">Niepoprawny email</p>'+
      'Wpisz email: <input type="text" name="email" id="forget_pass"/></div>';
     d.attr('title', 'Przypomnij hasło').html(html).simpleDialog(options);
   })
})
function updateCart(id, val){
   var params = {};
   params['option_id'] = id;
   params['quantity'] = val;
   $.post('/products/index/cartAddItem', params, function(data){
      if(data.error == 0){
	 location.reload(true)
      }
      else {
	 var d = $("<div />")
	 .attr('title', 'Informacja')
	 .html('<p>'+data.message+'</p>');
	 d.dialog({
	    modal: true,
	    resizable: false,
	    buttons : {
	       'OK' : function() {
		  $(this).dialog('close');
	       }
	    }
	 });
      }
   }, 'json')
}
$.fn.simpleDialog = function(options) {
   var th = $(this);
   var defaultOptions = {
      resizable: false,
      modal: true,
      close : function(){
	 $(this).remove();
      }
   }
   options = $.extend({}, options, defaultOptions);
   $(this).dialog(options);
}
$.fn.menuHover = function() {
   $(this).hover(function(){
      $(this).addClass('hover')
   },function(){
      $(this).removeClass('hover');
		
   })
}


