if( typeof GetScrollX != 'function' ) { function GetScrollX() { return window.scrollX || document.scrollLeft || document.documentElement.scrollLeft; } }
if( typeof GetScrollY != 'function' ) { function GetScrollY() { return window.scrollY || document.scrollTop || document.documentElement.scrollTop; } }

var just = { }

just.config = function(v) {
	var cfg = {
		settings: { },
		init: function() {
			if( this.verCheck(4.6) )
			{
				this.loadCfg();
				jUsers.hiddenSignIn();
			}
		},
		
		loadCfg: function() {
			var t = this;
			$.getJSON("/polish/getdata/config,json", function(data) {
				t.settings = data;
			});
		},
		
		verCheck: function(v) {
			return  this.v >= v ? true : false; // Na razie tak później będzie sprawdzał 1.2.3.4 itp.
		}
	}
	cfg.v = v;

	return cfg;
}

// version > 4.5
just.login = function(frm)
{
	return this.pLogin(frm);
}

just.pLogin = function(frm)
{
	var lg = {
		f: null,
		check: function()
		{
			if( this.f.username.value == '' )
			{
				alert("Nie podano nazwy użytkownika");
				return false;
			}
			
			if( this.f.password.value == '' )
			{
				alert("Nie podano hasła");
				return false;
			}
		}
	}
	
	lg.f = frm;
	
	return lg;
}

/*
function regulaminBF(s) {
	var regExp = new RegExp('/#'+s+'\/(.*?)', 'i');
	tab = window.location.hash.match(regExp)[1];
	if( s == 'baza-firm' )
	{
		window.replace('http://docs.google.com/View?id=dhfhd3vk_58fmpjt5nv');
	}
}
*/
just.openWindow = function(url, settings) { return just.go(url, settings); }
just.go = function(url, settings)
{
	var u = {
		hash: { },
		window: false,
		onGo: function() { this.track() },
		track: function() {
			
		},
		Set: function(attr, value) {
			if(typeof value != "undefined") { this[attr] = value; }
			else { for(var a in attr) this[a] = attr[a]; }
			return this;
		},
		getHash: function(key) {
			var tab = null
			if( typeof key != 'undefined' )
			{
				try {
					var regExp = new RegExp('/'+s+'\/(.*?)', 'i')[1];
					tab = window.location.hash.match(regExp);
				}
				catch(e) { /* just.log(e); */ }
			}
			else tab = window.location.hash;	
			this.hash.key = key;
			this.hash.val = tab;
		},
		open: function(u) {
			this.onOpen();
			if(this.window !== false) window.open(u, (this.window === true ? '_blank' : this.window));
			else window.replace(u);
		},
	}
	
	if( typeof settings != undefined )
		u.Set(settings);
	if( typeof url != 'undefined' )
		u.open(url);
	return u;
}

// Zarządzanie komunikatami
just.msg = function(obj) {
	var m = {
		obj: mint.$("msggl"),
		timeout: new Object(),
		setObj: function(obj)
		{
			try {
				mint.$(obj) ? this.obj = mint.$(obj) : this.create();
			}
			
			catch(e) {
				return null;
			}
		},
		hide: function(cl)
		{
			this.obj.innerHTML = "";
			this.obj.hide();
			if(cl) this.obj.removeClass(cl);
		},
		show: function(msg, cl)
		{
			this.obj.innerHTML = msg;
			if(cl) this.obj.addClass(cl);
			this.obj.show();
		},
		create: function()
		{
			this.obj = document.body.insertBefore(mint.$C('div', "msggl"), mint.$(document.body).down());
			this.obj.style.display = "none";
		},
		text: function(msg, cl, t)
		{
			if( !this.obj ) this.create();
			var that = this;
			var objName = this.obj.id;
			if( this.timeout[objName] )
			{
				window.clearTimeout(this.timeout[objName]);
				if( cl ) this.obj.removeClass(cl);
			}

			if( t && t >= 100)
			{
				this.timeout[objName] = window.setTimeout(function() { that.hide() }, t);
			}
			
			msg = msg.toString();
			msg == '' ? this.hide(cl) : this.show(msg, cl);
		},
		setError: function() {
			if( this.obj.hasClass('noerror') )
				this.obj.removeClass('noerror');
			if( !this.obj.hasClass('error') )
				this.obj.addClass('error');
		},
		setNoError: function() {
			if( this.obj.hasClass('error') )
				this.obj.removeClass('error');
			if( !this.obj.hasClass('noerror') )
				this.obj.addClass('noerror');
		}
	}

	m.setObj(obj);
	return m;
}

just.users = function(username, level, loggedIn, adm, facebookMode)
{
	var users = {
		username: "guest",
		level: 0,
		loggedIn: 0,
		adm: false,
		dbg: false,
		
		startup: function() {
			try {
				this.loadUserPanel();
			} catch(e) { console.log(e) }
		},
		
		loadUserPanel: function() {
			$('#container-top-user').slideDown();
			this.isLogged() ? this.onLogged() : this.onLogout();
			// $(this.isLogged() ? '#loggedin' : '#signInOff').slideUp();
		},
		
		onLogin: function () {
			
		},
		
		onLogged: function() {
			$('#signInOff').slideUp();
			$('#signInOn').slideUp();
			$('#loggedin').slideDown();
		},
		
		onLogout: function() {
			$('#loggedin').slideUp();
			$('#signInOn').slideUp();
			$('#signInOff').slideDown();
		},

		switchSignIn: function( v )
		{
			if( v )
			{
			  this.showSignIn();
			}
				else
				{
					this.hiddenSignIn();
				}
		},
		
		showSignIn: function()
		{
			$('#signInOff').slideUp();
			try{ $('#loggedin').hide(); } catch(e) {console.log(e)};
			$('#signInOn').slideDown();
		},
		
		hiddenSignIn: function()
		{
			$('#signInOn').slideUp();
			if( this.loggedIn )
			{
				$('#signInOff').slideUp();
				$('#loggedin').slideDown();
			}
				else
				{
					$('#signInOff').slideDown();
				}
		},
		
		signIn: function()
		{
			var btn = mint.$("submitBtn");
			var btn_val = mint.$("submitBtn").value;
			var obj_form = mint.$("user-login-form");
			var that = this;
			var msg = just.msg('loginMsgIn');
	
			advAJAX.submit(obj_form, { // assign
				onInitialization : function(obj)
				{
					msg.text('Trwa logowanie, proszę czekać...');
		      		obj.parameters["password"] = hex_md5(obj.parameters["password"]);
					obj.parameters["admin"] = that.level;
					btn.value = lang['Please_wait'];
		      	},
		      
				onComplete : function()
				{
		      		btn.value = btn_val;
					obj_form.disabled = false; 			// tmp
		      	},
		     
				onSuccess : function(obj)
				{
					if( typeof jPL.dbg != 'undefined' && jPL.dbg ) alert(obj.responseText);
					eval(obj.responseText);
					if( that.userLogged == 1 )
					{
						that.signInFinish(that.admin);
					}
						else
						{
							window.setTimeout("mint.$('password').focus();", 100);
						}
				},
		      
				onError: function(obj) {
		      		msg.text("Nie można nawiązać połączenia z serwerem, spróbuj później. ("+obj.status+")", 'error', 30000);
		      	}
		   });
		},
		
		signOut: function()
		{
			var t = this;
			$.post("/"+lang['language']+"/user,logout", { logout: "1" }, function(data) {
				try {
					if( typeof data.logout !== undefined ) {
						t.signOutFinish(data.logout);
					}
				}
				catch(e) { console.log(e); }
			}, 'json');
			
			/*onError : function(obj)
			{
		     	just.msg('loginMsgIn').text("Nie można nawiązać połączenia z serwerem, spróbuj później.", 'error', 60000);
				setTimeout('jUsers.signout()', 60000);
		   }*/
		},
	
		signOutFinish: function()
		{
			// f( this.admin == 1 )
			window.location.reload();
		},

		signInFinish: function(adminSession)
		{
			/** Temporary
			* @todo Załadować tylko bloki bez całej strony
			*/
			// if( adminSession != 1 )
			window.location.reload();
		},

		old_submit_form: function(id)
		{
			var s_error = false; // chwiliwo wyłączony - późnej dać false
			var name_focus = 'username';
			var object = window.document.getElementById(id);		

			object.register_submit.disabled = true;
			object.breset.disabled = true

			<!-- BEGIN switch_register -->
			if ( object.accept_rules.checked != true )
			{
				alert("Aby się zarejestrować musisz wyrazić zgodę na przetwarzanie danych osobowych!");
				name_focus = 'skype';
				s_error = true;
			}
			<!-- END switch_register -->
						
			if ( s_error == true )
			{
				object.register_submit.disabled = false;
				object.breset.disabled = false;
				eval("object." + name_focus + ".focus();");
				return;
			}
			object.submit();
		},
		
		isLogged: function(admin)
		{
			return typeof admin != 'undefined' && admin ? this.adm : this.loggedIn;
		}
	}
	
	if( typeof username != 'undefined' && username != "" )
		users.username =  username;
	if( typeof level != 'undefined' && level != "" )
		users.level = level;
	if( typeof loggedIn != 'undefined' && loggedIn != "" )
		users.loggedIn = loggedIn;
	if( typeof adm != 'undefined' && adm != "" )
		users.adm = adm;
	
	// if(!(typeof facebookMode != 'undefined' && facebookMode != true))
	users.startup();
	return users;
}

just.gMap = function(Lat, Lng, Zoom) {
	var gMap = {
		Lat: 50.07035,
		Lng: 19.86933,
		Zoom: 12,
		init: function(obj, title, infoContent) {
			var t = this;
			var myLatlng = new google.maps.LatLng(t.Lat, t.Lng);
			var myOptions = {
		   	zoom: t.Zoom,
		   	center: myLatlng,
		   	mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			var map = new google.maps.Map(obj, myOptions);
		  
			var marker = new google.maps.Marker({
		      position: myLatlng, 
		      map: map,
		      title: title,
				// draggable: true
			});
			
			if( infoContent && typeof infoContent != "undefined" )
			{
 				var infowindow = new google.maps.InfoWindow({
			   	content: infoContent
				});
			
				google.maps.event.addListener(marker, 'click', function() {
	    			infowindow.open(map,marker);
	  			});
			}
		}
	}
	if(Lat && typeof Lat != 'undefined') gMap.Lat = Lat;
	if(Lng && typeof Lng != 'undefined') gMap.Lng = Lng;
	if(Zoom && typeof Zoom != 'undefined') gMap.Zoom = Zoom;
	return gMap;
}

cJPL = function()
{
	this.version		=	3.0;
	this.dbg 			=	false; // debug
   this.className		=	"cJPL";
	this.project_ver	=	true;
   this._nUa			=	navigator.userAgent.toLowerCase();
	this._naV			=	navigator.appVersion;
	this._nOp 			=	(this._nUa.indexOf("opera") != -1 ? true : false);
   this._bIe			=	(this._nUa.indexOf("msie") !=-1 && !this._nOp ? true : false);
	this._bIe7			=	(this._naV.indexOf('MSIE 7') == -1);
	this._nIe4			=	(this._nIe && (this._nUa.indexOf("msie 2.") != -1 || this._nUa.indexOf("msie 3.") != -1 || this._nUa.indexOf("msie 4.") != -1) && !this._nOp ? true:false);
   this._nKh 			=	(this._nUa.indexOf("khtml") !=-1 ? true : false); // Google Chrome
	this._nWk			=	(this._nUa.indexOf("webkit") !=-1 ? true : false); // Google Chrome
	this._nGCh			=	(this._nUa.indexOf('chrome') != 1 ? true : false);
	this._nGe 			=	(this._nUa.indexOf("gecko") !=-1 && !this._nKh ? true:false);
   this._nN4 			=	(document.layers ? true:false);
   this._nMc			=	(this._nUa.indexOf("mac") != -1 ? true:false);
	this._niPhone		=	(this._nUa.indexOf('iPhone') != -1 ? true : false);
	this._nAndroid		=	(this._nUa.indexOf('Android') != -1  ? true : false);
	this._fm				= '<a href="mailto:%s">%s</a>';
	this.error_msg = new Array();
	this.cError = 0; this.oError;
	this.clientX = 0; this.clientY = 0; this.topX = 0; this.topY = 0; this.cursorX = 0; this.cursorY = 0; this.TcursorX = 0; this.TcursorY = 0;
	this.userLogged = 0; this.userId = -1; this.sSignIn = false;
	this.adm = 0; this.ct = 0;
	this.timeout = new Object;
	this.JsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
	this.JsPrt = (("https:" == document.location.protocol) ? "https://" : "http://");
	this.msgs = new Object();
	this.settings = new Object();
	this.lang = new Array(); // pl, polish
}

cJPL.prototype.__init = function()
{
	if( jPL.settings.autoRefreshTime > 30 ) setTimeout('location.replace("'+this.settings.currentUrl+'")', jPL.settings.autoRefreshTime*1000);
	if(window.name == '') window.name = this.settings.windowName;
	this.__getWindowData();
	if( !this._bIe ) document.captureEvents(Event.MOUSEMOVE)
	document.onmousemove = getMouseXY;
	window.onresize = jPLonResize;
	window.onscroll = jPLonScroll;
}

cJPL.prototype.__set = function(args)
{
	this.handleArguments(args);
}

cJPL.prototype.isIe=function() 			{ return this._bIe; }
cJPL.prototype.isIe7=function()			{ return !this._bIe7 }
cJPL.prototype.isOldIe=function() 		{ return this._bIe4; }
cJPL.prototype.isOpera=function()   	{ return this._bOp; }
cJPL.prototype.isGecko=function()		{ return this._bGe; }
cJPL.prototype.isOldNetscape=function(){ return this._bN4; }
cJPL.prototype.isMac=function()			{ return this._bMc; }
cJPL.prototype.isKhtml=function()		{ return this._bKh; }
cJPL.prototype.isHidden=function(o)
{
	return (o.style.visibility == "hidden" || o.style.display == "none" || o.className.match(/hidden/i)) ? true : false;
}

cJPL.prototype.__getWindowData = function()
{
	// wspolrzedne lewego, gornego rogu
	this.topX = GetScrollX();
	this.topY = GetScrollY()

	// wielkosc obszaru okna
	this.clientX = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	this.clientY = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}

cJPL.prototype.getMouseXY = function(e)
{
	this.__getWindowData();
	if(!e) var e = window.event;
	if(e.pageX || e.pageY)
	{
		this.cursorX = e.pageX; this.cursorY = e.pageY;
		this.TcursorX = this.cursorX - 262;
		this.TcursorY = this.cursorY + 10;
		// this.wMsg("x: "+this.TcursorX+" / y: "+this.TcursorY, 'msggl');
	}
		else
		{
			this.cursorX = e.clientX; this.cursorY = e.clientY;
			this.TcursorX = this.cursorX + this.topX - ((e.clientX || e.clientY) && this._bIe7 ? (document.body.clientLeft - 262) : (document.documentElement.clientLeft - 265));
			this.TcursorY = this.cursorY + this.topY - ((e.clientX || e.clientY) && this._bIe7 ? (document.body.clientTop + 10) : (document.documentElement.clientTop));
			// this.wMsg("2: ", 'msggl');
		}
	this._resize();
}

var op_test = false;

cJPL.prototype._resize = function()
{
	if(this.TcursorX < 10) this.TcursorX = 10;
	var xCursorX = this.topX+5;
	var xCursorY = this.topY+5;
	if(xCursorX < 5) xCursorX = 5;
	if(xCursorY < 5) xCursorY = 5;
	// var msg = this.cursorX+" ("+this.TcursorX+"), "+this.cursorY+" ("+this.TcursorY+"). "+this.topX+", "+this.clientX+" / "+this.topY+", "+this.clientY+". 1:"+document.body.clientLeft+", 2:"+document.body.clientWidth;
	// var msg = "<b>Góra</b>: [TcursorY: "+this.TcursorY+"], [topX: "+this.topX+"], [clientX: "+this.clientX+"], ["+document.documentElement.scrollTop+"]";
   // this.wMsg(msg, 'msggl');
	
	if( typeof jPL.Tooltip == 'class' && jPL.Tooltip.isActive)
	{
		if( !elEx('tooltip') )
		{
			mint.$('tooltip').style.left = this.TcursorX + 'px';
			mint.$('tooltip').style.top = this.TcursorY + 'px';
		}
			else
			{
				throw "notSupported";
			}
	}
	
	if( elEx('msggl') && GetStyleFast(mint.$('msggl'), "display") != "none" )
	{
		try {
	 		mint.$('msggl').style.left = xCursorX + 'px';
			mint.$('msggl').style.top = xCursorY + 'px';
		}

		catch(e) {
			if( !op_test )
			{
				alert(e+", "+this.topX+", "+this.topY);
				op_test = true;
			}
		}
	}
}

cJPL.prototype.urlEncode=function(s)
{
	s=""+s;
	s=s.replace(/\%/g,"%25");
	s=s.replace(/\s/g,"%20");
	s=s.replace(/\#/g,"%23");
	s=s.replace(/\&/g,"%26");
	s=s.replace(/\+/g,"%2B");
	s=s.replace(/\?/g,"%3F");
	s=s.replace(/\"/g,"%22");
	s=s.replace(/\'/g,"%27");
	s=s.replace(/:/g,"%3A");
	s=s.replace(/\//g,"%2F");
	s=s.replace(/</g,"%3C");
	s=s.replace(/>/g,"%3E");
	s=s.replace(/\\/g,"%5C");
	return s;
}

cJPL.prototype.copy = function(catchText)
{
	if( catchText == '' ) return false;
	if( window.clipboardData )
	{
		window.clipboardData.setData("Text", catchText);
	}
	   else if(window.netscape) 
	   {
			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
			if(!clip) return;
		   var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		   if(!trans) return;
	   	trans.addDataFlavor('text/unicode');
	   	var str = new Object(); var len = new Object();
	   	var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			var copytext = catchText;
			str.data=copytext;
	   	trans.setTransferData("text/unicode",str,copytext.length*2);
			var clipid=Components.interfaces.nsIClipboard;
			if(!clip) return false;
			clip.setData(trans,null,clipid.kGlobalClipboard);   
	   }
			else
			{
				var flashId = 'flashId-HKxmj5';
	        	/* Replace this with your clipboard.swf location */
   	    	var clipboardSWF = this.JsPrt+'justowska.pl/images/clipboard.swf';
				if( !mint.$(flashId) )
				{
            	var div = document.createElement('div');
					div.id = flashId;
					document.body.appendChild(div);
				}
				mint.$(flashId).innerHTML = '';
				mint.$(flashId).innerHTML = '<embed src="' + clipboardSWF + '" FlashVars="clipboard=' + encodeURIComponent(catchText) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
			}
   // alert("Following info was copied to your clipboard:\n\n" + catchText);
   //return false;
}

cJPL.prototype.setErrorObj = function(o)
{
	this.oError = mint.$(o);
}

cJPL.prototype.printError = function()
{
	if( this.error_msg.length != 0 )
	{
		this.oError.innerHTML = this.error_msg.join('<br />');
	}
}

cJPL.prototype.addError = function(msg)
{
	this.error_msg[this.cError] = msg;
	this.cError++;
}

cJPL.prototype.go = function(url)
{
	just.url(url).go();
}

cJPL.prototype.wMsg = function(msg, objName, t, e)
{
	return just.msg(objName).text(msg, (e ? 'bx_err' : 'bx_msg'), t);
}

cJPL.prototype.wMsg1 = function(msg, objName, t, e)
{
	if( typeof objName == 'undefined' || objName == false )
	{
		if( elEx('jmsgBox') ) objName = "jmsgBox";
			else if( elEx('msggl') ) objName = 'msggl';
			else return false;
	}
		else if( !elEx(objName) )
		{
			this.wMsg(msg, false, t, e);
			return;
		}
	
	if( typeof e != 'undefined' )
	{
		var addCls = (e ? "err" : "msg");
		var removeCls = ( e ? "msg" : "err" );
		if(mint.$(objName).hasClass('bx_'+removeCls))
			mint.$(objName).removeClass('bx_'+removeCls)
		mint.$(objName).addClass('bx_'+addCls);
	}
	
	if( this.timeout[objName] ) window.clearTimeout(this.timeout[objName]);
	mint.$(objName).innerHTML = msg;
	if( typeof t != 'undefined' && t >= 100)
	{
		this.timeout[objName] = window.setTimeout("mint.$(\'"+objName+"\').hide()", t);
	}
	
	if( msg == '' ) mint.$(objName).hide();
		else mint.$(objName).show();
}

// Poniższe przenieść do odpowiednich serwisów w zależoności od podtrzeb
cJPL.prototype.boxLayerResize = function()
{
	try 
	{
		if( elEx('boxLayer') && GetStyleFast(mint.$('boxLayer'), "display") != "none" )
			this.loadingImg();
	}
	
	catch(e) {
	
	}
}

cJPL.prototype.boxLayerDraw = function(val)
{
	var boxLayer = mint.$("boxLayer");
	boxLayer.show();
	boxLayer.style.top = this.topY + "px";
	boxLayer.style.left = this.topX + "px";
	boxLayer.style.width = this.clientX + "px";
	boxLayer.style.height = this.clientY + "px";
	mint.$('boxLayer-content').innerHTML = val;
}

cJPL.prototype.loadingImg = function()
{
	this.boxLayerDraw('<img src="/templates/default/images/loading.gif" alt="" style="" />');
}

cJPL.prototype.hiddenImgLoading = function()
{
	if( this.isHidden(mint.$("boxLayer")) ) return;
	// mint.$("boxLayer-content").innerHTML = "";
	objHidden(mint.$("boxLayer"));
}

cJPL.prototype.handleArguments = function(args)
{
	for(a in args)
	{
		if( typeof this[a] == "undefined" )
			this.settings[a] = args[a]; else {
	        	if( a != "settings" || a != 'lang' )
	           	this[a] = args[a];
					else
					{
	              	for(b in args[a])
	              	   this[a][b] = args[a][b];
					}
	      }
   }
}

cJPL.prototype.report_error = function(e)
{
	if( this.dbg ) alert(e);
}

cJPL.prototype.getLanguage = function()
{
	return this.lang[1];
}

cJPL.prototype.getLang = function()
{
	return this.lang[0];
}

/**
Tymczasowe rozwiązaania
*/

cJPL.prototype.xmlNodeValue = function(node)
{
	var n = (this._nKh && node.childNodes.length == 3) ? 1 : 0;
	if( node.childNodes[n].nodeType == 3 || node.childNodes[n].nodeType == 4 )
	{
		nValue = node.childNodes[n].nodeValue;
	}
	return nValue;
}
	 
function getMouseXY(e) { jPL.getMouseXY(e); }
function jPLonResize(e) { jPL.getMouseXY(e); jPL.boxLayerResize(); }
function jPLonScroll(e) { jPL.getMouseXY(e); }
