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



/**
 * 
 * 
 * @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;
}

// initialize common scripts
$(function(){ 
	pw.autohower();
	$('img.preload').pwPreloader({
 		imageIsload: function() {  },
 		imageOnload: function() { $(this).fadeIn('slow') }
 	});	
 	$('div.fillspace').fillSpace();
});



(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


/**
 * 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;
		if(my.css('float') != 'left' && my.css('float') != 'right') {
			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(my.css('padding-bottom')) + parseInt(my.css('padding-top'))) 
			- ( parseInt(my.css('margin-bottom')) + parseInt(my.css('margin-top'))) 
			- parseInt(corect);
		// alert(parent.attr('id')+' '+ph+' ustawiam '+mh+' zmiejszenie'+minusH);
		$(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);

/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_r(x, max, sep, l) {

	l = l || 0;
	max = max || 10;
	sep = sep || ' ';

	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}

	var
		i,
		r = '',
		t = typeof x,
		tab = '';

	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {

		l++;

		for (i = 0; i < l; i++) {
			tab += sep;
		}

		if (x && x.length) {
			t = 'array';
		}

		r += '(' + t + ") :\n";

		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}

	} else {

		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}

		r += '(' + t + ') ' + x + "\n";

	}

	return r;

};
var_dump = print_r;
