if(!window.console) {var console = {log: function(msg) {}}}

function show_dhtml_window(content, buttons, footer, is_not_show)
{
	var window_container = '<div id="%window_id%" class="window"><div class="h_window"></div><div class="m_window"><div class="c1"><div class="c2">%content%</div>%buttons_box%%footer%</div></div><div class="f_window"></div><!--[if lte IE 6.5]><iframe></iframe><![endif]--></div>';
	var button_container = '<button type="button" class="bt" onclick="%onclick%">%title%</button>';

	var now = new Date(), window_id = 'dhtml_' + now.getTime();

	var buttons_content = '';
	if(buttons instanceof Array && buttons)
	{
		for(var i in buttons)
		{
			if(buttons[i].params)
				var params = buttons[i].params;
			else
				var params = "'%window_id%'";

			buttons_content += button_container.replace('%title%', buttons[i].title).replace('%onclick%', buttons[i].handler + '(' + params + ')');
		}
	}

	var footer_content = '';
	if(footer)
		footer_content = footer;

	var window_content = window_container.replace('%content%', content).replace('%buttons_box%', buttons_content).replace('%footer%', footer_content).replace(/%window_id%/g, window_id);

	var w = $(window);
	var n = $(window_content)
		.css({left: (w.width() / 2) - 270, top: w.scrollTop() + (w.height() / 2) - 280})
		.appendTo(document.body);

	if(!is_not_show)
		n.show();

	w.bind('scroll', function(){n.css({top: w.scrollTop() + (w.height() / 2) - 180})});

	return window_id;
}

function set_notification(type, body, c)
{
	var content = get_system_window_content(body); 
	var params = c ? "'%window_id%', '" + c + "'" : "'%window_id%'";
	var window_id = show_dhtml_window(content, [{title: 'OK', handler: 'close_notification', params: params}]);
	$('#' + window_id).addClass('notice').find("button");
	
	if (c) $('#'+c).hide();
}

function set_confirm(type, body, callback, param, texts)
{
	var content = get_system_window_content(body);
	var params_yes = "'%window_id%', " + callback  + ", '" + param + "'";
	var params_no = "'%window_id%', false";
	var window_id = show_dhtml_window(content, [{title: 'Yes', handler: 'close_confirm', params: params_yes}, {title: 'No', handler: 'close_confirm', params: params_no}]);
	$('#' + window_id).addClass('notice').find("button");
}

function set_dialog(body, buttons)
{
	var container = '<div class="window_container2" id="open_dialog_container">%open_dialog_container%</div>';
	var content = container.replace('%open_dialog_container%', body);

	var window_id = show_dhtml_window(content, buttons, '', true);

	return window_id;
}

function get_system_window_content(body)
{
	var text = [];
	if(body instanceof Object)
		$.each(body, function (i, v){text.push(v)});
	else
		text = [body];

	var text_content = text.join('<br/>');
	var content = '<div class="window_container"><table style="height: 100px;"><tr><td style="height: 100%;">%text_content%</td></tr></table></div><div class="alert_ico"></div>';

	return content.replace('%text_content%', text_content).replace("<!--", '').replace("-->", '');
}

function close_system_window(window_id)
{
	$(window).unbind('scroll');
	$('#' + window_id).remove();
}

function close_notification(window_id, c)
{
	close_system_window(window_id);
	if (c) $('#'+c).show();
}

function close_confirm(window_id, callback_fnc, param)
{
	close_system_window(window_id);
	if($.isFunction(callback_fnc)) callback_fnc(param);
}

function redirect(url)
{
	window.location.href = url;
}

function do_request(section, subsection, params, receiver, file, show_loading, method)
{
	var req = new JsHttpRequest();
	var show_loading = (typeof(show_loading) != 'undefined') ? show_loading : true;

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			if(req.responseJS)
			{
				for(var i in req.responseJS)
				{
					if(i == 'error')
						set_notification('alert', req.responseJS[i]);
					else if(i == 'message')
						set_notification('notice', req.responseJS[i]);
					else if (i == 'redirect')
						redirect(req.responseJS[i]);
					else if(i != 'answer')
					{
						src = $('#' + i);

						if (!src.size()) continue;

						var regex_all = new RegExp('<script[^>]*>([\u0001-\uFFFF]*?)</script>', 'img');
						var regex_one = new RegExp('<script[^>]*>([\u0001-\uFFFF]*?)</script>', 'im');
						var matches = [];
						var match = '';

						matches = req.responseJS[i].match(regex_all);
						src.html(matches ? req.responseJS[i].replace(regex_all, '') : req.responseJS[i]);

						if (matches)
						{
							for(var i=0 ; i < matches.length ; i++ )
							{
								if(matches[i].match(regex_one)[1])
								{
									var sc = document.createElement("SCRIPT");
									sc.type="text/javascript";
									document.body.appendChild(sc);
									sc.text = matches[i].match(regex_one)[1];
								}
							}
						}

						$('form[@entity=ajax]', src).each(function()
						{
							var $$ = $(this), fn = $$.get(0).onsubmit, is_fn = $.isFunction(fn);
							if(is_fn) $$.removeAttr('onsubmit');
							$$.removeAttr('entity');
							$$.ajax_submit(false, is_fn ? fn : false, $$.get(0).method);
						});
					}
				}
			}
		
			if($.isFunction(receiver)) receiver(req.responseJS ? req.responseJS.answer : false);

			if(req.responseText) alert(req.responseText);

			$('#ajax_loading').hide();
		}
	}

	if(show_loading)
		$('#ajax_loading').show();

	if(file)
		params['file'] = $('!'+file);

	req.open(method || 'POST', CONF.host + section + '/' + subsection + '/', true);
	req.send(params);
}


String.prototype.str_replace = function(src, dst)
{
	return this.toString().split(src).join(dst);
}

$.params2json = function(d)
{
	if (d.constructor != Array) {
		return d;
	}
	var data={};
	for(var i=0;i<d.length;i++) {
		if (typeof data[d[i].name] != 'undefined') {
			if (data[d[i].name].constructor!= Array) {
				data[d[i].name]=[data[d[i].name],d[i].value];
			} else {
				data[d[i].name].push(d[i].value);
			}
		} else {
			data[d[i].name]=d[i].value;
		}
	}
	return data;
};

(function($) {
	$.fn.ajax_submit = function(cb, native_submit, method) {
		$(this).submit(function(){
			if((native_submit && native_submit()) || !native_submit) {
				var $$ = $(this), fn = $$.attr('id') + '_callback';
				var action = $$.attr('action').str_replace(CONF.host, '').split('/');
				var callback = (cb) ? cb : ((typeof(window[fn]) == 'function') ? function(r){window[fn](r);} : false);
				var file = ($$.attr('enctype') == 'multipart/form-data'
							&& typeof(file_id = $('input[@type=file]', this).attr('id')) != 'undefined'
							&& typeof($('input[@type=file]', this).attr('value')) != 'undefined'
							) ? file_id : false;

				do_request(action.shift(), action.shift(), $.params2json($$.serializeArray()), callback, file, true, method);
			}
			return false;
		});
	}
})(jQuery);

function now()
{
	var d = new Date();
	return parseInt(d.getTime()/1000 - d.getTimezoneOffset()*60)
}


function get_contents(id)
{
	return $('!'+id).innerHTML.replace("<!--", '').replace("-->", '');
}


$(document).ready(function() {

	if($.browser.msie)
	{
		var m = document.uniqueID && document.compatMode && !window.XMLHttpRequest && document.execCommand;
		try {
			if(!!m) m("BackgroundImageCache", false, true);
		}
		catch(oh){};
	}

	$('form[@entity=ajax]').each(function(){
		var $$ = $(this), fn = $$.get(0).onsubmit, is_fn = $.isFunction(fn);
		if(is_fn) $$.removeAttr('onsubmit');
		$$.removeAttr('entity');
		$$.ajax_submit(false, is_fn ? fn : false, $$.get(0).method);
	});
});

function htmlspecialchars(str)
{
	return str.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/, '"').replace(/\'/, '&prime;');
}

var cookie = {
	get: function(name)
	{
		var arg = name + "=";
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		while (i < clen)
		{
			var j = i + alen;
			if (document.cookie.substring(i, j) == arg)
				return this.get_value(j);

			i = document.cookie.indexOf(" ", i) + 1;
			if (i == 0)
				break;
		}
		return false;
	},

	set: function(name, value, expires, path, domain, secure)
	{
		document.cookie = name + "=" + escape (value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
	},

	delete_cookie: function(name, path, domain)
	{
		if(this.get(name))
			document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	},

	get_value: function(offset)
	{
		var endstr = document.cookie.indexOf (";", offset);
		if (endstr == -1)
			endstr = document.cookie.length;

		return unescape(document.cookie.substring(offset, endstr));
	},

	decode: function(utftext)
	{
		utftext = unescape(utftext);

		var string = '';
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length )
		{
			c = utftext.charCodeAt(i);

			if (c < 128)
			{
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224))
			{
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else
			{
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}

		return string;
	}
};