/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({ everyTime: function(interval, label, fn, times) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, times); }); }, oneTime: function(interval, label, fn) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, 1); }); }, stopTime: function(label, fn) { return this.each(function() { jQuery.timer.remove(this, label, fn); }); } }); jQuery.extend({ timer: { global: [], guid: 1, dataKey: "jQuery.timer", regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/, powers: { 'ms': 1, 'cs': 10, 'ds': 100, 's': 1000, 'das': 10000, 'hs': 100000, 'ks': 1000000 }, timeParse: function(value) { if (value == undefined || value == null) return null; var result = this.regex.exec(jQuery.trim(value.toString())); if (result[2]) { var num = parseFloat(result[1]); var mult = this.powers[result[2]] || 1; return num * mult; } else { return value; } }, add: function(element, interval, label, fn, times) { var counter = 0; if (jQuery.isFunction(label)) { if (!times) times = fn; fn = label;
label = interval; } interval = jQuery.timer.timeParse(interval); if (typeof interval != 'number' || isNaN(interval) || interval < 0) return; if (typeof times != 'number' || isNaN(times) || times < 0) times = 0; times = times || 0; var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {}); if (!timers[label]) timers[label] = {}; fn.timerID = fn.timerID || this.guid++; var handler = function() { if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn); }; handler.timerID = fn.timerID; if (!timers[label][fn.timerID]) timers[label][fn.timerID] = window.setInterval(handler,interval); this.global.push( element ); }, remove: function(element, label, fn) { var timers = jQuery.data(element, this.dataKey), ret; if ( timers ) { if (!label) { for ( label in timers ) this.remove(element, label, fn); } else if ( timers[label] ) { if ( fn ) { if ( fn.timerID ) { window.clearInterval(timers[label][fn.timerID]);
delete timers[label][fn.timerID]; } } else { for ( var fn in timers[label] ) { window.clearInterval(timers[label][fn]); delete timers[label][fn]; } } for ( ret in timers[label] ) break; if ( !ret ) { ret = null; delete timers[label]; } } for ( ret in timers ) break; if ( !ret ) jQuery.removeData(element, this.dataKey); } } } }); jQuery(window).bind("unload", function() { jQuery.each(jQuery.timer.global, function(index, item) { jQuery.timer.remove(item); }); });


jQuery(document).ready(function($) {
$.conf = {
      ref_time  :  "15s"
};




  $("#scrutinizingly").bind("click", function(){
    var text_w = $("table.db_searchform input.textlvl").css("width");
    $(this).hide();
    $("table.db_searchform").css({"width": "690px"});
    $("form[name='itemsearch'] input[name='search_type']").val("detailed");
    $(".item_id, .item_name").css({"width": text_w}); 
    $("table.db_searchform td:hidden").fadeIn(1000);   
    return false;   
  }); 




$("div.content").fadeIn();

/* Search bar */
$("#qsearch__in").click(function(){
   if($(this).val()=='' || $(this).val()==$.conf.searchval) $(this).val(''); 
}).blur(function(){  
  $(this).val($.conf.searchval); 
}).each(function(){
$.conf.searchval = $(this).val();
});

$("#add_news input, #add_news textarea,").click(function(){
   if($(this).val()=='Titulek' || $(this).val()=='Obsah zprávy..') $(this).val('');
});

/* Server status refresh */
$(".status .players").everyTime($.conf.ref_time, function(i) {
  var oldd = $(this).html(); 
  $.ajax({
    url: "lib/tpl/ragnarok/media/ajax/status.php",
    success: function(data)
    { 
      if(oldd != data) { 
        if (console && console.log) {     
          var time = new Date();
          var hour = time.getHours();
          var minutes = time.getMinutes();
          var seconds = time.getSeconds();
          console.log("Server status was reloaded from " + oldd + " to " + data + " at "+ hour + ":" + minutes + ":" + seconds +"! Refresh time is: "+$.conf.ref_time+".");
        }
        $(".status .players").html(data);
        return true; 
      }else if (console && console.log) {
        console.log("Server status is still same as before "+$.conf.ref_time+".");       
      }
      return false;      
    },
    error: function()
    {
      if (console && console.log) {
        // content cannot be reloaded.. whops!
        console.log("Server status can not be reloaded!");
        return false; 
      }     
    }
  }); 
});


/* Modal dialogs */
$("#msg .error, #msg .info, #msg .success, #msg .notify, .js_notice, .js_help").each(function(){
  var t_class = $( this ).attr('class');
    switch(t_class)
    {
      case 'error':   var title = 'Chyba';    break;
      case 'info':    var title = 'Info';     break;
      case 'success': var title = 'Úspěch';   break;
      case 'js_help': var title = 'Nápověda'; break;  
      default:
      case 'notify':  var title = 'Upozornění'; break;   
    }
  	$("." + t_class).dialog({
  		modal: true,
  		resizable: false,
  		title: title, 
  		zIndex: 9999,
  		buttons: {
  			Budiž: function() {
  				$( this ).dialog( "close" );
  			}
  		}
  	});  
}); 


$("<div title='Vyber si avatar novinky' id='avatar_list'><p></p></div>")
.dialog({
	autoOpen: false,
  resizable: false,
  position: ["right","bottom"],
  minWidth: 570,
  height: 400, 
  buttons: {
  	Zrušit: function() {
  		$( this ).dialog( "close" );
    }
  },
  create: function(event, ui) {
    // Initaliaze loading animation..
    $( this ).css({"background": "transparent url('lib/tpl/ragnarok/media/images/loader.gif') no-repeat center center"});
  },
  open: function(event, ui) {  
    if($("#avatar_list").css("background-image")!="none")
    {
      $.ajax({
        url: "lib/tpl/ragnarok/media/ajax/chooseavatar.php",
        success: function(data){           
          $("#avatar_list p").html(data); // Fill loaded data to this element
          $("#avatar_list").css("background-image", ""); // Shut down loader animation.
          $("#avatar__choosing table a").bind("click", function () {
            var selected_npc = $("img", this).attr("title");
            $("#add_news_form").css("background-image", "url('lib/tpl/ragnarok/media/images/npc/"+selected_npc+"')");
            $("#add_news input[name='npc_avatar']").val(selected_npc);  
            //$("#avatar_list").dialog("close"); 
            return false;
          });   
          console.log("NPC choosing page was loaded!");       
          return true; 
        },
        error: function()
        {
          console.log("NPC choosing page can not be loaded!"); 
          $( this ).css("background-image", "none"); // Shut down loader animation.
          return false; 
        }
      }); 
    }
  },
  beforeClose: function(event, ui) {}
});

$("#select_npc").click(function() {$("#avatar_list").dialog("open")});





$(".db_show").bind("click", function(){
    var element = $(this).siblings("[rel='hs']");
    if(element.is(":hidden"))
    {
      element.fadeIn();
      $(this).attr("class","db_hide");
      $(this).children('span').html(hide);    
    }else
    {
      element.hide();
      $(this).attr("class","db_show");
      $(this).children('span').html(show);     
    }
    return false;
});

$(".db_hs, .db_hs_hidden").bind("click", function(){
  var selector1 = $(this).closest("tr").siblings().eq(2)
  if(selector1.is(":visible"))
  {
    $(this).attr({'class':'db_hs_hidden','title':show});
    selector1.hide();
  }else
  {
    $(this).attr({'class':'db_hs','title':hide});
    selector1.show();
  }
  return false;
});


$(".recovery").bind("click", function(){
  var backup    = $(this).attr("id");
  var seletag   = $(this).attr("href").substring(1);
  $(this).siblings("input[name='"+seletag+"']").val(backup);
  return false;
});


/* Send form by pressing key */
if($("form[name='itemsearch']").length)
{
  $("*").keypress(function(e)
  {
      // if the key pressed is the enter key
      if (e.keyCode == 13)
      {
        $("form[name='itemsearch']").submit();
        return false;
      }
  }); 
}

$("select[name='print']").change(function(){$(this).closest("form").submit();return false;});

$(".tabs, #tabs").tabs({/*cookie: {expires: 1}*/});


}); // end of JQ defs.

// JS part
// Images preloader
function preload() {  
  var images = new Array();
	for (i = 0; i < preload.arguments.length; i++) {
			images[i] = new Image();
			images[i].src = temp_dir + preload.arguments[i];	
      //alert("Loading image: " + images[i].src);	
	}
}

// GET value of var from url
function getURLParameter(name) {
    if(name == false) var name = null;
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
