/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var lastForm = null;

function onSend(j) {
    if(lastForm == null) {
        return;
    }        
    $(lastForm).resetForm(j.error != null);
    if(j.error == null) {        
        $($('.ok', lastForm).parent()).show();
        try {
         lastForm.done();
        }catch(ex){}
    } else {        
        if(j.error.error_send) {
            $($('.default_error', lastForm).parent()).show();            
        } else {            
            $($('.item_error', lastForm).parent()).show();
            for (var er in j.error) {
                var input = $('#'+er.replace(/error_/,''), lastForm);
                input.addClass('error').attr('title',$('#'+er,lastForm).show().text());
            }            
        }
    }    
    lastForm = null;
    return;
}

function convertFileSize(size) {
    if(size > 1000000) {
        return (Math.round(size/10000)/100)+' MB';
    }
    if(size > 1000) {
        return (Math.round(size/10)/100)+' KB';
    }
    return size+' B';
}

function uploadAjaxFile() {
    $('.uploadFileButton').each(function(i){
       if(this.id!=null && this.id.length > 0) {
           var form = $(this).parents('form').get();           
           var type = $('[name=formtype]',form).val();
           var maxFiles = $('.formMaxFile',form).val();
           new AjaxUpload(this.id, {
               action: './upload-file.php',
               data: {
                  formtype: type
               },
               responseType: 'json',
               onSubmit: function(file, ext) {
                 var msize = $('.maxFileSize', form).val();
                 var rsize = 0;
                 if(jQuery.browser.mozilla) {
                     rsize =  this._input.files[0].fileSize;
                 }
                 if(rsize > msize) {
                     alert('Vámi náhrávaný soubor "'+file+'"('+convertFileSize(rsize)
                         +') je moc velký. \n Maximální povolená velikost souboru je '+convertFileSize(msize)+'.')
                     return false;
                 }else{
                     showLoadingPanel('Soubor:&nbsp;'+file, form);
                 }
               },
               onComplete: function(file , res){
                    if(res.success==1) {
                        $('[name=cv_files]',form).val($('[name=cv_files]',form).val()+'|'+file);
                        $('.list_file',form).append('<li class="fileItem">'+file+' - <a href="#" onclick="deleteAjaxFile(\''+file+'\',\''+type+'\', this); return false;" >smazat</a></li>');
                        if($('.list_file .fileItem',form).length >= maxFiles) {
                            $('.uploadFileButton',form).hide();
                        }
                    } else {
                        alert('Soubor "'+file+'" se nepoda\u0159ilo nahrát na server. \n Zkuste to prosím později nebo nás kontaktujte e-mailem.');
                    }
                    hideLoadingPanel(form);
               }
           });
       }
    });
}

function deleteAjaxFile(file, type, obj) {
     var link = $(obj);
     var form = link.parents('form');
     var list_files = $('[name=cv_files]',form);
     list_files.val(list_files.val().replace('|'+file,''));
     link.parents('li').remove();
      $('.uploadFileButton',form).show();
      hideLoadingPanel()
}

/* Form add panel Loading  */

function LoadingPanelEvents() {
    $('#ajaxLoadingPanel').css({top: $(document).scrollTop()+'px'});
}

 function showLoadingPanel(text, form) {
     var lpanel = $('#ajaxLoadingPanel');
     if(lpanel.length == 0) {
        $('body').append('<ul id="ajaxLoadingPanel"></ul>');
        lpanel = $('#ajaxLoadingPanel');
     }
     lpanel.append('<li><span>'+text+'</span></li>');
     lpanel.css({top: $(document).scrollTop()+'px'});
     $('.btnPridat, .btnReset',form).attr('disabled',true);
     $(window).bind('scroll',LoadingPanelEvents);
 }

function hideLoadingPanel(form) {
      $('#ajaxLoadingPanel').empty().hide();    
      $('.btnPridat, .btnReset',form).removeAttr('disabled');
      $(window).unbind('scroll',LoadingPanelEvents);
}

 jQuery.fn.extend({
  resetForm : function(disable_reset_value) {

     if(this.attr('tagName').toLowerCase() != 'form') return;
     if(disable_reset_value) {
        $('input[type=text], textarea, select',this).removeClass('error').attr('title','');
        $('.captcha_text',this).val('');
     } else {
        $('input[type=text], textarea, select',this).removeClass('error').attr('title','').val('');
        $('select',this).attr('selectedIndex',0);
        $('.list_file',this).empty().append('<li style="display: none;">&nbsp;</li>');
        $('.uploadFileButton',this).show();
        var lForm = this;
        $('.default_value',this).each(function(i) {
           $(this).val($('#default_'+this.id.replace(/@/,''), lForm).text());
        });
     }
     $('.error_mess', this).hide();
     $('li.error', this).hide();         
     if($('#recaptcha_response_field',this).length>0) {
      Recaptcha.reload();
     }else if($('.captcha_img',this).length>0) {
      $('.captcha_img',this).attr('src',$('.captcha_img',this).attr('src')+'0');
     }
  }
});

function onLoadSender() {    
    $('form.ajaxSender').submit(function(e){
           //$('.pravy_panel').html();           
           if(lastForm!=null) {
               return false;
           }           
           lastForm = e.target;
           lastForm.scrollIntoView(true);
           if($('.formSending',lastForm).length > 0) {
                $(lastForm).children('div').each(function(){$(this).toggle();});
           }
           showLoadingPanel('Odesílám zprávu ...', lastForm);
           $.post(e.target.action,
              $(e.target).serialize()+'&ajax=1',
              function(data, textStatus){
                  if($('.formSending',lastForm).length > 0) {
                        $(lastForm).children('div').each(function(){$(this).toggle();});
                  }
                  hideLoadingPanel(lastForm);
                  if(textStatus == 'success') {
                     onSend(data);
                  }
                  lastForm = null;
              }, "json");
           
           return false;
    });           
    $('.btnReset').click(function(e) {
        $($(e.target).parents('form').get(0)).resetForm();
        return false;
    });

    // Enable Ajax upload file    
        uploadAjaxFile();
        //showLoadingPanel('file.txt');
}


if(!(jQuery.browser.msie && jQuery.browser.version<=6)) {    
    $(document).ready(onLoadSender);
}
