;var timeStampLastMouseMove; 

;var getUrlParameter = function getUrlParameter(sParam, sUrl) {
	var sPageURL = decodeURIComponent(typeof sUrl === "undefined" || sUrl === null ? window.location.href : sUrl);
	var results = new RegExp('[\?&]' + sParam + '=([^&#]*)').exec(sPageURL);
    if (results == null){
       return null;
    }
    else {
       return decodeURI(results[1]) || 0;
    }
}; var Url = (function() {
	"use strict";
	var
		map = {
			protocol : 'protocol',
			host     : 'hostname',
			port     : 'port',
			path     : 'pathname',
			query    : 'search',
			hash     : 'hash'
		},

		defaultPorts = {
			"ftp"    : 21,
			"gopher" : 70,
			"http"   : 80,
			"https"  : 443,
			"ws"     : 80,
			"wss"    : 443
		},

		parse = function( self, url) {
			var
				d      = document,
				link   = d.createElement( 'a'),
				url    = url || d.location.href,
				auth   = url.match( /\/\/(.*?)(?::(.*?))?@/) || []
			;

			link.href = url;

			for (var i in map) {
				self[i] = link[map[i]] || '';
			}

			self.protocol = self.protocol.replace( /:$/, '');
			self.query    = self.query.replace( /^\?/, '');
			self.hash     = self.hash.replace( /^#/, '');
			self.user     = auth[1] || '';
			self.pass     = auth[2] || '';
			self.port     = (defaultPorts[self.protocol] == self.port || self.port == 0) ? '' : self.port; // IE, Android fix

			if (!self.protocol && !/^([a-z]+:)?\/\//.test( url)) {
				var
					base     = new Url( d.location.href.match(/(.*\/)/)[0]),
					basePath = base.path.split( '/'),
					selfPath = self.path.split( '/')
				;

				basePath.pop();

				for (var i = 0, props = ['protocol','user','pass','host','port'], s = props.length; i < s; i++) {
					self[props[i]] = base[props[i]];
				}

				while (selfPath[0] == '..') { // skip all "../
					basePath.pop();
					selfPath.shift();
				}

				self.path = (url.substring(0, 1) != '/' ? basePath.join( '/') : '') + '/' + selfPath.join( '/');
			}

			else {
				// fix absolute URL's path in IE
				self.path = self.path.replace( /^\/?/, '/');
			}

			parseQs( self);
		},

		decode = function(s) {
			s = s.replace( /\+/g, ' ');

			s = s.replace( /%([EF][0-9A-F])%([89AB][0-9A-F])%([89AB][0-9A-F])/g,
				function( code, hex1, hex2, hex3) {
					var
						n1 = parseInt( hex1, 16) - 0xE0,
						n2 = parseInt( hex2, 16) - 0x80
					;

					if (n1 == 0 && n2 < 32) {
						return code;
					}

					var
						n3 = parseInt( hex3, 16) - 0x80,
						n = (n1 << 12) + (n2 << 6) + n3
					;

					if (n > 0xFFFF) {
						return code;
					}

					return String.fromCharCode( n);
				}
			);

			s = s.replace( /%([CD][0-9A-F])%([89AB][0-9A-F])/g,
				function( code, hex1, hex2) {
					var n1 = parseInt(hex1, 16) - 0xC0;

					if (n1 < 2) {
						return code;
					}

					var n2 = parseInt(hex2, 16) - 0x80;

					return String.fromCharCode( (n1 << 6) + n2);
				}
			);

			s = s.replace( /%([0-7][0-9A-F])/g,
				function( code, hex) {
					return String.fromCharCode( parseInt(hex, 16));
				}
			);

			return s;
		},

		parseQs = function( self) {
			var qs = self.query;

			self.query = new (function( qs) {
				var re = /([^=&]+)(=([^&]*))?/g, match;

				while ((match = re.exec( qs))) {
					var
						key = decodeURIComponent(match[1].replace(/\+/g, ' ')),
						value = match[3] ? decode(match[3]) : ''
					;

					if (this[key] != null) {
						if (!(this[key] instanceof Array)) {
							this[key] = [this[key]];
						}

						this[key].push( value);
					}

					else {
						this[key] = value;
					}
				}

				this.clear = function() {
					for (key in this) {
						if (!(this[key] instanceof Function)) {
							delete this[key];
						}
					}
				};

				this.toString = function() {
					var
						s = '',
						e = encodeURIComponent
					;

					for (var i in this) {
						if (this[i] instanceof Function) {
							continue;
						}

						if (this[i] instanceof Array) {
							var len = this[i].length;

							if (len) {
								for (var ii = 0; ii < len; ii++) {
									s += s ? '&' : '';
									s += e( i) + '=' + e( this[i][ii]);
								}
							}

							else {
								s += (s ? '&' : '') + e( i) + '=';
							}
						}

						else {
							s += s ? '&' : '';
							s += e( i) + '=' + e( this[i]);
						}
					}

					return s;
				};
			})( qs);
		}
	;

	return function( url) {
		this.toString = function() {
			return (
				(this.protocol && (this.protocol + '://')) +
				(this.user && (this.user + (this.pass && (':' + this.pass)) + '@')) +
				(this.host && this.host) +
				(this.port && (':' + this.port)) +
				(this.path && this.path) +
				(this.query.toString() && ('?' + this.query)) +
				(this.hash && ('#' + this.hash))
			);
		};

		parse( this, url);
	};
}());

function removeQueryParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

function supportHistoryApi() {
	return !!(window.history && history.replaceState );
} 

function checkAuthTicket()
{
	var timeStampNow = new Date().getTime();
	var difference = timeStampNow - timeStampLastMouseMove;
    var minutsDiff = Math.floor(difference/1000/60);
	var period = (typeof _GPeriodOfInactivity == "undefined" ||  _GPeriodOfInactivity == null ? 30 :  _GPeriodOfInactivity);
	console.log('timeStampNow ' + timeStampNow);
	console.log('timeStampLastMouseMove ' + timeStampLastMouseMove);
	console.log('minutsDiff ' + minutsDiff);
	console.log('period ' + period);
	if (minutsDiff >= period) {
		return; // 68888
	}
    $.ajax({
        type: "POST",
        url: "service/authcheck.php",
        data: "url="+encodeURIComponent(window.location.href),
        success: function(arg){
			var msg = arg;
				if ( msg.toString().length > 0 ) { // if we got some answer try to login again
				// alert(msg); silent redirect to login page
				window.location.href = "login.php";
			}
        }
    });
}

$(document).mousemove(function( event ) {
	timeStampLastMouseMove = new Date().getTime();
});

function ShowModalWindow(show){
	var l_show = (typeof show === 'undefined' ? true : show);
	ShowGlassWindow(l_show);
	if(Dialog==null) Dialog=document.getElementById('modal');
	if(l_show){
		var c = getClientCenter();
		if (Dialog !== null && Dialog.style != undefined && Dialog.style !== null) {	
			Dialog.style.left = (c[0]-150)+'px';
			Dialog.style.top  = (c[1]-75)+'px';
			Dialog.style.display ='block';
		}
		if (Dialog !== null && Dialog.focus != undefined) {	
			Dialog.focus();
		}
	}
	else
		if (Dialog !== null && Dialog.style != undefined && Dialog.style !== null)
			Dialog.style.display='none';
}

var isIE = ($.browser.msie && $.browser.version.substr(0, 2) != '10');

var GlassWindow=null;
var Dialog=null;
function ShowGlassWindow(show){
	if(GlassWindow==null){
		GlassWindow=document.createElement('DIV');
		with(GlassWindow.style){
			display='none';
			position='fixed';
			height=0;	
			width=0;	
			zIndex=9999;
			if(isIE){
				backgroundColor = '#FFFFFF';
				filter="progid:DXImageTransform.Microsoft.Alpha(Opacity=40, Style=0)";
			}
			else
				backgroundImage = 'url(img/alfa40-fon.png)';
		}
		document.body.appendChild(GlassWindow);
	}
	if(show){
		var s = getDocumentSize();
		with(GlassWindow.style){
			left = top = 0;
			var scrollHeight = Math.max(
				document.body.scrollHeight, document.documentElement.scrollHeight,
				document.body.offsetHeight, document.documentElement.offsetHeight,
				document.body.clientHeight, document.documentElement.clientHeight
			  );
			width = s[0] +'px';
			height = '' + scrollHeight + 'px';
		}
	}
	GlassWindow.style.display=show?'block':'none';
}

function getDocumentSize(){
	return [document.body.scrollWidth > document.body.offsetWidth ? document.body.scrollWidth : document.body.offsetWidth,
			document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight];
}
function getClientSize(){
	if(document.compatMode=='CSS1Compat'/* && !window.opera*/)
		return [document.documentElement.clientWidth, document.documentElement.clientHeight];
	else
		return [document.body.clientWidth, document.body.clientHeight];
}

function getDocumentScroll(){
	return [self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft),
		 self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop)];
}

function getClientCenter(){
	var sizes = getClientSize();
	var scrl = getDocumentScroll();
	return [parseInt(sizes[0]/2)+scrl[0], parseInt(sizes[1]/2)+scrl[1]];
}


function fixBoxShadowBlur(jQueryObject){
    if($.browser.msie && ( $.browser.version.substr(0, 1) == '9' || $.browser.version.substr(0, 2) == '10') ){
	jQueryObject.each(function(){
            boxShadow = $(this).css('boxShadow');
            if(boxShadow != 'none'){
                var bsArr = boxShadow.split(' ');
		if (bsArr == null || bsArr.length < 4) { bsArr = ['1px','1px','0px','#d5dad6']} 
		bsBlur = parseInt(bsArr[2]) || 0;
		bsArr2 = bsArr[2];
                bsBlurMeasureType = bsArr2.substr(("" + bsBlur).length);
                bsArr[2] = (bsBlur * 2) + bsBlurMeasureType;
                $(this).css('boxShadow', bsArr.join(' '));
            }
        });
    }
}

//init trees on pages that have it
function initTrees(dataUrl, firstLineHide) {
	if( $("#mixed").length ) {
		$("#mixed").treeview({
		    url: dataUrl,
		    collapsed: true,
			ajax: {
				type: "post"
			}
		});
		var count = $('#mixed > li').size();
		var lifirst = $("ul#mixed li:first");
		if ( firstLineHide == null || firstLineHide ) {
			if ( count > 1 ) {
				lifirst.attr("style", "background: url(css/images/treeview-default-line-first.gif) 0 17px no-repeat;");
			} else if ( count == 1 ) {
				if (lifirst.hasClass("lastExpandable")) { 
					lifirst.attr("style", "background: none;").removeClass('lastExpandable').addClass('expandable');
					lifirst.find("div:first").removeClass('expandable-hitarea').removeClass('lastExpandable-hitarea').addClass('rootExpandable-hitarea');
				} else {
					lifirst.attr("style", "background: none;").removeClass('lastCollapsable').addClass('collapsable');
					lifirst.find("div:first").removeClass('collapsable-hitarea').removeClass('lastCollapsable-hitarea').addClass('rootCollapsable-hitarea');
				}
			}
		} 
	}
}

function goHome(defaultHome) {
    if (history.length > 1) {
        history.back();
    } else {
        document.location.href = defaultHome;
    }
}
	


$(document).ready(function()
{
	timeStampLastMouseMove = new Date().getTime();
	checkAuthTicket();

	setInterval(function() {
			checkAuthTicket()	
		}, 10*60000); // 10 minuts

	// 61631 ie workarround
	function setIETableWidth(){
		$(function() {
			var exists = false;
			$('#container').css('width','');
			var containerWidth = $('#container').width();
			$('table:not(".self-binding-width")').each(function(){
				if($(this).width() > (containerWidth - 70)){
					exists = true; 
					containerWidth = $(this).width();
				}
			});
			if (exists) {
				$('#container').width(containerWidth + 70);
			}
		});
	}
	
	$( window ).resize(function() {
		setIETableWidth();
	});
	
	setIETableWidth();

	fixBoxShadowBlur($('*'));
	
	var image = $('<img id="pic-test">').appendTo('header h1');
	
	image.load(function() {
	}).error(function() {
		$( ".btn-top" ).css( "color", "#000000" );
		$( ".btn-top" ).css( "text-indent", "0" );
		$( ".btn-fav" ).css( "color", "#000000" );
		$( ".btn-fav" ).css( "text-indent", "0" );
	}).attr('src','img/blank.gif');

	$( ".btn-top-lang" ).click(function() {
		var pos = $( this ).position();
		$("#list-lang").css({
        	top: ( pos.top + $( this ).outerHeight() - 1 )+ "px",
        	left: (pos.left + $( this ).width() - $("#list-lang").width()  ) + "px"
		}).toggle();
		$( this ).addClass( "btn-top-lang-pressed" );
		return false;
	});

	$( "#list-lang" ).mouseleave(function() 
   	{
		$( this ).hide();
		$( ".btn-top-lang"  ).removeClass( "btn-top-lang-pressed" );
	});

	$("#btn-toggle-header").show();
});

function ModalWindowShowMessage(event) {
	if(event && event.data && typeof event !== 'undefined' ){
		switch (event.data){
			case "showmodalwindow":
				ShowModalWindow(true);
				break;
			case "closemodalwindow":
				ShowModalWindow(false);
				break;
		}
	}
}

if (window.addEventListener) {
	window.addEventListener("message", ModalWindowShowMessage);
  } else {
	window.attachEvent("onmessage", ModalWindowShowMessage);
}

//ie fix
function isInteger(num) {
	return (num ^ 0) === num;
}

//check if there is an attribute on an element
$.fn.hasAttr = function(name) {  
	return this.attr(name) !== undefined;
};