// JavaScript Document
$.fn.outerHTML = function() {
    var doc = this[0] ? this[0].ownerDocument : document;
    return $('<div>', doc).append(this.eq(0).clone()).html();
};

$.maxZIndex = $.fn.maxZIndex = function(opt) {
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

$.fn.tagName = function() {
    return this.get(0).tagName.toLowerCase();
}


function gE(o){return document.getElementById(o);};
function cE(o){return document.createElement(o);};

function prepniHledani(zalozka)
{
   var d_rozsirene='', p_rozsirene='none', p_zakladni='', t_hledani=1;
   if (zalozka == "z") {
      d_rozsirene='none';
      p_zakladni='none';
      p_rozsirene='';
      t_hledani=0;
   }

  $("#typ_hledani").val(t_hledani);
  /*
  $("#t_rozsirene").css("display",d_rozsirene);
  $("#p_zakladni").css("display",p_zakladni);
  $("#p_rozsirene").css("display",p_rozsirene);
  */


  $("#p_zakladni").css("display",p_zakladni);
  $("#p_rozsirene").css("display",p_rozsirene);
     
  if (d_rozsirene == '')
      $("#t_rozsirene").show('slow');
    else
      $("#t_rozsirene").hide('slow');
  

}


// Funkce pro zobrazeni napovedy v bubline

function b_setEvent(){
$(document).click(function (event) { 
      if (!event) event =  window.event;
      docClick(event);
    });
}

function hideHelp(obj){
try {
    $("#bubbleHelp").slideUp();

}
catch (e) { 	}
}

function docClick(e){
  if (!e) e =  window.event;
  var obj = (e.target) ? e.target : e.srcElement;
  if (obj.tagName != "INPUT")
     hideHelp(obj);
}

function setHelp(obj){
    if (obj.getAttribute('nadpis') == null || obj.getAttribute('popis') == null) return true;
    if (!document.getElementById('bubbleHelp')) createBubble();
    var y = - 70;
    var x = obj.clientWidth + 4;
    for(var f=obj;f.offsetParent;f=f.offsetParent)
    {
      x+=f.offsetLeft;
      y+=f.offsetTop;
    }
    
    //try {
        gE('bubble_nadpis').innerHTML = obj.getAttribute('nadpis');
        gE('bubble_popis').innerHTML = obj.getAttribute('popis');
    
        var box = gE('bubbleHelp');
        box.style.left = x +"px";
        box.style.top = y+"px";
        //box.style.display = "";
        $("#bubbleHelp").show("slow");
    
        
        /*
    }
    catch (e) { 	}
    */
    b_setEvent();
}

function createBubble(){
    var c = document.createElement("DIV");
    c.id = "bubbleHelp";
    c.className = "bubble";
    c.style.display = "none";
    c.style.top = 0;
    c.style.left = 0;
    
    te = "<div class=\"bubble-cont\">"
             +"<p class=\"bubble-title\" id=\"bubble_nadpis\"></p>"
             +"<div id=\"bubble_popis\">"
             +"</div>"
             +"<p class=\"bubble-close\"><a href=\"#\" onclick\=\"hideHelp(); return false;\" title=\"Zavřít  nápovědu\"><span>Zavřít</span></a></p>"
         +"</div>"
    
    c.innerHTML = te
    
    document.body.appendChild(c);
}

//*   formatuje cenu na 10 000 000
function formatPrice(toto,ismez){
  formatInput($(toto));
}

function formatInput(obj){
    var reg = "[^[0-9]]*";
    if (obj.attr('regexp')) reg = obj.attr('regexp');
    var numbers = new RegExp(reg, "g");
    var x  = obj.val().replace (numbers, "");

    if (obj.attr('onlynum')) {
        y = x;
    } else {
        var po = 0, mark = "", y='';
        var odd=obj.attr('odd');
        if (isNaN(odd) || odd == '')
             odd=3;
          else
             odd = parseInt(odd, 10);

         for(var i=x.length-1;i>=0;i--){
            if (po == odd)  {
                    mark=" "; po = 0;
                    if (obj.attr('psc') == '1') po=-1;
            } else  mark = "";
            po++;
            y = x.charAt(i)+mark+y;
        }
    }


    obj.val(y);
}

function CountTxtArea(IDarea, countArea, MaxC) {
  if ( $("#"+IDarea).val().length > MaxC)
    // IDarea.value = IDarea.value.substring(0, MaxC);
    $("#"+IDarea).val($("#"+IDarea).val().substring(0, MaxC) );
  else
    $("#"+countArea).val(MaxC -     $("#"+IDarea).val().length);
}


function sendLoginForm(){
    if ($("#toploginname").val() == "" || $("#toploginpass").val() == "")
        alert("Prosím vyplňte uživatelské jméno a heslo");
    else
        $("#headlogon").submit();
}

function showOO(akce, id_inz, id_rubriky){
  if (akce == 'show') {
      nactiXmlOO(id_inz, id_rubriky);
  } else {
     $(".sp-lbox").hide();
  }
}

function nactiXmlOO(id_inz, id_rubriky){
  $.get("/jscripts/oo/inz.php", { rubrika: id_rubriky, id: id_inz}, zobrazOO);
}

function zobrazOO(request){
  
  if ($(request.responseXML).find("chyba").text() == 1) {
    alert("nastala chyba");
    return;
  }

  var rubrika = $("rubrika", request).text();
  
  if (rubrika == "2")
      var pid = [ 'nadpis', 'img', 'cena', 'kategorie', 'rok_vyroby', 'objem', 'vykon', 'najeto', 'odkaz_detail' ];

  if (rubrika == "11" || rubrika == "146")      
      var pid = [ 'nadpis', 'img', 'cena', 'kategorie', 'odkaz_detail' ];
        
  for (var i=0; i < pid.length; i++) {
    if (pid[i] == "odkaz_detail") {
        $("#oo_"+pid[i]).attr('href', $(pid[i], request).text());
        $("#oo_"+pid[i]).attr('title', "Více o "+$('nadpis', request).text());
        continue;
    } 

    if (pid[i] == "img") {
        $("#oo_"+pid[i]).attr('alt', $('nadpis', request).text());
        $("#oo_"+pid[i]).attr('src', $(pid[i], request).text());
        continue;
    } 
    
    $("#oo_"+pid[i]).text($(pid[i], request).text());
  }

     $(".sp-lbox").show('slow');  
}

function pridatDoOblibenychInzeratu(id_inz, typ){
 var url = document.location.toString();
 url = url.replace("#", ""); 
 $.get(url, { addtobag: 'yes', typ: typ, id: id_inz}, 
      function(data){ 
         var x = $(data).find("status").text();
         if (x) alert(x); 
      });
}

function newTop(topurl){
    var f = cE("FORM");
    f.setAttribute('method', 'post');
    f.setAttribute('action', topurl);
    inp = cE("input");
    inp.setAttribute('type', 'text');
    inp.setAttribute('name', 'mainurl');
    inp.setAttribute('value', document.location.toString());
    f.appendChild(inp);
    
    $("body").append(f);
    f.submit();
}

function prihlasitAvizo(){
    var url = "/";
    $.get(url, { glp: 'yes'}, 
      function(data){ 
         var x = $(data).find("l").text();
         var y = $(data).find("p").text();
         var u = $(data).find("u").text();
         if (x) {
            openAvizo(u, x, y);
         } 
      });
}

function openAvizo(u, l, p){
    //var url_login="http://www.avizo.cz";
    var url_login= u;
    var f = cE("FORM");
    f.setAttribute('method', 'post');
    f.setAttribute('target', '_new');
    f.setAttribute('action', url_login);
    f.style.visibility = 'hidden';
    
    var inp = cE("input");
    inp.setAttribute('type', 'text');
    inp.setAttribute('name', 'toploginname');
    inp.setAttribute('value', l);
    
    var inp2 = cE("input");
    inp2.setAttribute('type', 'password');
    inp2.setAttribute('name', 'toploginpass');
    inp2.setAttribute('value', p);
    
    var inp3 = cE("input");
    inp3.setAttribute('type', 'text');
    inp3.setAttribute('name', 'redirurl');
    inp3.setAttribute('value', u+'/vase-avizo/vase-inzeraty/inzeraty-noviny/');
    var inp4 = cE("input");
    inp4.setAttribute('type', 'text');
    inp4.setAttribute('name', 'allredir');
    inp4.setAttribute('value', 'yes');
    
    f.appendChild(inp);
    f.appendChild(inp2);
    f.appendChild(inp3);
    f.appendChild(inp4);
        
    $("body").append(f);
    f.submit();
}

function zapnuteCookies(name){
  var cookieValue = null;
  if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
          var cookie = jQuery.trim(cookies[i]);
          // Does this cookie string begin with the name we want?
          if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
          }
      }
  }
  return cookieValue;
}


var obj_city = new Object;
var ac;
var validator;
var obj_set = new Object;

function zamenObec(id){
  var url = "/";

  var vc = $("#"+id).val();


  $.post(url, { listobec: 'yes', city: vc },
      function(data){

        if ( $("#"+id).tagName() == 'input') {
             var p = $(data).find("o");
             var x = p.length;
             var v;
             if (x && x > 0) {
                var t = '<select id="'+id+'" name="'+id+'">';
                var i=0;
                p.each( function () {
                    sel = (i++ == 0)? ' selected="selected" ' : '';
                    t += "\n"+'<option value="'+$(this).text()+'" '+sel+'>'+$(this).text()+'</option>';
                });
                t += '</select><a href="" onclick="zrusObec(\''+id+'\'); return false;">Zruš výběr</a>';
                obj_city[id] = $("#"+id).outerHTML().replace('class="error"', '');

                $("#"+id).rules("remove");
                $("#"+id).replaceWith(t);

                ac.disable();
             }
      }
    });
}

function zrusObec(id){
    var t = obj_city[id];
    if (!t) t = '';
    $("#"+id).rules("remove");
    $("#"+id).parent().find("a,label").remove();
    $("#"+id).replaceWith(t);

    nastavNaseptavac(id);
    rulesObec(id, obj_set[id].stat, obj_set[id].req);
}

function rulesObec(id, stat, req){
 var r = req;
 var x = {id: id, stat: stat, req: req};
 obj_set[id] = x;
 
 $.validator.addMethod("testCity", function (value, element){
     $.ajax({
                cache:false,
                async:false,
                type: "POST",
                //contentType: "application/x-www-form-urlencoded;charset=windows-1250",
                 data: "&stat="+$("#"+stat).val()+"&typ="+element.tagName+"&city=" + value ,
                 url: '/jscripts/jnaseptavac/check-obec-ajax.php',
                 success: function(msg) {
                    if (msg=='2')  zamenObec(id);
                    ret = (msg=='1') ? true : false;

               }
      });
      return ret;
  }, "");


 $("#"+id).rules("add", {
                       required: r,
                       testCity: true
                       ,messages: {
                            required: "Zadejte lokalitu!",
                            testCity: "Obec není jednoznačná!"
                       }
                });

}

function nastavNaseptavac(id){
      ac = $('#'+id).autocomplete({
           serviceUrl:'/jscripts/jnaseptavac/obce.php',
           onSelect: function(value, data){
                //$("#"+id).valid();
           }
       });

}


function nastavNapovedu(napoveda) {

$.each(napoveda, function(key, value) {
        var obj = $("#"+key);
        if (obj) {
            obj.attr("nadpis", value.nadpis );
            obj.attr("popis", value.popis);
            obj.blur(function() { hideHelp(this); });
            obj.focus(function () { setHelp(this); });
        }
    });
}
