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 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");
	
	$(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', 
		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');
			}, 3200); 
		}
	});
	
	a.blur();
	return false;
}			


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'
	});
		
	// 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}
	);
	
	$('#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;
	});
	
	$("#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;
	});
	
	if($(":radio[@name='is_company']:checked").val() == "0")
		$(".companyHide").fadeOut({speed:"fast"});
	
	$(":radio[@name='is_company']").change(function(){
		
		if($(":radio[@name='is_company']:checked").val() == "1"){
			$(".companyHide").fadeIn({speed:"slow"});
		}else{
			$(".companyHide").fadeOut({speed:"slow"});
		} 
	});
	
	$("#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;
		}
	);
	
});