/**
 * 
 * @author LineLab Studio <http://www.linelab.pl> 
 * @version 1.0 
 */

// Klakulator funkcja obslugujaca zmiane formatu za pomoca formatek
function setSize(el) { 
	var rel = $(el).attr('rel');var sizes=rel.split('x');
	$('input.setWidth').val(sizes[0]);$('input.setHeight').val(sizes[1]);calcChange($('input.setWidth')); calcChange($('input.setHeight'));
}

/**
 * 
 * 
 * @param {Object} val
 * @param {Object} precise
 */
function myNumber(val,precise) {
	
	var mnoznik = 1;
	if(precise == undefined) {
		precise = 0;
	} else {
		mnoznik = Math.pow(10, precise);
	}	
	
	if(val != undefined) {
		if(isNaN(val)) {
			val = val.replace( new RegExp( "([a-zA-Z]|$|&|@|#| )?", "gi" ),'');
			if(val == "") {
				val = 0;
			} else {
				val = parseFloat( val.replace(',','.') );
			} 
		}
	} else {
		val = 0;
	}
	val = Math.round( val*mnoznik)/mnoznik;
	if(val.toFixed) val = val.toFixed(precise); 
	return val;
}

$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

var pw = {};
pw.autohower = function () { // Dla request ajax
	$('.ui-state-hover:not(.pw-helper-hover-disable)').hover(
	    function(){			
			$(this).addClass("ui-state-hover");
		},
	    function(){$(this).removeClass("ui-state-hover");}
	).removeClass("ui-state-hover");	
}
pw.autohover = pw.autohower;

pw.go = function(url) {
	window.location = url;
}

$(function(){ 
	pw.autohower();
	$('img.preload').pwPreloader({
 		imageIsload: function() {  },
 		imageOnload: function() { $(this).fadeIn('slow') }
 	});	
});

(function ($) {
/**
 * Zwraca kod elementu html wskazanego przez selektor
 * 
 * @return {String}
 */
$.fn.pwGetCodeElement = function(getInner){
	if(!getInner) {
		getInner = false;
	}
    var $nodes = jQuery("<div></div>");
    this.each(function() {
            $nodes.append(this.cloneNode(getInner));
    });
    return $nodes.html();
}; // $.fn.pwGetCodeElement elementHTML

/**
 * Centruje element wewnatrz bloku.
 * 
 * Dla elementow img centorwnie nastepuje po wczytaniu grafiki.
 */
$.fn.vAlign = function() {	// $.fn.vAlign = function(img)
	
	$.fn.vAlign.vcenter = function(o) {
		var ah = $(o).height();
		var ph = $(o).parent().height();
		var mh = (ph - ah) / 2;
		$(o).css('margin-top', mh);
	}
	
	$.fn.vAlign.checkLoad = function(img) {
		if (img.complete == true) {
			$.fn.vAlign.vcenter(img);
		} else {
			if(img.c < 10) {
				img.c++;	
				$.fn.vAlign.checkLoad(img);
			}
		}	
	}
	
	return this.each(function(){
		if($(this).attr('src')) 
		{
			if(this.complete == true) {
				$.fn.vAlign.vcenter(this);
			} else {
				this.c = 0;
				$.fn.vAlign.checkLoad(this);
			}
		} else {
			$.fn.vAlign.vcenter(this);
		}
		return this;
	});
}; // End $.fn.vAlign

/**
 * Ustawia przezroczystosc elementu
 * 
 * @param {Object} amount Prog przezroczystosci
 */
$.fn.opacity = function(amount) {
        if (amount > 1) amount = 1;
        if (amount < 0) amount = 0;
        if ($.browser.msie) {
                amount = (parseFloat(amount) * 100);
                this.css('filter', 'alpha(opacity='+amount+')');
        } else {
                this.css('opacity', amount);
                this.css('-moz-opacity', amount);
        }
        return this;
} // End $.fn.opacity

/**
 * Porownuje adresy (trasy ZF)
 * 
 * W zaleznosci od podanych opcji adresy moga byc porownywane w sposob:
 * skipParam: [] pomija wszystkie paramety podane w tablicy
 * onlyParam: [] porownuje tylko parametry podane w tablicy
 * sortUrl: true dodatkow przeksztalca adres w tablic sotujac wyniki 
 * 
 * @param {String} a First Url
 * @param {String} b Second Urle
 * @param {Object} myCfn Options
 * @return bool
 */	
$.pwCompareUrlZF = function (a,b,myCfn) {
	this.o = {
		skipParam: [],
		onlyParam: [],
		sortUrl: true
	}	
	this.cfn = $.extend({}, this.o, myCfn);

	if(this.cfn.onlyParam.length > 0) {
		for (var i = 0; i < this.cfn.onlyParam.length; i++) {
			var pn = this.cfn.onlyParam[i]; 
			var re = new RegExp('(/{1}'+pn+'/{1}[^/]*[^/])|$');
			var ma = re.exec(a);
			var mb = re.exec(b);
			if (ma[1] != mb[1]) {
				return false;
			}	
		}
		return true;	
	} // if this.cfn.onlyParam.length
	
	if( this.cfn.skipParam.length > 0) {
		for (var i = 0; i < this.cfn.skipParam.length; i++) {
			var pn = this.cfn.skipParam[i]; 
			var re = new RegExp('(/{1}'+pn+'/{1}[^/]*[^/])|$');
			var ma = re.exec(a);
			var mb = re.exec(b);
			a = a.replace(ma[1],"");
			b = b.replace(mb[1],"");
		}
	}
	
	if(a == b) return true;
	if(this.cfn.sortUrl == true)
	{
		a = a.split("/").sort().toString();
		b = b.split("/").sort().toString();
		if(a == b) return true;
	}
		return false;	
	
} // End $fn.pwCompareUrlZF


	
/**
 * Sprawda czy dany link jest zgodny z biezacym adresem url.
 * 
 * Jezeli wykryto zgodnosc dodaje dodaje do linku klasie stylu opisana w parametrze
 * konfiguracyjnym cssClass
 * 
 * Opcje:
 * cssClass: {String} nazwa klasy dodawana jezeli wykryto zgodnosc,
 * evalFx: {Object}|{null} Funkcja ktora moze zostac wykonana na linku w przpadku zgodnosci, 
 * skipParam: [] parametry pomijane podczas porownywania,
 * onlyParam: [] Porownywanie tylko wzgledem parametrow wskazanych w tablicy
 * sortUrl: true Porownanie poprzez sorotowanie nazw w adresie
 * 
 * @param {Object} myCfn
 */	
$.fn.pwActiveLinkZF = function( myCfn )
{
	jQuery.fn.pwActiveLinkZF.o = {
		cssClass: 'active',
		evalFx: null, // function (hash) { alert( $(hash).attr('href') ); } 
		location: null,
		skipParam: [],
		onlyParam: [],
		sortUrl: true
	}
	
	return this.each( function () {
		
		this.cfn = $.extend({}, jQuery.fn.pwActiveLinkZF.o, myCfn);

		var href = this.getAttribute('href',2);
		if(this.cfn.location != null){
			var location = this.cfn.location; 
		} else {
			var location = new String( window.location.pathname );
		}
		
		if ( $.pwCompareUrlZF (location, href, this.cfn )) {
			if( this.cfn.cssClass ) {
            	$(this).addClass( this.cfn.cssClass );
			}
			if(this.cfn.evalFx != null) {
				this.cfn.evalFx(this);
			}			
        }
		return this;
	});
}; // $.fn.pwActiveLinkZF

/**
 * Wypelnia wzgledem obiektu nadrzednego 
 * 
 * @param {Object} o
 */
$.fn.fillSpace = function (corect) {
	
	var dcfn = {
		minus: 0
	}

	return this.each(function(){
		if(corect == undefined) corect = 0;
		var my = $(this);
		var parent = $(this).parent(); 
		var ph  = parent.height();
		// var ppt = parent.css('padding-top');
		// var ppb = parent.css('padding-bottom');
		var minusH = 0;
		
		parent.children().each( function() {
			var t = $(this)
			if(!t.is('script') && !t.is('style')) {
				if(t.attr('id') != my.attr('id') || t.attr('class') != my.attr('class')) {
					minusH = minusH + t.height() 
							 + parseInt(t.css('padding-top')) 
							 + parseInt(t.css('padding-bottom')) 
							 + parseInt(t.css('margin-top')) 
							 + parseInt(t.css('margin-bottom'))
							 + parseInt(t.css('borderTopWidth'))
							 + parseInt(t.css('borderBottomWidth'));
				}
			} 
			t = null;	
		});
		var mh = parseInt(ph) - minusH - parseInt(corect);
		$(this).css('height',mh);
		return this;
	});	
};

/**
 * Preloader obrazków.
 * Image preloader.	
 * 
 * @author Paweł Wolański <pawella.code@2rze.com>
 * @license 
 * @param {Object} options
 *
 * 
 * Ładuje w tle grafikę, zastępując ją na okres ładowania blokiem div, po wczytaniu grafiki warstwa
 * zostaje usunięta a w jej miejsce ponownie wsawiony element img.
 * 
 * Opis parametrów
 * param =
 * {
 * 		preloaderClass: 'pwPreloader',	// nazwa klasy preloader
 * 		loaderOnload: function(){},    	// metoda wykonywana na warstwie preloader w momęcie jego utworzenia
 *  	loaderUnload: function(){},		// akcja zamykająca preloader, gdzie [this] to preloader a [image] instancja elementu img
 *  	imageIsload: function(){},		// funkacja która może być wywołana na zdjęciu kiedy zdjęcie nie było pobierane ponownie (zostało wczytane z cache)	
 *  	imageOnload: function(){}		// metoda która zostanie wywołana na zdjęciu po jego wczytaniu.		
 * }
 *  	 
 * 
 * $(document).ready(function() {
 * 	$('img.preload').pwPreloader({
 * 		imageIsload: function() { $(this).vAlign(); },
 * 		imageOnload: function() { $(this).fadeIn('slow').vAlign(); }
 * 	});
 * });
 * 
 */
$.fn.pwPreloader = function(options) {
	
	if(!options) options = {}
	
	var pwPreloaderDefaults = {
		preloaderClass: 'pwPreloader',
		loaderOnload: function () { /*$(this).vAlign();*/ },	
		loaderUnload: function (image) { $(this).fadeOut('fast', function() { $(this).remove(); image.cfn.imageIsload.call(image); image.cfn.imageOnload.call(image) } ); },
		imageIsload: function() { $(this).vAlign(); },		
		imageOnload: function() { $(this).vAlign().fadeIn('fast'); }		
	}
		
		return this.each(function(){
			
			this.cfn = $.extend({}, pwPreloaderDefaults, options);
			if(!this.cfn.imageIsload) this.cfn.imageIsload = function() {}
			if(!this.cfn.imageOnload) this.cfn.imageOnload = function() {}			
			
			this.hack = null;
			
			if($(this).attr('src')) {
				
				this.loadImage = new Image();
				this.loadImage.src = $(this).attr('src');
				
				 if(this.loadImage.complete == false) 
				 // if(this.complete == false)
				 {
					
					$(this).wrap('<div class="'+ this.cfn.preloaderClass +'"></div>');					
					$(this).hide();
					this.hack = $(this).parent();
				
					if(  this.hack.height() == 0  && $(this).height() > 0 ) {
						this.hack.height( $(this).height() );
					}
				
					if(this.cfn.loaderOnload) this.cfn.loaderOnload.call(this.hack);
	
					this.loadImage.o = this;
				
					$(this.loadImage).load( function() 
					{
						this.image = $(this.o).clone().appendTo(this.o.hack.parent());
						this.image.cfn = this.o.cfn; 
						// alert($(this.image).attr('class'));
						this.o.cfn.loaderUnload.call( this.o.hack , this.image);
					});
				} else {
					this.cfn.imageIsload.call(this);
				}
			}
		});	
		
};

/**
 * Dekoruje formularz
 */
$.fn.pwFormDecorators = function(options) {
	
	if(!options) options = {}
	
	var def = {
		hideErrors: true,
		bt : {
			 trigger: ['focus', 'blur'],
			 positions: ['right']
		}
	}; 
	
	return this.each(function(){
		
		this.mycfn = $.extend({}, def, options);
		var cfn = this.mycfn; 
		$('.element', this).each( function() {
			var i = $(this).attr('id').replace('zf_','');
			var e = $(this).find('ul.errors');
			if(e.attr('class')) {
				$('#'+i).bt( e.pwGetCodeElement(true), cfn.bt );
				if(cfn.hideErrors) {
					e.hide();			
				}
			}	
		});
	});	
	
}


})(jQuery);
