var bip_path = '';
var markers = new Array();
var mapCenterX = 52;
var mapCenterY = 19;
var mapZoom = 6;
var new_menu_id = '';
var menu_loaded = false;

//*********************************obsluga historii*************************

/*
 * wywolanie zakodowanej funkcji z urla
 *
 * @param string hash - zakodowana funkcja
 */

function pageload(hash){
	if (window.location.href.indexOf('#') != -1){
		var redirect = window.location.href.split('#');
		var _function = $.base64Decode(redirect[1]);
		try {
			eval(_function);
		} catch(e){
		}
	}
}

function addTohistory(_function){
	var hash = $.base64Encode(_function);
	$.history.load(hash);
}
//*********************************** koniec obslugi historii******************



$(document).ready(function(){
	
		$.cookie('bip_link', window.location.href); 
		bip_path = window.realUrl;
		
	    if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true')
			$("#path").html('<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a>');
		
		var xtheme = $("link[class=xtheme]").attr('href');
		var genXtheme = $("link[class=genXtheme]").attr('href');

		if( $("#szukaj_status").val() != 'undefined' )
			var searchVal = $("#szukaj_status").val();
		else
			var searchVal = "";
			
	    if( defaultLayout != 'bip_default') {
//			var xtheme = $("link[class=xtheme]").attr('href');
//			var genXtheme = $("link[class=genXtheme]").attr('href');
//		}
//		else {
			$(".searchBtn").attr({value: "" });
		}
		
		$.cookie('content_title', $("title")[0].text);
		// zainicjowanie historii
		$.history.init(pageload,{unescape: true});

		fixIEPng();
		
		// pokazywanie i ukrywanie obrazka loading przy ladowaniu strony 
		$("#loading").hide();
		$("#loading").ajaxStart(function(){
			$(this).show();

			//schowanie okna z noticem poprzedniego zapytania
			$("div#info_panel").remove();
			$("div#error_panel").remove();
		});
		$("#loading").ajaxStop(function(){ $(this).hide(); });

		//drukowanie
		$("#print").click(function(){
			window.print();
		});
		

		//zwiekszenie kontraastu strony
		$("#highContrast").click(function() {
			$.cookie('highContrast', 'true'); 
			if(typeof(Ext.config.developer) == 'undefined'){
				$("link[href=" + Ext.config.scripth_path + Ext.config.front_css + "]").attr({href : Ext.config.scripth_path + Ext.config.front_css_for_hc });
			}
			else {
				$('link.default').remove();
				var arrayFrontHcCss = Ext.config.front_css_for_hc.replace(/[\[\]]/g,'');
				arrayFrontHcCss = arrayFrontHcCss.split(',');
				for(var i=0; i<arrayFrontHcCss.length;i++) {
					$('head').append('<link class="highContrast" rel="stylesheet" type="text/css" href='+ arrayFrontHcCss[i] +'/>');
				}
			}
			if( xtheme != 'undefined' ) {
//					$("link[class=xtheme]").attr({href : ""});
//					$("link[class=genXtheme]").attr({href : ""});
					$('link.xtheme').remove();
					$('link.genXtheme').remove();
			}
			if( defaultLayout == 'bip_default') {
				if( xtheme ) {
					$("link[class=xtheme]").attr({href : ""});
					$("link[class=genXtheme]").attr({href : ""});
					}
			}
			else {
				$("#szukaj_status").attr({value: "Szukaj" });
				$(".searchBtn").attr({value: "Szukaj" });
			}
			$(this).hide();
			$("#defaultContrast").show();
	  		$(".options").find("img").each(function() {
	  			var hc = $(this).attr("src").replace('images/', 'images/hc/');
					$(this).attr("src", hc);
		   	});

		});
		
		//zmniejszenie kontrastu strony
		$("#defaultContrast").click(function() {
			$.cookie('highContrast', 'false'); 
			if(typeof(Ext.config.developer) == 'undefined'){
				//$("link[href=smarty/templates/" + defaultLayout + "/css/front-hc-min.css]").attr({href : "smarty/templates/" + defaultLayout + "/css/front-min.css"});
				$("link[href=" + Ext.config.scripth_path + Ext.config.front_css_for_hc + "]").attr({href : Ext.config.scripth_path + Ext.config.front_css });
			}
			else {
				$('link.highContrast').remove();
				var arrayFrontDefaultCss = Ext.config.front_css.replace(/[\[\]]/g,'');
				arrayFrontDefaultCss = arrayFrontDefaultCss.split(',');
				for(var i=0; i<arrayFrontDefaultCss.length;i++) {
					$('head').append('<link class="default" rel="stylesheet" type="text/css" href='+ arrayFrontDefaultCss[i] +'/>');
				}
			}
			if( defaultLayout == 'bip_default') {
				if( xtheme ) {
//					$("link[class=xtheme]").attr({href : xtheme});
//					$("link[class=genXtheme]").attr({href : genXtheme}); 
					$('head').append('<link class="genXtheme" rel="stylesheet" type="text/css" href='+ genXtheme +' />');
					$('head').append('<link class="xtheme" rel="stylesheet" type="text/css" href='+ xtheme +' />');
				}
			}
			else {
				$("#szukaj_status").attr({value: searchVal });
				$(".searchBtn").attr({value: "" });
			}
			$(this).hide();
			$("#highContrast").show();
			$(".options").find("img").each(function() {
	  			var hc = $(this).attr("src").replace('images/hc/', 'images/');
					$(this).attr("src", hc);
		   });
		});

		//wysyłanie maili z linkiem do strony
		$("#sendToFriend").click(function() {
			showSendmailWindow()
		});

		//funkcje pomocnicze do zamiany adresow linkow na ajaxowe wywolania

		enableListHover();
  		bindStats();
		bindRejestr();
		bindSiteMap();
		bindSearch();
		bindSios();
		bindTopMenu();
		bindPath();
		bindRss();
		bindSearchStatus();
		bindSearchStatusInContent();
		bindContents();
		bindSearchMod();
		bindRejestrMod();
//		bindOtherLinks();
		bindDefaultModule();
		bindSurveyLinks();
		
 		//zwiekszenie czcionek w contencie
 		$("#upperLetters").click(function () {
  			upper($("#content"));
		});

		//zmniejszenie czcionek w contencie
		$("#lowerLetters").click(function () {
  			lower($("#content"));
		});
 		
		if (typeof($("div.info")) != 'undefined'){
			$("div.info").slideDown('slow').fadeIn('slow');
		}

		//przycisk do zamkniecia gornego paska "info"
 		$(".close_info_bar").click(function(event){
		   event.preventDefault();
		   $(this.parentNode.parentNode).hide("slow",function(){$(this).remove();});
		 });
		 
		 
		 
		 //nadanie obslugi naglowkowi MENU
		 $("p#menu_top").click(function(){
		 	getIndex();
			$("ul#leftMenu").find("span,a").removeClass("my");
		});

		 //**************************obsluga mapki********************
		 //zaladowanie mapki google
		 load(markers,mapCenterX,mapCenterY);
		 
		 $("p#map_show").click(function(){
		 	if (!($("#map_search").val() == ''))
				mapFind();
		});

		$("#map_search").keypress(function(e){
			if (e.which == 13 && this.value != ''){
				mapFind();
			}
		});

		mapListHover();
		//***********************************************************
		$('#re_os').leviTip({sourceType: 'element', source: '#infoTipRe', hideSourceElement: true});
		$('#wpr_os').leviTip({sourceType: 'element', source: '#infoTipWpr', hideSourceElement: true});


		//zaladowanie dynamicznego menu ajaxowego
		if (window.location.href.indexOf('#') == -1){
			$("#leftMenu").empty();
			$("#leftMenu").treeview({
				url: "httprequest.php"
			});
			menu_loaded = true;
		}
		else {
			var redirect = window.location.href.split('#');
			var _function = $.base64Decode(redirect[1]);
			if (_function.indexOf('getContents') == -1 
					&& _function.indexOf('clickMenuGetContents') == -1 
					&& _function.indexOf('getContent') == -1){
				$("#leftMenu").empty();
				$("#leftMenu").treeview({
					url: "httprequest.php"
				});
				menu_loaded = true;
			}
		} 

		$("a.showTooltip,img.showTooltip").tooltip({
			position: ['bottom', 'left'],
			offset: [2, 10],
			effect: 'toggle',
			opacity: 0.7
		});
		
		$("a#re_os, a#wpr_os").tooltip({
			position: ['center', 'right'],
			offset: [2, 10],
			effect: 'toggle',
			opacity: 0.7
		});
		if( $.cookie('highContrast') != null && $.cookie('highContrast') == 'true' ) {
			$('#highContrast').click();
		}
		
});
 	
	// funkcja do pobierania zawartosci menu o id wraz z rozwinieciem drzewa menu do tego katalogu
	// funkcja odswiezania menu realizowana jest automatycznie podczas odczytania funkcji z urla	
	function getArticlesWithMenu(id){
		addTohistory('getContents('+id+')');
	}
	
	/*
	 * 
	 * FUNKCJE NARZEDZI UZYTKOWYCH
	 * 
	 */
	
	//funkcja do zwiekszania czcionki
 	function upper(obj){
			var size = obj.css("font-size");
			var height = obj.css("line-height"); 
			
  			if (size.substring(size.length-2) != 'px'){
				//alert(size);
				var s = obj.attr('size');
				
				if (s<7) obj.attr({size: parseInt(s)+1});
			} else {
				var s = parseInt(size.substring(-2,2)) + 1;
  				
				//alert(size.substring(0,size.length-2));
				obj.css("font-size", s + "px");
	  			(obj).children().each(function(){
	  				upper($(this));
	  			});	
				
			}
			if (height.substring(height.length - 2) != 'px') {
			} else {
				var h = parseInt(height.substring(0,height.length-2)) + 1;
				obj.css("line-height", h + "px");
			}
			
			
	}
	
	//funkcja do zmniejszania czcionki
	function lower(obj){
			var size = obj.css("font-size");
			var height = obj.css("line-height"); 
			
  			if (size.substring(size.length-2) != 'px'){
				//alert(size);
				var s = obj.attr('size');
				if (s>0)
					obj.attr({size: parseInt(s)-1});
				
			} else {
				var s = parseInt(size.substring(-2,2)) - 1;
  				
				if (s>0) obj.css("font-size", s + "px");
	  			(obj).children().each(function(){
	  				lower($(this));
	  			});	
			}
			if (height.substring(height.length - 2) != 'px') {
			} else {
				var h = parseInt(height.substring(0,height.length-2)) - 1;
				if (h > 0)
					obj.css("line-height", h + "px");
			}
	}
	
//wysylanie maila z linkiem do znajomego
function showSendmailWindow() {
	if(bip_mail_address == 'noConf' || Ext.getDom('recaptcha_widget') == null) {
		Ext.Msg.show({
			title:'Błąd',
			msg: 'Skrzynka nadawcza nie została skonfigurowana',
			buttons: Ext.Msg.OK,
			icon: Ext.MessageBox.ERROR
		});
		return;
	}
	
	
	$.getScript(document.location.protocol + '//www.google.com/recaptcha/api/challenge?k='+Ext.config.captchaKey, function(){
		   
		$.getScript(document.location.protocol +'//www.google.com/recaptcha/api/js/recaptcha.js', function(){
			   
			var formPanel = new Ext.form.FormPanel({
				labelAlign: 'left',
				buttonAlign: 'right',
				bodyStyle: 'padding: 5px;',
				url: 'httprequest.php',
				items: [{
					width: '90%',
					xtype: 'textfield',					
					fieldLabel: 'Adres e-mail',
					name: 'email',
					allowBlank: false,
					minLength: 5,
					maxLength: 100,
					vtype: 'email'
				},{
					width: '90%',
					xtype: 'textarea',
					fieldLabel: 'Treść wiadomości',
					name: 'tresc',
					value: 'Polecam Ci artykuł ' + $.cookie('content_title').trim() + ' \n\n' +
							(($.cookie('bip_link') == '' || $.cookie('bip_link') == 'null') ? bip_path : $.cookie('bip_link'))
				},{
					width: 335,
					xtype: 'panel',
					contentEl: 'recaptcha_widget',
					style: 'margin-bottom: 4px;margin-left: 105px;',
					border: true
								
				},{
					width: '90%',
					xtype: 'textfield',
					fieldLabel: 'Wpisz powyższe wyrazy',
					name: 'recaptcha_response_field',
					allowBlank: false
				}],
				buttons: [{
					text: 'Wyślij',
					type: 'submit',
					handler: function(){
						if(formPanel.getForm().isValid()) {
							formPanel.getForm().submit({
								url: 'httprequest.php',
								params: {
									"class": 'SendMail',
									method: 'defaultMethod',
									recaptcha_challenge_field: $('#recaptcha_challenge_field').attr('value')
								},
								success: function(form, action){
									if (typeof(action.result.content) != 'undefined') {
										if (typeof(action.result.error) != 'undefined') {
											Ext.Msg.show({
												title:'Błąd',
									   			msg: action.result.error,
									   			buttons: Ext.Msg.OK,
									   			icon: Ext.MessageBox.ERROR
											});
										}
										if (typeof(action.result.content.data) != 'undefined') {
											Ext.Msg.show({
												title:'Ok',
									   			msg: action.result.content.data,
									   			buttons: Ext.Msg.OK,
									   			icon: Ext.MessageBox.INFO
											});								
										}
									}
									windowForm.hide();
								},
								failure: function(form, action){
									Ext.Msg.show({
									   title:'Błąd',
									   msg: (typeof(action.result.error) != 'undefined' ? action.result.error : 'Błąd podczas wysyłania danych'),
									   buttons: Ext.Msg.OK,
									   icon: Ext.MessageBox.ERROR
									});
								}
							});
						}
						Recaptcha.reload();
					}
				},
				{
					text: 'Anuluj',
					handler: function(){
						windowForm.hide();
					}
				}]
			});
			
			var windowForm = new Ext.Window({
				title: 'Poleć ten artykuł znajomemu!',
				width: 500,
				closeAction: 'hide',
				constrainHeader: true,
				bodyStyle: 'padding: 3px;',
				items: formPanel
			});
			
			windowForm.show();
			   
		});
		   
	});
	
	
}
	
	/*
	 *
	 * FUNKCJE GORNYCH ZAKLADEK
	 * 
	 */
	
	
	// funkcja mapujaca id zakladki na obiekt, nie przekazujemy od razu obiektu z uwagi na to ze 
	// cala funkcja zapisywana do historii jest stringiem 
	function historyClickTopMenu(id){
		var obj = document.getElementById(id);
		clickTopMenu(obj);
	}
	
	// funkcja aktywujaca zakladke stats i wywolywujaca funkcje do pobrania danych
	function checkTabAndStrStats(str){
		var obj = document.getElementById('stats');
		activateCurrentTopMenuButton(obj);
		getStats(str);
	}
	
	//obsluga wygladu przyciskow w gornym menu
	function clickTopMenu(obj){
		activateCurrentTopMenuButton(obj);
		getTopMenuContent(obj);
 	}
	
	// funkcja aktywujaca odpowiednia zakladke
	function activateCurrentTopMenuButton(obj){
		border();

		top_buttons_deactiv();
		$(obj).removeClass("top_menu_buttons");
		$(obj).addClass("top_menu_active");
		//$(obj).find("a").css('color', '#333');
		$(obj).find("a").removeClass("nonactive");
		$(obj).find("a").addClass("active");

		$(obj).prev().removeClass("top_menu_buttons_right");
		$(obj).prev().addClass("top_menu_active_right");
		$(obj).next().removeClass("top_menu_buttons_left");
		$(obj).next().addClass("top_menu_active_left");

	}
	
	//deaktywuje wszystkie przyciski gornego menu
	function top_buttons_deactiv() {
		$(".top_menu_active").each(function(){
			$(this).removeClass("top_menu_active");
			$(this).addClass("top_menu_buttons");
			$(this).prev().removeClass("top_menu_active_right");
			$(this).prev().addClass("top_menu_buttons_right");
			$(this).next().removeClass("top_menu_active_left");
			$(this).next().addClass("top_menu_buttons_left");
			//$(this).find("a").css('color', '#5A81B2');
			$(this).find("a").removeClass("active");
			$(this).find("a").addClass("nonactive");
		});
	}
	
	
	/*
	 * pobierz tresc strony dla defaultModule
	 */

	function getDefaultModule(module, method, name, param){

		var callback = '$("ul#leftMenu").find("span,a").removeClass("my");' +
				'$.cookie(\'bip_link\', \'' + bip_path + '?module=' + module + (method != null ? '&method='+method : '') + '\');' +
				//link dla przeglądarek tekstowych
				'$("#text_page").attr({\'href\': \'index_text.php?module='+module+ (method != 'null' ? '&method='+method : '') +'\'});'+
				'$("#content").css("font-size", "13px");' +
			  	'$(".in_content").css("font-size", "13px");' +
				'if (typeof(menu_sciezka_config) != "undefined" && menu_sciezka_config == \'true\')' +
				'$("#path").html(\'<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a> <div class="breadcrumbs_separator"></div> <a class="menu_list2" href="?module='+ module + (method != null ? '&method='+method : '') + ((typeof(param)!="undefined" && param !="") ? "&param="+param : "") +'">' + name + '</a>\');' +
				'bindDefaultModule();'+
				'enableListHover();' +
				'bindPath();'+
				'bindSurveyForm();'+
				'if (typeof(scroll_to_top) != "undefined" && scroll_to_top == \'true\')scroll(0,0);';

				//'bindRejestrMod();' +
				//'bindRegisterForm();';
				
				if (module == 'DocflowRegistries'){
					callback += 'bindRegistries();';
					callback += 'top_buttons_deactiv();';
				}

		if (method == 'null' || method == null) method = 'defaultMethod';
		var data = "class="+module+"&method=" + method;
		data += (typeof(param)!="undefined" && param !="") ? "&param="+param : "";


		var obj = {
			data: data,
			success: callback
		}

		ajaxQuery(obj);

	}
	
	
	/*
	 * stworz grida z rejestrami
	 */

	function createRegistryGrid(regId, name){

		var callback = '$("ul#leftMenu").find("span,a").removeClass("my");' +
				'$.cookie(\'bip_link\', \'' + bip_path + '?module=DocflowRegistries&method=getGrid&reg_id=' + regId + '\');' +
				'if (typeof(menu_sciezka_config) != "undefined" && menu_sciezka_config == \'true\')' +
				'$("#path").html(\'<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a> <div class="breadcrumbs_separator"></div> <a href="?module=DocflowRegistries" class="defaultModule">Rejestry publiczne</a><div class="breadcrumbs_separator"></div> <a class="menu_list2" href="?module=DocflowRegistries&method=getGrid&reg_id='+ regId + '">' + name +'</a>\');' +
				//link dla przeglądarek tekstowych
				'$("#text_page").attr({\'href\': \'index_text.php?module=DocflowRegistries&method=getGrid&reg_id='+regId +'\'});'+
				//'bindSiteMap();' +
				//'bindStats();' +
				'bindDefaultModule();' +
				'bindPath();';
				//'bindSearchMod(); ' +
				//'bindRejestrMod();' +
				//'bindRegisterForm();';

		var obj = {
			data: "class=DocflowRegistries&method=getGrid&reg_id=" + regId,
			success: callback
		}

		ajaxQuery(obj);

	}
	
	
	//pobierz tresc contentu po kliknieciu na przycisk gornego menu
	function getTopMenuContent(obj){
		$.ajax({
		  type: "POST",
		  url: "httprequest.php",
		  data: "class="+obj.id+"&method=defaultMethod",
		  dataType: "json",
		  success: function(resp){
		  	if ( obj.id != 'sios') 
		  		$("#text_page").attr({'href': 'index_text.php?module=' + obj.id});
		  	$("ul#leftMenu").find("span,a").removeClass("my");
		  	$.cookie('bip_link', bip_path + '?module=' + obj.id);
		  	$("#content").css("font-size", "13px");
		  	$(".in_content").css("font-size", "13px");
		  	if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true') {
			  		$("#path").html('<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a> <div class="breadcrumbs_separator"></div> <a class="menu_list2" href="?module='+ obj.id+ '">' + obj.firstChild.firstChild.nodeValue + '</a>');
					bindDefaultModule();
		  	}
		  	if (resp.content){
				$("#content").html(resp.content.data);	
				if (typeof(resp.content.js) != 'undefined') {
					eval(resp.content.js);
				}
				if(obj.firstChild.firstChild.nodeValue == "Wykaz danych o środowisku"){
			  		$.cookie('content_title', $("td#content td.x-panel-header,.panel-header,.x-panel-header-text")[0].innerHTML);
			  	}else{
			  		$.cookie('content_title', obj.firstChild.firstChild.nodeValue);
			  	}
			}
		  	if (resp.info){
		    	$("#content").prepend(resp.info);
		    }
		  	
			if (obj.id == 'writers'){
				$("#writers_tab").tablesorter({ 
            		headers: { 
               		 	1: { 
                    		sorter:'polskie' 
                		} ,
                		2: { 
                    		sorter:'polskie' 
                		} ,
                		3: { 
                    		sorter:'polskie' 
                		} ,
                		4: { 
                    		sorter:'polskie' 
                		}
            		} ,
            		sortList: [[0,0]] 
        			});
			}

			if (typeof(resp.error) != 'undefined') {
				showError(resp.error);
			}
			
			if (resp.time){
				$("#czas_generowania").html(resp.time);
			}
			bindSiteMap();
			bindStats();
			bindSios(); 
			bindPath();
			bindSearchMod(); 
			bindRejestrMod();
		  }
		});
	}
	
	//funkcja pobierajaca dane z formularza do przeslania i wywolujaca funkcje getRejestr()
	function getHistoryRejestr(page,history){
		var dat = 'class=rejestr&method=getDetails&page=' + page;
		if (typeof(history) == 'undefined') {
			jQuery.each($("form#form_rejestr :input"), function(i, val){
				dat += '&' + val.name + '=' + val.value;
			});
		} 
		else
			dat += history;

		addTohistory('getRejestr('+page+',\''+dat+'\')');
		getRejestr(page,dat);
	}
	
	//pobieranie danych szczegolowych o rejestrze
	function getRejestr(page,dat){
		$("ul#leftMenu").find("span,a").removeClass("my");
		var obj = document.getElementById('rejestr');
		activateCurrentTopMenuButton(obj);
		if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true') {
				$("#path").html('<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a> <div class="breadcrumbs_separator"></div> ' + obj.firstChild.firstChild.nodeValue);
			}
		
		$.ajax({
		  type: "POST",
		  url: "httprequest.php",
		  data: dat,
		  dataType: "json",
		  success: function(resp){
		  	$.cookie('bip_link', bip_path + '?module=rejestr&page='+page);
		  	$("#content").html(resp.content.data);
		  	if (resp.info)
		    	$("#content").prepend(resp.info);

			if (typeof(resp.error) != 'undefined')
				showError(resp.error);
			
			if (resp.time)
				$("#czas_generowania").html(resp.time);

			bindRejestr();
			bindPath();
			bindRejestrMod();
			
		  }
		});
	}
	
	//pobiera szczegolowe statystyki
	function getStats(offset){
		$.ajax({
		  type: "POST",
		  url: "httprequest.php",
		  data: "class=stats&method=defaultMethod&offset=" + offset,
		  dataType: "json",
		  success: function(resp){
			$.cookie('bip_link', bip_path + '?module=stats');
			if (resp.content.data)
				$("#content").html(resp.content.data);
			
		  	if (resp.info)
		    	$("#content").prepend(resp.info);

			bindStats();
			bindPath();
			if (resp.time)
				$("#czas_generowania").html(resp.time);
		  }
		});
	}

	//funkcja sprawdzająca czy podana wartośc jest liczbą
	function IsNumeric(sText){
	    var ValidChars = "0123456789.";
	    var IsNumber = true;
	    var Char;
	    for (i = 0; i < sText.length && IsNumber == true; i++) {
	        Char = sText.charAt(i);
	        if (ValidChars.indexOf(Char) == -1) {
	            IsNumber = false;
	        }
	    }
	    return IsNumber;
	}
	// funkcja pobierajaca dane z formularza wyszukiwarek
	function getHistorySearch(from,history,paging){
		var dat = 'class=search&method=_search';
		paging = paging || 0;

		if (from == 1) {
			if (typeof(history) == 'undefined' || history == '') {
				jQuery.each($("form#form_search :input"), function(i, val){
					var v = val.value;
					//v = v.replace(/\//g,'%2F');
					//v = v.replace(/'/g,'%27');	
					v = v.replace(/'/g,'');
					dat += '&' + val.name + '=' + v;
				});
				dat += '&offset=' + paging;
			} 
			else
				dat += history+"&offset="+paging;
	    } 
	    else if (from == 3) {
	    	var pageOffset = $("#paging_offset").val(); 
	    	var maxOffset = $("#max_offset").val(); 
			var page = $("#page_nr").val();
			
			if (parseInt(pageOffset) <= 0  ) {
				alert("Numer strony nie może być mniejszy niż 1.");
				$("#paging_offset").val(page);
				return false;
			}
		    if (IsNumeric(pageOffset) == false) {
				alert("Wpisano niepoprawną wartość pola.");
				$("#paging_offset").val(page);
				return false;
			}
			if (parseInt(pageOffset) > parseInt(maxOffset) ) {
				alert("Nie można wpisywać wartości większych niż liczba stron.");
				$("#paging_offset").val(page);
				return false;
			}
			if (typeof(history) == 'undefined' || history == '') {
				jQuery.each($("form#form_search :input"), function(i, val){
					var v = val.value;
					//v = v.replace(/\//g,'%2F');
					//v = v.replace(/'/g,'%27');	
					//v = v.replace(/%/g,'');
					v = v.replace(/'/g,'');
					dat += '&' + val.name + '=' + v;
				});

				jQuery.each($("form#paging_search :input"), function(i, val){
					if(val.name == 'offset')
					{ dat += '&offset=' + (val.value - 1); };
				});
				
			} else {
				dat += history+"&offset="+paging;
			}
	    }
	    else {
	    	top_buttons_deactiv();
			
			if (typeof(history) == 'undefined' || history == '') {
		    	jQuery.each($("form#mod_search :input"), function(i, val) {
					var v = val.value;
					//v = v.replace(/\//g,'%2F');
					//v = v.replace(/'/g,'%27');
					v = v.replace(/'/g,'');
		      		dat += '&' + val.name + '=' + v;
		    	});
		    	dat += '&offset=' + paging;
			} else
				dat += history;
	    }
		addTohistory('getSearch('+from+',\''+dat+'\')');
	}
	
	//pobiera szczegolowe wyszukiwanie
	function getSearch(from,dat){
		$("ul#leftMenu").find("span,a").removeClass("my");
		var obj = document.getElementById('search');
		activateCurrentTopMenuButton(obj);
		if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true') {
			
				$("#path").html('<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a> <div class="breadcrumbs_separator"></div> ' + obj.firstChild.firstChild.nodeValue);
		}
		$.ajax({
		  type: "POST",
		  url: "httprequest.php",
		  data: dat,
		  dataType: "json",
		  success: function(resp){
		  	border();
		  	$.cookie('bip_link', bip_path + '?module=search');
			$("#content").html(resp.content.data)
			$.cookie('content_title', obj.firstChild.firstChild.nodeValue);
		  	if (resp.info){
		    	$("#content").prepend(resp.info);
		    }
		    if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true')
				$("#path").html('<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a> <div class="breadcrumbs_separator"></div> Szukaj' );
			bindSearch();
			bindPath();
			bindSearchMod();
			if (resp.time){
				$("#czas_generowania").html(resp.time);
			}
		  }
		});
	}
	
	//pobiera szczegolowe sios
	function getSios(card,year,id){
		$.ajax({
		  type: "POST",
		  url: "httprequest.php",
		  data: "class=sios&method="+card+"&rok="+year+"&id="+id,
		  dataType: "json",
		  success: function(resp){
		  	$.cookie('bip_link', bip_path + '?module=sios&t=' + card + '&rok=' + year + '&id=' + id);
			$("#content").html(resp.content.data)
		  	if (resp.info){
		    	$("#content").prepend(resp.info);
		    }
		  	
		    $("#rejestr_tab").tablesorter({ 
		        0: {sorter:"integer"},
		        headers: {
					1: {
		        		sorter: false
		        	},
		        	3: {
		        		sorter: false
		        	}
		        } 
	    	});
			bindSios(); 
			bindPath();
			if (resp.time){
				$("#czas_generowania").html(resp.time);
			}
		  }
		});
	}
	
	
	
	
	
	
	
	function clickMenuGetContents(id,page,arch){
		$("ul#leftMenu").find("span,a").removeClass("my");
		addMy($("#"+id).find("a"));

		getContents(id,page,arch);

	}

	function removeHTMLTags(param){
		var strInputCode = param;
		/* 
			This line is optional, it replaces escaped brackets with real ones, 
			i.e. < is replaced with < and > is replaced with >
		*/	
	 	param = param.replace(/&(lt|gt);/g, function (strMatch, p1){
		 	return (p1 == "lt")? "<" : ">";
		});
		var strTagStrippedText = param.replace(/<\/?[^>]+(>|$)/g, "");
		return strTagStrippedText;
	}	
	/*
	 * 
	 * FUNKCJE DO MAP GOOGLOWYCH
	 * 
	 */
	
	//ladowanie mapki google
	function load(markers,x,y) {
	  	$('#gmap').jmap('init',{
		 	mapCenter: [x, y],
			mapZoom: mapZoom
		});
		if (markers) {
		 	for (var i = 0; i < markers.length; i++) {
		 		var checkedDescribe = '';
				if(removeHTMLTags(markers[i].describe).trim() != ''){
					if(markers[i].describe.length >= 79) {
						checkedDescribe =  '<br/><b>Opis: </b>' + markers[i].describe.slice(0,79).trim() + ' ...';
					}
					else {
						checkedDescribe = '<br/><b>Opis: </b>' + markers[i].describe;
					}
				}
		 		$('#gmap').jmap("addMarker", {
					pointLatLng: [markers[i].x, markers[i].y],
//					pointHTML: markers[i].title + '<br/><hr style="margin: 3px;*margin: 0px;width: 250px;"/><b>Adres: </b>' + markers[i].address
					pointHTML 				:	markers[i].title + '<br/><hr style="margin: 3px;*margin: 0px;width: 250px;"/><b>Adres: </b>' + markers[i].address
												+ checkedDescribe   
					,pointMaxContent		:	markers[i].describe
					,pointMaxTitle			:	markers[i].title
					
				});
			}
		}
    }
	
	//funkcja do przemieszczania sie po punktach na mapie
	function goTo(x,y){
		$('#gmap').jmap("moveTo", {mapCenter: [x,y], centerMethod: "pan"});
	}
	
	//wycentruj mapke
	function mapCenter(){
		goTo(mapCenterX, mapCenterY);
	}
	
	//style dla listy obiektow na mapie
	function mapListHover(){
		$(".map_list_items").hover(
			function () {
				$(this).addClass('map_list_over');
		 	}, 
		   	function () {
				$(this).removeClass('map_list_over');
		  	}
		);
	}
	
	// wyszukiwanie adresow na mapie
	function mapFind() {
		$('#gmap').jmap("searchAddress", {
			address: $('#map_search').val()
		},
		function(options, point) {
			if (!point)
				alert('Nie można znaleźć lokalizacji: ' + $('#map_search').val());
			else {
				$('#gmap').jmap('addMarker', {pointLatLng:[point.y, point.x], pointHTML: options.address});	
			  	goTo(point.y, point.x);
				
				$("ul#map_list").append("<li class='map_list_items' onclick='goTo(" + point.y + "," + point.x + ")'>" + $('#map_search').val() + "</li>");
				mapListHover();
			}
		  });
	}
	
	
	
	
	/*
	 * 
	 * FUNKCJE DO MENU I OBSLUGI CONTENTU
	 * 
	 */
	
	//pokazuje rejestr zmian do konkretnego artykulu
	function pokazRejestr(cid) {
		if (document.getElementById('rej_tab')) {
			$("#rej_tab").remove();
			$("#pokaz_rejestr").text('Pokaż rejestr');
		}
		else { 
			$("#pokaz_rejestr").text('Ukryj rejestr');
			$.ajax({
			  type: "POST",
			  url: "httprequest.php",
			  data: "class=rejestr&method=getContentRejestr&cid=" + cid,
			  dataType: "json",
			  success: function(resp){
			  	$("#content").append(resp.content.data);
			  	if (resp.info)
			    	$("#content").append(resp.info);
				
				if (typeof(resp.error) != 'undefined')
					showError(resp.error);
			
				if (resp.time)
					$("#czas_generowania").html(resp.time);

				fixIEPng();
			  }
			});
		}
	}
	
	//pokaz index
	function getIndex(){
		$.ajax({
		  type: "POST",
		  url: "httprequest.php",
		  data: "class=index&method=defaultMethod",
		  dataType: "json",
		  success: function(resp){
		  	no_border();
		  	$.cookie('bip_link', bip_path);
		  	if (resp.content) {
		  		$("#content").html(resp.content.data);
				top_buttons_deactiv();
				//*************obsluga mapki****
					load(resp.content.markers,resp.content.mapCenterX,resp.content.mapCenterY);
					$("p#map_show").click(function(){
					 	if (!($("#map_search").val() == ''))
							mapFind();
						
					 });
					 $("#map_search").keypress(function(e){
						if (e.which == 13 && this.value != ''){
							mapFind();	
						}
					 });
					 mapListHover();
					 mapCenterX = resp.content.mapCenterX;
					 mapCenterY = resp.content.mapCenterY
				 //**************************
				 $("ul#leftMenu").find("span,a").removeClass("my");
				 
				 	$("#path").html('<div id="path_home"></div> <a class="menu_list" href="?id=0">Strona Główna</a>');
				 
				 bindPath();
		  	}
		  	if (resp.info)
		    	$("#content").prepend(resp.info);
			
			$.cookie('content_title', $("title")[0].text);
			if (typeof(resp.error) != 'undefined')
				showError(resp.error);
			
			if (resp.time)
				$("#czas_generowania").html(resp.time);

			fixIEPng();
		  }
		});
	}
	
	
	
	//pobierz artykul
	function getContent(id){
		$("#text_page").attr({'href': 'index_text.php?content=' + id});
		$.ajax({
			type: "POST",
			url: "httprequest.php",
			data: "class=content&method=defaultMethod&content=" + id,
			dataType: "json",
			success: function(resp){
			  	if (id == 0) no_border(); else border();
			  	if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true') {
		  			$("#path").html('<div id="path_home"></div> ' + resp.path);
		  		}
			  	if (resp.content.data) {
			  		$("#content").html(resp.content.data);
			  		$.cookie('bip_link',bip_path + '?content=' + id);
			  		$.cookie('content_title', $("td#content td.x-panel-header,td.panel-header")[0].innerHTML);
					$('#re_os').leviTip({sourceType: 'element', source: '#infoTipRe', hideSourceElement: true});
					$('#wpr_os').leviTip({sourceType: 'element', source: '#infoTipWpr', hideSourceElement: true});
			  	}
			  	
			  	if (typeof(resp.content.js) != 'undefined')
					eval(resp.content.js);
			  	
			  	if(typeof(resp.content.menu_id) != 'undefined')
					handleMenu(resp.content.menu_id);
				
			  	if (resp.info)
			    	$("#content").prepend(resp.info);
			  	
			  	$.cookie('content_title', $("td#content td.x-panel-header,.panel-header,.x-panel-header-text")[0].innerHTML);
				if (typeof(resp.error) != 'undefined')
					showError(resp.error);
	
			    top_buttons_deactiv();
//				bindOtherLinks();
				bindContents();  			
			  	bindPath();
				if (resp.time)
					$("#czas_generowania").html(resp.time);

				fixIEPng();	
				if (typeof(scroll_to_top) != 'undefined' && scroll_to_top == 'true')
				scroll(0,0);
			}
		});
	}
	
	//pobierz liste contentow z danego menu
	function getContents(id,page,arch, str){
		if (id == '0') {
			getIndex();
			return;
		}
		else {
			$.ajax({
				type: "POST",
				url: "httprequest.php",
				data: "class=content&method=getContents&id=" + id + "&page=" + page + (arch ? '&arch=1' : '') + (str ? '&str=1' : ''),
				dataType: "json",
				error: function(e){
					alert('Problem z pobraniem zawartości strony');
				},
				success: function(resp){
					//link dla przeglądarek tekstowych
					$("#text_page").attr({'href': 'index_text.php?id=' + id + '&page=' + page + (arch ? '&arch=1' : '') + (str ? '&str=1' : '')});
				  	$.cookie('bip_link', bip_path + '?id=' + id + '&page=' + page + (arch ? '&arch=1' : '') + (str ? '&str=1' : ''));
				  	if (typeof(menu_sciezka_config) != 'undefined' && menu_sciezka_config == 'true') {

				  			$("#path").html('<div id="path_home"></div> ' + resp.path);
				  		
				  	}
				  	if (typeof(resp.content) != 'undefined') {
				  		$("#content").html(resp.content.data);
				  		var title = $("td#content td.x-panel-header,td.panel-header");
				  		if(Ext.isDefined(title) && title.length > 0) {
				  			$.cookie('content_title', $("td#content td.x-panel-header,td.panel-header")[0].innerHTML);
				  		}
				  		if(typeof(resp.content.menu_id) != 'undefined')
				  			handleMenu(resp.content.menu_id);
	
						$('#re_os').leviTip({sourceType: 'element', source: '#infoTipRe', hideSourceElement: true});
						$('#wpr_os').leviTip({sourceType: 'element', source: '#infoTipWpr', hideSourceElement: true});
				  	}
				  	if (typeof(resp.content.js) != 'undefined')
						eval(resp.content.js);
					
				  	if (resp.info){
				    	$("#content").prepend(resp.info);
				    	$.cookie('content_title', $("td#content td.x-panel-header,td.panel-header")[0].innerHTML);
				    	}
					if (typeof(resp.error) != 'undefined')
						showError(resp.error);
					
				    top_buttons_deactiv();
				    
					
//					bindOtherLinks();
					enableListHover();
					bindPath();
					bindContents();
					if (resp.time)
						$("#czas_generowania").html(resp.time);
					
					fixIEPng();				
				}
			});
			if (typeof(scroll_to_top) != 'undefined' && scroll_to_top == 'true')
				scroll(0,0);
		}
	}
	
function handleMenu(menu_id) {
	if (!menu_loaded){
		$("#leftMenu").empty();
		$("#leftMenu").treeview({
			url: "httprequest.php",
			main: 1,
			id: menu_id
		});
		menu_loaded=true;
	}
	$("ul#leftMenu").find("span,a").removeClass("my");
	addMy($("#"+menu_id+" span:first"));
}
/*
function handleMenu(menu_id) { 		
	if (typeof(expanded_all) == 'undefined' && withMenu == true ){
		if (menu_id == null && !menu_loaded) {
			$("#leftMenu").empty();
			$("#leftMenu").treeview({
				url: "httprequest.php"
			});
			menu_loaded = true;
		}
		else
			refresh(menu_id);
	}
	else if(!menu_loaded) {
		$("#leftMenu").empty();
		$("#leftMenu").treeview({
			url: "httprequest.php"
		});
		menu_loaded = true;	
	}
	else {
		$("ul#leftMenu").find("span,a").removeClass("my");
		addMy($("#"+menu_id+" span:first"));
	}
}
*/	
	

	//wlacz style hover na liscie contentow
	function enableListHover(){
		$("td.list_content").hover(
	      function () {
		  	
			if ($(this).hasClass('arch_item')){
				$(this).find("div.list_content_a").removeClass('inactive_list_item_arch');
			}
			else {
				$(this).find("div.list_content_a").removeClass('inactive_list_item');
			}
			
			$(this).find("div.list_content_a").addClass('active_list_item');
	        $(this).find("div.list_content_a").find("a").css("text-decoration", "underline");
	      }, 
	      function () {
		  	$(this).find("div.list_content_a").removeClass('active_list_item');
		  	if ($(this).hasClass('arch_item')) {
				$(this).find("div.list_content_a").addClass('inactive_list_item_arch');
			}
			else {
				$(this).find("div.list_content_a").addClass('inactive_list_item');
			}
			
	        $(this).find("div.list_content_a").find("a").css("text-decoration", "none");
	      }
	    );
	}


	/*
	 * refresh rozwinietego menu
	 *
	 * @param int id - id menu do ktorego ma sie rozwinac
	 */

function refresh(id){
	$("#leftMenu").empty();

	$("#leftMenu").treeview({
		url: "httprequest.php",
		main: 1,
		id: id,
		prerendered: false
	});
	menu_loaded = true;
}

	
	//usuwanie obramowania glownego contentu
	function no_border() {
		$("td#content").removeClass("content_border");
		$("td#content").addClass("content_no_border");
	}
	
	//dodaje obramowanie glownego contentu
	function border() {
		$("td#content").removeClass("content_no_border");
		$("td#content").addClass("content_border");
	}
	
	// funkcja dodajaca pogrubienie na konkretny obiekt menu
	function addMy(item){
		item.addClass("my");
	}
	
	
	
	/*
	 * 
	 * FUNKCJE STATUSU SPRAW
	 * 
	 */
	
	
	//funkcja do pobrania statusu spraw
	function getStatusCase(uid){
		$.ajax({
			type: "POST",
			url: "httprequest.php",
			data: "class=search_status&method=defaultMethod&search_status_value=" + uid,
			dataType: "json",
			success: function(resp){
				if (resp.content.data) {
					$("#content").html(resp.content.data);
					border();
					bindSearchStatusInContent();
					//showInfoSearchStatus()
					$("#pokazInstrukcje").click(function(){
						$("#instrukcjaS").slideToggle('slow');
					});
					$("#pokazInstrukcje").toggle(function(){
						$(this).text('ukryj');
					},function(){
						$(this).text('pokaż');
					})
				}
				if (resp.time){
					$("#czas_generowania").html(resp.time);
				}
			}
		});
	}	
	
	/*
	 *
	 * FUNKCJE RSS
	 * 
	 */
	
	function getRss(class_name){
		window.open('?module=' + class_name);
	}
	
	
	
	/*
	 *
	 * FUNKCJE KALENDARZA
	 *
	 */


//aktywne / nieaktywne pola daty przy rejestrze zmian
function selectPeriod(value) {
	if (value=='period') {
		document.getElementById('periodFrom').disabled=false;	
		document.getElementById('periodTo').disabled=false;	
	} else {
		document.getElementById('periodFrom').disabled=true;	
		document.getElementById('periodTo').disabled=true;	
		document.getElementById('periodFrom').value='';
		document.getElementById('periodTo').value='';
		
	}
}


// JS Calendar
var calendar = null; // remember the calendar object so that we reuse
// it and avoid creating another

// This function gets called when an end-user clicks on some date
function selected(cal, date) {
	cal.sel.value = date; // just update the value of the input field
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks the "Close" (X) button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
	cal.hide();			// hide the calendar

  // don't check mousedown on document anymore (used to be able to hide the
  // calendar when someone clicks outside it, see the showCalendar function).
	Calendar.removeEvent(document, "mousedown", checkCalendar);
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
function checkCalendar(ev) {
  var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
  for (; el != null; el = el.parentNode)
  // FIXME: allow end-user to click some link without closing the
  // calendar.  Good to see real-time stylesheet change :)
  if (el == calendar.element || el.tagName == "A") break;
  if (el == null) {
    // calls closeHandler which should hide the calendar.
    calendar.callCloseHandler(); Calendar.stopEvent(ev);
  }
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id) {
  var el = document.getElementById(id);
  if (calendar != null) {
    // we already have one created, so just update it.
    calendar.hide();		// hide the existing calendar
    if (el.value=='rrrr-mm-dd') {
      tmpData = new Date(); //getFullYear(), getMonth(), el.caldate);
      calendar.parseDate(tmpData.getFullYear()+"-"+tmpData.getMonth()+"-"+tmpData.getDate()); // set it to a new date
      }
    else
      calendar.parseDate(el.value); // set it to a new date
  } else {
    // first-time call, create the calendar
    var cal = new Calendar(true, null, selected, closeHandler);
    calendar = cal;		// remember the calendar in the global
    cal.setRange(1900, 2070);	// min/max year allowed
    calendar.create();		// create a popup calendar
  }
  calendar.sel = el;		// inform it about the input field in use
  calendar.showAtElement(el);	// show the calendar next to the input field

  // catch mousedown on the document
  Calendar.addEvent(document, "mousedown", checkCalendar);
  return false;
}


/*
 * funkcja wyswietlania bledu
 * 
 * @param string text - tresc bledu
 */

function showError(text) {
	//Ext.Msg.alert('Błąd', text);
	
	$("div#error_panel").remove();
	$("div#info_panel").remove();
	
	$("#content").prepend(makeErrorPanel(text));
	$.scrollTo("div#error_panel",100);
	
	bindNotificationCloseButton();
}


/*
 * funkcja budujaca panel bledu
 * 
 * @param string text - tresc bledu
 */

function makeErrorPanel(text){
	var html = '<div id="error_panel" style="margin-bottom: 10px;"><div class="error-panel-header x-unselectable">Błąd</div>' + 
	'<div class="error-panel-body x-panel-body-padding">' + text + '</div></div>';
	
	return html;
}


/*
 * funkcja wyswietlania info
 * 
 * @param string text - tresc info
 */

function showInfo(text) {
	//Ext.Msg.alert('Informacja', text);
	
	$("div#info_panel").remove();
	$("div#error_panel").remove();
	
	$("#content").prepend(makeInfoPanel(text));
	$.scrollTo("div#info_panel",100);
	
	bindNotificationCloseButton();
}


/*
 * funkcja budujaca panel info
 * 
 * @param string text - tresc info
 */

function makeInfoPanel(text){
	var html = '<div id="info_panel" style="margin-bottom: 10px;"><div class="info-panel-header x-unselectable">Informacja</div>' + 
	'<div class="info-panel-body x-panel-body-padding">' + text + '</div></div>';
	
	return html;
}


/*
 * funkcja do zapytan ajaxowych
 *
 * @param object obj - obiekt z danymi do zapytania
 */

function ajaxQuery(obj){
	$.ajax({
		type: (typeof(obj.type) != 'undefined' ? obj.type : "POST"),
		url: (typeof(obj.url) != 'undefined' ? obj.url : "httprequest.php"),
		data: obj.data,
		dataType: "json",
		success: function(resp){
			
			if (typeof(resp.content) != 'undefined'){
				if (typeof(resp.content.data) != 'undefined') {
					$("#content").html(resp.content.data);
					if( typeof($("td#content td.x-panel-header,.panel-header,.x-panel-header-text")[0]) != 'undefined') {
						if($("td#content td.x-panel-header,.panel-header,.x-panel-header-text")[0].innerHTML == "Rejestry") {
							$.cookie('content_title', 'Rejestry');
						}
						else if($("td#content td.x-panel-header,.panel-header,.x-panel-header-text")[0].innerHTML == "Ankieta") {
							//ciasto generowane dla ankiet jest po stronie php
							//if musi być inaczej ciastko było nadpisywane
						}
						else {
							$.cookie('content_title', $("td#content td.x-panel-header,.panel-header,.x-panel-header-text")[0].innerHTML);
						}
					}
				}

				$("#boxContextMenu").empty();
				if (typeof(resp.content.js) != 'undefined') {
					eval(resp.content.js);
				}
				if (typeof(resp.content.contextMenu) != 'undefined'){
					$("#boxContextMenu").html(resp.content.contextMenu);
				}

				if (typeof(resp.content.boxLogin) != 'undefined') {
					$("div#boxLogin").html(resp.content.boxLogin);
					if (typeof(resp.error) != 'undefined') {
						bindLoginForm();
					}
				} 

				if (typeof(resp.content.info) != 'undefined') {
					showInfo(resp.content.info);
					//bindNotificationCloseButton();
				}

				if (typeof(resp.content.popUpUrl) != 'undefined'){

					var printFormWin = window.open(
							resp.content.popUpUrl,
							"printForm",
							"scrollbars, resizable, status"
							);

					if (printFormWin) {

						printFormWin.focus();
						printFormWin.print();
					}
				}
			}
			if (typeof(resp.path) != 'undefined'){
				$("#path").html('<div id="path_home"></div> ' + resp.path);
			}


			/*
			if (typeof(resp.error) != 'undefined'){

		    	$("body").prepend(resp.error);
				$("div.info").slideDown('slow').fadeIn('slow');

				//przycisk do zamkniecia gornego paska "info"
		 		$(".close_info_bar").show();
				$(".close_info_bar").click(function(event){
				   event.preventDefault();
				   $(this.parentNode.parentNode).hide("slow",function(){$(this).remove();});
				 });
		    } */
			if (typeof(resp.error) != 'undefined') {
				showError(resp.error);
				//bindNotificationCloseButton();
			}

			if (typeof(resp.time) != 'undefined'){
				$("#czas_generowania").html(resp.time);
			}


			if ("function" === typeof(obj.success)) {

				obj.success(resp);
			}
			else if (typeof(obj.success) != 'undefined'){

				eval(obj.success);
			}

			$("a.showTooltip,img.showTooltip").tooltip({
				position: ['bottom', 'left'],
				offset: [2, 10],
				effect: 'toggle',
				opacity: 0.7
			});
		},
		error: function(e){
			showError('Wystąpił błąd');
		}

	});
}



/*
 * przetwarzanie danych formularza do obiektu
 *
 * @param object o - formularz
 * @param string callback - funkcja ktora ma sie wywolac po sukcesie zapytania ajaxowego
 * @return object - obiekt gotowy do wyslania do funkcji ajaxQuery(obj)
 */

function formToAjaxFunction(o,callback,checkRequired,validate){
	if (typeof(callback) == 'string'){
		var obj = {
			success: callback
		}
	} else {
		var obj = {}
	}

	var data = {};
	$("span.errorFormFieldValueInfo").remove();
	if (checkRequired == true) {

		var required = {};
		var err = false;
		var errFields = 'Wypełnij wszystkie wymagane pola: ';
		var err1 = '';
		var err2 = '';
	}

	jQuery.each(o.elements, function(i, val){

		if (checkRequired == true){
			if (val.type == 'radio' || val.type == 'checkbox'){

			if ($(val).parent().parent().parent().hasClass("required")){

					var fieldId = $(val).parent().parent().attr('id');

					if (typeof(eval('required.' + fieldId)) != 'undefined'){
						if (val.checked == true) required[fieldId] = true;
					}
					else {
						if (val.checked != true) required[fieldId] = false;
						else if (val.checked == true) required[fieldId] = true;
					}
				}
			}
			else if ($(val).hasClass("required") && Validate.isEmpty(val.value)){
				err = true;
				err1 += $(val).prev()[0].firstChild.nodeValue;
			}
		}

		if (validate == true){

			if (!Validate.check(val)){
				$(val).parent().append('<span class="errorFormFieldValueInfo">Niepoprawnie wypełnione pole</span>');
				err = true;
				err2 = 'Niepoprawne dane w polach.';
			}
		}


		if (val.disabled == false){
			if (val.type == 'checkbox'){
				if (val.checked == true)
					data[val.name] = val.value;
				else
					data[val.name] = '';
			}

			if (val.type == 'radio' && val.checked == true)
				data[val.name] = val.value;


			if (val.type == 'text' || val.type == 'textarea' || val.type == 'password' || val.type == 'hidden'){
				//if (val.value != '')
					data[val.name] = val.value;
			}

			if (val.type == 'select-one'){
				//if (val.value != '')
					data[val.name] = val.value;
			}

			if (val.type == 'select-multiple'){

				var valuesList = $(val).val();

				if (null !== valuesList) {

					data[val.name] = valuesList;
				}
			}
		}
	});

	if (checkRequired == true){
		//sprawdzamy czy wszystkie wymagane pola sa wypelnione

		for (var i in required){
			if (required[i] == false) {
				err1 += $("#"+i).parent().prev()[0].firstChild.nodeValue;
				err = true;
			}
		}

		if (err === true) {
			if (err1 != ''){
				showError(errFields+err1+'<br/>'+err2);
			} else {
				showError(err2);
			}

			//bindNotificationCloseButton();

			return false;
		}
	}


	if (typeof(o.action) != 'undefined' && o.action != ''){
		var action = o.action;
		var action = action.split('?')[1];
		var vars = action.split('&');

		if (typeof(vars[0]) != 'undefined'){
			var _class = vars[0];
			data['class'] = _class.split('=')[1];
		}

		if (typeof(vars[1]) != 'undefined'){
			var _method = vars[1];
			data['method'] = _method.split('=')[1];
		}
	}


	obj.url = 'httprequest.php'
	obj.data = data;

	return obj;
}

	/**
	 * Submituje głos z ankiety
	 * @param {Object} obj
	 */
	function submitSurveyVote(obj){
		obj.data['class'] = 'Survey';
		obj.data.method = 'vote'
		
		ajaxQuery(obj);
	}

	function fixIEPng() {
		// obsluga png dla ie6
		if ($.browser.name == 'msie' && $.browser.version == '6.0') {
			$.getScript("smarty/templates/js_front_plugins/jquery.pngFix.pack.js",function(){
				try {
					$(document).pngFix();
				} catch (e){
					alert(e);
				}
			});
		}
	}
	/**
	 * 
	 * SIOS
	 */
	function prepareIdsList(items,fieldName){
		var ids = new Array();
	
		Ext.each(items, function(item){
			ids.push(eval('item.' + fieldName));
		});
	
		var idsList = ids.join(",");
	
		return idsList;

	}
	
	function printSiosCard( row) {

		var obj = {
				data: 'class=Sios&method=printSiosCard&id=' + row.data.card_id,
				success: function(resp){
					window.open(resp);

				}
		}
		ajaxQuery(obj);

	}
	
	//Zaawansowana wyszukiwarka SIOS
	function advSearchSios( data ) {
		var docType = 0;
		var stateId = -1;
		var powiatId = -1;

		if( data.search_type_id ) {
			docType = data.search_type_id;
		}
		if( data.state_id ) {
			stateId = data.state_id ;
		}
		if( data.powiat_id ) {
			powiatId = data.powiat_id ;
		}
		
		var searchDocType = new Ext.data.JsonStore({
			url: 'httprequest.php',
			root: 'result',
			autoLoad: true,
			remoteSort: true,
			fields: ["type_id", "type_description"],
			baseParams: {
				'class': 'Sios',
				method: 'getDocTypes'
			},
			listeners: {
				load: function(){
					if( docType > 0 )
						Ext.getCmp('search_type_id').setValue(docType); 

				},
				scope: this
			}
			
		});
		
		var searchWojewodztwa = new Ext.data.JsonStore({
			url: 'httprequest.php',
			root: 'result',
			remoteSort: false,
			autoLoad: true,
			fields: ['state', 'id'],
			baseParams: {
				'class': 'Sios',
				method: 'getRegion',
				'parent_id' : 0
			}
			
		});
		
		var searchPowiaty = new Ext.data.JsonStore({
			url: 'httprequest.php',
			root: 'result',
			remoteSort: false,
			autoLoad: true,
			fields: ['state', 'id'],
			baseParams: {
				'class': 'Sios',
				method: 'getRegion',
				'parent_id' : stateId
			}
		});
		
		var searchGmina = new Ext.data.JsonStore({
			url: 'httprequest.php',
			root: 'result',
			remoteSort: false,
			autoLoad: true,
			fields: ['state', 'id'],
			baseParams: {
				'class': 'Sios',
				method: 'getRegion',
				'parent_id' : powiatId
			}
		});	
	
		var searchDocTitle = new Ext.data.SimpleStore( {
			fields: [ "text" ],
			data: [
				[ 'Ochrona powietrza' ],
				[ 'Ochrona wód' ],
				[ 'Ochrona powierzchni ziemi' ],
				[ 'Ochrona przed hałasem' ],
				[ 'Ochrona przed polami elektromagnetycznymi' ],
				[ 'Ochrona kopalin' ],
				[ 'Ochrona zwierząt oraz roślin' ],
				[ 'Inny' ]
				]
			} );
		

	
		var searchWindow = new Mk.Window({
						title: 'Wyszukiwanie zaawansowane',
						width: 810,
						buttonAlign: 'center',
						items: new Mk.Form({
							id: 'siosSearchForm'
							,labelWidth: 200
							,border: false
							,autoScroll: true
							,layout: 'table'
							,defaults: {
//								xtype: 'fieldset'
								width: 410
								,labelWidth: 200
								
							}
							,layoutConfig: {
						        columns: 2
						        
			   				}
							,items: [
								{
								border: false
								,id: 'document-fieldset'
								,defaults: {
									xtype: 'fieldset'
									,labelWidth: 120
								}
								,items: [ {
										title: 'Dokument'
										,layout: 'form'
										,defaults: {
											anchor: '-10'
											,labelWidth: 80
										}
										,items: [{
												xtype: 'textfield'
												,fieldLabel: 'Nr karty'
												,name: 'search_card_nr'
												,id: 'search_card_nr'
											},{
												xtype: 'combo'
												,name: 'search_type_id'
												,id: 'search_type_id'
												,mode: "local"
												,ref: '../typeSearchCombo'
												,fieldLabel: 'Rodzaj dokumentu'
												,store: searchDocType
												,valueField: "type_id"
												,editable: false
						        				,lazyRender: true
						        				,triggerAction: "all"
												,displayField: "type_description"
												,forceSelection: true
												,hiddenName: "type_id"
												,emptyText: '--Wszystkie--'
											},{
												xtype: 'combo'
												,fieldLabel: 'Temat dokumentu'
												,name: 'search_doc_subject'
												,id: 'search_doc_subject'
												,store: searchDocTitle
												,valueField: "text"
												,displayField: "text"
												,typeAhead: true
												,mode: "local"
												,forceSelection: true
												,triggerAction: "all"
												,selectOnFocus: true
												,emptyText: '--Wszystkie--'
											},{
												xtype: 'textfield'
												,fieldLabel: 'Nazwa dokumentu'
												,name: 'search_doc_name'
												,id: 'search_doc_name'
											},{
												layout: 'table'
												,style: 'padding: 0px;'
												,border: false
												,defaults: {
													bodyStyle: 'padding: 0px;'
													,border: false
												}
												,layoutConfig: {
							       					 columns: 3
							        				,tableAttrs: {
			            								style: {
			                								width: '100%'
											            }
										        	}
				   								}
				   								,items: [{
				   									width: 120
				   									,cls: 'fieldset-date'
				   									,autoScroll: false,
				   									html: '<span class="siosLabel">Data wydania:</span>'
				   									,items: [{
					   									xtype: 'label'
														,fieldLabel: 'Data wydania'
														,autoScroll: false
													
				   									}]
				   									
				   								},{
			//										width: 170
				   									width: 120
				   									,style: 'padding-right: 0px;  padding-left: 0px;  padding-top: 0;  padding-bottom: 0;'
				   									,cls: 'fieldset-date'
				   									,autoScroll: false
													,items: [{
			//											xtype: 'textfield'
														autoScroll: false,
														id: 'search_doc_from'
														,hideLabel: true
														,xtype: 'datefield'
														,format: 'd-m-Y'
														,name: 'search_doc_from'
														,emptyText: 'Data od'
														,width: 95
														,listeners: {
															select: function (dd, newVal) {
																Ext.getCmp('search_doc_to').setMinValue(newVal);
															}
														}
			
													}]
												},{
													width: 120
													,autoScroll: false
													,cls: 'fieldset-date'
													,style: 'padding-right: 0;  padding-left: 0px;  padding-top: 0;  padding-bottom: 0;'
													,items: [{
														xtype: 'datefield'
														,format: 'd-m-Y'
														,hideLabel: true
														,autoScroll: false
														,width: 95
														,id: 'search_doc_to'
														,name: 'search_doc_to'
														,emptyText: 'Data do'
														,listeners: {
															select: function (dd, newVal) {
																Ext.getCmp('search_doc_from').setMaxValue(newVal);
															}
														}
													}]
												}
				   								]
				   								   								
				   								
											}]
									},{
										title: 'Obszar, którego dokument dotyczy'
										,layout: 'form'
										,defaults: {
											anchor: '-10'
											,labelWidth: 80
											,xtype: 'textfield'
										}
										,items: [{
												xtype: 'combo'
												,fieldLabel: 'Województwo'
												,id: 'search_state'
												,store: searchWojewodztwa
												,valueField: "state"
												,displayField: "state"
												,typeAhead: true
												,mode: "local"
												,forceSelection: true
												,triggerAction: "all"
												,selectOnFocus: true
												,emptyText: '--Wybierz--'
												,listeners: {
			
														select: function (combo, newVal, oldVal) {
															Ext.getCmp('search_gmina').clearValue();
															Ext.getCmp('search_powiat').clearValue();
			                  								searchPowiaty.load({params:{parent_id: newVal.id}});
			                  								searchGmina.load({params:{parent_id: -1}});
														},
														change: function (combo, newVal, oldVal) {
																if( newVal.replace(/^\s+|\s+$/g, '') == '') {
																	Ext.getCmp('search_gmina').clearValue();
																	Ext.getCmp('search_powiat').clearValue();
																	searchPowiaty.load({params:{parent_id: -1}});
			                  										searchGmina.load({params:{parent_id: -1}});
																}
														},
														scope: this
												}
											},{
												xtype: 'combo'
												,fieldLabel: 'Powiat'
												,id: 'search_powiat'
												,store: searchPowiaty
												,valueField: "state"
												,displayField: "state"
												,typeAhead: true
												,mode: "local"
												,forceSelection: true
												,triggerAction: "all"
												,selectOnFocus: true
												,emptyText: '--Wybierz--'
												,listeners: {
			
														select: function (combo, newVal, oldVal) {
															Ext.getCmp('search_gmina').clearValue();
			                  								searchGmina.load({params:{parent_id: newVal.id}});
														},
														change: function (combo, newVal, oldVal) {
																if( newVal.replace(/^\s+|\s+$/g, '') == '') {
																	Ext.getCmp('search_gmina').clearValue();
																	searchGmina.load({params:{parent_id: -1}});
																}
														},
														scope: this
												}
											},{
												xtype: 'combo'
												,fieldLabel: 'Gmina'
												,id: 'search_gmina'
												,name: 'gmina'
												,store: searchGmina
												,valueField: "state"
												,displayField: "state"
												,typeAhead: true
												,mode: "local"
												,forceSelection: true
												,triggerAction: "all"
												,selectOnFocus: true
												,emptyText: '--Wybierz--'
											}]
									}] 
							},{
								border: false
								,id: 'zakres-fieldset'
								,width: 380
								,height: '100%'
								,layout: 'table'
								,defaults: {
									xtype: 'fieldset'
								
								}
								,style: 'position: absolute; top: 10px;'
								,layoutConfig: {
							       					 columns: 1
							       					 ,tableAttrs: {
			            								style: {
			                								width: '100%'
											            }
											        }
				        
	   							}
								,items: [ {
										border: false
										,layout: 'form'
										,defaults: {
											anchor: '0'
											,xtype: 'textfield'
											,labelWidth: 80
										}
										,items: [{
												xtype: 'label'
												,html: '<span class="siosLabel">Zakres przedmiotowy dokumentu - opis dokumentu</span>'
												
											},{
												hideLabel: true
												,id: 'search_doc_description'
												,name: 'doc_description'
											},
											{
												fieldLabel: 'Znak sprawy'
												,id: 'search_case_sign'
												,name: 'case_sign'
											},{
												fieldLabel: 'Dokument wytworzył'
												,id: 'search_case_auhtor'
												,name: 'case_auhtor'
											},{
												fieldLabel: 'Dokument zatwierdził'
												,id: 'search_case_mod'
												,name: 'case_mod'
											}]
										},{
											layout: 'table'
											,border: false
											,style: 'padding: 0px;'
											,defaults: {
												border: false
												,labelWidth: 50
											}
											,layoutConfig: {
							       					 columns: 2
							       					 ,tableAttrs: {
			            								style: {
			                								width: '100%'
											            }
											        }
							        
				   							}
											,items: [{
													colspan: 2
													,labelWidth: 250
													,cls: 'fieldset-date'
													,html: '<span class="siosLabel">Data zamieszczenia w wykazie</span>'
	//										,labelWidth: 250
													,style: 'padding-bottom: 0; padding-top: 0; padding-left: 10px; '
												},{
													width: 180
													,autoScroll: false
													,layout: 'form'
													,cls: 'fieldset-date'
													,style: 'padding-bottom: 0; padding-top: 0; padding-left: 10px; '
													,items: [{
														
														fieldLabel: 'Od'
														,width: 95
														,id: 'search_date_from'
														,name: 'date_from'
														,emptyText: 'Data'
														,xtype: 'datefield'
														,format: 'd-m-Y'
														,emptyText: 'Data od'
														
														,listeners: {
															select: function (dd, newVal) {
																Ext.getCmp('search_date_to').setMinValue(newVal);
															}
														}
													}]
												},{
													width: 180
													,autoScroll: false
													,layout: 'form'
													,cls: 'fieldset-date'
													,items: [{
														xtype: 'datefield'
														,fieldLabel: 'Do'
														,width: 95
														,id: 'search_date_to'
														,name: 'date_to'
														,format: 'd-m-Y'
														,autoScroll: false
														,emptyText: 'Data do'
														,listeners: {
															select: function (dd, newVal) {
																Ext.getCmp('search_date_from').setMaxValue(newVal);
															}
														}
													}]
												}]
										}
								] 
							}
							]
						})
						,buttons: [{
							text: 'Szukaj'
							,handler: function(){ 
								
								Ext.getCmp('siosGrid').store.load({
									params: {
										'search_card_nr': Ext.getCmp('search_card_nr').getValue(),
										'type_id': Ext.getCmp('search_type_id').getValue(),
										'doc_subject': Ext.getCmp('search_doc_subject').getValue(),
										'search_doc_from': Ext.getCmp('search_doc_from').getValue(),
										'search_doc_to': Ext.getCmp('search_doc_to').getValue(),
										'doc_name': Ext.getCmp('search_doc_name').getValue(),
										'state': Ext.getCmp('search_state').getValue(),
										'powiat': Ext.getCmp('search_powiat').getValue(),
										'gmina': Ext.getCmp('search_gmina').getValue(),
										'doc_description': Ext.getCmp('search_doc_description').getValue(),
										'case_sign': Ext.getCmp('search_case_sign').getValue(),
										'case_auhtor': Ext.getCmp('search_case_auhtor').getValue(),
										'case_mod': Ext.getCmp('search_case_mod').getValue(),
										'date_from': Ext.getCmp('search_date_from').getValue(),
										'date_to': Ext.getCmp('search_date_to').getValue()
									}
								});
								searchWindow.close();
							}
						},{
							text: 'Zamknij'
							,handler: function(){ searchWindow.close();}
						}]
				
					});
				
					searchWindow.center();
					Ext.getCmp('siosSearchForm').getForm().setValues(data);
					
	}
	/*
	 * pobieranie list plikow do zaznaczonych dokumentow
	 *
	 * @param array rows - tablica obiektow wierszy z grida
	 * @param string type - typ grida z dokumentami
	 */
	
	function showDetailsFromGrid(rows,type){

	if (typeof(type) != 'undefined'){
		
		if (type == 'sios'){
			

			var idsList = prepareIdsList(rows,'json.card_id');
			var obj = {
				data: 'class=Sios&method=getSiosDetails&ids=' + idsList,
				success: function(resp){

					var window = new Mk.Window({
						title: 'Karta informacyjna',
						buttonAlign: 'center',
						items: [
								new Ext.Panel({
									autoScroll: true,
									border: false,
									bodyStyle: 'padding:10px;',
									html: resp
								})
												
							],
						buttons: [{
							text: 'Zamknij'
							,handler: function(){ window.close();}
						}]
				
					});
				
					//window.show();
				}
			}
			ajaxQuery(obj);
		}

	}
	/*
	 * End SIOS
	 */
	
}
