/**
 * Systemu Imperial CMS - API
 * @version		4.0
 * @author		Łukasz Sokół <lukasz@imperialcms.pl>
 */
(function($){
	$.Imperial = {
		options:{
			fileManagerWindow:null,//okno filemanagera
			helpWindow:null,//okno helpu
			isUiBlock:false,
			fmHome:null,
			//id_domain_group:null,//Id Domeny
			//id_domain:null,//Id Domeny
			//s_lang:'pl',//Język domeny
			//sa_lang:'pl',//Język admina
			//clientBase:'',//clientBAse
			//adminBase:'',//AdminBASE
			//template:'',//clientBAse
			//admin:'',//AdminBASE
			//isAdmin:false,//Czy wywołanie z admina
			//adminApiUrl
			anchor:null,//kotwica w adresie pzreglądarki
			fileManagerInitUrl:'/IFILEMANAGER/?r=%s&type=%s'//url do inicjalizacji filemanagera
		},

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

			//ustawienie anchora
			if(window.location.href != '')
			{
				var addr = window.location.href;
				var found = addr.match(/\#(.*?)$/g);
				
				if(found != null)
				{
					this.options.anchor = found[0];
				}
			}
			
			//dodanie dodatkowych metod dla validatorów
			if(typeof($.validator) == 'function')
			{
				this.Func.include('/lib/JS/jq.validator.costommethods.js');
			}

			if(this.options.isAdmin)//dla admina
			{
				//init lightboxa
				this.initLightbox();

				//init tooltip
				this.initTooltip();

				//odpalenie menu górnego
				$('ul.sf-menu').superfish();

				//button pomocy
				$('#SHOW_HELP').click(function(){
					var helpOptions = $(this).metadata();

					//{helpAdminPage:'',helpAction:'',helpComponent:''}
					
					var str = '';

					if(helpOptions.helpAdminPage != '')
					{
						str += 'ap:'+helpOptions.helpAdminPage+'/';
					}
					if(helpOptions.mod != '')
					{
						str += 'mod:'+helpOptions.mod+'/';
					}
					if(helpOptions.helpAction != '')
					{
						str += 'ac:'+helpOptions.helpAction+'/';
					}
					if(helpOptions.catalog != '')
					{
						str += 'c:'+helpOptions.catalog+'/';
					}
					if(helpOptions.window != '')
					{
						str += 'w:'+helpOptions.window+'/';
					}

					var locationWindow = '/IHELP/'+str;

					$.Imperial.options.helpWindow = window.open(locationWindow, '_blank', "top=0,left=0,width=600,height=600,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no");
					$.Imperial.options.helpWindow.focus();
				});

				this.setAdminActions();
			}
			else// dla aplikacji klienta
			{
				$('.refresh_catcha').click(function(){

					var el = $(this).attr('rel').split('|');

					var img = $('#'+el[0]);
					var input = $('#'+el[1]);
					
					var now = new Date().getTime();

					img.attr('src', img.attr('src').replace(/\?.*/, '?'+now));
					input.val('').focus();
				});

				//init tooltip
				this.initTooltip();

				//init lightboxa
				this.initLightbox();

				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
			$("#admin_languages").change(function(){
				window.location.href = actLocation+preque+'sa_lang='+$(this).val();
			});
			//zmiana języka zarządzania
			$("#client_languages").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/JS/jq.lightbox.js');

			$('a[rel=lightbox],a[class*=lightbox]').colorbox({
				current: '{current}/{total}',
				slideshow:true,
				slideshowAuto:false
			});
		},

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

			$('.ITIP').tooltip({
				track: true,
				delay: 300,
				showURL: false,
				showBody: false,
				fixPNG: true,
				bodyHandler: function(){
					var options = $(this).metadata();

					if(typeof(options.tipContClass) != 'undefined')
					{
						var handler = $('.'+options.tipContClass);

						if(handler.length > 0)
						{
							return handler.html();
						}
						else
						{
							return lang.noTooltipContent;
						}
					}
					else
					{
						return lang.noTooltipContent;
					}
				}
			});
		},
		
		//sprawdzenie okna parenta
		checkParentWindow:function(){
			if(parent.window.location.href.search($.Imperial.options.adminApiUrl) != '-1')
			{
				parent.window.location.href = '/';
			}
		},
		
		//otwarcie filemanagera
		openFileManager:function(options){
			if($.Imperial.options.fileManagerWindow != null)
			{
				$.Imperial.options.fileManagerWindow.close();
			}

			options = $.extend({
				width:875,
				height:513
			},options);

			if(typeof(options.return_id) != 'string')
			{
				alert('Podaj id');
			}
			else
			{
				$.Imperial.options.fileManagerWindow = window.open($.Imperial.Func.sprintf($.Imperial.options.fileManagerInitUrl, options.return_id, 'input_browse'), '_blank', "top=0,left=0,width="+options.width+",height="+options.height+",scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no");
				$.Imperial.options.fileManagerWindow.focus();
			}
		},

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

			switch(type)
			{
				case 'media':
					type = win.document.getElementById('media_type').value;
					break;
			}

			tinyMCE.activeEditor.windowManager.open({
				url: $.Imperial.Func.sprintf($.Imperial.options.fileManagerInitUrl, field_name, 'tinymce'),
				width: 875,
				height: 513,
				inline: 'no',
				close_previous: 'no'
			}, {
				parentWindow: win,
				viewMode:type,
				home:$.Imperial.options.fmHome
			});
		},
		//wyrzuć błąd do konsoli
		Console:{
			error:function(message)
			{
				if(typeof(console) != 'undefined')
					console.error(message);
			}
			/**
			 *console.log("hello world");
			console.error("hello world");
			console.debug("hello world");
			console.info("hello world");
			console.warn("hello world");*/
		},

		//Funkcje Imperial
		Func:{
			implode:function (glue, pieces){
				// Joins array elements placing glue string between items and return one string
				//
				// version: 1003.2411
				// discuss at: http://phpjs.org/functions/implode    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
				// +   improved by: Waldo Malqui Silva
				// +   improved by: Itsacon (http://www.itsacon.net/)
				// +   bugfixed by: Brett Zamir (http://brett-zamir.me)
				// *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: 'Kevin van Zonneveld'
				// *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
				// *     returns 2: 'Kevin van Zonneveld'
				var i = '', retVal='', tGlue='';
				if(arguments.length === 1)
				{
					pieces = glue;
					glue = '';
				}
				if(typeof(pieces) === 'object')
				{
					if(pieces instanceof Array)
					{
						return pieces.join(glue);
					}
					else
					{
						for(i in pieces)
						{
							retVal += tGlue + pieces[i];
							tGlue = glue;
						}

						return retVal;
					}
				}
				else
				{
					return pieces;
				}
			},
			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>');
			},

			serialize:function(mixed_value) {
				// Returns a string representation of variable (which can later be unserialized)
				//
				// version: 1004.2314
				// discuss at: http://phpjs.org/functions/serialize    // +   original by: Arpad Ray (mailto:arpad@php.net)
				// +   improved by: Dino
				// +   bugfixed by: Andrej Pavlovic
				// +   bugfixed by: Garagoth
				// +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
				// +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
				// +      input by: Martin (http://www.erlenwiese.de/)
				// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
				// -    depends on: utf8_encode    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
				// %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
				// *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
				// *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
				// *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
				var _getType = function(inp){
					var type = typeof inp, match;
					var key;
					if(type == 'object' && !inp){
						return 'null';
					}
					if (type == "object") {
						if (!inp.constructor) {
							return 'object';}
						var cons = inp.constructor.toString();
						match = cons.match(/(\w+)\(/);
						if (match) {
							cons = match[1].toLowerCase();}
						var types = ["boolean", "number", "string", "array"];
						for (key in types) {
							if (cons == types[key]) {
								type = types[key];break;
							}
						}
					}
					return type;
				};
				var type = _getType(mixed_value);
				var val, ktype = '';

				switch (type) {case "function":
						val = "";
						break;
					case "boolean":
						val = "b:" + (mixed_value ? "1" : "0");break;
					case "number":
						val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
						break;
					case "string":            //mixed_value = this.utf8_encode(mixed_value);
						val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
						break;
					case "array":
					case "object":val = "a";
						/*
						if (type == "object") {
							var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
							if (objname == undefined) {                    return;
							}
							objname[1] = this.serialize(objname[1]);
							val = "O" + objname[1].substring(1, objname[1].length - 1);
						}            */
						var count = 0;
						var vals = "";
						var okey;
						var key;for (key in mixed_value) {
							ktype = _getType(mixed_value[key]);
							if (ktype == "function") {
								continue;
							}
							okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
							vals += this.serialize(okey) +
									this.serialize(mixed_value[key]);
							count++;}
						val += ":" + count + ":{" + vals + "}";
						break;
					case "undefined": // Fall-through
					default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP            val = "N";
						break;
				}
				
				if (type != "object" && type != "array") {
					val += ";";}
				return val;
			},

			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
			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, closeFun, width, 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(title, text)
			{
				if(!$.Imperial.options.isUiBlock)
				{
					if(typeof(text) == 'undefined')
					{
						text = '<h4>'+lang.processing+'</h4>';
					}

					if(typeof(title) == 'undefined')
					{
						title = lang.iadmin;
					}

					$.Imperial.options.isUiBlock = true;
					$.blockUI({
						theme:true,
						message:'<h4>'+text+'</h4>',
						title:title,
						css:{
							padding:'4px',
							border:'1px solid #E9E9E9',
							color:'#3C6AB7',
							width:'auto'
						},
						overlayCSS:  {
							backgroundColor: '#D2D2D2',
							opacity:         0.5
						}
					});
				}
			},

			//usuniecie boxa ładowania
			hideLoading:function()
			{
				if($.Imperial.options.isUiBlock)
				{
					$.unblockUI();
					$.Imperial.options.isUiBlock = false;
				}
			}


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

