$(document).ready(function(){

  controls_set_functionality();

  $.ajaxSetup({
    complete: function(XMLHttpRequest, textStatus) {
      controls_set_functionality(); // the options for this ajax request
    }
  });


  /**
   * odkazy do nového okna
   */
  $("a.t_out").live("click", function(){
    open($(this).attr("href"));
    return false;
  });
  

  /**
   * rozbalovací texty po kliknutí na odkaz
   */
  $('a.showbox').live("click", function(){
    $($(this).attr('href') + ' p:first-child').css('margin-top','0px');
    $($(this).attr('href')).toggle(100);
    return false;
  });
  

  /**
   * ----------------- FORMULARE obecne ------------------------------
   */
  $("input.numbersonly").live("keypress", function(e){
    return numbersonly(e, false);
  });

  $("input.numbersonly_dec").live("keypress", function(e){
    return numbersonly(e, true);
  });

  $("input.psconly").live("keypress", function(e){
    return psconly(e);
  });

  $("input.static").live("keypress", function(e){
     return false;
  });
  /**
   * ----------------- FORMULARE obecne KONEC------------------------------
   */
   

  /**
   * -------------------------------- MENU ----------------------------------------------
   */
   
  /**
   * položky hlavního menu nejsou klikatelné
   */
  $("#menu_main_tbl a").live('click',function(){
    return false;
  });
  
  $("#menu_main_tbl > tbody > tr > td:first-child > a").addClass('first-child');
  $("#menu_main_tbl > tbody > tr > td:last-child > a").addClass('last-child');
  
  $("#menu_main td > a").mouseover(function() {
    var parent_active = $(this).parent().hasClass('active');
    if ( !parent_active ) {
      var item_id = $(this).attr("id");
      menu_reset_timeout(); /*ošetřuje speciální případ, kdy se z rozbaleného menu vrací zpět na tlačítko na liště*/
      skryj_menu("submenu_" + item_id);
      show_menu($("#submenu_" + item_id));
    }
  });
  
  $("#menu_main td > a").mouseout(function() {
    var parent_active = $(this).parent().hasClass('active');
    if ( !parent_active ) {
      menu_skryt_timeout();
    }
  });
  //$("ul.submenu").mouseover(function() {
  $("div.mm_submenu").mouseover(function() {
    var parent_id = $(this).attr('id').substr('submenu_'.length);
    var td_parent_active = $('#' + parent_id).parent().hasClass('active');
    /*
    var parent_active = $(this).parent().hasClass('active');
    */
    if ( !td_parent_active ) {
      //$(this).prev().addClass('active');
      $('#' + parent_id).addClass('active');
      menu_reset_timeout();
    }
  });
  //$("ul.submenu").mouseout(function() {
  $("div.mm_submenu").mouseout(function() {
    //var parent_active = $(this).parent().hasClass('active');
    var parent_id = $(this).attr('id').substr('submenu_'.length);
    var td_parent_active = $('#' + parent_id).parent().hasClass('active');
    
    if ( !td_parent_active ) {
      menu_skryt_timeout();
    }
  });
  
  
  $("div.mm_submenu a").hover(
    function() {
      $(this).parent().prev('td.sep').addClass('right_hl');
      $(this).parent().next('td.sep').addClass('left_hl');
      $(this).parent().prev('td.first_sep').addClass('first_hl');
      $(this).parent().next('td.last_sep').addClass('last_hl');
    },
    function() {
      $(this).parent().prev('td.sep').removeClass('right_hl');
      $(this).parent().next('td.sep').removeClass('left_hl');
      $(this).parent().prev('td.first_sep').removeClass('first_hl');
      $(this).parent().next('td.last_sep').removeClass('last_hl');
    }
  );
  /**
   * -------------------------------- MENU konec ----------------------------------------------
   */

  /**
   * levé menu
   */
  $('div.left_box').after('<div class="left_box_bottom"></div>');
   

  /**
   * tisk stránky
   */
  $("span#print_page").live('click',function(){
    window.print();
  });

  /**
   * odeslání stránky
   */
  $("span#send_page").live('click',function(){
    $("form#send_page_form").toggle();
    /**
     * odrolování, aby formulář byl vidět
     */
    $("form#send_page_form:visible").each(function(){
      var offset = $(this).offset();
      var height = $(this).outerHeight();
      var offset_bottom = offset.top + height;
      var window_bottom = $(window).scrollTop() + $(window).height();
      
      if ( offset_bottom>window_bottom ) {
        $(window).scrollTop( offset_bottom - $(window).height() );
      }
    });
  });

  /**
   * tisk a odeslání stránky
   */
  $("span#print_page, span#send_page").live('mouseover',function(){
    $(this).attr('old_color',$(this).css('color'));
    $(this).css('color','#910111');
  })
  .live('mouseout',function(){
    $(this).css('color',$(this).attr('old_color'));
  });

  /**
   * odeslání ajaxového formuláře
   */
  $("form.ajax_form").submit(function(){
    var form_obj = this;
    var ajax_ident = $(form_obj).find('input:hidden[name=ajax]');
    if ( !ajax_ident.length ) {
      $(this).append('<input type="hidden" name="ajax" value="ajax" />');
    }
    $(this).ajaxSubmit(
      {
        success: function(data){
          $(form_obj).find(".form_err").remove();
          $(form_obj).find(".form_done").remove();
          $(form_obj).find(".form_err_main").remove();
          if ( data.zpracovano=='ok' ) {
            $(form_obj).before('<p class="form_done">' + data.ok_msg + '</p>');
            $(form_obj).clearForm();
            $(form_obj).css('display','none');
          }
          else {
            if ( data.err_msg.length ) {
              $(form_obj).prepend('<p class="form_err_main">' + data.err_msg + '</p>');
            }
            
            for ( var i=0;i<data.err_elements.length;i++ ) {
              $(form_obj).find('#' + data.err_elements[i].err_msg_elem_id).html('<span class="form_err">' + data.err_elements[i].err_msg + '</span>');
            }
          }
        },
        dataType: 'json'
      }
    );
    return false;
  });


  /**
   * refresh log zákazníků v levém sloupci po 5 vteřinách
   */
  refresh_customers_left_col_p_timeout = setTimeout("refresh_customers_left_col()",5000);


});



function controls_set_functionality() {

  if ( !$("a.button").children('span.left_side, span.right_side').length ) {
    $("a.button").prepend('<span class="left_side"></span>').append('<span class="right_side"></span>');
  }


  /**
   * *************************** FORMULARE obecne ***********************************
   */
  /**
   * zmizení defaultního textu po získání focusu
   */
  $("input.default_text")
    .addClass('default_text_style')
    .attr("default_text",function(){return $(this).val();})
    .focus(function(){
      $(this).removeClass('default_text_style');
      $(this).attr("before_click_text",$(this).val());
      if ( $(this).val()==$(this).attr("default_text") ) {
        $(this).val("");
      }
    })
    .blur(function(){
      if ( !$.trim($(this).val()) && $(this).attr("before_click_text") ) {
        $(this).addClass('default_text_style');
        $(this).val($(this).attr("before_click_text"));
      }
    });
  /**
   * *************************** FORMULARE obecne KONEC ***********************************
   */




}


/**
 * -------------------------------- MENU ----------------------------------------------
 */
var menu_timeout = 150; /*timeout, po kterém bude menu zrušeno - může být klidně nula, tzn. ihned po opuštění kurzorem - používá se vlastně jen ve funkci skryt_timeout*/
var menu_p_timeout = null; /*ukazatel na volání fukce setTimeout - používá se ve fci skryt_timeout a reset_timeout*/

var show_active_menu_timeout = menu_timeout + 50;
var show_active_menu_p_timeout = null; /*ukazatel na volání fukce setTimeout - používá se ve fci skryt_timeout a reset_timeout*/

function menu_skryt_timeout() { /*tato funkce nastavuje timeout pro schování*/
  menu_p_timeout = setTimeout("skryj_menu()",menu_timeout);
  show_active_menu_p_timeout = setTimeout("show_active_menu()",show_active_menu_timeout);
}
function menu_reset_timeout() { /*a tato funkce ho ruší*/
  clearTimeout(menu_p_timeout);
  clearTimeout(show_active_menu_p_timeout);
}

function show_menu(menu_obj) {
  if ( menu_obj.length ) {
    /*if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {*/
      menu_obj.css('display','block');
    /*}
    else {
      menu_obj.slideDown("fast");
    }*/
  }
}

/**
 * skryje všechna menu kromě toho, jehož id je předáno
 */
function skryj_menu(except_id) {
  //$("ul.submenu").each(function() {
  $("div.mm_submenu").each(function() {
    var item_id = $(this).attr("id");
    var parent_id = item_id.substr('submenu_'.length);
    if ( item_id != except_id ) {
      /*if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {*/
        $(this).css('display','none');
        $('#' + parent_id).removeClass('active');
      /*}
      else {
        $(this).slideUp("fast", function() {
          $('#' + parent_id).removeClass('active');
        });
      }*/
    }
  });
}

function show_active_menu() {
  $("#menu_main td.active > a").addClass('active');
  //show_menu($("#menu_main > li.active > ul.submenu"));
  show_menu($("div.mm_submenu.active"));
}
/**
 * -------------------------------- MENU konec ----------------------------------------------
 */


/**
 * refresh ikonek zákazníků v levém sloupci
 */
var refresh_customers_left_col_p_timeout = null; /*ukazatel na volání fukce setTimeout*/

function refresh_customers_left_col() {
  clearTimeout(refresh_customers_left_col_p_timeout);
  $.getJSON(
    '/customers_logos.php',
    {},
    function(data) {
      if ( !data.error ) {
        $('#nasi_zakaznici').html(data.html);
        refresh_customers_left_col_p_timeout = setTimeout("refresh_customers_left_col()",5000);
      }
    }
  );
}




/**
 * @Name: number_format(number,decimals,dec_point,thousand_sep)
 * @Dependent on: function add_thousand_sep
 * @Author: Petr Novotný
 * @Date: 20.9.2008
 * @Description: Vrátí číslo (jako řetězec) v požadovaném formátu, inspirováno stejnojmennou PHP funkcí
 * @param float number          Číslo
 * @param int decimals          Počet desetinných míst
 * @param string dec_point      Oddělovač desetinných míst
 * @param string thousand_sep   Oddělovač tisíců
 */
function number_format(number,decimals,dec_point,thousand_sep) {

  number = parseFloat(number);
  
  if ( !decimals ) { decimals = 0; }
  if ( !dec_point ) { dec_point = ','; }
  if ( !thousand_sep ) { thousand_sep = ''; }

  var multi = Math.pow(10,decimals); //Zaokrouhlení na požadovaný počet desetinných míst
  var rounded = Math.round(number*multi) / multi;
  
  var rounded_str = rounded + ""; //převod na řetězec
  var numberparts = rounded_str.split('.',2); //rozdělení na celočíselnou a desetinnou část
  var intpart_str = numberparts[0]; //celočíselná část
  var decpart_str = '';
  if ( numberparts[1] ) { decpart_str = numberparts[1]; } //pokud je desetinná část
  else { //pokud není desetinná část, tak se vytvoří
    for ( var i=1;i<=decimals;i++ ) { decpart_str+= '0'; }
  }
  
  if ( thousand_sep.length ) { //pokud se požaduje oddělovač tisíců
    intpart_str = add_thousand_sep(intpart_str,thousand_sep); //přidá se oddělovač tisíců
  }
  
  var formated = intpart_str;
  if ( decimals ) { formated+= dec_point + decpart_str; }

  return formated;
}

/**
 * @Name: add_thousand_sep(number,thousand_sep)
 * @Author: Petr Novotný
 * @Date: 20.9.2008
 * @Description: Přidá oddělovač tisíců do celého čísla
 * @param int number            Číslo
 * @param string thousand_sep   Oddělovač tisíců
 */
function add_thousand_sep(number,thousand_sep) {

  var number_str = parseInt(number) + "";
  if ( !thousand_sep ) { thousand_sep = ''; }

  if ( thousand_sep.length ) {
    var number_str_new = "";
    var tmp = number_str;
    var last_trio = "";
    while ( tmp.length>3 ) {
      last_trio = tmp.substring(tmp.length-3);
      number_str_new = ( number_str_new.length ) ? last_trio + " " + number_str_new : last_trio;
      tmp = tmp.substring(0,tmp.length-3);
    }
    number_str = ( number_str_new.length ) ? tmp + " " + number_str_new : tmp;
  }
  
  return number_str;
}


//pouze čísla a případně desetinný oddělovač
function numbersonly(e, dec) {
  var key;
  var keychar;

  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;

  keychar = String.fromCharCode(key);

  if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
    return true;
  else if ( ("0123456789").indexOf(keychar) > -1 )
    return true;
  else if ( dec && ((".,").indexOf(keychar) > -1) ) {
    return true;
  }
  else
   return false;
}


/**
 * @Name: is_int(tested_value)
 * @Author: Petr Novotný
 * @Date: 28.3.2003
 * @Description: Zjistí, zda je hodnota typu integer
 * @param float|string tested_value   Testovaná hodnota
 */
function is_int(tested_value) {
  var tmp;
  tmp = parseInt(tested_value) + "";
  if ( tested_value.length==0 ) { return false; }
  else if ( tmp.length!=tested_value.length || isNaN(tmp) ) { return false; }
  else { return true; }
}

/**
 * @Name: is_float(tested_value)
 * @Author: Petr Novotný
 * @Date: 20.9.2008
 * @Description: Zjistí, zda je hodnota typu float
 * @param float|string tested_value   Testovaná hodnota
 */
function is_float(tested_value) {
  var tmp;
  tmp = parseFloat(tested_value) + "";
  if ( tested_value.length==0 ) { return false; }
  else if ( tmp.length!=tested_value.length || isNaN(tmp) ) { return false; }
  else { return true; }
}


/**
 * @Name: round(number,decimals)
 * @Author: Petr Novotný
 * @Date: 20.9.2008
 * @Description: Zaokrouhlení na požadovaný počet desetinných míst, inspired on web
 * @param float number          Číslo
 * @param int decimals          Počet desetinných míst
 */
function round(number,decimals) {
  number = parseFloat(number);
  var multi = Math.pow(10,decimals);
  return Math.round(number*multi) / multi;
}

//pouze čísla a mezera
function psconly(myfield, e) {
  var key;
  var keychar;

  if (window.event)
    key = window.event.keyCode;
  else if (e)
    key = e.which;
  else
    return true;

  keychar = String.fromCharCode(key);

  if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
    return true;
  else if (((' 0123456789').indexOf(keychar) > -1))
    return true;
  else
   return false;
}




