jQuery(window).unbind('unload').unload(function(){
	var elems = document.getElementsByTagName('*'),
	pos = elems.length + 1, // +1 for the document
	dummy = {};

	jQuery.data( dummy );
	for( var expando in dummy );
     
	while( pos-- ){
		var elem = elems[ pos ] || document, //add the document
		id = elem[expando];

		if( id && jQuery.cache[id] && jQuery.cache[id].events )
			jQuery.event.remove( elem );
	}
});


// Sprawdzanie, czy tablica zawiera element
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

var UNICODE_LETTERS =
   "\\u0041-\\u005a\\u0061-\\u007a\\u00aa\
   \\u00b5\\u00ba\\u00c0-\\u00d6\
   \\u00d8-\\u00f6\\u00f8-\\u01ba\\u01bc-\\u01bf\
   \\u01c4-\\u02ad\\u0386\\u0388-\\u0481\\u048c-\\u0556\
   \\u0561-\\u0587\\u10a0-\\u10c5\\u1e00-\\u1fbc\\u1fbe\
   \\u1fc2-\\u1fcc\\u1fd0-\\u1fdb\\u1fe0-\\u1fec\
   \\u1ff2-\\u1ffc\\u207f\\u2102\\u2107\\u210a-\\u2113\
   \\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\
   \\u212a-\\u212d\\u212f-\\u2131\\u2133\\u2134\\u2139\
   \\ufb00-\\ufb17\\uff21-\\uff3a\\uff41-\\uff5a";

$.fn.x = function(n) {
     var result = null;
     this.each(function() {
         var o = this;
         if (n === undefined) {
             var x = 0;
             if (o.offsetParent) {
                 while (o.offsetParent) {
                     x += o.offsetLeft;
                     o = o.offsetParent;
                 }
             }
             if (result === null) {
                 result = x;
             } else {
                 result = Math.min(result, x);
             }
         } else {
             o.style.left = n + 'px';
         }
     });
     return result;
};
$.fn.y = function(n) {
     var result = null;
     this.each(function() {
         var o = this;
         if (n === undefined) {
             var y = 0;
             if (o.offsetParent) {
                 while (o.offsetParent) {
                     y += o.offsetTop;
                     o = o.offsetParent;
                 }
             }
             if (result === null) {
                 result = y;
             } else {
                 result = Math.min(result, y);
             }
         } else {
             o.style.top = n + 'px';
         }
     });
     return result;
};

var nl2br = function(str){
  return str.replace(/([^>])\n/g, '$1<br />\n');
};

var isArrayInput = function(name, decode){
	if(!decode) { decode = true; }
	return (decode)? ((decodeURIComponent(name).indexOf('[]'))? true : false) : ((name.indexOf('[]'))? true : false)
}

$.fn.unserializeForm = function(data){
	tmpData = data.split('&')
	data = new Array()
	for(i in tmpData){
	  	data = data.concat(new Array(new String(tmpData[i]).split('=')))
	}
	for(i in data)
	{
		if(data[i][1]){
			if(isArrayInput(data[i][0]))
			{
				$('#'+this.attr('id')+' input[type="checkbox"][id="'+decodeURIComponent(data[i][0]).replace('[]', '')+'_'+data[i][1]+'"]').attr('checked', 'checked')
				$('#'+this.attr('id')+' input[type="radio"][id="'+decodeURIComponent(data[i][0]).replace('[]', '')+((data[i][1] == 0)? '' : '_'+data[i][1])+'"]').attr('checked', 'checked')
			} else
			{
				$('#'+this.attr('id')+' input[type="checkbox"][id="'+data[i][0]+((data[i][1] == 0)? '' : '_'+data[i][1])+'"]').attr('checked', 'checked')
				$('#'+this.attr('id')+' input[type="radio"][id="'+data[i][0]+((data[i][1] == 0)? '' : '_'+data[i][1])+'"]').attr('checked', 'checked')
			}
			$('#'+this.attr('id')+' input[type="text"][id='+data[i][0]+']').val(decodeURIComponent(data[i][1].replace('+', ' ')))
			$('#'+this.attr('id')+' textarea[id="'+data[i][0]+'"]').val(decodeURIComponent(data[i][1].replace('+', ' ')))
			$('#'+this.attr('id')+' select[id="'+data[i][0]+'"]').val(data[i][1])
		}
	}
}

jQuery.validator.addMethod("select", function(value, element, param) {
  return this.required(element) || (param && parseInt(value) > 0); },
  "Wybierz jedną możliwość");
jQuery.validator.addMethod("year", function(value, element, param) {
  return this.required(element) || (param && parseInt(value) > 1901 && parseInt(value) <= 2100); },
  "Podaj rok od 1901 do 2100");

var hideInfoBox = function(elem) {
	$(elem).hide("slow");
}

var showInfoBox = function(resp, elem) {
	$(elem).html(resp);
	$(elem).show("slow");
}

/**
 * Takes all matched elements and centers them, absolutely,
 * within the context of their parent element. Great for
 * doing slideshows.
 *   $("div img").center();
 */
$.fn.center = function(f) {
	return this.each(function(){
		if ( !f && this.nodeName == 'IMG' && !this.offsetWidth && !this.offsetHeight ) {
			var self = this;
			setTimeout(function(){
				$(self).center(true);
           	}, 13);
       	} else {
        	var s = this.style;
           	var p = this.parentNode;
           	if ( $.css(p,"position") == 'static' ) {
            	p.style.position = 'relative';
           	}
           	s.position = 'absolute';
           	s.left = (($.css(p,"width") - $.css(this,"width"))/2) + "px";
           	s.top = (($.css(p,"height") - $.css(this,"height"))/2) + "px";
       	}
	});
};

var fixFFModals = function(){
  //Nie można odpalić pod IE6, bo nie będzie się przewijał modal
  var arVersion = navigator.appVersion.split("MSIE")
  var version = parseFloat(arVersion[1])
  if ((version >= 5.5 && version < 7))
    return;
  $('.jqmWindow').each(function(){
    $('body').append($(this).clone());
    $(this).remove();
  });
}

/**
 * Obsługa wyświetlana błędów formularzy
 */
var showErrors = function(errorMap, errors, validator, errorBox) {
  validator.defaultShowErrors();
  visibleErrors = validator.errors();
  validator.toHide.each(function(){errorBox.children(':contains("'+$(this).text()+'")').remove();});
  validator.toShow.each(function(){errorBox.children(':contains("'+$(this).text()+'")').remove();});
  errorBox.append(validator.toShow.clone());
  visibleErrors.hide();
  if(validator.toShow[0])
  {
    var error = validator.toShow[0];
    $(error).before('<input type="text" id="errorFocus" />');
    $('#errorFocus').focus();
    $('#errorFocus').remove();
  }
}

/**
 * Obsługa wyświetlana błędów formularzy
 */
var validatorBlurElement = null;
var showErrorsFocus = function(errorMap, errors, validator) {
  validator.defaultShowErrors();
  if(validator.toShow[0] && validatorBlurElement == null)
  {
    var error = validator.toShow[0];
    $(error).before('<input type="text" id="errorFocus" />');
    $('#errorFocus').focus();
    $('#errorFocus').remove();
  }
}

/* Funkcje do obslugi nawigacji */
var current_navi_link = null
var current_sub_navi = null
navi_hover_in = function(element){
	var navi_box_pattern = new RegExp(/navi_link_([a-z]+)/i)
	var result = navi_box_pattern.exec(element.attr('id'))
	var navi_link_pattern = new RegExp(/navi_link_([a-z]+)_a/i)
	var currresult = navi_link_pattern.exec(current_navi_link)
	if(currresult)
	  var curr_name = currresult[1]
	var sub_navi_pattern = new RegExp(/navi_sub_([a-z]+)/i)
	var currsubnaviresult = navi_link_pattern.exec(current_sub_navi)
	if(currsubnaviresult)
	  var currsubnavi = currsubnaviresult[1]
	if(result)
	{
		var new_name = result[1]
		var current_hover_link = $('.__menuishover')
		var to_hoverout = $('.__menutohoveout')
		if(current_hover_link.length == 1 && to_hoverout.length == 1)
		{
			current_hover_link.addClass('hidden')
			current_hover_link.removeClass('__menuishover')
			to_hoverout.removeClass('hidden __menutohoveout')
		}
		$('#navi_link_'+new_name+'_ia').addClass('hidden __menutohoveout')
		var tmp = $('#navi_link_'+new_name+'_hover')
		tmp.removeClass('hidden')
		tmp.addClass('__menuishover')
		$('#navi_link_'+new_name+'_ia').addClass('__menutohoveout')
		$('#'+current_sub_navi).addClass('hidden')
		current_sub_navi = 'navi_sub_'+new_name
		$('#'+current_sub_navi).removeClass('hidden')
	}
}

/* funkcja wyswietlajaca okno dialogowe z wybrana informacja */
var displayDialogBox = function(title, msg){
	$('.jqm__dialogTitle').text(title);
	$('#dialogMsg').text(msg);
	$('#stdDialogBox').jqmShow();
}

$(window).load(function(){fixPNG()});

var showTooltip = function (tooltip, trigger, id, o){
	wrapper = $('<div></div>');
	wrapper.addClass('toolTipWrapper');
	wrapper.attr('id', 'tooltipwrapper_'+id);
	wrapper.append(tooltip.clone());
	trigger.append(wrapper);
	tooltip.remove();
	if(o.target != null)
	{
		var target = $('#'+o.target);
		wrapper.css('left', target.x()+o.xoffset);
		wrapper.css('top', target.y()+o.yoffset);
	}
	wrapper.children().show();
    wrapper.fadeIn();
};
var hideTooltip = function (id, trigger){
	var wrapper = $('#tooltipwrapper_'+id);
	wrapper.children().hide();
	trigger.after(wrapper.children());
	wrapper.remove();
};

$.fn.tooltip = function(options) {
	var defaults = {
    	target: null,
    	xoffset: 0,
    	yoffset: 0
  	};
  	var opts = $.extend(defaults, options);
  	return this.each(function() {
    	var $this = $(this);
    	var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
    	$this.hover(function(){
    		var element = $(this);
    		var idPattern = new RegExp(/tooltipTrigger_([a-zA-Z0-9]+)/i);
    		var result = idPattern.exec(element.attr('id'));
    		if(!result)
    	  		return false;
    		else
    	  		var id = result[1];
    		var tooltip = $('#toolTip_'+id);
    		showTooltip(tooltip, element, id, o);
    	}, function(){
    		var element = $(this);
    		var idPattern = new RegExp(/tooltipTrigger_([a-zA-Z0-9]+)/i);
    		var result = idPattern.exec(element.attr('id'));
    		if(!result)
    	  		return false;
    		else
    	  		var id = result[1];
    		var tooltip = $('#toolTip_'+id);
    		hideTooltip(id, element);
    	});

    });
};


var fixPNG = function(){
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5 && version < 7) && (document.body.filters))
	{
	   $('img.transparent').each(function(){
	   	  var img = $(this);
	      var imgID = (img.attr('id')) ? "id='" + img.attr('id') + "' " : "";
	      var strNewHTML = $('<span></span>');
	      strNewHTML.attr('id', imgID);
	      strNewHTML.addClass(img.attr('class'));
	      strNewHTML.attr('title', img.attr('alt'));
	      if (img.css('align') == 'left') strNewHTML.css('float', 'left');
	      if (img.css('align') == "right") strNewHTML.css('float', 'right');
	      if (img.parent('a').attr('href')) strNewHTML.css('cursor', 'pointer');
	      strNewHTML.css('display', 'block');
	      strNewHTML.css('line-height', img.css('height'));
	      strNewHTML.css('height', img.css('height'));
	      strNewHTML.css('width', img.css('width'));
	      strNewHTML.attr('style', img.attr('style') + strNewHTML.attr('style') + ';filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+img.attr('src')+'",sizingMethod="scale");');
	      img.after(strNewHTML);
	      img.remove();
	      
	      strNewHTML.removeClass('transparent');
	   })
	}
}

    var filename_on='vote_icon_on_v2.gif';
	var filename_off='vote_icon_off_v2.gif';


	function resetRate(element){
		var path;
        var oldsrc=$(element).attr("src");

        var src="";
        var catalog="";
        var i;
        path=oldsrc.split("/");
        for(i=0;i<path.length-1;i++){
            catalog=catalog+path[i]+"/";
        }

		var id = $(element).attr('id');
		var idString = id.substr(0,id.length-2);
		var number=$('#'+idString).val();
		for(i=1;i<=6;i++){
			if(i<=number){
				src=catalog+filename_on;
			}
			else{
				src=catalog+filename_off;

			}
			$('#'+idString+'_'+i).attr('src',src);
			if(number!=0){
				$('#'+idString+'_text').text(number+' - '+ratesArray[number]);
			}
			else{
				$('#'+idString+'_text').text('\u00A0');
	}
		}
	}

	function toggleRate(element,permanent){
		var path;
        var oldsrc=$(element).attr("src");

        var src="";
        var catalog="";
        var i;
        path=oldsrc.split("/");
        for(i=0;i<path.length-1;i++){
            catalog=catalog+path[i]+"/";
        }

		var id = $(element).attr('id');
		var number = id.substr(id.length-1,1);
		var idString = id.substr(0,id.length-2);
		for(i=1;i<=6;i++){
			if(i<=number){
				src=catalog+filename_on;
			}
			else{
				src=catalog+filename_off;
			}
			$('#'+idString+'_'+i).attr('src',src);
			if(number!=0){
				$('#'+idString+'_text').text(number+' - '+ratesArray[number]);
			}
			else{
				$('#'+idString+'_text').text('\u00A0');
			}
			if(permanent==true){
				$('#'+idString+'_'+i).removeClass("vote_active");
				$('#'+idString).val(number);
			}
		}
	}

var popoverLoaderShow = function(loaderID){
  $('#'+loaderID).jqm({modal:true});
  $('#'+loaderID).jqmShow();
};
var popoverLoaderHide = function(loaderID){
  $('#'+loaderID).jqmHide();
};

$.fn.helpCloud = function(options){
	var defaults = {
		id: null
	};
	var opts = $.extend(defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		$this.bind('click', {id: o.id}, function(e){
			$cloud = $('#helpCloud_'+e.data.id);
			if($cloud.is(':visible'))
			{
				$cloud.hide(0);
				$cloud.find('img.__hcClose').unbind('click');
				return;
			}
			$cloud.find('img.__hcClose').click(function(){
				$cloud.hide(0);
				$cloud.find('img.__hcClose').unbind('click');
			});
			pageWidth = $(document).width();
			cloudHeight = $cloud.height();
			cloudWidth = $cloud.width();
			triggerPosition = $('#hcTrigger_'+e.data.id).offset();
			triggerWidth = $('#hcTrigger_'+e.data.id).width();
			if(triggerPosition.left + cloudWidth > pageWidth)
				$cloud.css({top: triggerPosition.top-cloudHeight - 10, left: triggerPosition.left - cloudWidth + triggerWidth});
			else
				$cloud.css({top: triggerPosition.top-cloudHeight - 10, left: triggerPosition.left});
			$cloud.show(0);
		});
	});
};

$(document).ready(function() {
	current_navi_link = $('a.__navi_img_a').attr('id')
	current_sub_navi = $('.__navi_sub:visible').attr('id')
	$('td.__navi_link').mouseover(function(){navi_hover_in($(this))})
	fixFFModals();
	$('.jqmWindowWide').hide();
	
	$('.__tooltipTrigger').tooltip();
	$('.__hcTrigger').helpCloud();
});