function api(object, action, params, callback) {
    var url = '';
    url = "/api/" + object + "/" + action;
    $.getJSON(url, params, callback);
}

function specialKey(evt)
{
    var code = evt.keyCode;
    if(code == 9 || code == 16 || code == 17 || code == 18 || code == 144 || code == 20 || code == 145 || code == 27 || code == 19 || code == 91 || code == 92 || code == 93 || code == 116 || code == 37 || code == 38 || code == 39 || code == 40)
    {
        return true;
    }
    return false;
}

function sklonujSlovo(stem, p1, p2, p3, count, prepend_count)
{
    if(prepend_count)
    {
        stem = count + ' ' + stem;
    }
    if(count >= 5 || count == 0)
    {
        return stem += p3;
    }
    if(count >= 2)
    {
        return stem += p2;
    }
    return stem += p2;
}


function createPP(x, y)
{
    pp = $('#pp');
    if(pp.length)
    {
        pp.remove();
    }
    var pp = $('<div />').attr('id', 'pp').addClass('container');
    $('body').append(pp);
    pp.append('<p class="center">připravuji náhled ...</p>');
    pp.append('<p class="center"><img src="/images/loader.gif" alt="nahrávám" /></p>');
    
    if(x + 488 > $(window).width())
    {
        x -= 310;
    }
    
    pp.css('left', x + 'px');
    pp.css('top', y + 'px');
    
    
    return pp;
}

function showPreview(product)
{
    var tmp = product.attr('id').split('_');
    var id = tmp[1];
    var offset = product.offset();
    pp = createPP(offset.left, offset.top);
    api('products', 'get', {'id': id, '_template_': 'store_product_preview.tpl'}, function(response) 
    {
        if(response['result'])
        {
            pp.html(response['data']);
            pp.fadeIn('slow');
            pp.mouseleave(function() { pp.remove(); });
        }
        else
        {
            $('#pp').remove();
        }
    });
}

function recalcTotalPrice()
{
    var dp = $('#delivery_payment').val();
    if(dp == 1)
    {
        $('#total-departure').html('120');
    }
    else if(dp == 2)
    {
        $('#total-departure').html('0');
    }
    else if(dp == 3)
    {
        $('#total-departure').html('350');
    }
    var total = parseInt($('#total-items').html()) + parseInt($('#total-departure').html()) 
    $('#total-price').html(total);
}

var pp = false;
var pptimer = false;

function bindProductList(list)
{
    $('.product a', list).hover(function(evt) 
    {
        clearTimeout(pptimer);
        if($('#pp').length)
        {
            $('#pp').remove();
        }
        var product = $(this).parents('.product');
        pptimer = setTimeout(function() { showPreview(product); }, 1000);
    }, 
    function(evt) {
        //~ if($('#pp').length)
        //~ {
            //~ $('#pp').remove();
        //~ }
        clearTimeout(pptimer);
    });
}

$(document).ready(function() 
{
    if($('#order-prices').length)
    {
        recalcTotalPrice();
    }
    $('#delivery_payment').change(function() { recalcTotalPrice(); });
    
    bindProductList($('.products-list'));
    
    $('#photocontestbanner').flash(
        { src: '/flash/banner550x150.swf', height: 150, width: 550 },
        { version: 7 }
    );
    $("#tabs").tabs();
    $('#prodejna-navigate').submit(function() 
    {
        if($('#navigate_from').val() != '')
        {
            $('#progress').html('<p class="center bottom" style="color:#20A6DB;"><strong>Hledám trasu</strong></p><img src="/images/loader-long.gif" alt="pracuji" />');
            calcRoute();
        }
        return false;
    });
    $('#travel_mode').change(function() 
    {
        $('#prodejna-navigate').submit();
    });
    if($('form#order').length)
    {
        $('#company_check').change(function() {
            if($(this).is('[checked]'))
            {
                $('#company_div').fadeIn();
            }
            else
            {
                $('#company_div').fadeOut();
            }
        });
        $('#caddress_check').change(function() {
            if($(this).is('[checked]'))
            {
                $('#caddress_div').fadeIn();
            }
            else
            {
                $('#caddress_div').fadeOut();
            }
        });
    }
    $('a.contest-vote').click(function() {
        $( "#contest-vote-dialog" ).show();
        
        var id = $(this).attr('id').split('_')[1];
        
        $('button.contest-vote-button').val(id);
        //~ alert('xxx')
        //~ return false;
    });
    function buildProductFilterSliderWithSubmit()
    {
        $('#product-filter #price-slider').slider('destroy');
        var price_from = parseInt($('input[name=price_from]').val());
        var price_to = parseInt($('input[name=price_to]').val());
        var price_min = parseInt($('input[name=price_min]').val());
        var price_max = parseInt($('input[name=price_max]').val());
        if(price_max < price_to)
        {
            price_to = price_max;
        }
        if(price_min > price_from)
        {
            price_from = price_min;
        }
        
        $('#product-filter #price-slider').slider({
                range: true,
                min: price_min,
                max: price_max,
                values: [price_from, price_to],
                step: 100,
                slide: function(event, ui) 
                {
                    $('input[name=price_from]').val(ui.values[0]);
                    $('input[name=price_to]').val(ui.values[1]);
                    $("#price-info").html('Cena od ' + ui.values[0] + ' do ' + ui.values[1] + ' Kč');
                    
                },
                stop: function(event, ui)
                {
                    $('#store_product_filter').submit();
                }
                
        });
    }
    
    function buildProductFilterSlider()
    {
        $('#product-filter #price-slider').slider('destroy');
        var price_from = parseInt($('input[name=price_from]').val());
        var price_to = parseInt($('input[name=price_to]').val());
        var price_min = parseInt($('input[name=price_min]').val());
        var price_max = parseInt($('input[name=price_max]').val());
        if(price_max < price_to)
        {
            price_to = price_max;
        }
        if(price_min > price_from)
        {
            price_from = price_min;
        }
        
        $('#product-filter #price-slider').slider({
                range: true,
                min: price_min,
                max: price_max,
                values: [price_from, price_to],
                step: 100,
                slide: function(event, ui) 
                {
                    $('input[name=price_from]').val(ui.values[0]);
                    $('input[name=price_to]').val(ui.values[1]);
                    $("#price-info").html('Cena od ' + ui.values[0] + ' do ' + ui.values[1] + ' Kč');
                    
                },
                stop: function(event, ui)
                {
                    var hash = $('#store_product_filter').serialize();
                    window.location.hash = '#' + hash;
                    updateProducts();
                }
                
        });
        updatePriceSliderLabel();
    }
    
    function updatePriceSliderLabel()
    {
        var price_from = parseInt($('input[name=price_from]').val());
        var price_to = parseInt($('input[name=price_to]').val());
        var price_min = parseInt($('input[name=price_min]').val());
        var price_max = parseInt($('input[name=price_max]').val());
        if(price_max < price_to)
        {
            price_to = price_max;
        }
        if(price_min > price_from)
        {
            price_from = price_min;
        }
        $("#price-info").html('Cena od ' + price_from + ' do ' + price_to + ' Kč');
    }
    
    var productListLock = false;
    var productListHash = false;
    var productListTimer = false;
    var productListTextTimer = false;
    
    /*disabled*/
    if($('#sssssstore_product_filter').length)
    {
        updatePriceSliderLabel();
        buildProductFilterSliderWithSubmit();
    }
    /*enabled*/
    if($('#store_product_filter').length)
    {
        productListHash = '';
        $('#store_product_filter select').change(function() 
        {
            var hash = $('#store_product_filter').serialize();
            window.location.hash = '#' + hash;
            updateProducts();
        });
        $('#store_product_filter input[type=text]').keyup(function(evt) 
        {
            if(specialKey(evt))
            {
                return false;
            }
            if(productListTextTimer)
            {
                clearTimeout(productListTextTimer);
            }
            productListTextTimer = setTimeout(function() { 
                var hash = $('#store_product_filter').serialize();
                window.location.hash = '#' + hash;
                updateProducts();
            }, 1000);
        });
        $('#store_product_filter select[name=orderby]').change(function() 
        {
            var hash = $('#store_product_filter').serialize();
            window.location.hash = '#' + hash;
            updateProducts();
        });
        $('#store_product_filter button[name=filter]').remove();
        buildProductFilterSlider();
        bindProductListPager();
        productListTimer = setTimeout(function() { checkProductListHash(); }, 100);
    }
    
    function bindProductListPager()
    {
        $('#pager a').click(function() 
        {
            var stranka = 1;
            var tmp = $(this).attr('href').split('stranka=');
            if(tmp.length == 2)
            {
                tmp = tmp[1].split('&');
                stranka = tmp[0];
            }
            $('#store_product_filter input[name=stranka]').val(stranka);
            var hash = $('#store_product_filter').serialize();
            window.location.hash = '#' + hash;
            updateProducts();
            return false;
        });
    }
    
    var checkProductListHash = function()
    {
        if(window.location.hash != productListHash)
        {
            updateProductFilter();
        }
        productListTimer = setTimeout(function() { checkProductListHash(); }, 100);
    }
    
    var unlockProductList = function()
	{
		if(productListLock)
		{
			productListLock.remove();
			productListLock = false;
		}
	}	
	var lockProductList = function()
	{
		if(!productListLock)
		{
			var towrap = $('#products-content');
			var offset = towrap.offset();
			var height = towrap.outerHeight();
			var width = towrap.outerWidth();
			productListLock = $('<div />').css({'position': 'absolute', 'top': offset.top, 'left': offset.left, 'width': width, 'height': height, 'z-index': 1000});
			var shadow = $('<div />').css({'width': towrap.outerWidth(), 'height': towrap.outerHeight(), 'background-color': '#CCC', 'opacity': 0.7});
			
			var loader = $('<div />').css({'background-color': 'white', 'border': '2px solid #CCC', 'padding': '10px', 'width': '240px', 'margin': '0 auto', 'text-align': 'center', 'z-index': 10000, 'position': 'absolute'});
			
			loader.append('<p style="color:#5F7F96;font-weight:bold;margin-bottom:1em;">vyhledávám...</p>');
			loader.append('<img src="/images/loader-long.gif" />');
			//~ var loadertop = height / 2 - (loader.outerHeight() + 80) / 2;
			var loadertop = 100;
			var loaderleft = width / 2 - (loader.outerHeight() + 260) / 2;
			loader.css({'top': loadertop, 'left': loaderleft});
			
			productListLock.append(loader);
			
			productListLock.append(shadow);
			if(towrap.is(':visible'))
			{
				$('body').append(productListLock);
			}
		}
	}
    
    function updateProductFilter()
    {
        var items = window.location.hash.substr(1).split('&');
        $('#store_product_filter input[name=stranka]').val(1);
        $.each(items, function(i, item) {
            var tmp = item.split('=');
            if(tmp.length == 2)
            {
                switch(tmp[0])
                {
                    case 'producer_id':
                        $('#store_product_filter #producer_id').val(tmp[1]);
                        break;
                    case 'text':
                        $('#store_product_filter #text').val(tmp[1]);
                        break;
                    case 'orderby':
                        $('#store_product_filter select[name=orderby]').val(tmp[1]);
                        break;
                    case 'stranka':
                        $('#store_product_filter input[name=stranka]').val(tmp[1]);
                        break;
                    case 'price_from':
                        $('#store_product_filter input[name=price_from]').val(tmp[1]);
                        $('#product-filter #price-slider').slider('values', 0, [parseInt(tmp[1])]);
                        updatePriceSliderLabel();
                        break;
                    case 'price_to':
                        $('#store_product_filter input[name=price_to]').val(tmp[1]);
                        $('#product-filter #price-slider').slider('values', 1, [parseInt(tmp[1])]);
                        updatePriceSliderLabel();
                        break;
                }
                    
            }
            
        });        
        productListHash = window.location.hash;
        updateProducts();
    }
    
    function updateProducts()
    {
        if(typeof(pageTracker) != 'undefined')
        {
            pageTracker._trackPageview(window.location.pathname);        
        }
        lockProductList();
        var filter = $('#store_product_filter').serializeArray();
        var hash = $('#store_product_filter').serialize();
        productListHash = window.location.hash;
        filter.push({'name': 'response', 'value': 'product-list'});
        $.getJSON(window.location.pathname, filter, function(data) 
        {
            $('#products-content').html(data['content']);
            $('#product-filter-total').html('Celkem ' + sklonujSlovo('produkt', '', 'y', 'ů', data['total_count'], true));
            $('input[name=price_min]').val(data['price_min']);
            $('input[name=price_max]').val(data['price_max']);
            var producers = $('#store_product_filter #producer_id');
            var producer_id = producers.val();
            producers.html('<option value="">nerozhoduje&hellip;</option>');
            $.each(data['producers'], function(id, name) {
                producers.append('<option value="' + id + '">' + name + '</option>');
            });
            producers.val(producer_id);
            buildProductFilterSlider();
            bindProductListPager();
            bindProductList($('#products-content'));
            unlockProductList();
        });
        
    }

});

/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function(){
	
var $$;

/**
 * 
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 * 
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 * 
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
	height: 240,
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+escape(this[key])+'&';
	return s.replace(/&$/, '');		
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String 
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it 
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more 
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<embed ' + String(htmlOptions) + '/>';		
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}
	
})();
