var bestSellTimeout = '';
var options = { path: '/', expires: 10 };

$(document).ready(function() {

    $('#producerselectbox').change(function() {
      window.location.href = $(this).val();
    });    
    

    // popis dostupnosti
    $('.level0').each(function(){
      $(this).hover(
        function () {
          $(this).find('.ul2').show();
        }, 
        function () {
          $(this).find('.ul2').hide();
          $(this).parent().find('.ul2').hide();
        }
      );
    })

    // popis dostupnosti
    $('.level1').each(function(){
      $(this).hover(
        function () {
          $(this).find('.ul3').show();
        }, 
        function () {
          $(this).find('.ul3').hide();
          $(this).parent().find('.ul3').hide();
        }
      );
    })
    

    $('#lng-ver').change(function(){
      $('#langform').submit();    
    });

    // popis dostupnosti
    $('.dostupnostPopUp').each(function(){
      $(this).hover(
        function () {
          $(this).parent().find('.dostupnostPopUpText').css('display','inline');
        }, 
        function () {
          $(this).parent().find('.dostupnostPopUpText').css('display','none');
        }
      );
    })


    // napoveda pro parametry
    $('.parametrHelp').each(function(){
      PopUpBox($(this),'/jquery/parameterhelp.php?param='+$(this).attr('param'),300,300,'napoveda');
    });
    


    // hodnoceni
    $('#ratingform .hodnoceni .stars').mousemove(function(e){
      var rating = $(this).offset();
      var x = (e.pageX + 1) - rating.left;
      var ratingValue = (x);
      
      if (ratingValue <= 20){
        $posunuti = "-80px";
        $('#hodnoceniValue').val('0');
        $('#ratingform .values').html('0% Nepoužitelný');
      }else if ((ratingValue <= 40)&&(ratingValue > 20)){
        $posunuti = "-60px";
        $('#hodnoceniValue').val('30');
        $('#ratingform .values').html('30% Špatný');
      }else if ((ratingValue <= 60)&&(ratingValue > 40)){
        $posunuti = "-40px";
        $('#hodnoceniValue').val('50');
        $('#ratingform .values').html('50% Průměrný');
      }else if ((ratingValue <= 80)&&(ratingValue > 60)){
        $posunuti = "-20px";
        $('#hodnoceniValue').val('80');
        $('#ratingform .values').html('80% Velmi dobrý');
      }else if ((ratingValue <= 100)&&(ratingValue > 80)){
        $posunuti = "-0px";
        $('#hodnoceniValue').val('100');
        $('#ratingform .values').html('100% Perfektní');
      }
      $('#ratingform .hodnoceni .stars').css('background-position',$posunuti + ' 0px');

    });

    $('#ratingform .hodnoceni .stars').click(function(){
      $('#values').html($('#hodnoceniValue').val());
      $('#ratingform').submit();
    });


    // hodnoceni v recenzi
    $('#recenze .hodnoceni .stars').mousemove(function(e){
      var rating = $(this).offset();
      var x = (e.pageX + 1) - rating.left;
      var ratingValue = (x);
      
      if (ratingValue <= 20){
        $posunuti = "-80px";
        $('#hodnoceniRecenze').val('0');
        $('#recenze .values').html('0% Nepoužitelný');
      }else if ((ratingValue <= 40)&&(ratingValue > 20)){
        $posunuti = "-60px";
        $('#hodnoceniRecenze').val('30');
        $('#recenze .values').html('30% Špatný');
      }else if ((ratingValue <= 60)&&(ratingValue > 40)){
        $posunuti = "-40px";
        $('#hodnoceniRecenze').val('50');
        $('#recenze .values').html('50% Průměrný');
      }else if ((ratingValue <= 80)&&(ratingValue > 60)){
        $posunuti = "-20px";
        $('#hodnoceniRecenze').val('80');
        $('#recenze .values').html('80% Velmi dobrý');
      }else if ((ratingValue <= 100)&&(ratingValue > 80)){
        $posunuti = "-0px";
        $('#hodnoceniRecenze').val('100');
        $('#recenze .values').html('100% Perfektní');
      }
      $('#recenze .hodnoceni .stars').css('background-position',$posunuti + ' 0px');

    });

    //$('#recenze .hodnoceni .stars').click(function(){
    //  $('#values').html($('#hodnoceniValue').val());
    //});

 /*
    if ($('#ratingclose').val() == 0){
      $('.ratline-mask').mousemove(function(e){
        var rating = $(this).offset();
        var x = (e.pageX + 1) - rating.left;
        var ratingValue = ((x) * 2);
        ratingValue = (ratingValue / 10) + 0.2;
        ratingValue = Math.round(ratingValue*10)/10;
        if ((ratingValue == '')||(ratingValue == '0.4')){
          ratingValue = '0.0';
        }
        if ((ratingValue == '1')||(ratingValue == '2')||(ratingValue == '3')||(ratingValue == '4')||(ratingValue == '5')||(ratingValue == '6')||(ratingValue == '7')||(ratingValue == '8')||(ratingValue == '9')){
          ratingValue = ratingValue + '.0';
        }
        $(this).parent().find('.dpr-red').css('width',((x) * 2)+'%');
        $('.rat-number').find('strong').html(ratingValue);
        $('#rating').val(ratingValue);
      });
      
      $('.ratline-mask').mouseout(function(){
        var defaultValue = $('#rating-load').val();
        setTimeout(function () {
          $('.rat-number').find('strong').html(defaultValue);
          $('#rating-width').css('width',defaultValue*10+'%');
        },3000);
      });
*/

    // chat
    $('.smileys').find('img').each(function(){
      $(this).click(function(){
        $('#chattext').val($('#chattext').val() + $(this).attr('alt'));
      });
    });

    // silencer
    $('#words').keyup(function() {
      if ($(this).val().length >= 2){
        $('#silencer').css('display','inline');
        $('#silencer').html("<img src='/img/loader.gif' alt='' />");
        //var sHtml = "<ul class='silencer'>";
        $.get('/jquery/silencer.php?srch='+$(this).val(), function(data){
          if (data > ''){ 
            $('#silencer').html(data);          
          }else{
            $('#silencer').css('display','none');
          }
        });

      }
    });


    // horozntal hover efekt
    $('.horizontal').find('li').each(function(){
      $(this).hover(
        function () {

          $(this).addClass('sel');
          obj = $(this);
          obj.find('.catPopUp').css('display','inline');
          
        }, 
        function () {
          $(this).removeClass('sel');
          obj = $(this);
          obj.parent().find('.catPopUp').css('display','none');
        }
      );
    });

    $('.horizontal').find('li:first').each(function(){
      $(this).hover(
        function () {
          $(this).addClass('sel-first');
          $(this).find('a:first').addClass('sel');
        }, 
        function () {
          $(this).removeClass('sel-first');
          $(this).find('a:first').removeClass('sel');
        }
      );
    });
    $('.horizontal').find('li.last').each(function(){
      $(this).hover(
        function () {
          $(this).addClass('sel-last');
          $(this).find('a:first').addClass('selected');
        }, 
        function () {
          $(this).removeClass('sel-last');
          $(this).find('a:first').removeClass('selected');
        }
      );
    });
    

    $('.category').find('li.level0').each(function(){
      $(this).hover(
        function () {
          $(this).addClass('sele');
        }, 
        function () {
          $(this).removeClass('sele');
        }
      );
    });

    $('.category').find('li.level1').each(function(){
      $(this).hover(
        function () {
          $(this).addClass('select');
        }, 
        function () {
          $(this).removeClass('select');
        }
      );
    });

    $('.category').find('li.level2').each(function(){
      $(this).hover(
        function () {
          $(this).addClass('select');
        }, 
        function () {
          $(this).removeClass('select');
        }
      );
    });


    /*
    / zalozky v detailu zbozi
    */
    $('.bookmarks li').find('a').each(function(){
      if ($(this).attr('href').indexOf('gallery') <= 0){
        $(this).click(function(){
           $('.bookmarks li').each(function(){
              $(this).removeClass('bm-active');
           });
           $(this).parent().attr('class','bm-active');
           $.get('/detail.php'+$(this).attr('href')+'&j=1', function(data){
                $('#param-content').html(data);
           });
           return false;
        });
      }
    });
    
    /*
    / odeslani emailu a dalsi formulare v detailu zbozi, provazani se zalozkama
    */
    
    $('.buttons').find('a').each(function(){
      
      $(this).click(function(){
         $('.bookmarks li').each(function(){
            $(this).removeClass('bm-active');
         });
         $.get('/detail.php'+$(this).attr('href')+'&j=1', function(data){
              $('#param-content').html(data);
         });
         return false;
      });
    });
    
    
    /*
    * pridani focus a blur na novinky emailem
    */    
    $("#mailnewsinput").focus(function () {
      if ($(this).val() == 'váš@e-mail'){
        $(this).val('');
      }
    });
    $("#mailnewsinput").blur(function () {
      if ($(this).val() == ''){
        $(this).val('váš@e-mail');
      }
    });

    /*
    * pridani focus a blur na pole hledani
    */    
    $("#words").focus(function () {
      if ($(this).val() == 'Hledat...'){
        $(this).val('');
      }
    });
    $("#words").blur(function () {
      if ($(this).val() == ''){
        $(this).val('Hledat...');
      }
    });


    /*
    * pridani focus a blur na logovaci formular
    */    
    $("#logininput").focus(function () {
      if ($(this).val() == 'Přihlašovací jméno'){
        $(this).val('');
      }
    });
    $("#logininput").blur(function () {
      if ($(this).val() == ''){
        $(this).val('Přihlašovací jméno');
      }
    });
    

    /*
    * pridani focus a blur na logovaci formular
    */    
    $("#passwordinput").focus(function () {
      if ($(this).val() == 'heslo'){
        $(this).val('');
      }
    });
    $("#passwordinput").blur(function () {
      if ($(this).val() == ''){
        $(this).val('heslo');
      }
    });


    $("#mesto").blur(function () {
      if (($(this).val() > '')&&($('#psc').val() == '')){
        $.get('/jquery/psc.php?mesto='+$(this).val(), function(data){
           $('#psc').val(data);
        });        
      }
    });
    $("#psc").blur(function () {
      if (($(this).val() > '')&&($('#mesto').val() == '')){
        $.get('/jquery/psc.php?psc='+$(this).val(), function(data){
           //alert(data);
           $('#mesto').val(data);
        });        
      }
    });


    $('.advrt-control').find('li').each(function(){
      if ($(this).attr('class') == 'counter'){
        $(this).click(function(){ 
        //alert(mainTimeoutmainimg);
          clearTimeout(mainTimeoutmainimg);
          counter = (parseInt($(this).attr('id').replace('dot-','')) );
          //alert(XMLID);
          //$.cookie('advert-last'+XMLID, counter, options);
          XMLBan(XMLFILE,XMLID,counter,XMLTIME,'1','mainTimeoutmainimg');
        });
      }
    });

    // setrizeni selectboxu s vyrobcema - nutny plugin jquery
    $("#producerSelect").sortOptions();    
   
});

/*
* parsovani XML s bannerama a stridani banneru po sekundach
*/
var counter = 0;
var name = "";
var url = "";
var img = "";
var blank = "";
var text = "";
var params = "";
var items = "";

var XMLFILE = "";
var XMLID = "";
var XMLCOUNTER = "";
var XMLTIME = "";


function XMLBan(file,id,counter,time, bannerControlBool,timeoutName){
  
  clearTimeout(timeoutName);
          
  var i = 1;
  if (bannerControlBool == '1'){
    XMLFILE = file;
    XMLID = id;
    XMLCOUNTER = counter;
    XMLTIME = time;
    XMLCONTROL = bannerControlBool;
  }
  $.ajax({
    url: file,
    cache: false,
    success: function(data) {
      $(data).find('banner').each(function(){
          name = $(this).find('name').text();
          url = $(this).find('url').text();
          img = $(this).find('img').text();
          blank = $(this).find('blank').text();
          text = $(this).find('text').text();
          params = $(this).find('params').text();
          items = $(this).find('count').text();
          if ((parseInt(counter)) > items){
            $.cookie('advert-last'+id, 1, options);
          }else{
            $.cookie('advert-last'+id, (parseInt(counter)), options);
          }
          if ((parseInt($.cookie('advert-last'+id))) == i){
            if (bannerControlBool == '1'){
              SelectDot((parseInt($.cookie('advert-last'+id))));
            }
            ShowBanner(id,img,(parseInt($.cookie('advert-last'+id))),file,items,time,name,url,bannerControlBool,timeoutName);
            return false;
          }
          i += 1; 
      });
    }
  });


}

function ShowBanner(id,img,counter,file,items,time,name,url,bannerControlBool,timeoutName){
  if (img.indexOf('.swf') > 0){
    $('#'+id).hide();
    $("object").remove();
    $("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='1180' height='359' id='blade' align='middle'><param name='allowScriptAccess' value='sameDomain' /><param name='allowFullScreen' value='false' /><param name='movie' value='"+img+"' /><param name='quality' value='high' /><param name='bgcolor' value='#ffffff' /><embed src='"+img+"' quality='high' bgcolor='#ffffff' width='1180' height='359' name='blade' align='middle' allowScriptAccess='sameDomain' allowFullScreen='false' type='application/x-shockwave-flash' pluginspage='http://www.adobe.com/go/getflashplayer' /></object>").insertBefore($('#'+id));
  }else{
    $("object").remove();
    $('#'+id).show();
    $('#'+id).attr('src',img);
    $('#'+id).attr('alt',name);
    $('#'+id).attr('title',name);
    $('#'+id).parent().attr('href',url);
    $('#'+id).parent().attr('alt',name);
    $('#'+id).parent().attr('title',name);
  }
  Show(document.getElementById(id), 0);
  if ((parseInt(counter)) > items){
    counter = 1;
  }else{
    counter = parseInt(counter) + 1;
  }
  if (bannerControlBool){
    mainTimeoutmainimg = setTimeout(function () {XMLBan(file,id,counter,time,bannerControlBool,'mainTimeoutmainimg')},time);
  }else{
    timeoutName = setTimeout(function () {XMLBan(file,id,counter,time,bannerControlBool,timeoutName)},time);
  }
}

function SelectDot(counter){
  //alert(counter);
  $('.advrt-control').find('li').each(function(){
    if ($(this).attr('class') == 'selected'){
      $(this).attr('class','counter');
      //return false;
    }
  });
  $('#dot-'+counter).attr('class','selected');
}

function setOpacity (obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;
	obj.style.filter = "alpha(opacity:"+opacity+")"; 
	obj.style.KHTMLOpacity = opacity/100;  
	obj.style.MozOpacity = opacity/101; 
	obj.style.opacity = opacity/100; 
}

function Show(obj, opacity) {
	if (opacity <= 100 && obj) {
		setOpacity(obj, opacity);
		opacity += 10;
		setTimeout(function () { Show(obj, opacity) }, 30); // rekurze na tuto funkci, k provedení dalšího stupně změny průhlednosti
	}
}

function Hide(obj, opacity, img) {
	if (opacity >= 0 && obj) {
		setOpacity(obj, opacity);
		opacity -= 10;
		setTimeout(function () { Hide(obj, opacity, img) }, 30); // rekurze na tuto funkci, k provedení dalšího stupně změny průhlednosti
  	
	}//else{
	// obj.src = img;
	// Show(obj, 0);
	//}
}


/*
* kontrola formularu
*/
function ControlForm(form){
  var errorMessage = '';
  $('#'+form).find('input').each(function(){
    if ($(this).attr('mandatory') > ''){
      if (($(this).attr('type') == 'text')||($(this).attr('type') == 'password')){
        if ($(this).val() == ''){
          if ($(this).attr('name').search('mail') != -1){
            if(!EmailControl($(this).val())){
              errorMessage = errorMessage + $(this).attr('mandatory') + '\n';
            }
          }else{
              errorMessage = errorMessage + $(this).attr('mandatory') + '\n';
          }
        } 
      }else if ($(this).attr('type') == 'checkbox'){
        if (!$(this).is(':checked')){
          errorMessage = errorMessage + $(this).attr('mandatory') + '\n';
        } 
      }  
    }

  });
  $('#'+form).find('textarea').each(function(){
    if ($(this).attr('mandatory') > ''){
      if ($(this).val() == ''){
        errorMessage = errorMessage + $(this).attr('mandatory') + '\n';
      } 
    }
  });

  
  if (errorMessage > ''){
    alert(errorMessage);
    return false;
  }else{
    return true;
  }
}


function EmailControl(f){
    if ((f=='' || f=='vas@email.cz') || f.indexOf('..') != -1 || f.indexOf('.@') != -1 || f.indexOf('@.') != -1 || (f.indexOf('@') < 1 || f.indexOf('@') != f.lastIndexOf('@') || f.lastIndexOf('.') < f.lastIndexOf('@')+2  || f.lastIndexOf('.') > (f.length-3) || f.lastIndexOf('.') < (f.length-4))){
       return false;
      }
    if ((f.indexOf('ř') > -1) || (f.indexOf('ě') > -1) || (f.indexOf('š') > -1) || (f.indexOf('č') > -1) || (f.indexOf('ž') > -1) || (f.indexOf('ý') > -1) || (f.indexOf('á') > -1) || (f.indexOf('í') > -1) || (f.indexOf('é') > -1) || (f.indexOf('ů') > -1) || (f.indexOf('ú') > -1)){
       return false;
    }
    return true;
}

function DelCountBasket(ID){
  document[ID].count.value = 0;
  document[ID].submit();
}

function printDetail(url){
  window.open(url);
  //alert(url);
}

function ControlNumber(){
     if ((event.keyCode <48) || (event.keyCode >57)) event.returnValue = false;
}

function OpenWindow(sUrl,sParam){
  window.open(sUrl,"_blank",sParam);
}	


/*
* lightbox 
*/    

function PopUpBox(obj,sUrl,nWidth,nHeight,sClass){
    obj.click(function(){
      var screens = "";
      var containerWidth = nWidth;
      var containerHeight = nHeight;
      var fromLeft = ((parseInt(document.body.offsetWidth)/2) - (containerWidth/2));
      var fromTop = ((parseInt($(window).height())/2) - (containerHeight/2));
      // prekryti cernou barvou
      $("<div class='overlay' style='filter: alpha(opacity=75); ZOOM: 1; height: "+document.body.scrollHeight+"px;'></div>").appendTo('body');
      htmlData = "";
      $.get(sUrl, function(data){
        htmlData = data;

        // vytvoreni boxu pro formular
        sHtml = "<div class='"+sClass+"' style='width: "+containerWidth+"px; display: block; top: "+fromTop+"px; left: "+fromLeft+"px; height:"+containerHeight+"px;'>"+
            		"  <div class='content'>"+
            		"     <a href='#' title='Zavřít' alt='Zavřít' id='close-form'>Zavřít</a>"+
                "     "+htmlData+ ""+
                "  </div>"+
                "</div>";
    
    
        // priradim html k telu stranky
        $('html, body').animate({scrollTop:0}, 'slow'); 
        $(sHtml).appendTo('body');
        
        // akce pro tlacitko zavrit
        $('#close-form').click(function(){
          $('.'+sClass).remove();
          $('.overlay').remove();
        });
        $('.overlay').click(function(){
          $('.'+sClass).remove();
          $('.overlay').remove();
        });

      });


      return false;
    });    
}

function getBestSell(file){
  $.ajax({
    url: file,
    cache: false,
    success: function(data) {
      $('.bestsell').find('.cont').html(data);
      bestSellTimeout = setTimeout("getBestSell('/jquery/bestsell.php');",10000);
    }
  });

}

