
function hashize (id) {
    if (id != null && id != '') {
        if (id.toString().substr(0, 1) != '#') {
            return ('#'.concat(id));
        } else {
            return id;
        }
    } else if (id != null && id == '') {
        return '';
    } else {
        return null;
    }
}

function clickEmpty(item, text){
    if(item.value==text) {
        item.value="";
    }
}

var showAndHideDiv1 ='';
var showAndHideDiv2 ='';

function showAndHideBack() {
    if ($(hashize(showAndHideDiv1)) == null || $(hashize(showAndHideDiv2)) == null) {
        return false;
    }

    if (showAndHideDiv1 != "") {
        $(hashize(showAndHideDiv2)).show();
        $(hashize(showAndHideDiv1)).hide();
    }

    showAndHideDiv1="";
    showAndHideDiv2="";
}

function showAndHideAlone(id,id2) {
    if (id != null && $(hashize(id)) != null) {
        $(hashize(id)).show();
    }
    if (id2 != null && $(hashize(id2)) != null) {
        $(hashize(id2)).hide();
    }
}

function showAndHide(id,id2) {
    showAndHideBack();

    showAndHideDiv1=id;
    showAndHideDiv2=id2;

    if ($(hashize(showAndHideDiv1)) != null) {
        $(hashize(showAndHideDiv1)).show();
    }
    if ($(hashize(showAndHideDiv2)) != null) {
        $(hashize(showAndHideDiv2)).hide();
    }
}

/**
 * Comment
 */
function showAndHideAgain(id,id2) {
    if (id != null && $(hashize(id)).is(':visible')) {
        showAndHideAlone(id2, id);
    } else {
        showAndHideAlone(id, id2);
    }
}

var showAndHideDiv = '';
function show(id) {
    showAndHideDiv=id;
    $(hashize(showAndHideDiv)).show();
}

/**
 * Ma se formular po odeslani ajaxem resetovat?
 */
var resetFormAfterAjaxSuccess = false;
/**
 * Funkce pro odeslani formulare ajaxem. Po uspesnem odeslani resetuje form.
 * @param idDiv identifikace divu, spolecna cast pro id ke kterym se vstahuje
 *        odesilany formular, animace, message, a div pro zobrazeni
 * @param formDiv pokud je uvedeny, pouzije se jako zdrojovy formular.
 * @param idDivAnimationAndMessages pokud je uveden, pouzije se jako div pro animaci a hlasky
 */
function formupdateReset(idDiv,formDiv,idDivAnimationAndMessages){
    resetFormAfterAjaxSuccess = true;
    formupdate(idDiv,formDiv,idDivAnimationAndMessages);
}

/**
 * Pred element predany v argumentu vlozi hidden input s name 't' a value ma aktualni cas = promenna pro ajax
 */
function addTimeInputBefore(button) {
    $(button).before('<input type="hidden" name="t" value="'+ new Date().getTime() + '" />');
}
/**
 * funkce pro odeslani formulare ajaxem
 * vyuziva rozsireni http://malsup.com/jquery/form
 * @param idDiv identifikace divu, spolecna cast pro id ke kterym se vstahuje
 *        odesilany formular, animace, message, a div pro zobrazeni
 * @param formDiv pokud je uvedeny, pouzije se jako zdrojovy formular.
 * @param idDivAnimationAndMessages pokud je uveden, pouzije se jako div pro animaci a hlasky
 */
function formupdate(idDiv,formDiv,idDivAnimationAndMessages){
    // nastavime id vsech elementu
    var animationDiv = idDiv + "Anim";
    var formId = idDiv + "Form";
    var contentDiv = idDiv + "Ajax";
    var messageDiv = idDiv + "Msg";

    // pokud je zadan jiny formular pouzije se ten
    if (formDiv){
        formId = formDiv;
    }

    //pokud je zadan jiny div pro animaci a hlasky, pouzije se
    if (idDivAnimationAndMessages){
        animationDiv = idDivAnimationAndMessages + "Anim";
        messageDiv = idDivAnimationAndMessages + "Msg";
    }

    //zobrazime animaci prubehu
    $(hashize(animationDiv)).show();

    // pomoci metody odesleme formular na adresu ktera je zadana v elementu.
    $(hashize(formId)).ajaxForm({
        target: hashize(contentDiv),
        success: function() {
            $(hashize(contentDiv)).fadeIn('slow');
            showAndHideBack();
            $(hashize(animationDiv)).hide();
            if ($(hashize(messageDiv))) {
                setTimeout(function() {
                    $(hashize(messageDiv)).slideUp('slow');
                }, 2500);
            }
        },
        resetForm: resetFormAfterAjaxSuccess
    });

    return false;
}

/** funkce provede ajaxove odkaz a aktualizuje zadany div
 * @param idDiv identifikace divu, spolecna cast pro id ke kterym se vstahuje
 *        odesilany formular, animace, message, a div pro zobrazeni
 * @param adresa adresa pro zavolani
 * @param idDivAnimationAndMessages pokud je uveden, pouzije se jako div pro animaci a hlasky
 */
function linkupdate(idDiv,adresa,idDivAnimationAndMessages){
    // nastavime id vsech elementu
    var animationDiv = idDiv + "Anim";
    var contentDiv = idDiv + "Ajax";
    var messageDiv = idDiv + "Msg";

    //pokud je zadan jiny div pro animaci a hlasky, pouzije se
    if (idDivAnimationAndMessages){
        animationDiv = idDivAnimationAndMessages + "Anim";
        messageDiv = idDivAnimationAndMessages + "Msg";
    }

    //zobrazime animaci prubehu
    $(hashize(animationDiv)).show();

    // zavolame ajaxove obnoveni divu na konkretni adresu
    $.get(adresa, {}, function(responseHtml) {
        // schova animaci
        $(hashize(contentDiv)).html(responseHtml);
        $(hashize(animationDiv)).hide();
        //pokud se s odpovedi zobrazila zprava, schovame ji.
        if ($(hashize(messageDiv))) {
            setTimeout(function() {
                $(hashize(messageDiv)).slideUp('slow');
            }, 2500);
        }
    }, "html");
}

/** funkce provede ajaxove odkaz a aktualizuje zadany div
 * pouziva $.ajax misto $get - i pri status kodu jinem nez 200 se obsah response vlozi do zadaneho divu
 * @param idDiv identifikace divu, spolecna cast pro id ke kterym se vstahuje
 *        odesilany formular, animace, message, a div pro zobrazeni
 * @param adresa adresa pro zavolani
 * @param errorReload Pokud je true, tak pri http response code jinem nez 200 se po zmizeni hlasky provede reload stranky
 * @param idDivAnimationAndMessages pokud je uveden, pouzije se jako div pro animaci a hlasky
 */
function safelinkupdate(idDiv,adresa,errorReload,idDivAnimationAndMessages){
    // nastavime id vsech elementu
    var animationDiv = idDiv + "Anim";
    var contentDiv = idDiv + "Ajax";
    var messageDiv = idDiv + "Msg";

    if (typeof errorReload == 'undefined' || errorReload == null) {
        errorReload = false;
    }

    //pokud je zadan jiny div pro animaci a hlasky, pouzije se
    if (idDivAnimationAndMessages){
        animationDiv = idDivAnimationAndMessages + "Anim";
        messageDiv = idDivAnimationAndMessages + "Msg";
    }

    //zobrazime animaci prubehu
    $(hashize(animationDiv)).show();

    // zavolame ajaxove obnoveni divu na konkretni adresu
    $.ajax(
        {   url: adresa,
            success: function(responseHtml) {
                // schova animaci
                $(hashize(contentDiv)).html(responseHtml);
                $(hashize(animationDiv)).hide();
                //pokud se s odpovedi zobrazila zprava, schovame ji.
                if ($(hashize(messageDiv))) {
                    setTimeout(function() {
                        $(hashize(messageDiv)).slideUp('slow');
                    }, 2500);
                }
            },
            error: function(xhr) {
                // schova animaci
                $(hashize(contentDiv)).html(xhr.responseText);
                $(hashize(animationDiv)).hide();
                //pokud se s odpovedi zobrazila zprava, schovame ji.
                if ($(hashize(messageDiv))) {
                    setTimeout(function() {
                        $(hashize(messageDiv)).slideUp('slow');
                        if (errorReload) {
                            reload();
                        }
                    }, 3000);
                }
            }
        });
}

function linkupdateparams(idDiv,adresa,params,idDivAnimation){
    // nastavime id vsech elementu
    var animationDiv = hashize(idDiv + "Anim");
    var contentDiv = hashize(idDiv + "Ajax");

    //pokud je zadan jiny div pro animaci, pouzije se
    if (idDivAnimation){
        animationDiv = hashize(idDivAnimation + "Anim");
    }
    $(animationDiv).show();
    // zavolame ajaxove obnoveni divu na konkretni adresu
    $.get(adresa, params, function(responseHtml) {
        $(contentDiv).html(responseHtml);
        $(animationDiv).hide();
        $('p.success').each(function(){ //nechame postupne zmizet uspesnou hlasku
            var div = $(this);
            setTimeout(function() {
                div.slideUp('slow');
            }, 2500);
        });
    }, "html");
}

/**
 * funkce ajaxove zkontroluje navrhovany identifikator
 * @param divId identifikace divu, spolecna cast pro id elementu
 */
function checkSeoName2 (divId){
    // nastavime id vsech elementu
    var urlElem = 'userPageURL';
    var titleElem = 'userPageTitle';
    var animElem = divId + 'Anim';
    var msgElem = divId + 'Msg';

    var params = {
        action: 'seoName',
        userPageTitle : $(hashize(titleElem)).val(),
        userPageURL : $(hashize(urlElem)).val()
    };
    // zobrazime animaci
    $(hashize(animElem)).show();
    //ajaxovy pozadavek na konkretni adresu,metodou get, s vyse uvedenymi parametry
    $.post("/editRegistration", params, function(response){
        // ziskame pozadovane hodnoty z xml
        var returnMessage = $(response).find("message").text();
        var returnSeoName = "";
        if ($(response).find("userPageUrl").text() != "") {
            returnSeoName = $(response).find("userPageUrl").text();
        }

        $(hashize(urlElem)).val(returnSeoName);
        //zobrazime hlasku
        $(hashize(msgElem)).text(returnMessage);

        //schovame animaci
        $(hashize(animElem)).hide();
    }, "xml");
    return false;
}
function validateSeoName(seoElem) {
    var result = true;
    var regex = /.*\d$/;
    if(regex.test($(hashize(seoElem)).val())) {
        alert('SeoName restaurace nemá končit číslem, pokud není číslo na konci součástí názvu restaurace!');
        result = false;
    }
    return result;
}

/**
 * funkce ajaxove zkontroluje nebo navrhne seo name podniku
 * @param divId identifikace divu, spolecna cast pro id elementu
 */
function checkSeoName (divId){
    // nastavime id vsech elementu
    var seoElem= divId + 'SeoName';
    var restIdElem = divId +'Id';
    var nameElem = divId + 'Name';
    var animElem = divId + 'Anim';
    var msgElem = divId + 'Msg';

    // zkontrolujeme jestli je zadane id restaurace - pri editaci
    if ($(hashize(restIdElem)).val() != ''){
        var params = {
            action : "seoName",
            seoName : $(hashize(seoElem)).val(),
            restaurantId : $(hashize(restIdElem)).val(),
            checkedRestaurantName : $(hashize(nameElem)).val()
        };
    // jedna se o pridavani
    }else{
        var params = {
            action : "seoName",
            seoName : $(hashize(seoElem)).val(),
            checkedRestaurantName : $(hashize(nameElem)).val()
        };
    }

    // zobrazime animaci
    $(hashize(animElem)).show();
    //ajaxovy pozadavek na konkretni adresu,metodou get, s vyse uvedenymi parametry
    $.post("/adminRestaurantSeoName", params, function(response){
        // ziskame pozadovane hodnoty z xml
        var returnMessage = $(response).find("message").text();
        var returnLength = $(response).find("seoLength").text();

        var returnSeoName = "";
        if (returnLength>0){
            returnSeoName = $(response).find("seoName").text();
        }

        $(hashize(seoElem)).val(returnSeoName);
        //zobrazime hlasku
        $(hashize(msgElem)).text(returnMessage);

        //schovame animaci
        $(hashize(animElem)).hide();
        validateSeoName(seoElem);
    }, "xml");
}

/**
 * funkce ajaxove zkontroluje nebo navrhne seo name podniku
 * @param divId identifikace divu, spolecna cast pro id elementu
 */
function checkTagSeoName (divId){
    // nastavime id vsech elementu
    var seoElem= divId + 'SeoName';
    var idElem = divId +'Id';
    var nameElem = divId + 'Name';
    var animElem = divId + 'Anim';
    var msgElem = divId + 'Msg';

    // zkontrolujeme jestli je zadane id tagu - pri editaci
    if ($(hashize(idElem)).val() != ''){
        var params = {
            action : "seoName",
            seoName : $(hashize(seoElem)).val(),
            tagId : $(hashize(idElem)).val(),
            checkedTagName : $(hashize(nameElem)).val()
        };
    // jedna se o pridavani
    }else{
        var params = {
            action : "seoName",
            seoName : $(hashize(seoElem)).val(),
            checkedTagName : $(hashize(nameElem)).val()
        };
    }

    // zobrazime animaci
    $(hashize(animElem)).show();
    //ajaxovy pozadavek na konkretni adresu,metodou get, s vyse uvedenymi parametry
    $.post("/adminTagSeoName", params, function(response){
        // ziskame pozadovane hodnoty z xml
        var returnMessage = $(response).find("message").text();
        var returnLength = $(response).find("seoLength").text();

        var returnSeoName = "";
        if (returnLength>0){
            returnSeoName = $(response).find("seoName").text();
        }

        $(hashize(seoElem)).val(returnSeoName);
        //zobrazime hlasku
        $(hashize(msgElem)).text(returnMessage);

        //schovame animaci
        $(hashize(animElem)).hide();
    }, "xml");
}

// reload stranky
function reload() {
    window.location.reload()
}

// Surrounds the selected text with text1 and text2.
function surroundText(text1, text2, textarea)
{
    var range = textarea.getSelection();
    if (range.length > 0) {
        var text = range.text;
        var newText = text1+text+text2;

        textarea.replaceSelection(newText);
    } else {
        textarea.insertAtCaretPos(text1 + text2);
    }
}

// pridani k oblibenym
function AddFavorite(linkObj,addUrl,addTitle)
{
    if (document.all && !window.opera)
    {
        window.external.AddFavorite(addUrl,addTitle);
        return false;
    }
    else if (window.opera && window.print)
    {
        linkObj.title = addTitle;
        return true;
    }
    else if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function'))
    {
        if (window.confirm('Přidat stránku k oblíbeným?'))
        {
            window.sidebar.addPanel(addTitle,addUrl,'');
            return false;
        }
    }
    window.alert('Po potvrzení stiskněte CTRL+D,\nstránka bude přidána k oblíbeným odkazům.');
    return false;
}


function ucwords( str ) {
    // Uppercase the first character of each word in a string
    //
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_ucwords/
    // +       version: 810.819
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: _argos
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'

    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) {
        return $1.toUpperCase ( );
    } );
}// }}}


// zjisteni gps z adresy
function geocodeAddressMap(city,address,action) {
    if (city==""){
        alert("Vyberte, prosim, mesto");
        return false;
    }

    if (address==""){
        alert("Zadejte, prosim, ulici");
        return false;
    }

    address = ucwords(address);

    query = city +", "+address;

    find =address+ ", " + city;
    if (city == "Brno") find+=" mesto";
    var geocoder = new GClientGeocoder();
    if (geocoder) {
        geocoder.getLatLng(
            find,
            function(point) {
                if (!point) {
                    alert("Adresa nebyla nalezena : " + address );
                } else {

                    $('#lat').val(point.lat());
                    $('#lng').val(point.lng());
                    $('#q').val(query);
                    $('#city').val(city);

                    $('#mapForm').attr('action', "/"+action+"/");
                    $('#mapForm').submit();
                }
            }
            );
    }
    return false;
}

function refreshMap(city,query,action){
    $('#q2').val(query);
    $('#city2').val(city);
    $('#lat2').val(map.getCenter().lat());
    $('#lng2').val(map.getCenter().lng());
    $('#latDiff2').val((map.getCenter().lat() - map.getBounds().getSouthWest().lat()));
    $('#lngDiff2').val((map.getCenter().lng() - map.getBounds().getSouthWest().lng()));
    $('#zoom2').val(map.getZoom());

    $('#mapForm2').attr('action', action);
    $('#mapForm2').submit();
}

function geoConst(dir,min,max){
    return (Math.abs(dir-min)> Math.abs(dir-max)) ? Math.abs(dir-min): Math.abs(dir-max)
}

function getDistance(marker,center){
    distance = Math.ceil(marker.getLatLng().distanceFrom(center));
    if (distance < 100){
        distance = "";
    }
    else{
        distance = Math.floor(distance/100)*100;
        if (distance<1000){
            distance +=" m";
        }else{
            distance = Math.ceil(distance/100)/10 + " km";
        }
        distance = "+" + distance;
    }

    return distance;
}

//prida funkci func jako onload akci
function addLoadEvent(func) {
    $(document).ready(func);
}

//v jidelnim listku prehodi dva formulare - s a bez obrazku
function setImageForm(form, formImages, desc, descImageShow, descImageHide) {
    //nastavi hodnoty ve druhem formulari
    $($(hashize(formImages)+' [name=amount]')).val($($(hashize(form)+' [name=amount]')).val());
    $($(hashize(formImages)+' [name=restaurantMealName]')).val($($(hashize(form)+' [name=restaurantMealName]')).val());
    $($(hashize(formImages)+' [name=price]')).val($($(hashize(form)+' [name=price]')).val());
    $($(hashize(formImages)+' [name=restaurantMealDesc]')).val($($(hashize(form)+' [name=restaurantMealDesc]')).val());
    //zobrazi druhy formular a skryje prvni
    showAndHide(formImages, form);

    //zobrazeni nebo schovani divu s popisem podle toho, jestli byl nebo nebyl schovanej
    if ($(hashize(desc)).css('display') != 'none') {
        $(hashize(descImageShow)).hide();
        $(hashize(descImageHide)).show();
    }
}

//v jidelnim listku prehodi dva formulare - s a bez obrazku
function setDeliveryImageForm(form, formImages, desc, descImageShow, descImageHide) {
    //nastavi hodnoty ve druhem formulari
    $($(hashize(formImages)+' [name=amount]')).val($($(hashize(form)+' [name=menuAmount]')).val());
    $($(hashize(formImages)+' [name=restaurantMealName]')).val($($(hashize(form)+' [name=menuName]')).val());
    $($(hashize(formImages)+' [name=price]')).val($($(hashize(form)+' [name=menuPrice]')).val());
    $($(hashize(formImages)+' [name=restaurantMealDesc]')).val($($(hashize(form)+' [name=menuDescription]')).val());
    //zobrazi druhy formular a skryje prvni
    showAndHide(formImages, form);

    //zobrazeni nebo schovani divu s popisem podle toho, jestli byl nebo nebyl schovanej
    if ($(hashize(desc)).css('display') != 'none') {
        $(hashize(descImageShow)).hide();
        $(hashize(descImageHide)).show();
    }
}

// zobrazeni/schovani divu
function MM_findObj(n, d) { //v4.01
    $(document).ready(function() {
        var p,i,x;
        if(!d) d=document;
        if((p=n.indexOf("?"))>0&&parent.frames.length) {
            d=parent.frames[n.substring(p+1)].document;
            n=n.substring(0,p);
        }
        if(!(x=d[n])&&d.all) x=d.all[n];
        for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
        for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
        if(!x && d.getElementById) x=d.getElementById(n);
        return x;
    });
}
function MM_showHideLayers() { //v6.0
    $(document).ready(function() {
        var i,p,v,obj,args=MM_showHideLayers.arguments;
        for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) {
            v=args[i+2];
            if (obj.style) {
                obj=obj.style;
                v=(v=='show')?'visible':(v=='hide')?'hidden':v;
            }
            obj.visibility=v;
        }
    });
}

/**
 * Zkontroluje IC, jestli je platne, kontroluje jen IC z CR,
 * proto se v pripade nekorektnosti zobrazi jen vyzva ke kontrole.
 * Dokaze zkontrolovat jen 8 mistna IC.
 * @author Filip Oscadal from discussion http://latrine.dgx.cz/jak-overit-platne-ic-a-rodne-cislo
 */
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);
        return true;
    }
    catch(e) {
        alert('Zadané I\u010c pravděpodobně není korektní!\nProsím, zkontrolujte je.');
        return false;
    }
    return true;
}

/**
 * Kontrola RC, ktera se vyuziva v kontrole DIC
 * V pripade nekorektnosti se zobrazi jen vyzva ke kontrole.
 * @author Filip Oscadal from discussion http://latrine.dgx.cz/jak-overit-platne-ic-a-rodne-cislo
 */
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Ã© RÄŒ pravdÄ›podobnÄ› nenÃ­ korektnÃ­!\nProsÃ­m, zkontrolujte je.');
        return false;
    }
    return true;
}

/**
 * Kontrola DIC
 * V pripade nekorektnosti se zobrazi jen vyzva ke kontrole.
 * @author Filip Oscadal from discussion http://latrine.dgx.cz/jak-overit-platne-ic-a-rodne-cislo
 */
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ÄŒ pravdÄ›podobnÄ› nenÃ­ korektnÃ­!\nProsÃ­m, zkontrolujte je.');
        return false;
    }
}

//var hashs = new Array('#obecne', '#denni-menu', '#snidane', '#nase-nabidka', '#galerie', '#kontakt');
//var pathElements = new Array('obecne/', 'denni-menu/', 'snidane/', 'nase-nabidka/', 'galerie/', 'kontakt/');
var en = '/english';
var nen = 'english/';

function changeAdminLinks() {
    $('a[href*="#"]').each(function() {
        href = $(this).attr("href");
        //nahrazeni se neprovede, pokud adresa obsahuje rozvoz. Je to osetreni, aby se spravne vypisovaly odkazy rozvozovych kategorii
        if (href.indexOf(deliveriesAction) != -1){
            newHref = '';

            //projdeme vsechny akce #obecne, #denni_menu atd. krome #stale-menu
            for (i=0;i<tabs.length-1;i++) {
                //pokud url obsahuje cast #obecne, #denni_menu atd.
                if (href.search("#"+tabs[i]) != -1) {
                    if (href.search(en) == -1) {
                        newHref = href.substring(0, href.search("#"+tabs[i]));
                    } else {
                        newHref = href.substring(0,href.search(en));
                        newHref = newHref + nen;
                    }
                    newHref = newHref + tabs[i] + "/";
                    $(this).attr('href', newHref);
                    break;
                }
            }
        }
    });
}

// Input search

function onclick_in() {
    $(document).ready(function() {
        var el = document.getElementById('sf');
        if (el.value == 'Vyhledat..') {
            el.value = '';
        }
    });
}
function onblur_in() {
    $(document).ready(function() {
        var el = document.getElementById('sf');
        if (el.value == '') {
            el.value = 'Vyhledat..';
        }
    });
}

function getPageLoadTimeCategory(plload) {
    if(plload < 2000)
        lc = "Very Fast";
    else if (plload < 5000)
        lc = "Fast";
    else if (plload < 10000)
        lc = "Medium";
    else if (plload < 30000)
        lc = "Sluggish";
    else if (plload < 45000)
        lc = "Slow";
    else
        lc="Very Slow";

    return lc;
}


function insertSpinner(divId) {
    spinnerCont = '<img id="'+divId+'-spinner" src="/img/spinner.gif" alt="" />';
    $(spinnerCont).appendTo($(hashize(divId)));
}

function ismaxlength(obj){
    var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length>mlength)
        obj.value=obj.value.substring(0,mlength)
}

/**
 * Podbarvi spatne vyplneny input, muze mu nastavit focus
 * Pokud existuje element s id {divId}Error, tak ho zobrazi a nastavi mu onclick schovat
 */
function invalidInput(divId, focus, messageDiv, dismissTime) {
    if (typeof divId == 'undefined' || divId == null) {
        return false;
    }
    if (typeof focus == 'undefined' || focus == null) {
        focus = true;
    }
    if (typeof badInput == 'undefined' || badInput == null) {
        badInput = "background: red; color: white;";
    }
    if (typeof messageDiv == 'undefined' || messageDiv == null) {
        messageDiv = divId+"Error";
    }
    if (typeof dismissTime == 'undefined' || dismissTime == null) {
        dismissTime = 0;
    }
    if (focus == true) {
        $(hashize(divId)).attr("style", badInput).select().focus();
    } else {
        $(hashize(divId)).attr("style", badInput).select();
    }
    $(hashize(messageDiv)).show().attr("onclick", "javascript:$(hashize('"+messageDiv+"')).hide()");

    if (dismissTime > 0) {
        setTimeout(function() {
            $(hashize(messageDiv)).slideUp('slow');
        }, dismissTime);
    }
}

// zobrazeni iFrame s odkazem
// slouzi pro odeslani pozadavku na FB + zavodani metodu pro update db
function facebookUpdate(url, frame, idDiv, adresa, idDivAnimationAndMessages) {
    document.getElementById(frame).src=url;
    linkupdate(idDiv,adresa,idDivAnimationAndMessages);
}

/**
 * stisk enteru na idInput vyvola klik na idClickTo
 */
function bindEnterClick(idInput, idClickTo) {
    $(hashize(idInput)).ready(function() {
        $(hashize(idInput)).bind('keypress', function(e) {
            if(e.keyCode==13){
                $(hashize(idClickTo)).click();
            }
        });
    });
}

/**
 * pokud neni input prazdny a nerovna se default textu, vrati true, jinak false
 * defaultText je nepovinny
 */
function validateRequired(idInput, defaultText) {
    if (typeof defaultText == 'undefined') {
        defaultText = '';
    }
    
    if ($.trim($(hashize(idInput)).val()) != "" &&  $.trim($(hashize(idInput)).val()) != defaultText) {
        return true;
    }
    return false;
}

function ajaxDeliveryMenus2(address, restaurantId, imageId) {
    var newAddress = '/deliveryMenus' + address + '&restaurantId=' + restaurantId;
    linkupdate('restMenuCategories', newAddress, imageId);
}

function followObjednavka(web, isPW) {

    if (web == 'pt') {
        // jezdici objednavka pro PIZZATIME
        $('#floatmenu').insertAfter('#nav');
        if (isPW){
            $('#floatmenu').scrollFollow( {
                speed: 500,
                offset: 0,
                offsetTop: 20,
                relativeTo: "bottom",
                maxFloatDiv: "deliveryMenusDiv"
            } );
        } else {
            $('#floatmenu').scrollFollow( {
                speed: 500,
                offset: 130,
                offsetTop: 300,
                relativeTo: "bottom",
                maxFloatDiv: "deliveryMenusDiv"
            } );
        }
    } else if (web == 'lt') {
        // jezdici objednavka pro LUNCHTIME
        $('#floatmenu').insertAfter('#nav');
        $('#floatmenu').scrollFollow( {
            speed: 500,
            offset: 0,
            offsetTop: 35,
            relativeTo: "bottom",
            maxFloatDiv: "deliveryMenusDiv"
        } );
    }
}

function evenUpPTMenuPage(isPW) {
    evenUpOrderPage("deliveryMenusDiv");
    followObjednavka("pt", isPW);
}

function evenUpLTMenuPage() {
    evenUpOrderPage("deliveryMenusDiv");
    followObjednavka("lt");
}

function evenUpOrderPage(mainDiv) {
    $('#floatmenu').ready(function() {
        var box = $('#floatmenu');
        var boxHeight = parseInt( box.attr( 'offsetHeight' ) + ( parseInt( box.css( 'marginTop' ) ) || 0 ) + ( parseInt( box.css( 'marginBottom' ) ) || 0 ) );
        var divName = '#' + mainDiv;
        var formDiv = parseInt( $(divName).height() );

        var i=0;
        // cyklus prida maximalne tolik radku, kolik je potreba do dorovnani rozdilu nebo 1000
        while ((boxHeight >= formDiv) && (i < 100)) {
            i++;
            formDiv = parseInt( $(divName).height() );
            var div = document.getElementById("moreLineForFloating");
            var br = document.createElement('br');
            div.appendChild(br);
        //            var row =document.createTextNode("row=" + i);
        //            div.appendChild(row);
        };
    });
}

/**
 * najede na zadany element
 */
function goToByScroll(id){
    $('html,body').animate({
        scrollTop: $("#"+id).offset().top
    },'slow');
}

/**
 *  x > y
 */
function isGreater(x, y){
    return x > y;
}


//Napoveda formulare
$(document).ready(function(){
	$("a.form_tool").hover(function() {
		$(this).next(".form_help").animate({opacity: "show"}, 300);
	}, function() {
		$(this).next(".form_help").animate({opacity: "hide"}, 300);
	});
});

function confirmDeleteActualityPhoto(question){
    if ($("#chooseImg").attr("style") != 'display: none' && $("#chooseImg").val() == ''){
        if (confirm(question)){
            $("#deleteImage").attr("value", "true");
        }
    }
}
