//name space for any global function.
// Please extend this object if you create any function or define any variable
// Sample:
/*
//namespace
var encjaNS = {};

//create global function:
encjaNS.yourFn = function(){  yourCode }

//create global variable
encjaNS.yourVar = yourValue


*/
var encjaNS = {};

//ajax reference holder
encjaNS.ajaxiesRef = new Array();
//Ajax for encjacom (wrapper
encjaNS.ajax = function(o){

	var o = $.extend({
		url			: null,
		data  		: {},
		beforeSend	: null,
		complete	: null,
		type		:'POST',
		cancel		: true,
		clear		: false,
		global		: false


	},o);
	//tell server I'm ajax
	//	o.data = $.extend({ajax:1},o.data);
	//abort any active ajax ref
	if( o.clear ) {
		encjaNS.abortAjaxies();
	}

	var ajaxHandler = $.ajax(o);
	//if ajax can be aborted add its reference
	if( o.cancel ) {

		encjaNS.rejestrAjax(ajaxHandler);
	}
	return ajaxHandler;
}

//add reference to array
encjaNS.rejestrAjax = function(obj)
{
	encjaNS.ajaxiesRef.push(obj);

}

//for each element of array cancel ajax request
encjaNS.abortAjaxies =  function ()
{

	for ( a in encjaNS.ajaxiesRef ) {

		try{
			//			console.dir(jQuery.ajaxiesRef[a].open);
			//			console.info(jQuery.ajaxiesRef[a].open);
			encjaNS.ajaxiesRef[a].abort();
			encjaNS.ajaxiesRef[a] = null;

		}catch(e){
			console.info(e);
		}

	}
	encjaNS.ajaxiesRef = new Array();


}

encjaNS.submitFormByAjax = function ( formObj,complete, params )
{
	if( !params ) { var params = {} }
	formObj = $(formObj);
	var data = $(formObj).serialize();

	if ( params.constructor == String ) {
		data += '&'+params;
	} else if ( params.constructor == Object || params.constructor == Array ) {
		for( p in params ) {
			data += "&" + p + "=" + params[p];
		}
	}
	$('input,select,textarea',formObj).attr('disabled',true);
	encjaNS.ajax({
		type	:'POST',
		cancel	: false,
		url		: formObj.attr('action'),
		data	: data,
		complete: function(obj, status){

			$('input,select,textarea',formObj).attr('disabled',false);
			if( $.isFunction( complete )){

				complete( obj );
			}
		}

	});

}

encjaNS.reloadImageCode = function(idImg)
{
	$('img.'+idImg).attr('src',$('img.'+idImg).attr('src')+'b');
	return false;
}


//translation of javascript files
//encjaNS.dictionary is generated by PHP
encjaNS.transJS = function (name)
{
	if( typeof mainTplNS == 'undefined' ) {
		return false;
	}
	if( typeof mainTplNS.dictionary == 'undefined' || typeof mainTplNS.dictionary[name] == 'undefined'){
		return '';

	} else {

		return mainTplNS.dictionary[name];
	}

}
//ajaxowa aplikacja
encjaNS.startModule =  function (option)
{

	var option = $.extend({

		url			: '', //url
		type		:'GET', //type
		data		:{},	//data
		beforeSend	: null, //beforeSend(XMLHttpRequest)
		complete	: null, //complete(XMLHttpRequest, textStatus) or success(returnserver, status)
		async		: true,
		target		:'#center1',
		cancel		:true,
		clear       :true,
		show        :true,
		noHistory	:false
	},option);

	if( !option.noHistory ) {

		$.fn.encjaMenu.setHistory( option.url );

	}

	if ( option.clear ) {

		$(option.target).siblings().html('');
		$(option.target).siblings().hide('');

	}

	if ( option.show ) {

		$(option.target).show();

	}

	// raw_script potrzebny do modulu pomocy
	var raw_script = option.url.substr(0,option.url.indexOf('.php'))+'_controller';

	var target = option.target;

	if( typeof $(target)[0] == 'undefined' ) {
		return;
	}
	//remember story
	if( !option.crumbs ) {

		encjaNS.storeHistory(option.url,false,option.data);

	}
	
	if ( !option.customLoader ) {
	
		$(target).html('<div class="ui-ajax-onload" ></div>');
		
	} else {
		
		$(target).parents('#boxWrapper').children( '#loaderWrapper' ).html('<div class="ui-ajax-onload" ></div>');
		
	}

	//info for module to set ajax view
	option.data.ajax = 1;

	encjaNS.ajax({
		type		:option.type,
		url			:option.url,
		data		:option.data,
		beforeSend	:function(obj){
			if( $.isFunction( option.beforeSend )  ){
				
				option.beforeSend(obj);
				
			}
		},
		complete	:function(obj, status){

			$(target).html(obj.responseText);

			if( $.isFunction( option.complete )  ){
				
				option.complete(obj);
			}
		},
		cancel		:option.cancel,
		clear		:true

	});
}

encjaNS.restoreHistory = function()
{
	var clickOn = $.session('actualClick_asjson_');

	if( clickOn && clickOn.pop && clickOn.length - 2 >= 0){

		var o = {
			url: clickOn[clickOn.length - 2].url,
			data:clickOn[clickOn.length - 2].data,
			crumbs : true

		};

		clickOn.pop();

		$.session('actualClick_asjson_',clickOn);
		if( clickOn.length < 2 ) {
			$('#backInput').addClass('ui-history-buttonu-disable');
		}

		if( o.url.indexOf('_runnoajax') != (-1) ) {

			window.location.href = o.url.substr(0,o.url.indexOf('_runnoajax') );

		} else {

			encjaNS.startModule(o);
		}

	}


}
//function remember url. if sync function use window.location.href property to load page, else encjaNS.startModule function
encjaNS.storeHistory = function(url, sync,data )
{
	if( !data ) {
		var data = {};
	}
	var historyBack =  $.session('actualClick_asjson_') || new Array();
	if( sync ) {
		var url =  url+'_runnoajax';
	}

	//	if( url != historyBack[ historyBack.length-1] ) {
	historyBack.push({url:url,data:data});
	//	}

	$.session('actualClick_asjson_',historyBack);
	if( historyBack.length >= 2 ) {

		if( $('#backInput').size() > 0 ) {
			$('#backInput').removeClass('ui-history-buttonu-disable');
		} else {
			$(document).ready(function(){
				$('#backInput').removeClass('ui-history-buttonu-disable');
			});
		}
	}

}

encjaNS.mouseIsOver =  function(obj,e)
{
	var pos = $(obj).offset();
	var width = $(obj).width();
	var height = $(obj).height();

	if( e.pageX >= pos.left+2 && e.pageX <=pos.left + width -2  && e.pageY >= pos.top+2 && e.pageY <= pos.top + height-2 ) {

		return true;

	} else {
		return false;
	}
}


//przyjrzec sie dzialaniu w jqgridzie
encjaNS.setMiddle = function ( $obj )
{
	var tw = (jQuery(document).height() / 2) - ( $('#north').is(':visible') ? $('#north').height() : 0 );
	var lw = jQuery(document).width() / 2 ;
	var orgW = $obj.width()/2;
	var orgH = $obj.height()/2;
	var left = (lw-orgW) < 0 ? 0 : lw-orgW;
	var top = (tw-orgH) <0 ? 0 : tw-orgH;
	$obj.css({top: top+"px",left: left+"px"});
}

encjaNS.setCss = function(o)
{
	var o = $.extend({
		theme   : 'smoothness',
		pre		: ''
	},o);
	var t = $("<link rel='stylesheet' href='"+o.pre+"css/themes/"+o.theme+"/"+o.theme+".css' type='text/css' media='screen' />");
	var linkId = o.theme+'_cssframe';
	var oldCss = $('head').data('includedCss');
	t.attr('id',linkId);
	$('head').append(t);

	if( typeof oldCss != 'undefined' ){
		$('head #'+oldCss).remove();

	}
	$('head').data('includedCss',linkId);


}


//przerobic na jquery plugin
$.fn.makeSublist = function (parent,child,isSubselectOptional,childVal, obj)
{
	var that = this;

	if( typeof $('select#'+parent+child)[0] == 'undefined' ) {

		$("body").append("<select style='display:none' id='"+parent+child+"'></select>");
		$('#'+parent+child).html($("#"+child+" option", that));
	}


	var parentValue = $('#'+parent,that).attr('value');
	//wypelnienie dziecka wartosciami na podstawie indexu rodzica ale tylko podczas initu
	$('#'+child,that).html($("#"+parent+child+" .sub_"+parentValue).clone());

	//domyslna wartosc indexu w dziecku ktora trzeba zaznaczyc moze byc pusta
	childVal = (typeof childVal == "undefined")? "" : childVal ;

	//jezeli puste zrob disbled selecta ale tylko podczas initu
	if( $('#'+child,that).children().length == 0) {

		$("#"+child,that).attr('disabled','disabled');
		$('#'+child,that).prepend("<option value='0'>brak</option>")
	} else {

		if(isSubselectOptional) $('#'+child,that).prepend("<option value='0'> -- Wybierz -- </option>");
		$("#"+child,that).attr('disabled','');
	}
	$('#'+parent,that).unbind('change');
	//zdarzenie onchange rodzica
	$('#'+parent,that).change(
	function()
	{
		var parentValue = $('#'+parent,that).attr('value');
		//wypelnienie dziecka wartosciami na podstawie indexu rodzica
		$('#'+child,that).html($("#"+parent+child+" .sub_"+parentValue).clone());



		//jezeli puste zrob disbled selecta
		if( $('#'+child,that).children().length == 0) {

			$("#"+child,that).attr('disabled','disabled');
			$('#'+child,that).prepend("<option value='0'>brak</option>")
		} else {

			if(isSubselectOptional) {
				$('#'+child,that).prepend("<option value='0'> -- Wybierz -- </option>");
			}
			$("#"+child,that).attr('disabled','');
		}

		//zaznaczenie domyslnej opcje w select dziecko
		$('#'+child,that).trigger("change");
		$('#'+child,that).focus();
		$("#"+child+' option[value="0"]',that).attr('selected','selected');
	}
	);
	//zaznaczenie domyslnej opcji w dziecku ale tylko podczas initu
	$("#"+child+' option[value="'+ childVal +'"]',that).attr('selected','selected');
}

encjaNS.openWindow = function(o)
{


	var o = $.extend({
		dial			: {modal:true},
		content 		: '<div>no content set</div>',
		c				: '_dialog',//class if you want to know
		ajax			: null,
		rm				: true,
		parent			: 'body',
		onSubmit		: null,
		sData			: encjaNS.transJS('save') || 'Zapisz',
		onClose			: null,
		cData			: encjaNS.transJS('cancel') || 'Zakończ',
		noBtn			: false,
		setTime			: false

	},o);



	var wd = $('<div></div>');
	wd.addClass(o.c);
	if( o.setTime  && !o.ajax ) {
		wd.bind('dialogopen', function(event, ui) {
			setTimeout(function(){ wd.dialog("close") },o.setTime);
		});
		o.dial.resizable = false;

	}


	if( ! o.noBtn && !o.setTime ) {
		var btn = {};
		if( $.isFunction( o.onSubmit ) ) {
			var onSbm = function(){ o.onSubmit(wd); $(wd).dialog("close");};

			btn[o.sData] = onSbm ;

		}
		btn[o.cData] = function(){ $(wd).dialog("close"); } ;

		o.dial.buttons = $.extend(btn,o.dial.buttons);

	}

	o.dial = $.extend({
		autoOpen :true,
		title 	 :encjaNS.transJS('winTitle') || 'Okno',
		width	 : 500,
		zIndex	 :encjaNS.getMaxZindex(),
        modal:true
	},o.dial );

	if( $.isFunction( o.onClose) ) {
		wd.bind('dialogclose', function(event, ui) {
			o.onClose(event, ui);
		});
	}


	if( o.rm ) {
		wd.bind('dialogclose', function(event, ui) {
			setTimeout(function(){ $(wd).remove() },100);
		});
	}


	$(o.parent).append(wd);
	if( o.ajax ) {
		wd.html("<img src = '../graph/backend/LayoutPreloader.gif'>");

       wd.dialog("option","position","top");


		var _complete;
		if( $.isFunction( o.ajax.complete ) ) {

			_complete = o.ajax.complete;
		}

		if( o.setTime ){
			o.dial.resizable = false;
		}


		var onCompleteAjax = function(obj, status){
			if( $.isFunction(_complete ) ) {
				_complete(obj, status);
			}
			if( typeof o.dial.position == 'undefined' ){

                if( o.ajax ){
                    
                    wd.dialog("option","position","top");

                } else {

                    encjaNS.setMiddle(wd.dialog("option","position","center") );
                }
                
            }
			
			if( o.setTime ){
				setTimeout(function(){ wd.dialog("close") },o.setTime);
			}

			wd.html(obj.responseText);
		}
		o.ajax.complete = onCompleteAjax;



		var ajaxH = encjaNS.ajax(
		o.ajax
		);

		wd.bind('dialogclose', function(event, ui) {
			ajaxH.abort();
		});

	} else {
		wd.html( $(o.content) );
	}

	wd.dialog(o.dial);
	return wd;
}



encjaNS.getMaxZindex = function(){
	var zi=10;
	$('*').each(function() {
		if($(this).css("position")=="absolute"){
			var cur = parseInt($(this).css('zIndex'));
			zi = cur > zi ? parseInt($(this).css('zIndex')) : zi;
		}
	});

	return zi+1;
}

$.fn.runTiny1 = encjaNS.runTiny = function(o,elem)
{

	//override this options if you need
	/*mode : "exact",
	elements : "elm1",	*/
	if( elem ) {
		var self = $(elem);
	} else {
		var self = $(this);
	}

	var defaults = {

		// General options
		mode 		: "exact",//mode : "textareas",
		elements	: self.attr('id'),
		theme 		: "advanced",
		height		: "500",
		width		: "700",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

		// Theme options
		theme_advanced_buttons1 : "{mySave},bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,hr,removeformat,sub,sup,charmap,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,media,|,table, row_props, cell_props,addOnClick,|,insertdate,inserttime,|,forecolor,backcolor,styleprops,cleanup,code",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		theme_advanced_font_sizes : '8px,10px,12px,14px,18px,24px,28px,32px,36px,38px,49px,56px,62px,72px',
		force_br_newlines : true,
		forced_root_block : '',
		//		save_onsavecallback : "mySave",
		//		setup : function(ed) {
		//			// Add a custom button
		//			ed.addButton('addOnClick', {
		//				title : '{gotoPost}',
		//				image : '../graph/Layout/icons/anchor.png',
		//				onclick : function() {
		//					tinyMCE.execCommand('mceReplaceContent',false,'<a href="javascript:void(0);" title="{$selection}">{$selection}</a>');
		//				}
		//			});
		//			ed.onClick.add(function(ed, e) {
		//				if ( e.target.nodeName == "A" ) {
		//					goToPost(e.target.title);
		//				}
		//			});
		//		},


		// Example content CSS (should be your site CSS)
		//		content_css : "css/content.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js"


	};

	var opt = $.extend(defaults,o);

	tinyMCE.init(opt);

}

$.fn.runTiny = encjaNS.runTiny = function(o,elem)
{

	var runBr = function(a,b,c,d) {

		encjaNS.fileBrowser(
		{
				onSelect		:function(id,win,files){ $( '#'+a,d.document ).val(files[id].path );
																		try {
																			d.ImageDialog.showPreviewImage(files[id].path,0);
																			} catch(e) {
																				try{d.updatePreview()}catch(x){};
																			} },
				multi			:0,
				closeOnSelect	:true,
				ext				:'*.jpg,*.gif,*.png,*.flv,*.swf,*.pdf',
				data			:{},
				getFiles		: true
		}
		);

	}


	//override this options if you need
	/*mode : "exact",
	elements : "elm1",	*/
	if( elem ) {
		var self = $(elem);
	} else {
		var self = $(this);
	}

	var defaults = {

		// General options
		mode 		: "exact",//mode : "textareas",
		elements	: self.attr('id'),
		theme 		: "advanced",
		height		: "500",
		width		: "700",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		// Theme options
		theme_advanced_buttons1 : "{mySave},bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,hr,removeformat,sub,sup,charmap,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,media,|,table, row_props, cell_props,addOnClick,|,insertdate,inserttime,|,forecolor,backcolor,styleprops,cleanup,|,code,|,pasteword",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		theme_advanced_font_sizes : '8px,10px,12px,14px,18px,24px,28px,32px,36px,38px,49px,56px,62px,72px',
		force_br_newlines : true,
		forced_root_block : '',
		file_browser_callback : runBr,
		relative_urls:true,
		remove_script_host: true,
        convert_urls:false,
//        urlconverter_callback:function(a,b,c,d){alert(a);alert(b);alert(c);alert(d); console.dir(this);},
                extended_valid_elements : "iframe[src|width|height|name|align]",
		//		save_onsavecallback : "mySave",
		//		setup : function(ed) {
		//			// Add a custom button
		//			ed.addButton('addOnClick', {
		//				title : '{gotoPost}',
		//				image : '../graph/Layout/icons/anchor.png',
		//				onclick : function() {
		//					tinyMCE.execCommand('mceReplaceContent',false,'<a href="javascript:void(0);" title="{$selection}">{$selection}</a>');
		//				}
		//			});
		//			ed.onClick.add(function(ed, e) {
		//				if ( e.target.nodeName == "A" ) {
		//					goToPost(e.target.title);
		//				}
		//			});
		//		},


		// Example content CSS (should be your site CSS)
		//		content_css : "css/content.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js"


	};

	var opt = $.extend(defaults,o);

	tinyMCE.init(opt);

}


encjaNS.remTiny = function(obj)
{

	try{
		tinyMCE.execCommand( "mceRemoveControl",false,$(obj).attr('id') );
	}catch(e) {
		alert(e);
	}
}

encjaNS.showMessage = function(msg, opt)
{

	if( !msg ) {

		var msg = "No message was send";

	}

	var opt = $.extend({

		type	:	"alert", // types - alert; success; warning;
		timeOut	:	5000,
		wrapper :   "#regionCenter"

	},opt);

	$(".ui-message", opt.wrapper).addClass( "ui-message-" + opt.type ).html( msg );

	$(".ui-message", opt.wrapper).slideDown("slow");

	setTimeout( function() {

		$(".ui-message", opt.wrapper).slideUp("slow", function() {

			$(".ui-message", opt.wrapper).removeClass( "ui-message-" + opt.type ).html("");

		});

	}, opt.timeOut );

}

encjaNS.jqgridAfterAddEditWindow = function ( jqGridIdTable ) {

	if( !jqGridIdTable ) {

		jqGridIdTable = "#jqgridTable";

	}

	$(jqGridIdTable).trigger("reloadGrid");
	$('._dialog:div').dialog("close");

}

encjaNS.jqgridAddEditWindow = function ( NSmoduleObj, addData, windowTitle ) {

	encjaNS.openWindow({
		ajax    : {   url     :	NSmoduleObj.moduleSetting.script+'?ajax=1',
		data    :	addData },
		dial    : { title : windowTitle,modal:true }

	});

}

encjaNS.jqgridAfterAddEditBlank = function ( jqGridIdTable, noReload ) {

	if( typeof noReload == 'undefined' ) {
		var noReload = false;
	}

	if( !jqGridIdTable ) {

		jqGridIdTable = "#jqgridTable";
	}
	$("#center2").html("");
	$("#center1").toggle();
	if( !noReload ) {
		$(jqGridIdTable).trigger("reloadGrid",true);
	}


}

encjaNS.jqgridAddEditBlank = function ( NSmoduleObj, addData, params ) {

	var params = $.extend({
		main		:'#center1',
		form		:'#center2',
		noHistory 	: false,
		crumbs		: false}
		,params
		);

		$(params.main).toggle();



		encjaNS.startModule({
			url       :	NSmoduleObj.moduleSetting.script,
			data      :	addData,
			target    : params.form,
			clear     : false,
			noHistory : params.noHistory,
			crumbs	  : params.crumbs
		});

}

encjaNS.messageFromAjaxResponseText = function( AjaxObj ) {

	eval('var messageObj = '+ AjaxObj.responseText );

	if ( typeof messageObj.params !== 'object') {

		encjaNS.showMessage( messageObj[1].content, messageObj[1].params );

	} else if (typeof messageObj.params === 'object') {

		encjaNS.showMessage( messageObj.content, messageObj.params );

	}


}



encjaNS.downloadFile = function(idFile)
{

	if( !idFile ) { return false; }

	window.location.href = "download.php?id=" + idFile;

}

encjaNS.openPrompt = function( o )
{
	var o = $.extend({
		info	: encjaNS.transJS('win_default_info'),
		onYes   : function() {},
		dial	: {}
	}, o );

	o.dial = $.extend({

		modal:true,
		title: "&nbsp;",
		width: 300,
		resizable: false

	},o.dial);


	encjaNS.openWindow( {
		content: '<div class="ui-prompt-window">'+o.info+' ?</div>',
		dial: o.dial,
		sData: encjaNS.transJS('yes') || 'Tak',
		cData: encjaNS.transJS('no') || 'Nie',

		onSubmit: function( windowObj ) {

			o.onYes( windowObj );

		}
	});

}

encjaNS.setCategoryMenuActions = function( jqGridTable )
{

	if( ! jqGridTable ) {

		return false;
	}

	var grid = $(jqGridTable);

	$(".ui-category-menu").find("span.ui-category").each(function() {

		$(this).click(function() {

			var idCategory 	= $(this).attr("idcategory");
			var catName		= $(this).html();

			$(".ui-category-selected").removeClass("ui-category-selected");
			$(this).addClass("ui-category-selected");
			$("input#category").val(idCategory);
			$("._catMenuPath").html( " > " + catName );
			grid.appendPostData({ category: idCategory, _search: true });
			grid.trigger('reloadGrid');

			$("#cButton").click(function() {

				$(".ui-category-selected").removeClass("ui-category-selected");
				$("input#category").val('');
				$("._catMenuPath").html('');

			});

		});

	});

}

encjaNS.getElementsOfForm = function ( form ) {

	var form = $(form)[0];

	try{

		var ret = {};
		for (var nr = 0; nr < form.elements.length; nr++) {

			var e = form.elements[nr];
			if (e.disabled)
			continue;
			switch (e.type) {
				case "text":
				case "password":
				case "hidden":
				case "textarea":
				ret[e.name] =  e.value;
				break;
				case "select-one":
				if (e.selectedIndex >= 0)
				ret[e.name] = e.options[e.selectedIndex].value;
				break;
				case "select-multiple":
				var opt = [];
				for (var nr2 = 0; nr2 < e.options.length; nr2++)
				if (e.options[nr2].selected)
				opt.push(e.options[nr2].value);
				if( opt.length >0 ) {
					ret[e.name] = [];
					ret[e.name].push(opt);
				}

				break;
				case "checkbox":
				case "radio":
				if (e.checked)
				ret[e.name] = e.value;
				break;
			}
		}
	} catch(e) {

		alert(e);
	}


	return ret;
}

$.fn.fileBrowser = encjaNS.fileBrowser = function(o, elem)
{
	if( typeof elem == 'undefined') {
		var self = $(this);
	} else {
		var self = $(elem);
	}

	var opt = $.extend({
		onSelect		:0,
		multi			:1,
		closeOnSelect	:false,
		ext				:'*.*',
		data			:{},
		getFiles		: true
	},o);

	var ajaxData 		= opt.data;
	ajaxData['ext'] = opt.ext;
	var closeMe;
	var dial = {};
	dial.buttons = {};

	if( $.isFunction( opt.onSelect ) ) {
		ajaxData['select'] = opt.multi ? 1 : 0;
		dial.buttons[encjaNS.transJS('select')] = function(){



			var selRows = Array();//
			if( ajaxData['select'] ) {

				if( $('#fileListGrid').is(':visible') ) {

					selRows = $('#jqgridFileBrowserTable').getGridParam('selarrrow');

					if( !selRows ) {
						return;
					} else if( selRows.length <=0 ) {
						return;
					}

				} else if( $('#folderListGrid').is(':visible') ) {

					var row =  $('#jqgridFolderBrowserTable').getGridParam('selrow');

					if( row ) {

						if( row.indexOf('_file') == -1 ) {
							return;
						} else  {
							selRows.push( row.substr(0,row.indexOf('_file') ) );
						}
					}


				}

			} else {

				if( $('#fileListGrid').is(':visible') ) {

					selRows.push( $('#jqgridFileBrowserTable').getGridParam('selrow') );
					if( !selRows ) {
						return;
					} else if( selRows.length <=0 ) {
						return;
					}

				} else if( $('#folderListGrid').is(':visible') ){

					var row =  $('#jqgridFolderBrowserTable').getGridParam('selrow');
					if( row ) {

						if( row.indexOf('_file') == -1 ) {
							return;
						} else  {
							selRows.push( row.substr(0,row.indexOf('_file') ) );
						}
					}


				}

			}

			if( $('#folderMiniatures').is(':visible') ) {

				$('._itemSelected','#folderMiniatures').each( function() {

					if( !$(this).hasClass('_folder') ) {
						var thisId =  $( this ).attr('id');
						selRows.push( thisId.substr(0,thisId.indexOf('_file') ) );

					}

				});

			}

			if( selRows.length == 0 ) {
				encjaNS.openWindow({
					content : '<div>Nie wybrano żadnego pliku</div>',
					dial: {
						modal:true,
						title: 'Ostrzeżenie',
						width: 200,
						height:30
					},
					cData : 'OK'
				});
				return;
			}
			if( opt.getFiles ) {
				encjaNS.ajax({
					url:'filebrowser.php',
					data:{
					'files[]':selRows,
					'filebrowser_controller': 9
					},
					complete:function(ret){
						var files = eval( '('+ret.responseText+')');
						opt.onSelect(selRows,closeMe,files);

						if( opt.closeOnSelect ){
							$(closeMe).dialog('close') ;
						}
					}
				});
			} else {
				opt.onSelect(selRows,closeMe);
				if( opt.closeOnSelect ){
					$(closeMe).dialog('close') ;
				}
			}



		};
	}


	dial.title 	= encjaNS.transJS('fileBrowserTitle');
	dial.width	 = 650;
	dial.height = 580;
	dial.modal = true;
	//jak to zuniwersalizowac
	//	var pos = self.offset();
	//	var top = pos.top;
	//	var left = pos.left;
	//	var wH = $(document).height();
	//	var wW = $(document).width();
	//
	//	if( top + dial.height > wH ){
	//		top = wH - dial.height;
	//		if( top < 0 ){
	//			top = 0;
	//		}
	//	}
	//	if( left + dial.width > wW ){
	//		left = wW - dial.width;
	//		if( left < 0 ){
	//			left = 0;
	//		}
	//	}
	//
	//	dial.position = [left,top];
	dial.position = ['center',0];

	//kocham javascript :)
	closeMe = encjaNS.openWindow({
		dial			: dial,
		ajax			: {
			url			: 'filebrowser.php?ajax=1',
			data  		: ajaxData
		}

	});
	return closeMe;
}
encjaNS.sendNewsletter = function(o)
{
	var defaults = {
		id_newsletter 	: 0
	}

	var opt = {};
	opt.url						  = 'sendnewsletter.php';
	opt.sendnewsletter_controller = 1;
	opt.data = $.extend(defaults,o);
	opt.data.ajax				 = 1;
	opt.data.window				 = 1;

	encjaNS.openWindow({
		ajax:opt,
		c:"_sendNewsletterWin",
		dial:{
			width:200,
			modal :	true,
			title : encjaNS.transJS('sendNewsletter') || 'Wysyłanie newslettera'
		}

	});
}

encjaNS.sendingNewsletter = function(f){

	$('._sendNewsletterWin').dialog('close');

	$("._preloaderNewsletter").slideDown("slow");
	$("._preloaderNewsletter").addClass('ui-newsletter-sending').html("Wysyłanie wiadomości");



	encjaNS.submitFormByAjax( f , function( obj ) {
		var c = eval("("+obj.responseText+")");
		$("._preloaderNewsletter").removeClass( "ui-newsletter-sending").html(c.content);
		//		encjaNS.messageFromAjaxResponseText( obj );
		setTimeout( function() {

			$("._preloaderNewsletter").slideUp("slow", function() {

				$("._preloaderNewsletter").html("");

			});

		}, 5000 );

	});
}

encjaNS.animateBackground = function(level){

     if( typeof level == "undefined" || !level )
     {
         level = true;
         $(".extend-li").animate({backgroundColor: '#FFBFC3'}, 1500);
     } else {
         level = false;
         $(".extend-li").animate({backgroundColor: '#EE1921'}, 1500);
     }

     setTimeout(function(){ encjaNS.animateBackground(level) },1000 );


}


$.fn.selectNltTpl = encjaNS.selectNltTpl = function(o, elem)
{
	if( typeof elem == 'undefined') {
		var self = $(this);
	} else {
		var self = $(elem);
	}

	var opt = $.extend({
		onSelect		:0,
		closeOnSelect	:true,
		data			:{}
	},o);

	var ajaxData 		= opt.data;
	ajaxData.select = 1;
	var closeMe;
	var dial = {};
	dial.buttons = {};

	if( $.isFunction( opt.onSelect ) ) {
		dial.buttons[encjaNS.transJS('select')] = function(){
			var selRows = $('#jqgridNewsletterTplTable').getGridParam('selrow');
			opt.onSelect(selRows,closeMe);
			if( opt.closeOnSelect ){
				$(closeMe).dialog('close') ;
			}
		};
	}

	//	dial.position = [self.offset().top,self.offset().left];
	dial.title 	= encjaNS.transJS('newsletterTplMaintitle');
	dial.width	 = 600;
	dial.height = 580;
	dial.modal = true;
	//jak to zuniwersalizowac
	//	var pos = self.offset();
	//	var top = pos.top;
	//	var left = pos.left;
	//	var wH = $(document).height();
	//	var wW = $(document).width();
	//
	//	if( top + dial.height > wH ){
	//		top = wH - dial.height;
	//		if( top < 0 ){
	//			top = 0;
	//		}
	//	}
	//	if( left + dial.width > wW ){
	//		left = wW - dial.width;
	//		if( left < 0 ){
	//			left = 0;
	//		}
	//	}

	dial.position = ['center',10];

	//kocham javascript :)
	closeMe = encjaNS.openWindow({
		dial			: dial,
		ajax			: {
			url			: 'newslettertpl.php?ajax=1',
			data  		: ajaxData
		}

	});
	return closeMe;
}

$(document).ready(function(){
	
	if( $.browser.msie ) {
		if( Number( $.browser.version ) <= 6 ) {
			$('img[src*=.png]').each(function(){

				$(this).css( { filter:'progid:DXImageTransform.Microsoft.Alpha(opacity=0)' } );
				var w = $('<div></div>');
				$(this).parent().append(w);
//				w.attr('width',$(this).width());
//				w.attr('height',$(this).height());
				
				w.css( { display: 'inline-block', margin:0, padding:0 });
				w.append(this);
				w.css( { filter:'progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+$(this).attr("src")+')' } );
			
			});
		}
	}

//    encjaNS.animateBackground(false);
    if( $.fn.corner ){
        $('.extend-li').corner("5px");
    }
    


//    if( typeof mainTplNS.MAIN_URLROOTPATH != 'undefined'){
//
//
//        $('div#content').find('[src],[href]').each(function(){
//
//           var item = '';
//           var attr = '';
//           if( $(this).attr('src') ){
//               item = $(this).attr('src');
//               attr = 'src';
//
//           } else {
//               item = $(this).attr('href');
//               attr = 'href';
//           }
//
////           if( item.indexOf('../files/') != -1 ){
////            alert(item);
////            alert(attr);
////            $(this).attr(attr,item.replace('../files/',mainTplNS.MAIN_URLROOTPATH+'files/'));
////           }
//        }
//
//        );
//    }

})
