/**
  * chaos v poctu parametru
  * (puvodne definovana se dvemi parametry a vetsinou volana s jednim => problem)
  */
function k2GetElementById()
{
	if ($('#' + arguments[0]).get(0)) {
	  return $('#' + arguments[0]).get(0);
	 }
	else {
		return document.getElementById(arguments[0]);
	}
}

function notImplemented(name)
{
	alert("Function " + name + " is not implemented, pls contact web development team!");
}

function ajax_innerHTML(param) {notImplemented('ajax_innerHTML');}
function ajax_fillSelect(param) {notImplemented('ajax_fillSelect');}
function ajax_setValue(param) {notImplemented('ajax_setValue');}
function ajax_fill_select(param) {notImplemented('ajax_fill_select');}
function ajax_ShowPopup(param) {notImplemented('ajax_ShowPopup');}
function ajax_k2SubmitForm(param) {notImplemented('ajax_k2SubmitForm');}
function k2_CallK2BL(app, object, func, param, ajax_wait) {notImplemented('k2_CallK2BL');}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

var k2 = {
	scripts: []
};

k2.scripts.add = function (url)
{
	if (k2.scripts.indexOf(url) == -1) k2.scripts.push(url);
};

$.ajaxSetup({
	type: 'post'
//	dataType: 'json' //petr.001 jQuery 1.3 fix, seems to be working ;-)
});

$._ajax = $.ajax;

$.ajax = function (options)
{
	if (options.loaderShow)
	{
		$(options.loaderHTML
			? options.loaderHTML
			: '<div style="position: absolute; top: '
			+ ($(window).scrollTop() + ($(window).height() / 2) - 30)
			+ 'px; left: 0px; width: 100%; text-align: center; z-index: 999999;">'
			+ '<div style="width: 15em; margin: 0 auto; padding: .5em; background: #fff; border: #000 1px solid; color: #000;">'
			+ '<p><img src="/mda/css/blue/ajax-loader-big.gif" alt="..." /></p>'
			+ '<p><b>Loading...</b></p></div></div>')
			.hide().appendTo(options.loaderAppendTo ? options.loaderAppendTo : 'body')
			.ajaxStart(function () { $(this).show().bgIframe({opacity: true}); })
			.ajaxStop(function () { $(this).hide().remove(); });

		delete options.loaderShow;
	}

	options.url += ((options.url.indexOf("?") == -1) ? "?" : "&")
			+ "k2jsPageId=" + k2.pageId
			+ "&k2sessionId=" + k2.sessionId;

	/*
	if (options.manager)
	{
		m = options.manager;
		delete options.manager;
		m.add(options);
	}
	else
	*/
	{
		k2.ajax.isError = false;
		$._ajax(options);
		k2.ajax.isError = false;
	}
};


$._getScript = $.getScript;

$.getScript = function (url, callback)
{
	clean_url = url.replace(/.r=[0-9]+$/, ''); // get rid of revision number

	if (k2.scripts.indexOf(clean_url) == -1)
	{
		k2.scripts.add(clean_url);
		$._getScript(url, callback);
	}
	else if (typeof callback == 'function')
	{
		callback();
	}
};


/**
	* JavaScript ekvivalent funkce CK2Application::MakeUrl() (resp. k2DoActionUrl())
	*
	* @param Object request - parametry pro vyskladani requestu:
	*   app: 'string' ... pokud nezadan, pouzije se z aktualni url
	*   action: 'string'
	*   module: 'string'
	*   object: 'string'
	*   func: 'string'
	*   mode: int
	*
	* @return string
	*/
k2.makeUrl = function (request)
{
	if (request.app)
	{
		url = 'http://' + location.hostname + (location.port ? (':' + location.port) : '') + '/' + request.app + '/';
	}
	else
	{
		url = location.href.replace(/\?.*$/, '');
	}

	params = [];

	if (request.action) params.push('k2MAIN[action]=' + request.action);
	if (request.module) params.push('module=' + request.module);
	if (request.object) params.push('object=' + request.object);
	if (request.func) params.push('function=' + request.func);
	if (request.mode) params.push('mode=' + request.mode);

	url = url + '?' + params.join('&');

	return url;
};


/**
	* Pomocnik pro AJAX v knihovne k2work
	*
	* @param properties - objekt, vsechno co akceptuje $.ajax() plus neco navic:
	*   taconite: boolean (true if not set)
	*
	* vybiram dulezite z akceptovanych $.ajax()
	*   data: Object
	*   success: function ... pokud nastavena, nikdy nepouzije taconite
	*/
k2.ajax = function (properties)
{
	if (!properties.url)
	{
		properties.mode = 5; // AJAX
		properties.url = k2.makeUrl(properties);
	}

	if (typeof(properties.taconite) == 'undefined')
	{
		properties.taconite = 1;
	}

	if (properties.taconite && typeof(properties.success) == 'undefined')
	{
		properties.url += '&taconite=1'
		properties.dataType = 'xml';
	}
	else if (typeof(properties.dataType) == 'undefined')
	{
		properties.dataType = 'json';
	}

	$.ajax(properties);
};


/**
 * Prints a message to firebug console (if available)
 *
 * @see $.taconite.log
 */
k2.log = function ()
{
	if (!window.console || !window.console.log) return;
	window.console.log('[k2] ' + [].join.call(arguments,''));
}


k2.chainedSelectChange = function (event)
{
	//val = $(this).val();
	//all = $('#' + event.data.id + ' select').serializeArray();

	var chainedSelectChangeParams = {url: event.data.url, data: {'sel': event.data.sel, 'id': event.data.id}, loaderShow: event.data.loaderShow};
	pattern = '^' + event.data.name + '\\[([^\\]]+)\\].*$';
	var chainedSelectChangeRE = new RegExp(pattern);

	$('#' + event.data.id + ' select, #' + event.data.id + ' input').each(function ()
	{
		chainedSelectChangeParams.data[$(this).attr('name').replace(chainedSelectChangeRE, 'chain[$1]')] = $(this).val();
		// pro funkcnost s multiselectem
		if (($(this).val() != null) && ($(this).attr('multiple')))
		{
			var key = $(this).attr('name').replace(chainedSelectChangeRE, 'chain[$1]');

			for (k in $(this).val())
			{
				if (k != 'inArray')
				{
					chainedSelectChangeParams.data[key+'['+k+']'] = $(this).val()[k];
				}
			}
		}
	});

	k2.ajax(chainedSelectChangeParams);
};


k2.formElementArrayAdd = function (id)
{
	opts = k2.formElementArray[id];

	html = $(opts.template
					.replace(new RegExp("%i%" + id + "%", "g"), opts.count)
					.replace(/%h/g, (opts.count + 1))).hide();
	
	$(opts.row_selector + ':last').after(html);
	
	if ($(opts.row_selector + ':last').size() == 0)
	{
		aux = $(opts.arr_selector).prepend(html);
		/*$('.k2form-element-array-adder', aux).removeClass('k2form-element-array-adder-zero')
			.html('<span class="p">' + opts.adder_plus + '</span>');*/
	}

	if (opts.callback_add(id, opts.count, html))
	{
		if (opts.validator)
		{
			if (opts.validator.rules) eval(opts.validator.rules.replace(new RegExp("%i%" + id + "%", "g"), opts.count));
			if (opts.validator.messages) eval(opts.validator.messages.replace(new RegExp("%i%" + id + "%", "g"), opts.count));
		}
		
		if (opts.init_js)
		{
			eval(opts.init_js.replace(new RegExp("%i%" + id + "%", "g"), opts.count));
		}

		if (opts.allow_del)
		{
			html.find('.k2form-element-array-remover').click(opts.event_del);
		}

		k2.formElementArray[id].count++;
		k2.formElementArray[id].real_count++;
		
		html.show();
		
		if ( $(html).is("tr") ) {$(html).css("display", "");}//jq 1.4 -> show produces display:block
	}
	else
	{
		html.remove();
	}
};

k2.formElementArrayDel = function (id, row)
{
	opts = k2.formElementArray[id];//alert(id+' '+row);
	
	//unknown bug bugfix
	if(!isNaN(row) && row<0) return;
	
	if (opts.callback_del(id, row))
	{
		$(opts.row_selector + (row == 'last' ? ':last' : ':eq(' + row + ')')).hide().remove();

		k2.formElementArray[id].real_count--;

		/*if (k2.formElementArray[id].real_count == 0)
		{
			$(opts.arr_selector + ' .k2form-element-array-adder')
				.addClass('k2form-element-array-adder-zero')
				.html('<span class="c">' + opts.adder_caption + '</span> <span class="p">' + opts.adder_plus + '</span>');
		}*/
	}
};

k2.formElementArrayDelEvent = function (id, element)
{
	offset = $('#k2form-element-array-' + id + ' .k2form-element-array-remover-' + id).index(element);
	//alert(id + " " + offset);
	k2.formElementArrayDel(id, offset);
};


k2.setValue = function (params)
{
	for (key in params) {
		if (key != "inArray") // TODO: QA: WTF? prinejmensim chybi comment, co to dela
			$("#"+key).val(params[key]);
	}
};


$.fn.loadSelect = function (newContent)
{
	this.empty().append(newContent);
};


k2.previousSelectedIndex = null;

k2.disableSelects = function ()
{
	$('select')
		.focus(function () { k2.previousSelectedIndex = this.selectedIndex; })
		.change(function ()
			{
				if ($(this.options[this.selectedIndex]).is('.disabled'))
				{
					this.selectedIndex = k2.previousSelectedIndex;
				}
				else
				{
					k2.previousSelectedIndex = this.selectedIndex;
				}
			});
};


/**
 * Udalost - stisk klavesy enter na elementu
 */
$.fn.enterDown = function (cb)
{
	k2.enterDownCallback = cb;
	$(this).keydown(function (event) { if (event.keyCode == 13) return cb(event); });
};


k2.dialogOpen = function (id)
{
	dlg = k2.dialog[id];

	if (dlg.k2ajax)
	{
		k2.ajax({
			url: dlg.k2ajax.url,
			dataType: 'html',
			dialog: dlg,
			data: dlg.k2ajax.data,
			loaderShow: true,
			success: function (result) { this.dialog.html(result).dialog('open'); }
			});
	}
	else
	{
		dlg.dialog('open');
	}

	return dlg;
};

k2.dialogClose = function (id)
{
	k2.dialog[id].dialog('close');

	return k2.dialog[id];
};


k2.dateFix = function ()
{
	$(this).val(k2.dateFixServant($(this).val()));
};
k2.dateFixServant = function (d)
{
	if (d.length == 6) return d.replace(/([0-9]{2})([0-9]{2})([0-9]{2})/, "$1.$2.20$3");
	else if (d.length == 8) return d.replace(/([0-9]{2})([0-9]{2})([0-9]{4})/, "$1.$2.$3");
	else return d;
};

k2.dateFix_hu = function ()
{	
	$(this).val(k2.dateFixServant_hu($(this).val()));
};
k2.dateFixServant_hu = function (d)
{
	if (d.length == 6) return d.replace(/([0-9]{2})([0-9]{2})([0-9]{2})/, "20$1.$2.$3");
	else if (d.length == 8) return d.replace(/([0-9]{4})([0-9]{2})([0-9]{2})/, "$1.$2.$3");
	else return d;
};

k2.formSelectAndOtherChangeCB = function ()
{
	var txtWrapper = $(this).parent().parent().children().eq(1);

	if ($(this).children(':last').is(":selected"))
	{
		txtWrapper.css("display", "inline-block");
//		txtWrapper.children('input').val('');
	}
	else
	{
		txtWrapper.css("display", "none");
		txtWrapper.children('input').val($(this).children(':selected').text());
	}
}

/* fce pro vycentrovani prvku
	pokud je zadan element_close_id prida na tento prvek na onclick
	fci pro odstraneni divu
	(<div id="element_div"><div id="element_close_div">content</div></div>)

	TODO: overit, jestli tohle neresi jquery.dimension plugin
	TODO: refactor: k2.centerElement
*/
function centerElement(element_id, element_close_id)
{
	if (window.innerWidth){
		winW = window.innerWidth;
		winH = window.innerHeight;
	}else if (document.documentElement && document.documentElement.clientWidth != 0){
		winW = document.documentElement.clientWidth;
		winH = document.documentElement.clientHeight;
	}
	else if (document.body){
		winW = document.body.clientWidth;
		winH = document.body.clientHeight;
	}

	var poz_y = (((winH/2)+document.documentElement.scrollTop)-((((document.getElementById(element_id).style.height).replace('px','')*1)/2))+'px');
	var poz_x = (((winW/2)+document.documentElement.scrollLeft)-((($("#"+element_id).css('width').replace('px',''))/2)*1)+'px');

	$("#"+element_id).css('position', 'absolute');
	$("#"+element_id).css('top', poz_y);
	$("#"+element_id).css('left', poz_x);
	$("#"+element_id).css('visibility', 'visible');

	if (element_close_id)
	{
		$("#"+element_close_id).click(function()
			{
				$("#"+element_close_id).parent("div").css("visibility", "hidden");
				$("#"+element_close_id).parent("div").children().eq(1).empty();
			});
	}
}

var centerDiv = centerElement;


$.fn.colorize = function ()
{
	$(this).find('tr').click(function () { $(this).toggleClass('hilite'); });
};

