function formatSearch(row) {
	return row[2] + ' > ' + row[1];
}

function redirectSearch(event, data, formatted) {
	$('#search_query').val(data[1]);
	document.location.href = data[3];
}

function jumpToCategory(id_category){
	if(id_category > 0){
		$.scrollTo("#category_"+id_category, 1600);
	}else{
		return true;
	}
	return false;
}

function formSubmit(){
	$("#formNoValidation").submit(); 
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function showCategoryDescription(){
	
	if($("#cat_desc_content").is(":hidden")){
		$("#cat_desc_content").show();
	}else{
		$("#cat_desc_content").hide();
	}
	return false;
}

function addToBasket(a, prod_id){
	
	var inputField = $(a).prev();
	var inputProductId = 	inputField.prev();
	var qty = parseInt(inputField.val());
	var tooltip = 	$(a).parent().next(); 
	var indicator = $(tooltip).children(".tooltip_indicator");
	var ajax_text = $(tooltip).children(".tooltip_text");
	
	
	qty = qty > 0 ? qty : 1;
	
	$(tooltip).fadeIn('slow');
	$(indicator).show();
	$(ajax_text).html('');
	
	$.ajax({
		url:baseDir+"cart.php?add&ajax=true&qty="+qty+"&token="+token+"&id_product="+prod_id,
		dataType: 'json', 
		cache: false,
		error: function(data){
			alert('Błąd dodawania do koszyka, skontaktuj się z administratorem');
		},
		success: function(data){
			if(data.hasError){
				for(i=0; i<data.errors.length; i++){
					$(ajax_text).html( data.errors[i] );
				}
			}else{
				$("#navi_basket").html(data.totalQuantity);
				$(ajax_text).html('Dodano <B>'+qty+'</B> sztuk produkt!<BR><BR>Koszyk zawiera:<B>'+data.totalQuantity+'</B> produktów');
			} 
			$(indicator).hide();
			setTimeout(function(){
				$(tooltip).fadeOut('slow');
   				return false;
			}, 2200); 
		}
	}); 
   a.blur();
   
   return false;
}			

$("#cat_desc_content").hide();
    
var topMenuApi;
var topMenuTabsApi;
var exposeApi;
var formApi;

$(document).ready(function() {
	

	// Validator translation	
	$.tools.validator.localize("pl", {
	'*'			: 'Pole wymagane',
	':email'  	: 'Błędny email',
	':number' 	: 'Wymagana liczba',
	':url' 		: 'Podaj właściwy adres url',
	'[max]'	 	: 'Pole powinno zawierać co najmniej $1 znaki',
	'[min]'		: 'Pole powinno zawierać co najwyżej $1 znaki',
	'[required]': 'Pole wymagane'
	});
		
	$("#cat_desc_content").hide();
	// Top menu
	// Fix seo links
	$("a.topMenuNext").each(function () {
		var href= $(this).attr("href");
		var size=8;
		href = href.substring(size);
		var index = href.indexOf("/")+size;
		$(this).attr("href", "/ajax"+$(this).attr("href").substring(index));
		$(this).attr("title", "");
     });  
     
     
    function showAll(){
		$(".showAll").unbind('click');
    	$(".showAll").click(function () {
				$("ul.cm_sub_categories li").each(function () {
					$(this).show();
				});
				$(".showAll").show();
				$(".showAll").html("Zwiń menu");
				$(".showAll").click(function(){hideAll()});
		});
    }
    function hideAll(){
    	
	    var listCounter=0;
	    var displayLimit=5;
  
		$("ul.cm_sub_categories li").each(function () {
			listCounter++;
			
			if(listCounter>displayLimit){
				$(".showAll").html("Pokaż więcej");
				$(this).hide();
			}
			if(listCounter == displayLimit+1){
				$(".showAll").show();
				showAll();
			}
		});
    }
    hideAll();
    
   	topMenuTabsApi = $("#top_menu").tabs("#async_content", 
		{effect: 'ajax', api:true , 
		onBeforeClick:function(event){
			$("#async_content").html("");
			$("#ajax_category_indicator").show();
			setTimeout(function(){$("#ajax_category_indicator").hide()}, 2000); 
		}
		});
		
	topMenuApi = $("#top_menu").scrollable(
		{ size:1, api: true, speed:1300, clickable:false}
	);
	
	$('#nav_products').hover(function () {
		$('#top_menu').fadeIn(50);
	});
	
	$('#top_menu').mouseleave(function() {
		$('#top_menu').fadeOut(300);  
		topMenuApi.seekTo(0);
	});
	
	$('#menu_left_back').click(function(event){
		topMenuApi.seekTo(0);
		return false;
	});
	
	
	// Z-index IE6 fix
	
	var zIndexNumber = 800;
	
	$('div').each(
		function() {
			if(zIndexNumber > 0){
				$(this).css('zIndex', zIndexNumber);
				zIndexNumber -= 10; 
			}
		}
	);	
	
	// Autosuggestion 
	$("#search_query").autocomplete(
			'/search.php', {
			minChars: 2,
			max:12,
			width:300,
			scroll: false,
			formatItem:formatSearch,
			extraParams:{ajaxSearch:1,id_lang:3}
		}).result(redirectSearch);
	
	
	// Products scrollers @ front page
	$(".front_page_scroll").scrollable({ 
		size:3,
		speed:600,
		clickable:false
	}).navigator()
	.circular()
	.autoscroll(
		{autoplay: true,
		 autopause: true,
		 interval:8086,
		 steps:1
	});
	
	// Accordion front page
	$("#accordion").tabs("#accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null});
	$("#accordion_product").tabs("#accordion_product div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null});
 
	$(".gallery_thumb").click(function(event){
		
  		$(".gallery_thumb").each(function () {
			$(this).removeClass("shown");			
  		}); 
		$("#bigpic").attr("src",  $(this).attr("href"));
		$(this).addClass("shown");	 
		return false;
   });
   
	
   $(".show_ajax_popup").click(function() {
   		
		$("#ajax_popup").show();
   		exposeApi = $("#ajax_popup").expose({
	 		opacity:0.3,
	 		api:true, 
	 		lazy:true,
			onClose: function(event) {
 				$("#ajax_popup").hide();
 			}
		}).load();
   		$.scrollTo("#header", 500); // @TODO FIX NAME
		
		return false;
	   });
   
	$("a.close").click(function(event){
	
		$("#exposeMask").fadeOut(100); // FAIL
		$("#ajax_popup").hide();
		return false;
	});
	
	$("#reloadComments").click(function(event){
		
	 	$("#comment_0>i").html('');
	 	$("#comment_0>p").html('');
	 	$("#comment_1>i").html('');
	 	$("#comment_1>p").html('');
		
		$.ajax({
		  url: "/ajax_comments.php",
		  dataType: 'json',
		  success: function (d){ 
		 	$("#comment_0>i").html(d[0].comment);
		 	$("#comment_0>p").html(d[0].author);
		 	$("#comment_1>i").html(d[1].comment);
		 	$("#comment_1>p").html(d[1].author);
		  }	
		});
		return false;
	}); 
	
	
	
	
	$("#login_button").click(function(event){
		  
		var form = $("#ajax_authentication");
 
		$.ajax({
		  url: "/ajax_authentication.php",
		  dataType: 'json', 
		  data: form.serialize(),
		  success: function (d){ 
		  	if(d.isLogged){
		  		$("#exposeMask").fadeOut(100);
				$("#ajax_popup").hide();
				$("#login_link").html("Witaj, <span>"+d.firstName+" "+d.lastName+" (<a title=\"Wyloguj mnie\" href=\"/index.php?mylogout\">Wyloguj</a>)");
				
				var back = getUrlVars()["back"];
				if( back != undefined ){
					window.location.href=back; 
				}else{
					location.reload(); 
				}
		  	}else{		
		  		$("#ajax_login_output").fadeIn(10);  	
		  		$("#ajax_login_output").html(d.error);
		  		$("#ajax_login_output").css("background","#FF0F2F");
		  		$("#ajax_login_output").css("color","white");
		  		
				setTimeout(function(){
			  		$("#ajax_login_output").css("background","#E1EEFF");
			  		$("#ajax_login_output").css("color","black");
			  		return false;
				}, 2000); 
		  		
		  	}
		  }
		});
		return false;
	}); 
	
	
	function enableCompany(status){
		
		$("#company").attr("disabled", status);
		$("#address2").attr("disabled",status);
			
		return true;
	}
	
	
	if($(":radio[@name='is_company']:checked").val() == "0"){
		$(".companyHide").fadeOut({speed:"fast"});
		$("#alias").val("ADRES NA PARAGONIE");
		$("#firstname").val($("#customer_firstname").val());
		$("#lastname").val($("#customer_lastname").val());
		
			

	}else{
		$("#alias").val("ADRES DO FAKTURY");
		$("#firstname").val($("#customer_firstname").val());
		$("#lastname").val($("#customer_lastname").val());
		 
		enableCompany(false);
	}
	
	$(":radio[@name='is_company']").change(function(){
		if($(":radio[@name='is_company']:checked").val() == "1"){
			
			$(".companyHide").fadeIn({speed:"slow"});
			$("#alias").val("ADRES DO FAKTURY");
			
			enableCompany(false);
				
		}else{
			$(".companyHide").fadeOut({speed:"slow"}); 
			$("#alias").val("ADRES NA PARAGONIE");
			
			$("#company").val("");
			$("#address2").val("");
			
			enableCompany(true);
		} 
		  
	});
	
	
	$("#account-creation_form").validator({  // @TODO FIX NAME
		position: 'top left', 
		offset: [-8, 200],
		formEvent:null,
		lang:'pl',
		message: '<div><em/></div>' // em element is the arrow
	});
	
	formApi = $("#account-creation_form").data("validator");
	
	$(".ajax_submit").click(
		function(){
			if(formApi.checkValidity())
				$("#account-creation_form").submit(); // @TODO FIX NAME
			else
				$.scrollTo("#account-creation_form", 500); // @TODO FIX NAME
			$(this).blur();
			return false;
		}
	);
	
	
	$("#fb_logo").click(function(){
		var iframe ='<iframe id="fb_frame" src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FCopyMedia%2F137692826281923&amp;width=240&amp;colorscheme=light&amp;locale=pl_PL&amp;connections=8&amp;stream=false&amp;header=true&amp;height=285" scrolling="no" frameborder="0" style="border:none;background:white; overflow:hidden; width:0px; height:285px;" allowTransparency="false"></iframe>';
		
		$(this).css("z-index","1000");
		$(this).css("right", "240px");
		
		if(!$("#fb_frame").size()){
			$(this).html(iframe);
			$("#fb_frame").mouseleave(function(){
					$("#fb_logo").css("right","0px");
					$(this).css("width","0px");
			});
		}
		$("#fb_frame").css("width","240px");
	});
	
});
