 /**
  * autocomplete 
  * @param input -> id pre tag inputu  
  * @param params -> parametere $_GET pre autocomplete.php  
  */

 /**
  * funkcia ktora sa nacita hned
  */    
 function getReady()
 {
  $(document).ready(function(){ 
    /**
     *     inicializaica tooltip pre rozne casti stranky
     *     pouzitie :: ... class="tooltip" title="$this->getTooltip('text',boolean)"     
     */
    $('.tooltip').tooltip();  
      
    /**
     *     zrusenie autocomplete pre inputy
     *     pouzitie :: <input class="ac_off" ...
     */
//		$('.ac_off').attr('autocomplete', 'OFF')[0];

    /**
     *    hodiny na stranke
     */
    $('#clock').jclock();   
           
    /**
     *  nahradenie target_"blank" v tagu a kvoli xhtml validite
     *  example <a href="creoneo.com" rel="external" >text</a>     
     */ 
    targetBlank();
    
    document.keyup = removeAjaxWindow();   
   
  });
  /*
   * posun podmenu na stred
   */    
  $(function(){
    $('#navigation > li > ul').each(function()
    {
      $this = $(this).parent();
      var moveleft = ($this.width()-$this.find('ul').width())/2;
      $this.mouseenter(function(){$(this).find('ul').css('left',moveleft).show();});
      $this.mouseleave(function(){$(this).find('ul').hide();});
    });
  }); 
  
  // po nacitani stranky
  $(window).bind("load",function(){
   //preload obrazkov
   imagePreload();
   
  });
  
   
 }     

 
  /**
   *  nahradenie target_"blank" v tagu a kvoli xhtml validite
   *  example <a href="creoneo.com" rel="external" >text</a>     
   */ 
  function targetBlank()
  {                 
    $('a[rel*=external]').click( function() {  
         window.open(this.href);
         return false;
    });  
  }   
  
  
  /**
   * preload obrazkov
   * najde vsetky onmouseovery a preloadne ich
   */         
  function imagePreload(){
   $('img').each(function(i){    
    // alternativa
    // var mouse_over = "["+($(this).attr("onmouseover")+"]";   
    var mouse_over = "["+(this.onmouseover)+"]"; 
    // v Firefoxe undefined, inde null
    if(mouse_over != "[undefined]" && mouse_over != "[null]")
    {                      
     // hladame retazec v umiestneny medzi "
     var srctext = mouse_over.match(/"(.*?)"/);
     if(srctext == null || srctext == undefined)
     {                                 
      // hladame retazec v umiestneny medzi '
      var srctext = mouse_over.match(/'(.*?)'/);  
     }                                
     // ak sa takyto retazec nasiel tak prida objekt ako obrazok
     if(srctext != null && srctext != undefined){
      var image = $("<img>").attr("src",srctext[1]);
     }       
    }
   });  
   return; 
  }
  
  function checkCheckBbox(form, reg)
  {
   if($(reg).is(':checked') == true){ 
    checkAll(form, 1);
   }
   else{     
    checkAll(form, 0);  
   }
  }
  
  /**
   * @param string form - id formularu
   * @param int data - 1 ak checked, 0 ak unchecked
   */          
  function checkAll(form,data)
  {
   if(data == 1)
    $("#"+form+" INPUT[type='checkbox']").attr('checked', true);
   else                 
    $("#"+form+" INPUT[type='checkbox']").attr('checked', false);  
  }
  
  
 function removeAjaxWindow()
 {
   $(document).keypress(function(e) {
     // click Esc
     if(e.keyCode == 27){
      RemoveTag("ajaxwindow","class");  
     }
   });
 }
 
 
 function submitFilter(formid,remove) {
  if(remove != undefined)
  {
   $("select[name='"+remove+"'] option[value='0']").attr("selected", true);
  }
  document.getElementById(formid).submit();
 }


  
/**
 *
 * upload suborov pomocou jquery a ajaxu
 *  
 * @param upload_tag      : id tagu pre upload
 * @param answer_tag      : id tagu pre odpoved z uploadu
 * @param dir             : directory pre upload suboru 
 * @param upload_name     : nazov uploadu $_FILES[filename]['..']
 * @param file_name       : nazov suboru pre upload       
 * @param file_type       : typ uploadu ['image', 'doc', 'movie', ''] suboru pre upload    
 * @param rewrite         : prepisovanie suborov        
 * @param save            : ulozenie do databazy 
 *                          napr. save = learn_lesson/file/10 ulozi do tabulky learn_lesson stlpca file a id 10 zaznam o nazve suboru  
 * @params params         : napr. value=name&value2=name2  
 */ 
function upload_Ajax(module, upload_tag, answer_tag, dir, upload_name, file_name, file_type, rewrite, save, params)
{
           
	var button      = $('#'+upload_tag), interval;     
	var button_text = button.text();

  if(rewrite == undefined){
   rewrite = false;
  }
                  
  if(upload_name == ""){
   upload_name = "myfile";
  }   
  
  if(save == undefined){
   save = "";
  }  
  
  if(params == undefined){
   params = "";
  }
	         
	         
	new AjaxUpload(button,{
		action: getPath() + '/upload.php', 
		name: upload_name,    
		data : {
		  'module'      : module,
		  'upload_name' : upload_name,
			'file_name'   : file_name,
			'type'        : file_type,  
			'destination' : dir,    
			'rewrite'     : rewrite,
			'save'        : save,     
			'params'      : params
		},
		onSubmit : function(file, ext){   
	               
			button.text('Uploading');
			this.disable();
			
			// Uploding -> Uploading. -> Uploading...
			interval = window.setInterval(function(){
				var text = button.text();
				if (text.length < 13){
					button.text(text + '.');					
				} else {
					button.text('Uploading');				
				}
			}, 200);
		},
		onComplete: function(file, response){ 
			button.text(button_text);						
			window.clearInterval(interval);						
			// enable upload button
			this.enable();	
			$('#'+answer_tag).html('');			
			$('#'+answer_tag).html(response);						
		}
	});
 return;
}

 function selectText(reg)
 {    
  return reg.select();
 }

 function infoclose(reg)
 {
  return $("." + reg).hide();
 }

 function CheckCorrect(reg, get_form, show_tag, scroll_tag)
 {  
  var ret = true;           
  var reg_value = $('#'+reg).val();      
        
  if(reg_value == '')
  {                     
   document.getElementById(get_form).submit();
   return;
  }      
  var exploded = reg_value.split(',');  
  	              
  $.each(exploded, function() {
   var this_value = this;          
   if($("#" + this_value).val() == "")
   {		
     $("#" + this_value).css("border", "1px solid red");
     ret = false;
   }
   else{ 
     $("#" + this_value).css("border", "1px solid #ddd");
   }
  });

  if(ret == true)
  {
    document.getElementById(get_form).submit();
  }
  else{
    $('.' + show_tag).show();    
 	  $.scrollTo('#' + scroll_tag, 800);
  }
  return; 	
 }

 function switchTags(tag_from,tag_to)
 {                    
   $("#"+tag_to).show(300);   
   $("."+tag_to).show(300);                  
   $("#"+tag_from).hide();                 
   $("."+tag_from).hide(); 
   return;
 }

 function showTag(tag, type){          
  switch(type){
   case 'id': { return $("#"+tag).show(); }  
   case 'class': { return $("."+tag).show(); } 
   default: { return $("#"+tag).show(); }   
  }
 }  

 function hideTag(tag, type){          
  switch(type){
   case 'id': { return $("#"+tag).hide(); }  
   case 'class': { return $("."+tag).hide(); } 
   default: { return $("#"+tag).hide(); }   
  }
 }

 function showTagParent(tag,type){
  switch(type){
   case 'id': { return $("#"+tag).parent().show(); }  
   case 'class': { return $("."+tag).parent().show(); } 
   default: { return $("#"+tag).parent().show(); }   
  } 
 }
 // skritie tagu parenta volaneho tagu
 function hideTagParent(tag,type){
  switch(type){
   case 'id': { return $("#"+tag).parent().hide(); }  
   case 'class': { return $("."+tag).parent().hide(); } 
   default: { return $("#"+tag).parent().hide(); }   
  } 
 } 
 
 //vymazanie tagu a jeho children()
  function RemoveTag(tag, type){  
    switch(type){   
     case 'id': { return $("#"+tag).remove(); }  
     case 'class': { return $("."+tag).remove(); } 
     default: { return $("#"+tag).remove(); }    
    }
  }
 
 //vymazanie parent tagu a jeho children()
  function RemoveTagParent(tag, type){  
    switch(type){   
     case 'id': { return $("#"+tag).parent().remove(); }  
     case 'class': { return $("."+tag).parent().remove(); } 
     default: { return $("#"+tag).parent().remove(); }    
    }
  }   
 
  // zatial nevyuzite !!!!
  function ajaxSelect(value,path, window, scroll){
    var parameter = value.serialize();
    $.ajax({
    type: "POST",
    url: path,
    data: parameter,
    success:  function(data){
					 $('.'+window).show(300);
					 $.scrollTo('#'+scroll, 500 );
				}

  });

  }

 function getAutocomlete()
 {    
   return getPath() + "/support/autocomplete.php";
  
 } 
 
 function getAjax(path)
 {                                 
   return getPath() + "/support/ajax.php";   
 }
 
  /**
   * pracuje s $_GET premennimi a spracuva linku na pozadi
   *      
   * @param modul = urcuje v ktorom module bola funkcia volana
   * @param params = pridavne $_GET parametre napr. expamle=1&exaple2=3
   */            
  function checkJSON(modul, params)
  {                           
    var path = getAjax();      
    var window_id = 'ajaxjson'+$.randomBetween(10, 10000)+'_message';
                      
    if(params != "")
    {
       path += "?" + params;
    }           
    $.getJSON( path , { modul:modul, scriptfunction:'json', ajaxrequest:'1'}, function(response){  
                          
      $('body').append('<div id="'+window_id+'" class="ajaxwindow"></div>');
               
     if(response.info != undefined && response.message != ""){ 
       $('#'+window_id).html('<div class="info_ajax"><div class="info_ajax_head">INFORMATION</div><div class="info_ajax_body">'+ response.message+ '</div></div>');
       $('.info_ajax').append('<div class="ajax_close"><a onclick="RemoveTagParent(\'info_ajax\',\'class\');">Closed</a></div>');
       centerTag(window_id, '');    
      }
     else if(response.error != undefined && response.message != ""){
       $('#'+window_id).html('<div class="error_ajax"><div class="error_ajax_head">ERROR</div><div class="error_ajax_body">'+ response.message+ '</div></div>');
       $('.error_ajax').append('<div class="ajax_close"><a onclick="RemoveTagParent(\'error_ajax\',\'class\');">Closed</a></div>');
       centerTag(window_id, '');  
      }
     else if(response.ok != undefined && response.message != ""){    
       $('#'+window_id).html('<div class="ok_ajax"><div class="ok_ajax_head">MESSAGE</div><div class="ok_ajax_body">'+ response.message+ '</div></div>');
       $('.ok_ajax').append('<div class="ajax_close"><a onclick="RemoveTagParent(\'ok_ajax\',\'class\');">Closed</a></div>');
       centerTag(window_id, '');  
      }
      else{   
       if(response.message != "")
       {      
         $('#'+window_id).html(response.message);   
         RemoveTag(window_id);
       }
      }
     
     if(response.hidden != undefined)
     {
       RemoveTag(response.hidden);    
     }
      
    });     
                   
  } 
  
  /**
   * Ajax funkcia  
   * @param modul = urcuje v ktorom module bola funkcia volana
   * @param formid = id formularu
   * @param typeajax = POST alebo GET alebo prazdna hodnota undefined  
   * @param params POST premenne natrvdo definovane   
   * @param createwindow - vytvarat okno    
   * @param session_update - obnovovanie session pre user_log     
   * @param loading - zobrazovat loading pri vykonavani    
   * @param timeout - timeout pre error spravu           
   * @param showerror - zobrazovanie chyby   
   */    
  function checkAjax(modul, formid, typeajax, scrolling, params, createwindow, session_update, loading, timeout, showerror){
    var path      = getAjax(); 
    var ajax_type = 'POST'; 
    var inputs    = "";   
    var time_out  = 10000;
    var window_id = 'ajax'+$.randomBetween(10, 10000)+'_message';
    var create_window = true; //vytvori sa ajaxove okno  
   
    if(createwindow != undefined && createwindow == false)
    {           
     create_window = false;
    }     
          
    if(timeout != undefined)
    { 
     time_out = parseInt(timeout);
    }
    
    if(scrolling == undefined || scrolling == true)
    {  // skrolovanie stranky 
     scrolling = true;
    }   
    
    if(showerror == undefined || showerror == true)
    {  // skrolovanie stranky 
     showerror = true;
    }   
                         
    if(session_update == undefined || session_update == true){
     session_update = 1;    
    }
    else{
     session_update = 0;
    }                                    
            
    if(formid != undefined && formid != ""){
     inputs  = $("#"+formid).serialize();
    }
        
    if(params != undefined && params != "")
    {   
     inputs += params;
    }    
       
    inputs += '&modul='+modul+'&'+'scriptfunction=ajax&session_update='+session_update;
       
    if(typeajax != undefined && typeajax != "") {
     ajax_type = typeajax;
    }             
       
    $('body').append('<div id="'+window_id+'" class="ajaxwindow"></div>');
            
    $.ajax({
     cache: false,
     type: ajax_type,
     url: path,
     data: inputs,
     dataType: "html",
     timeout: time_out,    
                      
     beforeSend: function(){  
        if(loading == undefined || loading == true){                   
          $("#"+window_id).html('<div class="loading"></div>');
          showTag('loading','class');          
          centerTag(window_id, '');    
          if(scrolling)
          {  
           $.scrollTo( "#" + window_id , {offset:-50});
          }         
        }
     },

     success: function(response) {  

        $("#" + window_id ).html(response);
        centerTag(window_id, '');      
    
        if(create_window == false)
        {                     
          RemoveTag(window_id);
        }                
  
     },
     
     error: function( objAJAXRequest, strError ){
      
      if(showerror == true)
      {  
       $("#" + window_id ).html('<div class="error_ajax"><div class="error_ajax_head">Error</div><div class="error_ajax_body">Error! Type: ' + strError + '</div></div>').fadeOut(7000);
      }
       centerTag(window_id, '');

     }
            
    }); 
 
  }
   
 jQuery.extend({
 	 random: function(X) {
	    return Math.floor(X * (Math.random() % 1));
	 },
	 randomBetween: function(MinV, MaxV) {
	   return MinV + jQuery.random(MaxV - MinV + 1);
	 }
 });
 
  

 function centerTag(tag, parent_tag)
 {
    var msg    = $("#"+tag);
    if(parent_tag == '')
    {
     parent_tag = window;
    }else{
     parent_tag = '#' + parent_tag;
    }
    var height = $(parent_tag).height();
    var width  = $(parent_tag).width();
    
     msg.css({
        'position' : 'fixed',
        'left' : width/2 - (msg.width() / 2),  // half width - half element width
        'top' : height/2 - (msg.height() / 2) // similar
    }); 
      
    $("#"+tag).css({"cursor":"move"}).draggable();
 }

 
