$(document).ready(function() {

  /* prettyPhoto */
  if ($("a[rel^='prettyPhoto']").length) $("a[rel^='prettyPhoto']").prettyPhoto();
   
  /* tabulky */
  $('#middle-col table').wrap('<div class="table-border"><div class="table-left-top"><div class="table-left-bottom"><div class="table-right-bottom"><div class="table-right-top">');
  $('#middle-col table tbody tr:even').addClass("even");

  /* kulate rohy  */
  $('#ae-content div.corner').wrap('<div class="corner-top"><div class="corner-bottom">');
  $('#middle-col div.company').wrap('<div class="company-top"><div class="company-bottom">');
  $('#middle-col div.white-box').wrap('<div class="white-box-top"><div class="white-box-bottom">');
  $('#middle-col div.white-box-img').wrap('<div class="white-box-top"><div class="white-box-bottom">');
   
  /* pismo, bookmark, print */
  if  ($('#middle-col').length) {  
    
    var orig_size = parseFloat($('#middle-col').css('font-size'), 10);
    
    $("#font-up").click(function() {
      var size = parseFloat($('#middle-col').css('font-size'), 10);
      var new_size = size * 1.2;
      new_size = ((size < orig_size) && (new_size > orig_size)) ? orig_size : new_size;
      $('#middle-col').css('font-size', new_size);
      return false;
    });
    
    $("#font-down").click(function() {
      var size = parseFloat($('#middle-col').css('font-size'), 10);
      var new_size = size * 0.8;
      new_size = ((size> orig_size) && (new_size < orig_size)) ? orig_size : new_size;
      $('#middle-col').css('font-size', new_size);
      return false;
    });
    
    $("#bookmark").click(function() {  
      if (window.sidebar) {
        window.sidebar.addPanel(document.title, window.location, "");
      }
      else if (window.external) {
        window.external.AddFavorite(window.location, document.title);
      }
      return false;      
     });
  
    $("#print").click(function(){
      window.print();
      return false;
    });
  }


  /* form - povinne pole */
  if ($('#main-form').length) {  
    $('#main-form ul li.req').append('<img class="req" src="/images/form_req.png" alt="Required" title="Required" />');
    $('#main-form ul li.req input, #main-form ul li.req textarea').bind('change focusout', function() {form_test(this);});

    $('#main-form ul li.req input').each(function() {
       if ($(this).val() != '' && this.type != 'radio') {
          form_test(this);
       }
    });
    
    // antispam
    $('#li-as').hide();
    var as = {'1': '15', '2': 'green', '3': 'blue', '4': '20', '5': '12'};
    $('#as').val(as[String($('#as_id').val())]);
  }

  function form_test(el) {

    var error   = false, 
        form_ok = true,    
        sel     = (el) ? '#main-form ' + el.nodeName + '[name=' + el.name + ']': '#main-form li.req input, #main-form li.req textarea';
    
    $(sel).each(function() {
         
      if ($(this).hasClass('reqtext')) {
        error = ($.trim(this.value).length < 1) ? true : false;
      }
      if ($(this).hasClass('reqphone')) {
        error = !/^\+?[0-9 ]{9,}$/.test(this.value);
        if (error && !$('#phone-help').length) {
            $(this).after('<div id="phone-help" style="color:red;clear:both;margin:3px 0 0 140px;">e.g. +012 123 456 789</div>')
        }
        else if (!error) {
            $('#phone-help').remove();
        }
      }
      if ($(this).hasClass('reqemail')) {
        error = !/^[-a-zA-Z0-9_.+]+@[-a-zA-Z0-9_.+]+\.[a-zA-Z0-9]{2,6}$/.test(this.value);
      }
      if ($(this).hasClass('reqzip')) {
         error = !/^[0-9]{5}$/.test(this.value);
      }
      if ($(this).hasClass('reqradio')) {        
        error = ($('#main-form input[name=' + this.name + ']:checked').length) ? false : true;
      }
      
      var li = $(this).closest('li.req');
      var img = $('img.req', li)[0];
      if (img) {
        img.title = (error) ? 'Required' : 'OK';
        img.src = (error) ? '/images/form_error.png' : '/images/form_ok.png';
      }

      if (error) form_ok = false;

    });
    if (!el) return form_ok;
  }
  
  var can_submit = true;
  $('#main-form').submit(function() {       
    
    // hidden fields
    $('#main-form select').each(function() {
        $('#hidden_' + this.id).val($('option:selected', this).text());   
    });

    var check_text = '';   
    $('#main-form input[type="checkbox"]:checked').each(function() {
        if (check_text) check_text += ', ';
        check_text += $('#main-form label[for="' + this.id + '"]').text();
    });
    $('#hidden_checkboxes').val(check_text);
    
    $('#main-form input[type="radio"]:checked').each(function() {
        $('#hidden_typ_form').val($('#main-form label[for="' + this.id + '"]').text());
    });
    
    return can_submit ? form_test(false) : false;
  });
 
   /* odesilani souboru */
   var upload = function() {
    
      var files_count = $('input.id_file[value!=""]').length;

      if (files_count > 4) {
         alert($('#max_pocet').val());
         return false;
      }
      
      // zakazeme odeslani formu
      can_submit = false;
      $('#main-form input.subm').attr('disabled', true).css('visibility', 'hidden');

  		$('#loading').ajaxStart(function(){
        	$(this).show();
  		})
  		.ajaxComplete(function(){
  			$(this).hide();
  		});
        
  		$.ajaxFileUpload(
			{
				url:             'file/', 
				upload:          upload,
                secureuri:       false,
				fileElementId:   'files',
				dataType:        'xml',
				success:         function(data, status) {
                  					if (typeof(data.error) != 'undefined')	{
                  						if (data.error != '') {
                  							alert(data.error);
                  						}
                                    else {
                  							alert(data.msg);
                  						}
                  					} 
                                 else {
                  					   var id_file   = $('id', data).text(),
                  					       filename  = $('filename', data).text(),
                  					       error     = $('error', data).text();
                  					   if (error) {
                  					      alert($('#povolene_typy').val());
                       					   $('input#files').val('');
                                    } 
                                    else {
                                       var input = $('input.id_file:hidden[value=""]')[0];
                                       input.value = id_file;                    					 
                                       alert($('#soubor_nahran').val());
                                       $('div#uploaded-files').append('<div class="file-info" id="div-' + input.id + '">'  
                                                                      + $('#nahrany_soubor').val() + filename 
                                                                      + ' <span onclick="delFile(\'' + input.id + '\')">x</span>');
                  					    }
                                 }
				                     // povolime odeslani formu
                                    can_submit = true;
				                    $('#main-form input.subm').attr('disabled', false).css('visibility', 'visible');
                             },
				error:           function(data, status, e)	{
					                 alert(e);
				                 }
		 });     

      return false;
   }; 
   $('#main-form input[type="file"]').change(upload);
   
  /* carousel */
  if ($('#carousel').length) {
      $('#carousel').jcarousel({
         scroll: 2,
        // visible: 3,
         wrap: 'circular'
      });
    
      $('#carousel li').hover(function() {
          $(this).height('261px').addClass('carousel-hover');
          $('#footer-hp').css('z-index', '-1');
          $('div.carousel-img', this).addClass('carousel-div');
       },
       function() {
          $(this).height('188px').removeClass('carousel-hover');
          $('div.carousel-img', this).removeClass('carousel-div');
          $('#footer-hp').css('z-index', '100');
       });
  }
     
});

/* smazani souboru */
function delFile(id) {
   $('#' + id).val('');   
   $('#div-' + id).remove();
}
