

//####################################//


function checkInputData(type)
{
	if(type == 'int')
	{
		if((event.keyCode < 48) || (event.keyCode > 57) && event.keyCode != 13)
			event.returnValue = false;
	}
	else
	if(type == 'float')
	{
		if((event.keyCode < 48 || event.keyCode > 57)
			 && event.keyCode != 46 && event.keyCode != 44 && event.keyCode != 13)
			event.returnValue = false;
	}
}


//####################################//


function displayMenu(id, menu)
{
	menuSrc = $("#"+menu);
	if(!menuSrc)
		return;
	
	$img = $("#IMG_"+menu);
	
	if(menuSrc.is(":hidden"))
	{
		menuSrc.slideDown("normal"); 
	}
	else
	{
		menuSrc.slideUp("normal"); 
	}
	
	$img.toggleClass('menu-image-plus');
	$img.toggleClass('menu-image-minus');
}


//####################################//

checkoutUrl = "";

function orderIt(IDp){
   var No = 1;
   var Loc = Name = '';
   if(document.getElementById("No"+IDp))
      No = document.getElementById("No"+IDp).value;
   Loc = checkoutUrl.replace(/&amp;/g,'&');
   Loc = Loc.replace('PRODUCT', IDp).replace('NO', No);
   window.location.href = Loc;
}


//####################################//
// Select variants

var sel_values = new Array();
var variations = new Array();
var selects = new Array();
var order_not_in_store = false;

function registerSelect(select_id){
       selects[selects.length]=$("#"+select_id);
}

function variationChanged(label_id, select_id, num)
{
       if(selects[num] == null)
               return;

       var val = selects[num].val();
       sel_values[num] = val;

       setAvailable(num);

       findCombination();
}

function findInArray(arr, value)
{
       for(index in arr)
               if(arr[index] == value)
                       return true;

       return false;
}

function setAvailable(num)
{	
      for(var x = num; x< selects.length; x++)
       {
               if(x > 0)
                       value =  selects[x-1].val();
               options = selects[x].get(0).options;
               for(var option = 0; option< options.length; option++)
               {
                       disable = true;
                       for(variation in variations)
                       {
                               if(x > 0 && !findInArray(variations[variation]["combinations"], value))
                                       continue;

                               if(!findInArray(variations[variation]["combinations"], options[option].value))
                                       continue;

                               if(order_not_in_store == true || variations[variation]["in_store"] > 0)
                                       disable = false;
                       }

                       selects[x].get(0).options[option].disabled=disable;
               }
       }
}

function selectFirstAvailable()
{
       for(variation in variations)
       {
               if(order_not_in_store == true || variations[variation]["in_store"] > 0)
               {
                       for(var x = 0; x < variations[variation]["combinations"].length; x++)
                       {
                               sel_values[x] = variations[variation]["combinations"][x];
                               selects[x].val(variations[variation]["combinations"][x]);
                       }
                       break;
               }
       }

       setAvailable(0);

       findCombination();
}

function findCombination()
{
       var result = new Array(variations.length);
       for(var y = 0; y < variations.length; y++)
               result[y] = variations[y];
       var found_iter = null;

       for(var y = 0; y < result.length; y++)
       {
               var count_identical = 0;

               for(var x = 0; x < sel_values.length; x++)
               {
                       var item_id = parseInt(sel_values[x]);
                       for(var z = 0; z < result[y]['combinations'].length; z++)
                       {
                                       //alert(item_id + ' == ' + result[y]['combinations'][z]);
                               if(item_id == result[y]['combinations'][z])
                               {
                                       count_identical++;
                               }
                       }

               }

               if(count_identical == count_labels)
               {
                       found_iter = y;
                       break;
               }
       }

       var found = false, var_id = '', in_store = '-', delivery_time = 'tuto variantu nelze objednat', price = 0;
       if(found_iter != null  &&  result[found_iter] != null)
       { 
    	   found = true; 
    	   var_id = result[found_iter]['id']; 
    	   in_store = result[found_iter]['in_store']; 
    	   delivery_time = result[found_iter]['delivery_time'];
    	   price = result[found_iter]['price'];
	   }
       if(found_iter != null  &&  result[found_iter] != null && result[found_iter]['in_store'] <= 0 && result[found_iter]['delivery_time']=="vyprodáno")
    	   found = false;

       // vypsat
       $('#deliveryTimeVariation').html(delivery_time); 
       $('#inStoreVariation').html(in_store);
       if(price[0] != '0')
	   {
    	   $('#priceVariation').html(price);
           $('#priceVariationWrap').show("fast");
	   }
       else
    	   $('#priceVariationWrap').hide("fast");
       
       $('#cartVar').val(var_id); 
       $('#cartPieces').attr('disabled', (!found)); 
       $('#cartButton').attr('disabled', (!found));
}

$(function(){
	$('#priceVariationWrap').hide();
	selectFirstAvailable();
});

//####################################//

function loadPage(url, part)
{
	$("#middle").fadeTo("fast", 0.33);
	
	$("#middle").load(
		url+" #in_middle", 
		null, 
		function(){
			$("#middle").fadeTo('fast', 1);
		}
	);

	return false;
}

function unserialise(Data){
    var DataParts = Data.split("&");
    var Serialised = new Object();
    $.each(DataParts, function(index, value){
        var Properties = value.split("=");
        if(Properties.length == 2)
        	Serialised[Properties[0]] = Properties[1];
    });
    return Serialised;
};

//############### CATEGORY LOAD AJAX #####################//
var filter_current_hash = '';
function loadCategory(appendUrl, baseUrl)
{
	if(!$.isArray(appendUrl))
		appendUrl = unserialise(appendUrl);

	if(baseUrl == undefined)
		baseUrl = window.location.href;
	
	queryUrl = (baseUrl.indexOf("#") > -1) ? baseUrl.substring(0, baseUrl.indexOf("#")) :  baseUrl;
	baseUrl = (queryUrl.indexOf("?") > -1) ? queryUrl.substring(0, queryUrl.indexOf("?")) :  queryUrl;
	queryUrl = queryUrl.substring(baseUrl.length+1);
	
	queryArray = unserialise(queryUrl);
	$.each(appendUrl, function(index, value){
		queryArray[index] = value;
	});
	
	queryUrl = new Array();
	$.each(queryArray, function(index, value){
		queryUrl.push(index+"="+value);
	});
	queryUrl = decodeURIComponent(queryUrl.join("&"));

	if(filter_current_hash != queryUrl)
	{
		if(window.location.hash != "#"+queryUrl)
			window.location.hash = queryUrl;
		
		filter_current_hash = window.location.hash.substring(1);

		$("#productList").fadeTo("slow", 0.33);
		
		fillFilter(unserialise(queryUrl));
		
		$("#productList").load(
			baseUrl+"?"+queryUrl+" #productList", 
			null, 
			function(){
				$("#productList").fadeTo('slow', 1);
			}
		);
	}

	return false;
}

function loadCategoryPage(url)
{
	loadCategory($("#filter_form").serialize(), url);
	scrollTo("#filtr-obal");
	return false;
}

function scrollTo(anchor)
{
	$anchor = $(anchor);
	$('html, body').stop().animate({
		scrollTop: $anchor.offset().top
		}, 1000);
}


function fillFilter(values)
{
	for(key in values)
	{
		obj = $("#filter_form :input[name='"+key+"']");
		obj.val(values[key].replace(/\+/g, " "));
		obj.trigger("loadChange");
	}
}

//############### LOAD HASH PARAMETERS #####################//
if(window.$ != undefined)
	$(document).ready(function() {
		window.setInterval(function() {
			hash = window.location.hash;
			if(hash == "")
				hash = "#";
		    if (hash != "#"+filter_current_hash) {
		    	loadCategory(hash.substring(1));
		    }
		}, 100);
	}); // wrapping this function in the jQuery selector delays setting up the timeout until the page has loaded.

//############### FILTER #####################//

function filterOnLoad(responseText, textStatus, XMLHttpRequest)
{
	if(textStatus == "success" || textStatus == "notmodified")
	{
		filter_loaded = true;
		$("#filter_loading").slideUp("slow");
		$("#filter").slideDown("slow");
	}
}

function filterToggle()
{
	if($("#filter").is(":hidden"))
	{
		if(!filter_loaded)
		{
			$("#filter").load(filter_url, null, filterOnLoad);
			$("#filter_loading").slideDown("slow");
		}
		else
			$("#filter").slideDown("slow");
	}
	else 
	{
		$("#filter").slideUp("slow");
		loadCategory("");
	}
}

function setFilterValue(input, from, to)
{
   input.val(from.toFixed(0) + ' Kč - ' + to.toFixed(0) + ' Kč');
}

function initFilterPrice(slider, input) {
	var doNoUpdate = false;
	slider.slider({
		range: true,
		min: filter_price_min,
		max: filter_price_max,
		values: [filter_price_min, filter_price_max],
		slide: function(event, ui) {
		   setFilterValue(input, ui.values[0], ui.values[1]);
		},
		change: function(event, ui) {
			if(doNoUpdate)
				return;
			setFilterValue(input, ui.values[0], ui.values[1]);
			loadCategoryPage();
		}
	});
	setFilterValue(input, slider.slider("values", 0), slider.slider("values", 1));
	input.bind("loadChange", function(){
		var regexp = /\d+/g;
		var matches = input.val().match(regexp);
		if(matches.length == 2)
		{
			if(slider.slider("values", 0) != matches[0] || slider.slider("values", 1) != matches[1])
			{
				doNoUpdate = true;
				slider.slider("values", 0, matches[0]);
				slider.slider("values", 1, matches[1]);
				doNoUpdate = false;
			}
		}
	});
};

function initFilter(form){
	$(form + " :input").change(
		function(o){
			loadCategoryPage();
		}
	);
};

//############### AUTOCOMPLETE #####################//

function initAutocomplete(input, type)
{
	$(function() {
		$input = $(input);
		$input.autocomplete({
			minLength: 2,
			source: "/launch.php?s=autocomplete&type="+type
		});
		
		$input.bind( "autocompleteselect", function(event, ui) {
			$input.val(ui.item.value);
			$($input[0].form.submit).click();
		});
	});
}
