$(document).ready(function() 
{	
	//editMode = new editMode;
	$(document).bind('keydown', 'ctrl+e', function() { editMode.toggleShow(); });
	
	if(typeof window.location.hash != 'undefined' && window.location.hash.toString() != '' && window.location.hash.toString() != '#')
	{
		var urlObject = $.parseQuery(window.location.hash.toString());
		$.ajax({
			type: 'get',
			url: window.location.hash.toString().replace('#', ''),
			dataType: 'json',
			success: function(msg)
			{
				if(typeof msg.error != 'undefined' && msg.error == true) showNotice(msg['notice'], msg['error']);
				if(typeof msg.data != 'undefined') $('#'+urlObject.object).replaceWith(msg.data);
				if(typeof msg.getUrl != 'undefined' && msg.getUrl != false) window.location.hash = msg.getUrl;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				//showNotice(trans.translate(textStatus.toUpperCase()), true);
			}
		});
	}
	
	$('input.confirm').each(function()
	{
		var oldfunc = $(this).attr('onclick');
		$(this).removeAttr('onclick');
		$(this).unbind('click');
		var input = this;
		var dialog = document.createElement("div");
		$(dialog).html(trans.translate('AREYOUSHURE'));
		$(input).click(function(event)
		{
			//event.preventDefault();
			var buttons = {};
			buttons[trans.translate('NO')] = function() { $(this).dialog("close"); };
			buttons[trans.translate('YES')] = function() 
			{
				if($(input).attr('type') == 'submit') $(input).closest('form').append('<input type="hidden" value="'+$(input).val()+'" name="'+$(input).attr('name')+'" />');
				if(typeof oldfunc != 'undefined')
				{
					var func = oldfunc.toString().replace('this', 'input');
					eval('var func = '+func);
					func();
				}
				else
				{
					$(input).closest('form').submit();
				}
				$(this).dialog("close");
			};
			
			$(dialog).dialog(
			{
				autoOpen: false,
				width: 200,
				modal: true,
				resizable: false,
				buttons: buttons
			});
			$(dialog).dialog('open');
			return false;
		});
	});
});

//user classes
var User = [];
User.Lang = function()
{
	this.translate = function(key)
	{
		if(!this.translator) alert('Error', 'Language not defined');
		else
		{
			if(this.translator[key]) return this.translator[key];
			else 
			{
				var param = {};
				$.fn.submitForm(false, false, true, { 'func': 'Translator::checkTrans', 'key': key  });
				return '#'+key;
			}
		}
	}
};

User.Vars = function()
{

}

var trans = new User.Lang;
var vars = new User.Vars;

var editClass = function()
{
	this.editMode = false;
	this.editorInstance = false;
	
	this.toggleShow = function()
	{
		if(vars.auth == 0) return;
		
		if(this.editMode == false)
		{
			var box = $('<div></div>')
				.dialog({
					autoOpen: false,
					title: 'Edit mode',
					position: ['right', 'top'],
					resizable: false,
					draggable: false,
					hide: 'slide',
					show: 'slide',
					stack: false,
					width: 200,
					close: function() { editMode.closeEditMode(); }
			});
			box.attr('id', 'edit-mode-info');
			box.dialog('open');	
			this.editMode = true;
			$('.wiki-edit-module').addClass('wiki-bordered');
		}
		else $('#edit-mode-info').html(trans.translate('YOUAREALLREADYINEDITMODE'));
	};
	
	this.replaceHtml = function(val)
	{
		var myDiv = $('<div></div>')
			.html(val['data'])
			.dialog({
				dialogClass: '',
				title: trans.translate('TRANSLATION'),
				resizable: true,
				draggable: true,
				hide: 'slide',
				show: 'slide',
				width: 680,
				stack: false
		});
	}
	
	this.closeEditMode = function()
	{
		this.editMode = false;
		$('.wiki-edit-module').removeClass('wiki-bordered');
	}
	
	this.editorDestroy = function()
	{
		$.fn.submitForm(false, false, false, { 'func': 'WikiObject::getWikiByName', wikiName: this.wikiName }, function(val)
		{
			this.editorInstance = false;
			$('#textarea-'+this.wikiId).remove();
			$('.wiki-edit-module').addClass('wiki-bordered');
			$('#'+this.wikiName).show().html(val['data']);
			$(document).unbind('dblclick');
		});
	}
	
	this.finishWikiUpdate = function(val)
	{
		
	}
	
	this.wikiUpdate = function()
	{
		var content = $('#textarea-'+this.wikiId).val();
		$.fn.submitForm(false, false, false, { 'func': 'WikiObject::updateWiki', name: this.wikiName, content: content, wikiId: this.wikiId }, function(val)
		{
			$('#edit-mode-info').html(val['notice']);
		});
	}
	
	this.addFrontPageEditor = function(wikiName, wikiId, object)
	{
		this.wikiName = wikiName;
		this.wikiId = wikiId;
		if(this.editMode == false) return false;
		this.object = object;
		this.editorInstance = true;
		$('.wiki-edit-module').removeClass('wiki-bordered');
		var data = { wikiId: wikiId };
		$.fn.submitForm(false, false, false, { 'func': 'WikiObject::getWikiSource', wikiId: wikiId }, function(val)
		{
			if(val['error'] == true) $('#edit-mode-info').html(val['notice']);
			else
			{
				var myDiv = $('<div></div>')
					.html('<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" onclick="editMode.wikiUpdate();">'+trans.translate('SAVE')+'</button>')
					.dialog({
						dialogClass: '',
						title: 'Editor',
						resizable: true,
						draggable: true,
						hide: 'slide',
						show: 'slide',
						stack: false,
						width: 160,
						height: 110,
						close: function() { editMode.editorDestroy(); }
				});
				
				$('#'+this.wikiName).hide().after('<textarea class="wiki-editor" id="textarea-'+this.wikiId+'">'+val['data']+'</textarea>');			
			}	
		});
	}
};
var editMode = new editClass; 

(function(jQuery){jQuery.fn.__bind__=jQuery.fn.bind;jQuery.fn.__unbind__=jQuery.fn.unbind;jQuery.fn.__find__=jQuery.fn.find;var hotkeys={version:'0.7.9',override:/keypress|keydown|keyup/g,triggersMap:{},specialKeys:{27:'esc',9:'tab',32:'space',13:'return',8:'backspace',145:'scroll',20:'capslock',144:'numlock',19:'pause',45:'insert',36:'home',46:'del',35:'end',33:'pageup',34:'pagedown',37:'left',38:'up',39:'right',40:'down',109:'-',112:'f1',113:'f2',114:'f3',115:'f4',116:'f5',117:'f6',118:'f7',119:'f8',120:'f9',121:'f10',122:'f11',123:'f12',191:'/'},shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"},newTrigger:function(type,combi,callback){var result={};result[type]={};result[type][combi]={cb:callback,disableInInput:false};return result;}};hotkeys.specialKeys=jQuery.extend(hotkeys.specialKeys,{96:'0',97:'1',98:'2',99:'3',100:'4',101:'5',102:'6',103:'7',104:'8',105:'9',106:'*',107:'+',109:'-',110:'.',111:'/'});jQuery.fn.find=function(selector){this.query=selector;return jQuery.fn.__find__.apply(this,arguments);};jQuery.fn.unbind=function(type,combi,fn){if(jQuery.isFunction(combi)){fn=combi;combi=null;}
if(combi&&typeof combi==='string'){var selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();var hkTypes=type.split(' ');for(var x=0;x<hkTypes.length;x++){delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];}}
return this.__unbind__(type,fn);};jQuery.fn.bind=function(type,data,fn){var handle=type.match(hotkeys.override);if(jQuery.isFunction(data)||!handle){return this.__bind__(type,data,fn);}
else{var result=null,pass2jq=jQuery.trim(type.replace(hotkeys.override,''));if(pass2jq){result=this.__bind__(pass2jq,data,fn);}
if(typeof data==="string"){data={'combi':data};}
if(data.combi){for(var x=0;x<handle.length;x++){var eventType=handle[x];var combi=data.combi.toLowerCase(),trigger=hotkeys.newTrigger(eventType,combi,fn),selectorId=((this.prevObject&&this.prevObject.query)||(this[0].id&&this[0].id)||this[0]).toString();trigger[eventType][combi].disableInInput=data.disableInInput;if(!hotkeys.triggersMap[selectorId]){hotkeys.triggersMap[selectorId]=trigger;}
else if(!hotkeys.triggersMap[selectorId][eventType]){hotkeys.triggersMap[selectorId][eventType]=trigger[eventType];}
var mapPoint=hotkeys.triggersMap[selectorId][eventType][combi];if(!mapPoint){hotkeys.triggersMap[selectorId][eventType][combi]=[trigger[eventType][combi]];}
else if(mapPoint.constructor!==Array){hotkeys.triggersMap[selectorId][eventType][combi]=[mapPoint];}
else{hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length]=trigger[eventType][combi];}
this.each(function(){var jqElem=jQuery(this);if(jqElem.attr('hkId')&&jqElem.attr('hkId')!==selectorId){selectorId=jqElem.attr('hkId')+";"+selectorId;}
jqElem.attr('hkId',selectorId);});result=this.__bind__(handle.join(' '),data,hotkeys.handler)}}
return result;}};hotkeys.findElement=function(elem){if(!jQuery(elem).attr('hkId')){if(jQuery.browser.opera||jQuery.browser.safari){while(!jQuery(elem).attr('hkId')&&elem.parentNode){elem=elem.parentNode;}}}
return elem;};hotkeys.handler=function(event){var target=hotkeys.findElement(event.currentTarget),jTarget=jQuery(target),ids=jTarget.attr('hkId');if(ids){ids=ids.split(';');var code=event.which,type=event.type,special=hotkeys.specialKeys[code],character=!special&&String.fromCharCode(code).toLowerCase(),shift=event.shiftKey,ctrl=event.ctrlKey,alt=event.altKey||event.originalEvent.altKey,mapPoint=null;for(var x=0;x<ids.length;x++){if(hotkeys.triggersMap[ids[x]][type]){mapPoint=hotkeys.triggersMap[ids[x]][type];break;}}
if(mapPoint){var trigger;if(!shift&&!ctrl&&!alt){trigger=mapPoint[special]||(character&&mapPoint[character]);}
else{var modif='';if(alt)modif+='alt+';if(ctrl)modif+='ctrl+';if(shift)modif+='shift+';trigger=mapPoint[modif+special];if(!trigger){if(character){trigger=mapPoint[modif+character]||mapPoint[modif+hotkeys.shiftNums[character]]||(modif==='shift+'&&mapPoint[hotkeys.shiftNums[character]]);}}}
if(trigger){var result=false;for(var x=0;x<trigger.length;x++){if(trigger[x].disableInInput){var elem=jQuery(event.target);if(jTarget.is("input")||jTarget.is("textarea")||jTarget.is("select")||elem.is("input")||elem.is("textarea")||elem.is("select")){return true;}}
result=result||trigger[x].cb.apply(this,[event]);}
return result;}}}};window.hotkeys=hotkeys;return jQuery;})(jQuery);

//load mask
(function($){
	
	/**
	 * Displays loading mask over selected element(s). Accepts both single and multiple selectors.
	 *
	 * @param label Text message that will be displayed on top of the mask besides a spinner (optional). 
	 * 				If not provided only mask will be displayed without a label or a spinner.  	
	 * @param delay Delay in milliseconds before element is masked (optional). If unmask() is called 
	 *              before the delay times out, no mask is displayed. This can be used to prevent unnecessary 
	 *              mask display for quick processes.   	
	 */
	$.fn.mask = function(label, delay){
		$(this).each(function() {
			if(delay !== undefined && delay > 0) {
		        var element = $(this);
		        element.data("_mask_timeout", setTimeout(function() { $.maskElement(element, label)}, delay));
			} else {
				$.maskElement($(this), label);
			}
		});
	};
	
	/**
	 * Removes mask from the element(s). Accepts both single and multiple selectors.
	 */
	$.fn.unmask = function(){
		$(this).each(function() {
			$.unmaskElement($(this));
		});
	};
	
	/**
	 * Checks if a single element is masked. Returns false if mask is delayed or not displayed. 
	 */
	$.fn.isMasked = function(){
		return this.hasClass("masked");
	};

	$.maskElement = function(element, label){
	
		//if this element has delayed mask scheduled then remove it and display the new one
		if (element.data("_mask_timeout") !== undefined) {
			clearTimeout(element.data("_mask_timeout"));
			element.removeData("_mask_timeout");
		}

		if(element.isMasked()) {
			$.unmaskElement(element);
		}
		
		if(element.css("position") == "static") {
			element.addClass("masked-relative");
		}
		
		element.addClass("masked");
		
		var maskDiv = $('<div class="loadmask"></div>');
		
		//auto height fix for IE
		if(navigator.userAgent.toLowerCase().indexOf("msie") > -1){
			maskDiv.height(element.height() + parseInt(element.css("padding-top")) + parseInt(element.css("padding-bottom")));
			maskDiv.width(element.width() + parseInt(element.css("padding-left")) + parseInt(element.css("padding-right")));
		}
		
		//fix for z-index bug with selects in IE6
		if(navigator.userAgent.toLowerCase().indexOf("msie 6") > -1){
			element.find("select").addClass("masked-hidden");
		}
		
		element.append(maskDiv);
		
		if(label == undefined) label = '&nbsp;';
		var maskMsgDiv = $('<div class="loadmask-msg" style="display:none;"></div>');
		maskMsgDiv.append('<div>' + label + '</div>');
		element.append(maskMsgDiv);
		
		//calculate center position
		maskMsgDiv.css("top", Math.round(element.height() / 2 - (maskMsgDiv.height() - parseInt(maskMsgDiv.css("padding-top")) - parseInt(maskMsgDiv.css("padding-bottom"))) / 2)+"px");
		maskMsgDiv.css("left", Math.round(element.width() / 2 - (maskMsgDiv.width() - parseInt(maskMsgDiv.css("padding-left")) - parseInt(maskMsgDiv.css("padding-right"))) / 2)+"px");
		
		maskMsgDiv.show();
		
	};
	
	$.unmaskElement = function(element){
		//if this element has delayed mask scheduled then remove it
		if (element.data("_mask_timeout") !== undefined) {
			clearTimeout(element.data("_mask_timeout"));
			element.removeData("_mask_timeout");
		}
		
		element.find(".loadmask-msg,.loadmask").remove();
		element.removeClass("masked");
		element.removeClass("masked-relative");
		element.find("select").removeClass("masked-hidden");
	};
 
})(jQuery);

/**
 * A simple querystring parser.
 * Example usage: var q = $.parseQuery(); q.fooreturns  "bar" if query contains "?foo=bar"; multiple values are added to an array. 
 * Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object .
 * http://actingthemaggot.com/jquery
 *
 * Copyright (c) 2008 Michael Manning (http://actingthemaggot.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/
jQuery.parseQuery = function(qs,options) {
	var q = (typeof qs === 'string'?qs:window.location.search), o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}, options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options, o = jQuery.extend({}, o, options), params = {};
	jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){
		p = p.split('=');
		p[1] = o.f(p[1]);
		params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1];
	});
	return params;
}

/**
 * strstr
 * @access public
 * @return void
 **/
function strstr( haystack, needle, bool ) 
{
    var pos = 0;
    haystack += '';
    pos = haystack.indexOf(needle);
    if (pos == -1) return false;
    else
	{
        if(bool) return haystack.substr(0, pos);
        else return haystack.slice(pos);
    }
}

(function($) 
{
	$.fn.fieldSerialize = function(submitName)
	{
		var values = new Object();
		this.each(function()
		{
			if(typeof this.name == 'undefined' || this.name == '') return true;
			if(this.type == 'checkbox' || this.type == 'radio')
			{
				if(this.checked == true) 
				{
					if(strstr(this.name, '[]', true))
					{
						var tmp = this.name.replace(/\[\]/, '');
						if(typeof values[tmp] == 'undefined') values[tmp] = {};
						var x = 0;
						while(typeof values[tmp][x] != 'undefined') x++;
						values[tmp][x] = $(this).val();
					}
					else values[this.name] = $(this).val();
				}
			}
			else if(this.type == 'submit')
			{
				if(typeof submitName != 'undefined' && this.name == submitName)
				{
					values[this.name] = $(this).val();
				}
			}
			else if(typeof this.name != 'undefined' && this.name != '')
			{
				if(strstr(this.name, '[]', true))
				{
					var tmp = this.name.replace(/\[\]/, '');
					if(typeof values[tmp] == 'undefined') values[tmp] = {};
					var x = 0;
					while(typeof values[tmp][x] != 'undefined') x++;
					values[tmp][x] = $(this).val();
				}
				else values[this.name] = $(this).val();
			}
		});
		return values;
	}
	
})(jQuery);

jQuery.fn.autocomplete = function(url, settings )
{
	return this.each( function()//do it for each matched element
	{
		//this is the original input
		var textInput = $(this);
		//create a new hidden input that will be used for holding the return value when posting the form, then swap names with the original input
		textInput.after('<input type=hidden name="' + textInput.attr("name") + '_text" id="value' + textInput.attr("name") + '"/>').attr("name", textInput.attr("name"));
		var valueInput = $(this).next();
		//create the ul that will hold the text and values
		//valueInput.after($('.autocomplete').clone().html(''));
		valueInput.after('<ul id="autocompleteitem"></ul>');
		var list = valueInput.next().css({top: textInput.offset().top + textInput.outerHeight(), left: textInput.offset().left});
		var oldText = '';
		var typingTimeout;
		var size = 0;
		var selected = 0;

		settings = jQuery.extend(//provide default settings
		{
			minChars : 1,
			timeout: 1000,
			after : null,
			before : null,
			validSelection : true,
			parameters : {'inputName' : valueInput.attr('name'), 'inputId' : textInput.attr('id')}
		} , settings);

		function getData(text)
		{
			window.clearInterval(typingTimeout);
			if (text != oldText && (settings.minChars != null && text.length >= settings.minChars))
			{
				clear();
				if (settings.before == "function")
				{
					settings.before(textInput,text);
				}
				textInput.addClass('autocomplete-loading');
				settings.parameters.text = text;
				
				$.fn.submitForm(false, false, false, settings.parameters, function(data)
				{
					//val = jQuery.parseJSON(data);
					var items = '';
					var val = data.data;
					if(val && val != false && typeof val == 'object')
					{
						size = val.length;
						for (key in val)//iterate over all options
						{
							if(isArray(val[key]))
							{
								list.append($('#autocompleteitem').clone().attr('id', 'autocompleteitem'+key).html('<li>'+val[key][0]+'</li>').attr('rel', val[key][1]));
								//items += $('#autocompleteitem').clone().attr('id', 'autocompleteitem'+key).val(val[key][1]).html(val[key][0]);
								//'<li id="listaproba'+key+'" value="' + val[key][1] + '">' + val[key][0] + '</li>';
							}
							else
							{
								list.append($('#autocompleteitem').clone().attr('id', 'autocompleteitem'+key).html('<li>'+val[key]+'</li>').attr('rel', key));
							}
						}
						//on mouse hover over elements set selected class and on click set the selected value and close list
						$('#autocompleteitem'+key).attr('value', 'dada');
						list.show().children().hover(function() 
						{ 
							$(this).addClass("selected").siblings().removeClass("selected");
						}, function() 
						{ 
							$(this).removeClass("selected") 
						}).click(function () 
						{
							if (typeof settings.after == "function")
							{
								settings.after($(this).attr('rel'), $(this).text());
								clear();
							}
							else
							{
								valueInput.val($(this).attr('rel'));textInput.val($(this).text()); clear(); 
								if(typeof settings.parameters.callback != 'undefined') eval(settings.parameters.callback)($(this).attr('rel'));
							}
						});
					}
					textInput.removeClass('autocomplete-loading');

				});
				oldText = text;
			}
		}

		function clear()
		{
			list.html('');
			size = 0;
			selected = 0;
		}

		textInput.keydown(function(e)
		{
			window.clearInterval(typingTimeout);
			if(e.which == 27)//escape
			{
				clear();
			} else if (e.which == 46 || e.which == 8)//delete and backspace
			{
				clear();
				//invalidate previous selection
				if (settings.validSelection) valueInput.val('');
			}
			else if(e.which == 13)//enter
			{
				if ( list.css("display") == "none")//if the list is not visible then make a new request, otherwise hide the list
				{
					getData(textInput.val());
				} else
				{
					clear();
				}
				e.preventDefault();
				return false;
			}
			else if(e.which == 40 || e.which == 9 || e.which == 38)//move up, down
			{
			  switch(e.which)
			  {
				case 40:
				case 9:
				  selected = selected >= size - 1 ? 0 : selected + 1; break;
				case 38:
				  selected = selected <= 0 ? size - 1 : selected - 1; break;
				default: break;
			  }
			  //set selected item and input values
			  textInput.val( list.children().removeClass('selected').eq(selected).addClass('selected').text() );
			  valueInput.val( list.children().eq(selected).attr('value') );
			} else
			{
				//invalidate previous selection
				if (settings.validSelection) valueInput.val('');
				typingTimeout = window.setTimeout(function() { getData(textInput.val()) },settings.timeout);
			}
		});
	});
};

var modalBox = function(content, width, height, callback) 
{
	if(!content)
	{
		$('#ntz_modal').remove();
		$('#ntz_overlay').fadeOut(function(){ $(this).remove(); });
		return false;
	}

	$('body').append('<div id="ntz_overlay"></div>');
	
	$('#ntz_overlay').css(
	{
		width: '100%',
		height:	$(document).height(),
		position: 'absolute',
		left: 0,
		top: 0,
		backgroundColor: '#FFFFFF',
		zIndex:	9990,
		opacity: 0
	}).fadeTo(200, 0.5);
	
	$('body').append('<div id="ntz_modal"></div>');
	
	$('#ntz_modal').css(
	{
		border:	modalBox.prototype.border,
		width: width ? width : 350,
		height:	height ? height : 350,
		backgroundColor: '#FFFFFF',
		position:	'absolute',
		//overflow:   'auto',
		'top': '50%',
		'left': '50%',
		zIndex:	9995,
		marginLeft:	-(Math.ceil((width ? width : 800)/2))
	}).append(content);
	//$('*').blur();
	$('#ntz_modal a:eq(0), #ntz_modal input, #ntz_modal textarea').focus();
	try
	{
		callback.call();
	}
	catch(err)
	{};
	$(document).bind('scroll', function()
	{
		$('#ntz_modal').css(
		{
			top:$(document).scrollTop()
		});
	});
};

//default values
modalBox.prototype.border = '2px solid #006464';

/**
 * Showing loading gif
 * @access public
 * @return void
 **/
function loading() 
{
	modalBox('<div style="text-align: center; width: 100px; padding-top: 40px;"><img src="/images/admin/loading.gif" /></div>', 100, 100);
}

/**
 * Save all fields in admin by given div id
 * @access public
 * @return void
 **/
function adminSave(formid, object, id, refresh, focus, callback) 
{
	var data = {};
	if(id == false) var func = 'insertRow';
	else 
	{
		var func = 'updateRow';
		data['id'] = id;
	}
	data['func'] = object+'::'+func;
	$.fn.submitForm(formid, refresh, true, data, callback);
	if(typeof focus != 'undefined' && focus == true)
	{
		$('#'+formid+' :input').each(function()
		{
			this.focus();
			return false;
		});
	}
}

/**
 * Delete row
 * @access public
 * @return void
 **/
function adminDelete(id, func, refresh)
{
	var data = { id: id };
	data['func'] = func+'::deleteRow';
	$.fn.submitForm(false, refresh, true, data);
}

/**
 * Save checked items
 * @access public
 * @return void
 **/
function adminSaveChecked(rows, object, table)
{
	loading();
	$("[id^='"+rows+"']").each(function()
	{
		if($(this).find("."+table+"-selection").attr('checked') == true)
		{
			$(this).find(".yeslink").click();
		}
	});
	modalBox();
}

(function($) 
{
	$.fn.submitForm = function(formId, refresh, generalDisplay, params, callback, hideLoading)
	{
		var origSize = $(params).size();
		var oldHtml = null;
		if(typeof refresh != 'undefined' && refresh != false)
		{
			var data = $('#'+formId+' :input').fieldSerialize($(this).attr('name'));
			oldHtml = $("[id^='"+refresh+"-']").html();
			if(typeof hideLoading == 'undefined' || hideLoading == false) 
			{
				$("[id^='"+refresh+"-']").mask();
				//$("[id^='"+refresh+"-']").html('<div style="height: '+$("[id^='"+refresh+"-']").height()+'px; width: '+$("[id^='"+refresh+"-']").width()+'px;"><img src="/images/prettyPhoto/facebook/loader.gif" style="margin-left: '+$("[id^='"+refresh+"-']").width()/2+'px; margin-top: '+$("[id^='"+refresh+"-']").height()/2+'px;"  /></div>');
			}
			var id = $("[id^='"+refresh+"-']").attr('id');
		}
		else
		{
			var id = $("[id^='"+formId+"-']").attr('id');
			var data = $('#'+id+' :input').fieldSerialize($(this).attr('name'));
			if($(data).size() == origSize) var data = $('#'+formId+' :input').fieldSerialize($(this).attr('name'));
			oldHtml = $('#'+id).html();
			if(typeof hideLoading == 'undefined' || hideLoading == false)
			{
				$('#'+id).mask();
				//$('#'+id).html('<div style="height: '+$('#'+id).height()+'px; width: '+$('#'+id).width()+'px;"><img src="/images/prettyPhoto/facebook/loader.gif" style="margin-left: '+$('#'+id).width()/2+'px; margin-top: '+$('#'+id).height()/2+'px;" /></div>');
			}
		}
		
		data['object'] = id;
		if(typeof params != 'undefined') 
		{
			for(key in params)
			{
				data[key] = params[key];
			}
		}
		
		var type = "POST";
		var method = $(this).parents('form:first').attr('method');
		if(typeof method != 'undefined')
		{
			if(method.toUpperCase() == "GET") 
			{
				type = "GET";
				data['methodGet'] = true;
				if(typeof window.location.hash != 'undefined' && window.location.hash != '' && window.location.hash != '#') var urlObject = $.parseQuery(window.location.hash.toString());
				if(typeof urlObject != 'undefined') 
				{
					var hash = window.location.hash.toString();
					for(key in urlObject)
					{
						if(typeof data[key] != 'undefined')
						{
							hash = hash.replace('&'+key+'='+urlObject[key], '').replace(key+'='+urlObject[key], '');
						}
					}
					window.location.hash = hash;
				}
			}
		}
		
		if(typeof window.location.hash != 'undefined' && window.location.hash != '' && window.location.hash != '#')
		{
			$.ajaxSetup({
			  url: window.location.hash.toString().replace('#', '')
			});
		}

		$.ajax({
			type: type,
			//url: (typeof url != 'undefined') ? url : false,
			data: data,
			dataType: 'json',
			success: function(msg)
			{
				if(typeof msg.error != 'undefined' && msg.error == true) showNotice(msg['notice'], msg['error']);
				if(typeof msg.data != 'undefined') $('#'+id).replaceWith(msg.data);
				if(typeof generalDisplay != 'undefined' && generalDisplay != false) showNotice(msg['notice'], msg['error']);
				if(typeof msg.getUrl != 'undefined' && msg.getUrl != false) window.location.hash = msg.getUrl;
				if(typeof callback == 'function') 
				{
					$.extend(data, msg);
					callback(data);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				$('#'+id).html(oldHtml);
				showNotice(trans.translate(textStatus.toUpperCase()), true);
			}
		});
	}
})(jQuery);

/**
 * Function that asks for confirmation
 * @access public
 * @return void
 **/
function confirmAction(msg, todo) 
{
	if(confirm(msg)) eval(todo);
	else return false;
}

/**
 * Selects all checkboxes
 * @access public
 * @return void
 **/
function adminSelectAll(what)
{
	$('.'+what+'-selection').each(function(){
		if($(this).attr('checked') == true) $(this).attr('checked', false);
		else $(this).attr('checked', true);
	});
}

/**
 * Define hr type float number
 * @access public
 * @return void
 **/
function defineNum(numGiven) 
{
	if(isNaN(numGiven))
	{
		numGiven = numGiven.replace(',', '.');
		numGiven = parseFloat(numGiven);
	}
	numGiven = Math.round(numGiven * 100)/100;
	numGiven += '';
	numGiven = numGiven.replace('.', ',');
	var split = numGiven.split(',');
	if (typeof (split[1]) == 'undefined') {
		numGiven += ',00';
	} else if (split[1].length == 1) {
		numGiven += '0';
	}
	return numGiven;
}


/**
 * Show notices
 * @access public
 * @return void
 **/
//global variable for notice div and hiding
var divsec = 0;
function showNotice(noticeGiven, error, container) 
{
	var notice = '';
	if (isArray(noticeGiven))
	{
		for (key in noticeGiven)
		{
			notice = notice + noticeGiven[key] + '<br /><br />';
		}
	} 
	else notice = noticeGiven + '<br /><br />';
	if(typeof container == 'undefined') container = 'noticediv';
	$('#'+container).hide();
	divsec++;
	if(error == true) notice = '<span style="color: #FF0000;">'+notice+'</span>';
	$('#'+container).html(notice);
	$('#'+container).show("slow");
	setTimeout("hideNotice('"+container+"');", 5000);
}

/**
 * Hide notices
 * @access public
 * @return void
 **/
function hideNotice(container) 
{
	divsec--;
	if (divsec == 0) {
		$('#'+container).hide('slow');
	}
}

function setCookie(c_name,value,expiredays) 
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate)
}

function getCookie(c_name) 
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
		}
	}
	return null;
}

/**
 * Check if a variable is an array
 * @access public
 * @return void
 **/
function isArray(obj) 
{
   if (typeof(obj) == "string") return false;
   else return true;
}

/**
 * Log out function
 * @access public
 * @return void
 **/
function logOut()
{
	$.fn.submitForm(false, false, false, { 'func': 'Session::logOut' }, function() { window.location = "/"; });
}

/**
 * Change acl
 * @access public
 * @return void
 **/
function changeAclStatus(action, objectId, groupId, element)
{
	if ($(element).attr('checked')) var checked = '1';
	else var checked = '0';

	var data = { func: 'AclPrivilages::updatePrivilage', action: action, objectId: objectId, groupId: groupId, checked: checked };
	$.fn.submitForm(false, false, true, data);
}

/**
 * Delete cache
 * @access public
 * @return void
 **/
function deleteCache()
{
	$.fn.submitForm(false, false, true, {'func': 'Cache::deleteCache'});
}

/**
 * Delete wiki cache
 * @access public
 * @return void
 **/
function deleteWikiCache()
{
	$.fn.submitForm(false, false, true, {'func': 'WikiObject::deleteWikiCache'});
}

/**
 * Cookie setting
 * @access public
 * @return void
 **/
function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function adminLogginUser(username)
{
	var data = { username: username, 'func': 'Session::adminLogginUser' };
	$.fn.submitForm(false, false, true, data);
}

function submitWiki()
{
	var name = $('#wikiName').val();
	var header = $('#wikiHeader').val();
	var langId = $('#wikiLang').val();
	var categoryId = $('#wikiCategory').val();
	var content = $('#wysiwyg0').val();
	
	var data = { 'func': 'WikiObject::submitWiki', name: name, langId: langId, header: header, categoryId: categoryId, content: content };

	$.fn.submitForm(false, false, false, data, function submitWikiFinish(val)
	{
		if(val['error'] == true) showNotice(val['notice'], val['error']);
		else
		{
			window.location = '/admin_new_wiki.html?id='+val['lastId'];
		}
	});
}

function editWiki(wikiId)
{
	var name = $('#wikiName').val();
	var header = $('#wikiHeader').val();
	var langId = $('#wikiLang').val();
	var categoryId = $('#wikiCategory').val();
	var content = $('#wysiwyg0').val();

	var data = { 'func': 'WikiObject::updateWiki', name: name, langId: langId, header: header, categoryId: categoryId, content: content, wikiId: wikiId };
	$.fn.submitForm(false, false, true, data);
}

function setWysiwyg()
{
	var data = {};
	$.fn.submitForm(false, false, false, {'func': 'WikiObject::setStyles'}, function setWysiwygFinish(val)
	{
		var select = '';
		for(var style in val['styles'])
		{
			select += '<option value="' + val['styles'][style] + '">' + val['styles'][style] + '</option>';
		}
		wysiwygStyles = select;

		editors = $("[id^='wysiwyg']").rte({
			css: ['css/wysiwyg.css'],
			controls_rte: rte_toolbar,
			controls_html: html_toolbar
		});
	});
}

function insertImage(id)
{
	var data = $('#'+id+' :input').fieldSerialize(false);
	window.opener.CKEDITOR.tools.callFunction(data['funcNum'], data['height'], function() 
	{
		// Get the reference to a dialog.
		var element, dialog = this.getDialog();

		// Check if it is an Image dialog.
		if (dialog.getName() == 'image') 
		{
			// Get the reference to a field that holds the "border size".
			element = dialog.getContentElement('info', 'txtHSpace');
			if(element) element.setValue('5');
			
			element = dialog.getContentElement('info', 'txtVSpace');
			if(element) element.setValue('5');
			
			element = dialog.getContentElement('info', 'txtAlt');
			if(element) element.setValue(data['imageName']);
			
			element = dialog.getContentElement('advanced', 'txtGenLongDescr');
			if(element) element.setValue(data['imageDesc']);
		}
	});
	self.close();
}

jQuery.fn.toogleRow = function(cssClass)
{
	var parent = $(this).parent();
	$(parent).children().each( 
		function()
		{
			$(this).removeClass(cssClass);
		}
	);
	$(this).addClass(cssClass);
};
