/**
 * Systemu Imperial CMS - API
 * @version		2.5
 * @author		Łukasz Sokół <lukasz@imperialcms.pl>
 */
(function($){
	$.Imperial = {
		options:{
			id_domain:null,//Id Domeny
			s_lang:'pl',//Język domeny
			isAdmin:false,//Czy wywołanie z admina
			anchor:null,//kotwica w adresie pzreglądarki
			fileManagerInitUrl:'/filemanager/?r=%s&type=tinymce'//url do inicjalizacji filemanagera
		},

		//Init
		init:function(options){
			//złączenie opcji
			this.options = $.extend(this.options, options);

			//wczytanie pliku z langami
			var langFile = ((this.options.isAdmin)?'admin_':'')+this.options.s_lang+'.js';
			this.Func.include('/lang/'+langFile);

			//init lightboxa
			this.initLightbox();

			//init tooltip
			this.initTooltip();

			//ustawienie anchora
			if(window.location.href != '')
			{
				var addr = window.location.href;
				var found = addr.match(/\#(.*?)$/g);
				
				if(found != null)
				{
					this.options.anchor = found[0];
				}
			}

			if(this.options.isAdmin)//dla admina
			{
				
				//odpalenie menu górnego
				$('ul.sf-menu').superfish();

				this.setAdminActions();
			}
			else// dla aplikacji klienta
			{
				this.checkParentWindow();
			}
		},

		//ustawienie akcji admina
		setAdminActions:function(){
			var actLocation = window.location.href;
			actLocation = actLocation.replace(/sa_lang=(.*?)$/,'');
			actLocation = actLocation.replace(/s_lang=(.*?)$/,'');
			
			var pat = /\?/;
			preque = (pat.test(actLocation))?'&':'?';

			//zmiana języka administracji
			$("#languages").change(function(){
				window.location.href = actLocation+preque+'sa_lang='+$(this).val();
			});
			//zmiana języka zarządzania
			$("#portalLang").change(function(){
				window.location.href = actLocation+preque+'s_lang='+$(this).val();
			});
		},

		//inicjalizacja lightboxa
		initLightbox:function(){
			//wczytanie biblioteki lightbox jeśli nie istnieje
			if(typeof($.fn.lightbox) == 'undefined')this.Func.include('/lib/CONTROLLER/JS/jq.lightbox.js');
			
			$('a[rel=lightbox],a[class*=lightbox]').lightbox({
				'fileLoadingImage': 'gfx/lightbox/lightbox-ico-loading.gif',
				'fileBottomNavCloseImage': 'gfx/lightbox/lightbox-btn-close.gif',
				strings:{
					help: '',
					prevLinkTitle: '',
					nextLinkTitle: '',
					prevLinkText:  '&laquo;&laquo;',
					nextLinkText:  '&raquo;&raquo;',
					closeTitle: '',
					image: '',
					of: ' '+lang.from+' '
				}
			});
		},

		//Inicjalizacja tooltipa
		initTooltip:function(){
			//wczytanie biblioteki tooltipa jeśli nie istnieje
			if(typeof($.fn.tooltip) == 'undefined')this.Func.include('/lib/CONTROLLER/JS/jq.tooltip.js');

			$('.IMP_Tip').tooltip({
				track: true,
				delay: 500,
				showURL: false,
				showBody: false,
				bodyHandler: function(){
					var handler = $('#IMP_Tip_C_'+$(this).attr('id'));
					if(handler.length > 0)
					{
						return handler.html();
					}
					else
					{
						return lang.noTooltipContent;
					}
				}
			});
		},
		
		//sprawdzenie okna parenta
		checkParentWindow:function(){
			if(parent.window.location.href.search("/_admin.php") != '-1')
			{
				parent.window.location.href = '/';
			}
		},

		//Inicjalizacja filemenagera dla tinyMCE
		FileMenagerTinyMceInit:function(field_name, url, type, win){

			switch(type)
			{
				case 'media':
					type = win.document.getElementById('media_type').value;
			}
			
			tinyMCE.activeEditor.windowManager.open({
				url: $.Imperial.Func.sprintf($.Imperial.options.fileManagerInitUrl, field_name),
				width: 875,
				height: 513,
				inline: 'no',
				close_previous: 'no'
			}, {
				parentWindow: win,
				viewMode:type
			});
		},

		//Funkcje Imperial
		Func:{

			prepareLink:function(value, lang)
			{
				var toChange = new Array();
				var change = new Array();
				
				switch(lang)
				{
					case 'pl':
						toChange = ["ą","Ą","ć","Ć","ę","Ę","ń","Ń","ś","Ś","ó","Ó","ł","Ł","ż","Ż","ź","Ź"];
						change =   ["a","a","c","c","e","e","n","n","s","s","o","o","l","l","z","z","z","z"];
					break;
				}

				for(i=0;i<toChange.length;i++)
				{
					regex = new RegExp(toChange[i],'g');
					value = value.replace(regex, change[i]);
				}

				value = value.toLowerCase().replace(/[\s]/g,'-').replace(/[^a-z0-9-_]/g,'').replace(/[-]{1,}/g,'-').replace(/[_]{1,}/g,'_');

				return value;
			},

			include:function(url){
				$('body').append('<script type="text/javascript" src="'+url+'"></script>');
			},

			sprintf:function()
			{
				// Return a formatted string
				//
				// version: 909.322
				// discuss at: http://phpjs.org/functions/sprintf
				// +   original by: Ash Searle (http://hexmen.com/blog/)
				// + namespaced by: Michael White (http://getsprink.com)
				// +    tweaked by: Jack
				// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
				// +      input by: Paulo Ricardo F. Santos
				// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
				// +      input by: Brett Zamir (http://brett-zamir.me)
				// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
				// *     example 1: sprintf("%01.2f", 123.1);
				// *     returns 1: 123.10
				// *     example 2: sprintf("[%10s]", 'monkey');
				// *     returns 2: '[    monkey]'
				// *     example 3: sprintf("[%'#10s]", 'monkey');
				// *     returns 3: '[####monkey]'
				var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
				var a = arguments, i = 0, format = a[i++];

				// pad()
				var pad = function (str, len, chr, leftJustify) {
					if (!chr) {chr = ' ';}
					var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
					return leftJustify ? str + padding : padding + str;
				};

				// justify()
				var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
					var diff = minWidth - value.length;
					if (diff > 0) {
						if (leftJustify || !zeroPad) {
							value = pad(value, minWidth, customPadChar, leftJustify);
						} else {
							value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
						}
					}
					return value;
				};

				// formatBaseX()
				var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
					// Note: casts negative numbers to positive ones
					var number = value >>> 0;
					prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
					value = prefix + pad(number.toString(base), precision || 0, '0', false);
					return justify(value, prefix, leftJustify, minWidth, zeroPad);
				};

				// formatString()
				var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
					if (precision != null) {
						value = value.slice(0, precision);
					}
					return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
				};

				// doFormat()
				var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
					var number;
					var prefix;
					var method;
					var textTransform;
					var value;

					if (substring == '%%') {return '%';}

					// parse flags
					var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
					var flagsl = flags.length;
					for (var j = 0; flags && j < flagsl; j++) {
						switch (flags.charAt(j)) {
							case ' ': positivePrefix = ' '; break;
							case '+': positivePrefix = '+'; break;
							case '-': leftJustify = true; break;
							case "'": customPadChar = flags.charAt(j+1); break;
							case '0': zeroPad = true; break;
							case '#': prefixBaseX = true; break;
						}
					}

					// parameters may be null, undefined, empty-string or real valued
					// we want to ignore null, undefined and empty-string values
					if (!minWidth) {
						minWidth = 0;
					} else if (minWidth == '*') {
						minWidth = +a[i++];
					} else if (minWidth.charAt(0) == '*') {
						minWidth = +a[minWidth.slice(1, -1)];
					} else {
						minWidth = +minWidth;
					}

					// Note: undocumented perl feature:
					if (minWidth < 0) {
						minWidth = -minWidth;
						leftJustify = true;
					}

					if (!isFinite(minWidth)) {
						throw new Error('sprintf: (minimum-)width must be finite');
					}

					if (!precision) {
						precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
					} else if (precision == '*') {
						precision = +a[i++];
					} else if (precision.charAt(0) == '*') {
						precision = +a[precision.slice(1, -1)];
					} else {
						precision = +precision;
					}

					// grab value using valueIndex if required?
					value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

					switch (type) {
						case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
						case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
						case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
						case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
						case 'i':
						case 'd':
							number = parseInt(+value, 10);
							prefix = number < 0 ? '-' : positivePrefix;
							value = prefix + pad(String(Math.abs(number)), precision, '0', false);
							return justify(value, prefix, leftJustify, minWidth, zeroPad);
						case 'e':
						case 'E':
						case 'f':
						case 'F':
						case 'g':
						case 'G':
							number = +value;
							prefix = number < 0 ? '-' : positivePrefix;
							method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
							textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
							value = prefix + Math.abs(number)[method](precision);
							return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
						default: return substring;
					}
				};

				return format.replace(regex, doFormat);
			},

			//validacja adresu email
			emailValidator:function(email)
			{
				var reg = /^[^\W][a-zA-Z0-9\_\-\.]+([a-zA-Z0-9\_\-\.]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/;
				if(email.match(reg))
				{
					return true;
				}
				else
				{
					return false;
				}
			},

			//przeładowanie strony
			reload:function()
			{
				window.location.href = window.location.href;
			},

			//przekierowanie na zadanego urla
			redirect:function(url)
			{
				window.location.href = url;
			},

			//formatownie końcówki ceny
			CurrencyFormatted:function(amount)
			{
				var i = parseFloat(amount);
				if(isNaN(i)) { i = 0.00; }
				var minus = '';
				if(i < 0) { minus = '-'; }
				i = Math.abs(i);
				i = parseInt((i + .005) * 100);
				i = i / 100;
				s = new String(i);
				if(s.indexOf('.') < 0) { s += '.00'; }
				if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
				s = minus + s;
				return s;
			},

			//formatowanie ceny dodanie przecinków przecinków
			CommaFormatted:function(amount)
			{
				var delimiter = ",";
				var a = amount.split('.',2)
				var d = a[1];
				var i = parseInt(a[0]);
				if(isNaN(i)) { return ''; }
				var minus = '';
				if(i < 0) { minus = '-'; }
				i = Math.abs(i);
				var n = new String(i);
				var a = [];
				while(n.length > 3)
				{
					var nn = n.substr(n.length-3);
					a.unshift(nn);
					n = n.substr(0,n.length-3);
				}
				if(n.length > 0) { a.unshift(n); }
				n = a.join(delimiter);
				if(d.length < 1) { amount = n; }
				else { amount = n + '.' + d; }
				amount = minus + amount;
				return amount;
			}
		},//FUNC END

		//BOX START
		mBox:{
			//alert informacyjny/warning/error/info
			alert:function(title, alertText, type , callbackFun, width, closeFun, buttons)
			{
				if(typeof(callbackFun) == 'undefined' || callbackFun == null)
				{
					callbackFun = function(){
						$(this).dialog('close');
					}
				}

				if(typeof(closeFun) == 'undefined' || closeFun == null)
				{
					closeFun = function(){}
				}

				if(typeof(width) == 'undefined' || width == null)
				{
					width = 350;
				}

				if(typeof(type) == 'undefined')
				{
					type = 'warning';
				}

				if(typeof(buttons) == 'undefined' || buttons == null)
				{
					buttons = {
						' OK ': callbackFun
					};
				}

				switch(type)
				{
					case 'error':
						var spanIco = '<span class="ui-icon ui-icon-circle-close" style="margin: 0pt 7px 20px 0pt; float: left;"/>';
						break;
					case 'no-ico':
						var spanIco = '';
						break;
					case 'ok':
						var spanIco = '<span class="ui-icon ui-icon-circle-check" style="margin: 0pt 7px 50px 0pt; float: left;"/>';
						break;
					case 'info':
						var spanIco = '<span class="ui-icon ui-icon-info" style="margin: 0pt 7px 50px 0pt; float: left;"/>';
						break;
					default:
						var spanIco = '<span class="ui-icon ui-icon-alert" style="margin: 0pt 7px 20px 0pt; float: left;"/>';
				}

				$('<div>'+spanIco+alertText+'</div>').dialog({
					title:title,
					bgiframe: true,
					resizable: true,
					modal: true,
					width:width,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					buttons:buttons,
					close: closeFun
				});
			},

			//pytanie
			question:function(title, question, answers, width)
			{
				if(typeof(answers) == 'undefined')
				{
					answers = {};
				}

				if(typeof(width) == 'undefined')
				{
					width = 350;
				}

				var spanIco = '<span class="ui-icon ui-icon-help" style="margin: 0pt 7px 20px 0pt; float: left;"/>';

				$('<div>'+spanIco+question+'</div>').dialog({
					title:title,
					bgiframe: true,
					resizable: true,
					modal: true,
					width:width,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					buttons:answers
				});
			},

			//loading box
			loading:function(titleWindow, text, loadingIco)
			{
				if(typeof(loadingIco) == 'undefined')
				{
					loadingIco = 'gfx/loading.gif';
				}

				$.ui.dialog.overlay.create({options:{
						//tutaj opcje owerlaya - z dialog można dodawać
				}}).bgiframe();

				$('<div class="ISL_BOX"><div class="ISL_TITLE">'+titleWindow+'</div><div class="ISL_CONTENT"><img src="'+loadingIco+'" alt="loading" /><br/>'+text+'</div></div>').appendTo('body');

				$('.ISL_BOX').css({
					top:(parseInt($(window).height()/2)-parseInt($('.ISL_BOX').height()/2)-(parseInt($('.ISL_BOX').css('padding-top'))))+'px',
					left:(parseInt($(window).width()/2)-(parseInt($('.ISL_BOX').width()/2))-(parseInt($('.ISL_BOX').css('padding-left'))))+'px'
				});
			},

			//usuniecie boxa
			hide:function()
			{
				$('.ISL_BOX').fadeOut(function(){$(this).remove();});
				$.ui.dialog.overlay.destroy($('.ui-widget-overlay'));
			}


		}//BOX END
	};
})(jQuery);

function reload()
{
	window.location.href = window.location.href;
}
function emailValidator(email)
{
	var reg = /^[^\W][a-zA-Z0-9\_\-\.]+([a-zA-Z0-9\_\-\.]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/;
	if(email.match(reg))
	{
		return true;
	}
	else
	{
		return false;
	}
}
function sprintf ( ) {
    // Return a formatted string
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/sprintf
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'
    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];

    // pad()
    var pad = function (str, len, chr, leftJustify) {
        if (!chr) {chr = ' ';}
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };

    // justify()
    var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };

    // formatBaseX()
    var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };

    // formatString()
    var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };

    // doFormat()
    var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
        var number;
        var prefix;
        var method;
        var textTransform;
        var value;

        if (substring == '%%') {return '%';}

        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) {
            switch (flags.charAt(j)) {
                case ' ': positivePrefix = ' '; break;
                case '+': positivePrefix = '+'; break;
                case '-': leftJustify = true; break;
                case "'": customPadChar = flags.charAt(j+1); break;
                case '0': zeroPad = true; break;
                case '#': prefixBaseX = true; break;
            }
        }

        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }

        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }

        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }

        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }

        // grab value using valueIndex if required?
        value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd':
                number = parseInt(+value, 10);
                prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                number = +value;
                prefix = number < 0 ? '-' : positivePrefix;
                method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            default: return substring;
        }
    };

    return format.replace(regex, doFormat);
}
function mBoxAlert(title, alertText, type , callbackFun, width, closeFun, buttons)
{
	if(typeof(callbackFun) == 'undefined' || callbackFun == null)
	{
		callbackFun = function(){
			$(this).dialog('close');
		}
	}

	if(typeof(closeFun) == 'undefined' || closeFun == null)
	{
		closeFun = function(){}
	}

	if(typeof(width) == 'undefined' || width == null)
	{
		width = 350;
	}

	if(typeof(type) == 'undefined')
	{
		type = 'warning';
	}

	if(typeof(buttons) == 'undefined' || buttons == null)
	{
		buttons = {
			' OK ': callbackFun
		};
	}

	switch(type)
	{
		case 'error':
			var spanIco = '<span class="ui-icon ui-icon-circle-close" style="margin: 0pt 7px 20px 0pt; float: left;"/>';
			break;
		case 'no-ico':
			var spanIco = '';
			break;
		case 'ok':
			var spanIco = '<span class="ui-icon ui-icon-circle-check" style="margin: 0pt 7px 50px 0pt; float: left;"/>';
			break;
		case 'info':
			var spanIco = '<span class="ui-icon ui-icon-info" style="margin: 0pt 7px 50px 0pt; float: left;"/>';
			break;
		default:
			var spanIco = '<span class="ui-icon ui-icon-alert" style="margin: 0pt 7px 20px 0pt; float: left;"/>';
	}

	$('<div>'+spanIco+alertText+'</div>').dialog({
		title:title,
		bgiframe: true,
		resizable: true,
		modal: true,
		width:width,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons:buttons,
		close: closeFun
	});
}
function mBoxQuestion(title, question, answers, width)
{
	if(typeof(answers) == 'undefined')
	{
		answers = {};
	}

	if(typeof(width) == 'undefined')
	{
		width = 350;
	}

	var spanIco = '<span class="ui-icon ui-icon-help" style="margin: 0pt 7px 20px 0pt; float: left;"/>';

	$('<div>'+spanIco+question+'</div>').dialog({
		title:title,
		bgiframe: true,
		resizable: true,
		modal: true,
		width:width,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons:answers
	});
}
function mBoxShowLoading(titleWindow, text, loadingIco)
{
	if(typeof(loadingIco) == 'undefined')
	{
		loadingIco = 'gfx/loading.gif';
	}

	$.ui.dialog.overlay.create({options:{
		bgiframe: true
			//tutaj opcje owerlaya - z dialog można dodawać
	}});

	$('<div class="ISL_BOX"><div class="ISL_TITLE">'+titleWindow+'</div><div class="ISL_CONTENT"><img src="'+loadingIco+'" alt="loading" /><br/>'+text+'</div></div>').appendTo('body');

	$('.ISL_BOX').css({
		top:(parseInt($(window).height()/2)-parseInt($('.ISL_BOX').height()/2)-(parseInt($('.ISL_BOX').css('padding-top'))))+'px',
		left:(parseInt($(window).width()/2)-(parseInt($('.ISL_BOX').width()/2))-(parseInt($('.ISL_BOX').css('padding-left'))))+'px'
	});
}
function mBoxHide()
{
	$('.ISL_BOX').fadeOut(function(){$(this).remove();});
	$.ui.dialog.overlay.destroy($('.ui-widget-overlay'));
}
function redirect(url)
{
	window.location.href = url;
}
function showDatePicker(fieldId)
{
	$("#"+fieldId).datepicker("show");
}

function setCookie(name,value,expires,path,domain,secure)
{
	var today = new Date();
	today.setTime( today.getTime() );

      if(expires)
      {
		expires = expires * 1000 * 60 * 60 * 24;
      }
      var expires_date = new Date( today.getTime() + (expires) );

      document.cookie = name + "=" +escape(value) +
      ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
      ( ( path ) ? ";path=" + path : "" ) +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ( ( secure ) ? ";secure" : "" );
}

function getCookie(check_name) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


// this deletes the cookie when called
function deleteCookie(name,path,domain)
{
      if(getCookie(name)) document.cookie = name + "=" +
      ( ( path ) ? ";path=" + path : "") +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//new not used
/*
 * wywołanie tylko w document.ready()
 */
function impThickbox(content, showExit, ajaxUrl, ajaxOptions, ajaxLoadingText)
{
	$.ui.dialog.overlay.create({options:{
		//tutaj opcje owerlaya - z dialog można dodawać
	}}).bgiframe();

	if(typeof(showExit) == 'undefined')
	{
		showExit = true;
	}

	var exitBtn = '';

	if(showExit)
	{
		exitBtn = '<a href="javascript:void(0);" class="IT_BOX_EXIT">x</a>';
		$('.IT_BOX_EXIT').unbind('click').click(function(){
			$('.IT_BOX').fadeOut(function(){$(this).remove();});
			$.ui.dialog.overlay.destroy($('.ui-widget-overlay'));
		});
	}

	if(typeof(ajaxUrl) != 'undefined')
	{
		if(typeof(ajaxLoadingText) == 'undefined')
		{
			ajaxLoadingText = '';
		}

		content = '<div class="ISL_CONTENT"><img src="gfx/loading.gif" alt="loading" /><br/>'+ajaxLoadingText+'</div>';

		var defalutAjaxOpt = {
			type:'post',
			url:ajaxUrl,
			success:function(cb){
				$('.IT_BOX_CONT').html(cb);
				$('.IT_BOX').animate({
					top:(parseInt($(window).height()/2)-parseInt($('.IT_BOX').height()/2)-(parseInt($('.IT_BOX_CONT').css('padding-top'))))+'px',
					left:(parseInt($(window).width()/2)-(parseInt($('.IT_BOX').width()/2))-(parseInt($('.IT_BOX_CONT').css('padding-left'))))+'px'
				});
			}
		};

		defalutAjaxOpt = $.extend(defalutAjaxOpt, ajaxOptions);

		$.ajax(defalutAjaxOpt);
	}

	$('<div class="IT_BOX">'+exitBtn+'<div class="IT_BOX_CONT">'+content+'</div></div>').appendTo('body');
	if(showExit)
	{
		$('.IT_BOX_EXIT').unbind('click').click(function(){
			$('.IT_BOX').fadeOut(function(){$(this).remove();});
			$.ui.dialog.overlay.destroy($('.ui-widget-overlay'));
		});
	}
	$('.IT_BOX').css({
		top:(parseInt($(window).height()/2)-parseInt($('.IT_BOX').height()/2)-(parseInt($('.IT_BOX_CONT').css('padding-top'))))+'px',
		left:(parseInt($(window).width()/2)-(parseInt($('.IT_BOX').width()/2))-(parseInt($('.IT_BOX_CONT').css('padding-left'))))+'px'
	});


}

