var lastTMenuOpen = null;
var fadeoutTmr = null;

 var timeout = 1500;
var closetimer = 0;
var ddmenuitem = 0;
var lastShow = null;
var lastShowObj = null;
function mainSel(obj, val) {
    if (val == 1) {
//        if (obj.className == 'l1 sel') return;
//        lastShowObj = obj;
//        lastShow = setTimeout(showLast, 2000);

        if (obj.className == 'l1')
            obj.className = 'l1 sel';
        if (obj.className == 'last')
            obj.className = 'last sel';
        var ul = obj.getElementsByTagName("ul")[0];
        ul.style.display = 'block';

    } else {
       
        if (obj.className == 'l1 sel')
            obj.className = 'l1';
        if (obj.className == 'last sel')
            obj.className = 'last';
        var ul = obj.getElementsByTagName("ul")[0];
        ul.style.display = 'none';clearTimeout(lastShow);
    }
}
function showLast()
{
    
}
function detailImgSel(url,obj) {
    var o = document.getElementById('image-detail');
    o.src = url;
    var e = document.getElementsByName("detail-galery");
    for (var i = 0; i < e.length; i++) { e[i].className = ''; }
    obj.parentNode.className = 'sel';
}


$(document).ready(function() {
    $("a.lightbox").fancybox({ 'titleShow': false, 'type': 'image' });
    $("a.group").fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true, 'titleShow': false
    });

    /*Detail - založky*/
    var tabContainers = $('#tabs-panel > div');
    $('ul.tabs a').click(function() {
        tabContainers.hide();
        tabContainers.filter(this.hash).show('fast');
        $('ul.tabs li').removeClass('selected');
        $(this).parent().addClass('selected');
        if ($(this).attr("href") == '#tab-splatky')
            renderSplatkyFirst(document.getElementById('detailPrice').value);
        return false;
    });
    $('ul.tabs li.selected a').click();

    $("#linkDisposition").fancybox({
        'padding': 10,
        'autoScale': true,
        'titleShow': false,
        'transitionIn': 'none',
        'transitionOut': 'none'
    });
    $("#linkPhehelp").fancybox({
        'padding': 10,
        'autoScale': true,
        'titleShow': false,
        'transitionIn': 'none',
        'transitionOut': 'none'
    });

     $("#linkSperkovnice").fancybox({
        'padding': 10,
        'autoScale': true,
        'titleShow': false,
        'transitionIn': 'none',
        'transitionOut': 'none'
    });


    /* TOP MENU */
    $("#main-menu ul li").mouseleave(function() {
        if (fadeoutTmr != null) { clearTimeout(fadeoutTmr); }
        $(this).find("ul.dynamic-menu").slideUp('fast').hide();
        $(this).removeClass("sel");
    });
    $("#main-menu ul li").mousemove(function() {
        $(this).addClass("sel");
        lastTMenuOpen = $(this).find("ul.dynamic-menu");
        if (fadeoutTmr != null) {
            clearTimeout(fadeoutTmr);
        }
        fadeoutTmr = setTimeout(function() {
            if (fadeoutTmr != null) { clearTimeout(fadeoutTmr); }
            lastTMenuOpen.slideDown('fast').show();
        }, 150);
    });


    /* VYHLEDÁVÁNÍ */
    var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
    function fnFormatResultItem(value, data, currentValue, s) {
        var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
        var name = value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
        if (s.Type == 'pr') {
            var akce = '';
            var sleva = '';
            var novinka = '';
            var icons = '';
            if (s.SearchAttributes.toString().indexOf('A') > -1) {
                akce = '<span class="akce">Akce</span>';
            }
            if (s.SearchAttributes.toString().indexOf('N') > -1) {
                novinka = '<span class="novinka">Novinka</span>';
            }
            if (s.SearchAttributes.toString().indexOf('S') > -1) {
                sleva = '<span class="sleva">Sleva ' + s.Discount + '%</span>';
            }
            if (akce != '' && sleva != '' && novinka != '') {
                icons = '<div class="labels-ajax">' + akce + sleva + '</div>'
            } else if (akce != '' || sleva != '' || novinka != '') {
                icons = '<div class="labels-ajax">' + akce + novinka + sleva + '</div>'
            }




            return '<img class="im" height="50" width="62" src="' + core_hUrl + 'image.aspx?t=search&id=' +
            s.ImageKey + '"/><div class="d1"><h4>' + name + '</h4>' + s.Description + '</div><div class="d2"><strong>' + s.PriceWithVatFormat + '</strong>' + icons + '</div><div class="clear"></div>';
        } else {
            return '<div class="cat">' + name + '</div>';
        }
    }
    function fnLoadingSearch() { $("#img-loading").attr("src", core_hPath + 'images/ajax_loading.gif'); }
    function fnLoadedSearch() { $("#img-loading").attr("src", core_hPath + 'images/ajax_search_ok.gif'); }

    var sBox = $("#main-search-box"); //width: sBox.width(), left: 15
    options = { serviceUrl: core_hUrl + 'service-search.aspx?', width: '376px',
        headers: [{ type: 'pr', text: 'Produkty' }, { type: 'cat', text: 'Kategorie'}],
        onSelectNotSetInput: true,
        onSelect: function(s) {
            document.location = s.Url;
            return;
        },
        fnFormatResult: fnFormatResultItem
        ,onLoading: fnLoadingSearch,
        onLoaded: fnLoadedSearch,
        minChars:2,
        maxHeight: 650
    };
    $("#searchInput").autosearch(options);


    $("#tab-paramlist span").tooltip();


});




(function($) {

    var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

    function fnFormatResult(value, data, currentValue, s) {
        var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
        return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
    }

    function AutoSearch(el, options) {
        this.el = $(el);
        this.el.attr('autosearch', 'off');
        this.suggestions = [];
        this.data = [];
        this.badQueries = [];
        this.selectedIndex = -1;
        this.currentValue = this.el.val();
        this.intervalId = 0;
        this.cachedResponse = [];
        this.onChangeInterval = null;
        this.ignoreValueChange = false;
        this.serviceUrl = options.serviceUrl;
        this.isLocal = false;
        this.options = {
            autoSubmit: false,
            minChars: 1,
            maxHeight: 380,
            deferRequestBy: 300,
            width: 0,
            highlight: true,
            params: {},
            fnFormatResult: fnFormatResult,
            delimiter: null,
            zIndex: 9999,
            headers: [],
            onSelect: null,
            onSelectNotSetInput: false /*Udává zda vyplňovat*/,
            onLoading: null,
            onLoaded: null
        };
        this.initialize();
        this.setOptions(options);
    }

    $.fn.autosearch = function(options) {
        return new AutoSearch(this.get(0), options);
    };


    AutoSearch.prototype = {

        killerFn: null,

        initialize: function() {

            var me, uid, autocompleteElId;
            me = this;
            uid = new Date().getTime();
            autocompleteElId = 'Autocomplete_' + uid;

            this.killerFn = function(e) {
                if ($(e.target).parents('.autocomplete').size() === 0) {
                    me.killSuggestions();
                    me.disableKillerFn();
                }
            };

            if (!this.options.width) { this.options.width = this.el.width(); }


            this.mainContainerId = 'AutocompleteContainter_' + uid;

            $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none;"></div></div></div>').appendTo('body');

            this.container = $('#' + autocompleteElId);

            this.fixPosition();
            if (window.opera) {
                this.el.keypress(function(e) { me.onKeyPress(e); });
            } else {
                this.el.keydown(function(e) { me.onKeyPress(e); });
            }
            this.el.keyup(function(e) { me.onKeyUp(e); });
            this.el.blur(function() { me.enableKillerFn(); });
            this.el.focus(function() { me.fixPosition(); });
        },

        setOptions: function(options) {
            var o = this.options;
            $.extend(o, options);
            if (o.lookup) {
                this.isLocal = true;
                if ($.isArray(o.lookup)) { o.lookup = { suggestions: o.lookup, data: [] }; }
            }
            $('#' + this.mainContainerId).css({ zIndex: o.zIndex });
            this.container.css({ maxHeight: o.maxHeight + 'px', width: o.width });
        },

        clearCache: function() {
            this.cachedResponse = [];
            this.badQueries = [];
        },

        disable: function() {
            this.disabled = true;
        },

        enable: function() {
            this.disabled = false;
        },

        fixPosition: function() {
            var offsetLocal = this.el.offset();
            $('#' + this.mainContainerId).css({ top: (offsetLocal.top + this.el.innerHeight()) + 'px', left: offsetLocal.left + 'px' });
        },

        enableKillerFn: function() {
            var me = this;
            $(document).bind('click', me.killerFn);
        },

        disableKillerFn: function() {
            var me = this;
            $(document).unbind('click', me.killerFn);
        },

        killSuggestions: function() {
            var me = this;
            this.stopKillSuggestions();
            this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300);
        },

        stopKillSuggestions: function() {
            window.clearInterval(this.intervalId);
        },

        onKeyPress: function(e) {
            if (this.disabled || !this.enabled) { return; }
            // return will exit the function
            // and event will not be prevented
            switch (e.keyCode) {
                case 27: //KEY_ESC:
                    if ($.isFunction(this.options.onLoaded)) { this.options.onLoaded(); }
                    this.el.val(this.currentValue);
                    this.hide();
                    break;
                case 9: //KEY_TAB:
                case 13: //KEY_RETURN:
                    if (this.selectedIndex === -1) {
                        this.hide();
                        return;
                    }
                    this.select(this.selectedIndex);
                    if (e.keyCode === 9/* KEY_TAB */) { return; }
                    break;
                case 38: //KEY_UP:
                    this.moveUp();
                    break;
                case 40: //KEY_DOWN:
                    this.moveDown();
                    break;
                default:
                    return;
            }
            e.stopImmediatePropagation();
            e.preventDefault();
        },

        onKeyUp: function(e) {
            if (this.disabled) { return; }
            switch (e.keyCode) {
                case 38: //KEY_UP:
                case 40: //KEY_DOWN:
                    return;
            }
            clearInterval(this.onChangeInterval);
            if (this.currentValue !== this.el.val()) {
                if (this.options.deferRequestBy > 0) {
                    // Defer lookup in case when value changes very quickly:
                    var me = this;
                    this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
                } else {
                    this.onValueChange();
                }
            }
        },

        onValueChange: function() {
            clearInterval(this.onChangeInterval);

            this.currentValue = this.el.val();
            var q = this.getQuery(this.currentValue);
            this.selectedIndex = -1;
            if (this.ignoreValueChange) {
                this.ignoreValueChange = false;
                return;
            }
            if (q === '' || q.length < this.options.minChars) {
                this.hide();
            } else {
                this.getSuggestions(q);
            }
        },

        getQuery: function(val) {
            var d, arr;
            d = this.options.delimiter;
            if (!d) { return $.trim(val); }
            arr = val.split(d);
            return $.trim(arr[arr.length - 1]);
        },

        getSuggestionsLocal: function(q) {
            alert('getSuggestionsLOCAL');
            var ret, arr, len, val, i;
            arr = this.options.lookup;
            len = arr.suggestions.length;
            ret = { suggestions: [], data: [] };
            q = q.toLowerCase();
            for (i = 0; i < len; i++) {
                val = arr.suggestions[i];
                if (val.toLowerCase().indexOf(q) === 0) {
                    ret.suggestions.push(val);
                    ret.data.push(arr.data[i]);
                }
            }
            return ret;
        },

        //vrací návrhy - data
        getSuggestions: function(q) {

            if ($.isFunction(this.options.onLoading)) { this.options.onLoading(); }

            var cr, me;
            cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
            if (cr && $.isArray(cr.suggestions)) {
                this.suggestions = cr.suggestions;
                this.data = cr.data;
                this.suggest();
            } else if (!this.isBadQuery(q)) {
                me = this;
                me.options.params.query = q;
                //stahuji data ze serveru
                $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text');
            }
        },

        isBadQuery: function(q) {
            var i = this.badQueries.length;
            while (i--) {
                if (q.indexOf(this.badQueries[i]) === 0) { return true; }
            }
            return false;
        },

        hide: function() {
            if ($.isFunction(this.options.onLoaded)) { this.options.onLoaded(); }
            this.enabled = false;
            this.selectedIndex = -1;
            this.container.hide();
            this.container.parent().hide();

        },

        suggest: function() {
            //pokud je výsledek 0, skryju
            if (this.suggestions.length === 0) {
                this.hide();
                return;
            }

            var me, len, div, f, v, i, s, mOver, mClick, span, divCat;
            me = this;
            len = this.suggestions.length;

            f = this.options.fnFormatResult; /*formatovací funkce*/
            v = this.getQuery(this.currentValue);
            mOver = function(xi) { return function() { me.activate(xi); }; };
            mClick = function(xi) { return function() { me.select(xi); }; };
            this.container.hide().empty();


            //render headers
            //span = '<div class="products">';
            for (i = 0; i < this.options.headers.length; i++) {
                divCat = $('<div id="' + this.mainContainerId + this.options.headers[i].type + '" class="box"><h3>' + this.options.headers[i].text + '</h3></div>');
                this.container.append(divCat);
                if (this.options.headers[i].type == 'pr') {
                    divCat = $('<div class="link-all"><a href="#" id="' + this.mainContainerId + 'sAll">ukaž všechno nalezené zboží</a></div>');
                    divCat.click(function() { Core_Search(v, '', 'zadejte hledaný text'); return false; });
                    this.container.append(divCat);

                }
            }
            //span = span + '</div>';


            for (i = 0; i < len; i++) {

                //podle typu výsledku hledání rozděluji na produkty a kategorie
                s = this.suggestions[i];

                div = $((me.selectedIndex === i ? '<div class="item selected"' : '<div class="item"') + ' title="' + s.Name + '">' + f(s.Name, s.pkProducts, v, s) + '</div>');
                div.mouseover(mOver(i));
                div.click(mClick(i));

                $('#' + this.mainContainerId + s.Type).append(div);
                //this.container.append(div);
            }
            for (i = 0; i < this.options.headers.length; i++) {
                div = $('#' + this.mainContainerId + this.options.headers[i].type);
                if (div.children().size() <= 1) {
                    div.remove();
                    if (this.options.headers[i].type == 'pr') {
                        this.container.children('.link-all').remove();
                    }
                }
            }

            this.enabled = true;
            this.container.parent().show();
            this.container.show();
            if ($.isFunction(this.options.onLoaded)) { this.options.onLoaded(); }
        },

        //zrpacování odpovědí
        processResponse: function(text) {
            var response;

            try {
                response = eval('(' + text + ')');
            } catch (err) { return; }
            if (!$.isArray(response.data)) { response.data = []; }
            this.cachedResponse[response.query] = response; //uložim do cache poslední odpověd
            if (response.suggestions.length === 0) { this.badQueries.push(response.query); }

            if (response.query === this.getQuery(this.currentValue)) {
                this.suggestions = response.suggestions;
                this.data = response.data;
                this.suggest();
            }
        },

        activate: function(index) {
            var divs, activeItem;
            divs = this.container.children().children('.item');

            // Clear previous selection:
            if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
                $(divs.get(this.selectedIndex)).attr('class', 'item');
            }
            this.selectedIndex = index;
            if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
                activeItem = divs.get(this.selectedIndex);
                $(activeItem).attr('class', 'item selected');
            }
            return activeItem;
        },

        deactivate: function(div, index) {
            div.className = '';
            if (this.selectedIndex === index) { this.selectedIndex = -1; }
        },

        select: function(i) {
            var selectedValue, f;
            selectedValue = this.suggestions[i].Name;
            if (selectedValue) {

                if (this.options.onSelectNotSetInput != true) {
                    this.el.val(selectedValue);
                }

                if (this.options.autoSubmit) {
                    f = this.el.parents('form');
                    if (f.length > 0) { f.get(0).submit(); }
                }
                this.ignoreValueChange = true;

                this.hide();

                this.onSelect(i);

            }
        },

        moveUp: function() {
            if (this.selectedIndex === -1) { return; }
            if (this.selectedIndex === 0) {
                this.container.children().children('.item').get(0).className = 'item';
                this.selectedIndex = -1;
                this.el.val(this.currentValue);
                return;
            }
            this.adjustScroll(this.selectedIndex - 1);
        },

        moveDown: function() {
            if (this.selectedIndex === (this.suggestions.length - 1)) { return; }
            this.adjustScroll(this.selectedIndex + 1);
        },

        adjustScroll: function(i) {
            var activeItem, offsetTop, upperBound, lowerBound;
            activeItem = this.activate(i);
            offsetTop = activeItem.offsetTop;
            upperBound = this.container.scrollTop();
            lowerBound = upperBound + this.options.maxHeight - 25;
            if (offsetTop < upperBound) {
                this.container.scrollTop(offsetTop);
            } else if (offsetTop > lowerBound) {
                this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
            }
            //this.el.val(this.suggestions[i]);
        },

        onSelect: function(i) {

            var me, onSelect, getValue, s, d;
            me = this;
            onSelect = me.options.onSelect;

            getValue = function(value) {
                var del, currVal, arr;
                del = me.options.delimiter;
                if (!del) { return value; }
                currVal = me.currentValue;
                arr = currVal.split(del);
                if (arr.length === 1) { return value; }
                return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
            };
            s = me.suggestions[i];

            //d = me.data[i];
            //me.el.val(getValue(s));
            if (this.options.onSelectNotSetInput != true) {
                me.el.val(s.Name);
            }
            if ($.isFunction(onSelect)) { onSelect(s); }



        }

    };

} (jQuery));





function testICO(x)
{
  try
  {
    var a = 0;
    if(x.length == 0) return true;
    if(x.length != 8) throw 1;
    var b = x.split('');
    var c = 0;
    for(var i = 0; i < 7; i++) a += (parseInt(b[i]) * (8 - i));
    a = a % 11;
    c = 11 - a;
    if(a == 1) c = 0;
    if(a == 0) c = 1;
    if(a == 10) c = 1;
    if(parseInt(b[ 7]) != c) throw(1);
  }
  catch(e)
  {
    //alert('Zadané IČ není korektní!');
    return false;
  }
  return true;
}


function testDIC(x)
{
  try
  {
    if(x.length == 0) return true;
    var id = x.substr(0, 2).toUpperCase();
    x = x.substr(2);
    if((id == 'CZ') || (id == 'SK'))
    {
      if(x.length < 8) throw 1;
      if(x.length > 11) throw 1;
      if(x.length == 8)
      {
        return testICO(x);
      }
      else
      {
        return testRC(x, 18);
      }
      throw 1;
    }
    //alert('Není možné zkontrolovat DIČ mimo Českou a Slovenskou republiku!');
    return true;
  }
  catch(e)
  {
    //alert('Zadaný DIČ není korektní!');
    return false;
  }
}



function testRC(x, age)
{
  if(!age) age = 0;
  try
  {
    if(x.length == 0) return true;
    if(x.length < 9) throw 1;
    var year = parseInt(x.substr(0, 2), 10);
    var month = parseInt(x.substr(2, 2), 10);
    var day = parseInt( x.substr(4, 2), 10);
    var ext = parseInt(x.substr(6, 3), 10);
    if((x.length == 9) && (year < 54)) return true;
    var c = 0;
    if(x.length == 10) c = parseInt(x.substr(9, 1));
    var m = parseInt( x.substr(0, 9)) % 11;
    if(m == 10) m = 0;
    if(m != c) throw 1;
    year += (year < 54) ? 2000 : 1900;
    if((month > 70) && (year > 2003)) month -= 70;
    else if (month > 50) month -= 50;
    else if ((month > 20) && (year > 2003)) month -= 20;
    var d = new Date();
    if((year + age) > d.getFullYear()) throw 1;
    if(month == 0) throw 1;
    if(month > 12) throw 1;
    if(day == 0) throw 1;
    if(day > 31) throw 1;
  }
  catch(e)
  {
    //alert('Zadaný údaj není korektní!');
    return false;
  }
  return true;
}

  //kontrola formatu ICQ
  function check_format_psc(my_field) {
      format = /^[0-9]{5}$/
      if (format.test(my_field.value) == true)
   	   return true;
      else
           return false;
   }

function randomString() {
	var chars = "12";
	var string_length = 1;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}
