//// zalozky na strankach
function tabs() {
    this.area_ids = [];
    this.areas = jQuery.makeArray($(".form-tabs > dl"));
    if (this.areas.length == 0) {        
        this.areas = jQuery.makeArray($("#calc > div > dl"));
    }    
    for (var i = 0; i < this.areas.length; i++) {
        this.area_ids[i] = this.areas[i].id;        
    }
    this.default_id = this.area_ids.length == 0 ? '' : this.area_ids[0];        
                      
    this._hide = function(id) { $("#" + id).hide(); };
    this._show = function(id) { $("#" + id).show(); };
    this._hideAll = function() { for (var i = 0; i < this.area_ids.length; i++) { this._hide(this.area_ids[i]); } };
    this.show = function(id) { this._hideAll(); this._show(id); };
        
    var name = document.location.href.replace(/^[^#]*#?(.*)$/, '$1');
    this.show(name == '' ? this.default_id : name);                                  
};

var tabs_instance = null;
function tabs_init() { if (tabs_instance == null) tabs_instance = new tabs(); };
function tabs_show(id) { if (tabs_instance == null) tabs_instance = new tabs(); tabs_instance.show(id); };


//// poznamky onmouseover
var notes_instances = [];
var notes_instances_ids = [];
function notes(id) {
    if (!id) {
        // skryje vsechny poznamky
        for (var i = 0; i < notes_instances_ids.length; i++) {
            notes_instances[notes_instances_ids[i]].hideReal();
        }
        return null;
    } else {
        // get one note
        if (!notes_instances[id]) { notes_instances[id] = new notes_one_note(id); notes_instances_ids[notes_instances_ids.length] = id; }        
        return notes_instances[id];        
    }
}

function notes_one_note(id) {
    this.id = id;
    // najde element a popisek k nemu
    this.element = $("#" + id);
    this.description = $("#" + id + "_desc");
    // promenna urcujici, zda je popisek zobrazen
    this.shown = false;
    this.description.hide();
    // promenna urcujici, zda je mys nad popiskem
    this.mouseAtDesc = false;
        
    // funkce pro zobrazeni popisku
    this.show = function(mouseEvent) {
        if (!this.shown) {
            // hide all
            notes();
            this.shown = true;
            this.description.css({ left: mouseEvent.pageX + 'px', top: (mouseEvent.pageY + 6) + 'px' });
            this.description.show();
        }
    };    
    
    // funke pro skryti popisku
    this.hide = function() {
         // provede az za nejakou dobu
        if (this.shown) setTimeout("notes('"+this.id+"').hide2();", 700);
    };
    
    // funkce pro skryti po 2 sekundach od odjeti mysi
    this.hide2 = function() {
        // provede pouze, pokud mys neni nad popiskem
        if (!this.mouseAtDesc) this.hideReal();
    };
    
    // funkce pro skutecne skryti :)
    this.hideReal = function() { 
        this.shown = false;
        this.description.hide(); 
    };
    
    // triggery na jednotlive pohyby mysi
    this.element.mouseover( function(e) { var ev = e ? e : window.event; notes(id).show(ev); } );
    this.element.mouseout( function() { notes(id).hide(); } );
    this.description.mouseover( function(e) { notes(id).mouseAtDesc = notes(id).shown; } );
    this.description.mouseout( function() { notes(id).mouseAtDesc = false; notes(id).hide(); } );   
    
    // a nejake to formatovani :)    
    this.description.addClass('popis_descr');  
    this.element.addClass('popis_link');     
}

function notes_init() {
    var na = jQuery.makeArray($("*[id^=popis_]"));    
    for (var i = 0; i < na.length; i++) { 
        if (na[i].id.match(/_desc$/)) continue;
        notes(na[i].id);
    }
};


function calc(form, id) {    
    var url = '/calc.ws?calc_id=' + id;
    var inputs = form.elements;
    for (var i = 0; i < inputs.length; i++) {    
        if (inputs[i].id.match(/^calc_[a-z_]+_([a-z]+)$/)) {
            var d = inputs[i].id.replace(/^calc_[a-z_]+_([a-z]+)$/, '$1');            
            var v = inputs[i].value;
            url += '&' + d + '=' + escape(v);
        }
    }    
    var res = $("#" + form.id + "_result");    
        
    $.get(url, null,
        function(result){
            res.html(result);
            res.show();
        });
    return false;
};

var psc_value = '';
function cofidis_psc(psc) {
  if (psc.length >= 5) {
      $.get("/psc.ws", { psc: psc },
          function(data){
              if (data != '' && $("#mesto").val() == psc_value) { $("#mesto").val(data); psc_value = data; };
          });
  }
};

function cofidis_tabulka(vyse, delka, td) {
  var vysec = vyse;
  if (vysec.search(/[^0-9]+/)) vysec = vyse.replace(/([^0-9]+)/,'') + '000';
  $("#vyse_pujcky").val(vysec);
  $("#delka").val(delka);  
};

$(window).load(
    function() {
        $("#sophia_form_ucel").hide();
        $("#sophia_form_ucel_zmen").click(  
                    function() {
                        $("#sophia_form_ucel").fadeIn();
                        $("#sophia_form_ucel_zmen").fadeOut();
                        return false;
                    }
                );
        $("#sophia_form_ucel_zmen_skryj").click(  
                    function() {
                        $("#sophia_form_ucel").fadeOut();
                        $("#sophia_form_ucel_zmen").fadeIn();
                        return false;
                    }
                );
        tabs_init();   
        hledej_datum();  
        notes_init();                  
    }
);

function hledej_datum(val) {
    if (val) {
        var from;
        var to;
        var date = new Date();
        switch(val) {
            case 'today':
                from = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();
                to = from;                
                break;
            case 'yesterday':
                date.setTime(date.getTime() - 86400000);
                from = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();
                to = from;                
                break;               
            case 'week':                
                while (date.getDay() != 1) date.setTime(date.getTime() - 86400000);
                from = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();
                while (date.getDay() != 0) date.setTime(date.getTime() + 86400000);
                to = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();                                            
                break;
            case 'lastweek':
                while (date.getDay() != 1) date.setTime(date.getTime() - 86400000);                
                date.setTime(date.getTime() - 86400000);
                while (date.getDay() != 1) date.setTime(date.getTime() - 86400000);
                from = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();
                while (date.getDay() != 0) date.setTime(date.getTime() + 86400000);
                to = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();                                            
                break;                  
            case 'month':                
                from = '1.' + (date.getMonth() + 1) + '.' + date.getFullYear();
                while (date.getDate() != 1) date.setTime(date.getTime() + 86400000);
                date.setTime(date.getTime() - 86400000);
                to = date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear();                                            
                break; 
            case 'year':                
                from = '1.1.' + date.getFullYear();
                to = '31.12.' + date.getFullYear();                                            
                break;                
                                           
        }
        if (!from || !to) {
            from = ''; to = '';
        }        
        $("input[name='hledej_datumod']").val(from);
        $("input[name='hledej_datumdo']").val(to);
        $("#forms_filtr").submit();
        return;
    }
    var d = $("#hledej_datumdo_key");    
    d.append('<a href="javascript:hledej_datum(\'today\');">dnes</a><br />');
    d.append('<a href="javascript:hledej_datum(\'yesterday\');">včera</a><br />');
    d.append('<a href="javascript:hledej_datum(\'week\');">tento týden</a><br />');
    d.append('<a href="javascript:hledej_datum(\'lastweek\');">minulý týden</a><br />');
    d.append('<a href="javascript:hledej_datum(\'month\');">tento měsíc</a><br />');
    d.append('<a href="javascript:hledej_datum(\'none\');">libovolné datum</a><br />');            
};

function partner_forms_oznacene() {
    var url = 'forms.html?';
    var cnt = 0;
    jQuery.each($(":checkbox[id^='form']:checked"), function() {    
        url += 'detail['+this.id.replace('form_','')+']=1&';
        cnt++;        
    });
    url += '1=1';
    if (cnt == 0) {
        alert('Nejprve zvolte alespoň jednu žádost pomocí zaškrtavácích políček.');
        return;        
    }
    window.open(url, 'detail', 'width=800,height=600,toolbar=yes,menubar=yes');
};

function partners_forms_open(id) {
    window.open('/partner/forms.html?detail['+id+']=1', 'detail', 'width=800,height=600,toolbar=yes,menubar=yes');
};

function admins_forms_oznacene() {
    var url = '/admin/forms.html?';
    var cnt = 0;
    jQuery.each($(":checkbox[id^='form']:checked"), function() {    
        url += 'detail['+this.id.replace('form_','')+']=1&';
        cnt++;        
    });
    url += '1=1';
    if (cnt == 0) {
        alert('Nejprve zvolte alespoň jednu žádost pomocí zaškrtavácích políček.');
        return;        
    }
    window.open(url, 'detail', 'width=800,height=600,toolbar=yes,menubar=yes');
};

function admins_forms_open(id) {
    window.open('/admin/forms.html?detail['+id+']=1', 'detail', 'width=800,height=600,toolbar=yes,menubar=yes');
};

function partners_forms_notes(id) {
    var actual_note = $("#form_n_" + id).text();
    var r = prompt('Zadejte nové znění poznámky k této žádosti a stiskněte OK.', actual_note);
    if (r != null) {
        var url = location.href.replace(/(&|\?)poznamka=[0-9]+&text=[^&]*/, '');
        location.href =  url + (url.search(/\?/) != -1 ? '&' : '?' ) + 'poznamka=' + id + '&text=' + (!r ? '' : r);
    }  
};

function admins_forms_provize(id, provize, fakt) {
    if (fakt != '') return;
    var r = prompt('Zadejte novou hodnotu provize za tuto žádost a stiskněte OK (používejte desetinnou TEČKU).', provize);
    if (r != null && r != provize) {                    
        if (!confirm('U této žádosti bude provize nově nastavena na ' + r + 'Kč. Pro pokračování stiskněte OK.')) return;
        var url = location.href.replace(/(&|\?)provize=[0-9]+&hodnota=[0-9\.]*/, '');        
        location.href =  url + (url.search(/\?/) != -1 ? '&' : '?' ) + 'provize=' + id + '&hodnota=' + (!r ? 0 : r);
    }  
};


function prn() {
document.write('\074a href=\"javascript:goprn();\"\076tisk stránky\074/a\076 \| ');
}
function goprn() {
window.print();
}
