

// presmeruje stranku do noveho okna
function redirect(url){
    window.open(url, '');
}


// zkraceny zapis document.getElementById(id);
function element(element_id){
    return document.getElementById(element_id);
}

function open_window(url, width, height, left, top){
    if (url.lenght == 0){// pokud neni zadana url adresa, tak se nic neprovede
        return(false);
    }
    if (isNaN(width)){// defaultni sirka je 1000px
        width = 1000;   
    }
    if (isNaN(height)){// defaultni vyska je 500px
        height = 500;
    }
    if (isNaN(left)){// pokud neni nastavena pozice z leva, tak ji dam na stred
        left = (screen.availWidth - width)/2;
    }
    if (isNaN(top)){// pokud neni nastavena pozice ze shora, tak ji dam na stred       
        top = (screen.availHeight - height)/2;
    }
    
    var popup = window.open('', '', 'width='+width+',height='+height+',menubar=0,resizable=0,left='+left+',top='+top+',location=0,scrollbars=1');
    popup.location = url;
    return popup;
}

     
/**
 * show_hide(el_id);
 * Author: Josef Traxler
 * Date: 2011-04-13
 * Description:
 *      Zobrazi/skryje dany element 
 * Params:
 *      el_id (string) - id elementu, ktery chci skryt, nebo zobrazit     
 */ 
function show_hide(el_id){
    var el = document.getElementById(el_id);
    if (el){
        var show = false;
        var new_class = '';
        var classes = el.className.split(' ');
        for(var i in classes){
            if (classes[i] == 'hide') { show = true; } 
            else if (classes[i] == 'show') { show = false; }
            else { new_class += classes[i]+' '; }
        }
        if (show) new_class += 'show';
        else new_class += 'hide'; 
        el.className = new_class;
    }
}

     
/**
 * show(el_id);
 * Author: Josef Traxler
 * Date: 2011-07-18
 * Description:
 *      Zobrazi dany element 
 * Params:
 *      el_id (string) - id elementu, ktery chci zobrazit     
 */ 
function show(el_id){
    var el = document.getElementById(el_id);
    if (el){
        var new_class = '';
        var classes = el.className.split(' ');
        for(var i in classes){
            if (classes[i] == 'hide') { } 
            else if (classes[i] == 'show') { }
            else { new_class += classes[i]+' '; }
        }
        new_class += 'show';
        el.className = new_class;
    }
}

     
/**
 * hide(el_id);
 * Author: Josef Traxler
 * Date: 2011-07-18
 * Description:
 *      Skryje dany element 
 * Params:
 *      el_id (string) - id elementu, ktery chci skryt  
 */ 
function hide(el_id){
    var el = document.getElementById(el_id);
    if (el){
        var new_class = '';
        var classes = el.className.split(' ');
        for(var i in classes){
            if (classes[i] == 'hide') { } 
            else if (classes[i] == 'show') { }
            else { new_class += classes[i]+' '; }
        }
        new_class += 'hide';
        el.className = new_class;
    }
}




/**
 * alert_error(e);
 * Author: Josef Traxler
 * Date: 2011-08-02
 * Description:
 *      Funkce vypise informace o chybe    
 */ 
function alert_error(e){
    var obj_err = document.getElementById('javascript_error_message');
    if (!obj_err){
        var b = document.getElementsByTagName('body')[0];
        b.innerHTML += '<div id="javascript_error_message" ondblclick="this.style.display = \'none\'" ></div>';
        obj_err = document.getElementById('javascript_error_message'); 
    }
    obj_err.style.display = 'block';
    obj_err.innerHTML = '<b class="red" >Javascriptová chyba:</b><br />\n';
    if (typeof(e) == 'error'){ 
        obj_err.innerHTML += 'Soubor: <b>'+e.fileName+'</b><br />\n'+
        'Na řádku: <b>'+e.lineNumber+'</b><br />\n'+
        '<b class="red" >'+e.message+'</b><br />\n';
    }  
    else {
        obj_err.innerHTML += '<b class="red" >'+e+'</b><br />\n';
    }
    obj_err.innerHTML += '<br />\n/* Hlášku zrušíte dvojklikem */';
}




 

/**
 *      Funkce slouzi k overeni typu hodnoty, navratova hodnota je typu boolean
 *      @param      mixed       val     kontrolovana hodnota
 *      @param      string      typ     typ, ktery by to mel byt
 */ 
function isType(val, typ, params){// :boolean
    var result = true;
    switch(typ){
        case 'date':             
            result = isDate(val);
        break;
        case 'int': case 'integer':
            return !isNaN(val);
        break;
        case 'float':
            return !isNaN(val.replace(',', '').replace('.', ''));
        break;
        case 'empty':
            return (val.trim().length == 0);
        break;
    }
    return result;
}

function isDate(val){
    format = /^([0-9]{2}).([0-9]{2}).([0-9]{4})$/;
    return format.test(val); 
}






/**
 * get_array_from_answer(answer);
 * Author: Josef Traxler
 * Date: 2011-05-03
 * Description:
 *      Rozkoduje zakodovany string, ve kterem jsou predany informace v poli, 
 *      zakodovaci funkce je v knihovne Fce funkce set_array_to_answer pouziti Fce::set_array_to_answer($array);
 *      pouziti rozkodovaci funkce je get_array_from_answer(answer);
 *      do indexu pole se mohou vlozit bud retezce, nebo cisla
 *      hodnoty mohou byt integer, real, string  
 * Params:
 *      answer (string) - zakodovane pole do retezce  
 */ 
function get_array_from_answer(answer){
    var result = new Array();
    var data = new Array();
    var datas = answer.split(/\{array_separator\}/);
    for(var i in datas){
        data = datas[i].split(/\{data_separator\}/);  
        if (data.length > 1){
            result[data[0]] = data[1];
        }
    }
    return result;
}




/**
 * check_all(head_el);
 * Author: Josef Traxler
 * Date: 2011-04-07
 * Description:
 *      Zakrtne, nebo odskrtne vsechny checkboxy, ktere maji nastaveny stejny attribut class + "_check_me" jako ridici checkbox (head_el)
 * Params:
 *      head_el (object) - ridici checkbox, podle ktereho se urcuje ktery checkbox se bude menit a jak      
 */ 
function check_all(head_el){
    var form_el = head_el.form;// formular elementu
    var head_classes = head_el.className.split(' ');
    for(var i = 0; i < form_el.length; i++){
        var classes = form_el[i].className.split(' ');
        for(var j in classes){
            for(var k in head_classes){
                if (head_classes[k]+'_check_me' == classes[j]){// pokud ma stejny attribut class jako ridici checkbox
                    form_el[i].checked = head_el.checked;
                }
            }
        }
    }
    return true;
}

/* o(d)znaci vsechny checkboxy ve formulari podle elementu theElement */
function selectAll(theElement) {
     var theForm = theElement.form, z = 0;
	 for(z=0; z<theForm.length;z++){
      if(theForm[z].type == 'checkbox') {
		  	theForm[z].checked = theElement.checked;
	  }
   }
}



function is_string(input){
    return typeof(input)=='string';
  }



/**
 *      Prirazeni funkci trim pouziti promenna.trim();
 */ 
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.tofloat = function() {
	return (this.replace(' ','').replace(',', '.')/1);
}

function round(val, precision){// zaokrouhleni na urcity pocet desetinnych mist
    if (!val) val = 0;
    if (!precision) precision = 0;
    return (Math.round(val*Math.pow(10, precision))/Math.pow(10, precision));
}






// trida pro text
var Text = {
    // nahodny text
    rand: function(len, chars) {
        if (!len) len = 10;
        if (!chars) chars = 'qwertyuiopasdfghjklzxcbnmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        
        var string = '';
        for (var i = 0; i < len; i++){
            var pos = Math.rand(chars.length-1);
            string += chars[pos];
        }
        return string;
    }
}

if(!Math.rand){
    // nahodne cislo v intervalu
    // pokud nezadate druhe cislo bere se to jako 0 - X
    Math.rand = function(line1, line2){// line1 = 0, line2 = 1 pokud zadate pouze prvni hodnotu bude to v rozmezi 0 - X
        if (!line2) { line2 = line1; line1 = 0; }
        if (!line2) line2 = 2147483647;
           
        return Math.floor(Math.random() * (line2 - line1 + 1) + line1);
    };
}



/**
 * printTable(submitElement, modul);
 * Author: Tomas Pohorelsky
 * Date: 2011-10-20
 * Descripiton:
 *      Script odesle formular pro tisk do noveho okna a zpet mu nastavi jeno parametry
 *      pouziti 
 *          <input type="submit|button" value="Tisk" onclick="return printTable(this, 'nazev_orm_modulu');" /> 
 *      !!! nikdy nepouzivejte name="submit", zablokuje to odesilani formulare !!!
 * Params:
 *      buttonElement (object) - odesilaci tlacitko, nebo jiny element formulare
 *      modul - modul, ktery budu tisknout
 * Result:
 *      (boolean) - vrati false 
 *      Odesle formular v novem okne         
 */ 
function printTable(buttonElement, modul){
    // deklarace promennych
    var f = buttonElement.form; // formular, ktery budu odesilat
    
    // osetreni formulare
    if (!f && document.getElementById('form')) f = document.getElementById('form');
    if (!f && document.getElementById('customers_table_form')) f = document.getElementById('customers_table_form');
    
    // zaloha formulare
    var action = f.getAttribute('action');// zaloha akce formulare
    var target = f.getAttribute('target');// zaloha zpusobu otevreni okna formulare
    
    
    // nastaveni pro odeslani a odeslani formulare
    f.setAttribute('action', '/printTables/edit/'+modul);//priradim formulari novou akci  
    f.setAttribute('target', '_blank');
    f.submit();// odeslu formular 
    
    // vratim puvodni hodnoty formulari
    f.setAttribute('action', action);//priradim formulari novou akci  
    f.setAttribute('target', target);
    
    return false;// pro zakazani odeslani formulare znovu
}

/**
 * admin_clock_show_ip();
 * Author: Tomas Pohorelsky
 * Date: 2011-11-16
 * Descripiton:
 *      skryje/zobrazí ip adresu v admin_clock      
 */ 
function admin_clock_show_ip(){
    $('#admin_clock_ip').toggle();
}

/**
 * delete_admin_ip();
 * Author: Tomas Pohorelsky
 * Date: 2011-11-21
 * Description:
 *      skryje ip adresu a nastaví ji na smazání    
 */ 
function delete_admin_ip(element){
    var admin_ips_id = $(element).next('.admin_ids_id').attr('value');
    $(element).parent('div').html('<input type="hidden" name="delete_admin_ip[]" value="'+admin_ips_id+'" />');
    
}

/**
 * admin_set_IP();
 * Author: Tomas Pohorelsky
 * Date: 2011-11-21
 * Description:
 *      nastaví do inputu admin_ip aktuální ip adresu    
 */ 
function admin_set_IP(){
    var admin_ip = $('#admin_ip').attr('value');
    $('input[name="admin_ip"]').attr('value', admin_ip);
}    

/**
 * add_new_ip();
 * Author: Tomas Pohorelsky
 * Date: 2011-11-21
 * Description:
 *      přidá do seznamu ip adres data z inputů    
 */ 
function add_new_ip(){
    var ip = $('input[name="admin_ip"]'); 
    var description = $('input[name="admin_ip_note"]'); 
    
    var html = '<div><div style="width: 83px; display: inline-block;">'+ip.val()+'</div>'+
                    '<div style="width: 83px; display: inline-block;">'+description.val()+'</div>'+
                    '<a href="javascript:;" onclick="delete_admin_ip(this);">X</a>'+
                    '<input type="hidden" name="admin_ips[]" value="'+ip.val()+' : '+description.val()+'">'+
                '</div>';                
    $('div#list_ips').append(html);
    ip.val('');
    description.val('');
} 




/**
 * session_set(variable, value);
 * Author: Josef Traxler
 * Date: 2012-02-13
 * Description:
 *      Nastavi session na zadanou hodnotu    
 */ 
function session_set(variable, value){
    if (value === false) value = '0';
    if (value === true) value = '1';
    
    ajax_request('/ajax/session_set/'+variable+'/'+value, 'get', session_setted);
}

function session_setted(answer){

}


          



/**
 * jQuery funkce
 */



 
$(document).ready(function(){// funkce po nacteni stranky
    //
    // vsechny inputy s tridou only_numbers nastavim tak, aby do ni sly zadavat pouze cisla
    //
    //set_processing('Web je ve vyvoji');
    $('input.only_numbers').keydown(function(event){// pridam funkci pri stisku klavesy pro inputy pouze s cisly
        var keynum = event.which || event.keyCode;
        if (event.ctrlKey == 1) return true;
        if ((keynum >= 48) && (keynum <= 57)){// 0 - 9 na ceske i anglicke klavesnici
            this.value += keynum - 48;
            return false;
        }
        if ((keynum >= 96) && (keynum <= 105)){// numpad0 - numpad9
            this.value += keynum - 96;
            return false;
        }
        switch(keynum){
            case 8:// backspace
            case 9:// tab
            case 37:// left arrow
            case 39:// right arrow
            case 46:// delete 
                return true; 
            break;
            case 13:// enter
                this.onchange();
                return true;
            break;
        }
        return false;
    });
});


