/*
function buttons() {
	$("button.button,input.button").hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	);
};

function create_dialog(jqObj) {
	jqObj.dialog({
		autoOpen: false,
		modal: true,
		width: 'auto',
		//hide: 'slide',
		position: 'center',
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});
}
*/

function create_dialog(id) {
	if (!$('#' + id)[0])
		$('body').append('<div id="' + id + '" class="jqmWindow" style="display:none">dialog</div>');

	return $('#' + id).jqm({ modal : true });
}

function attach_dialog(jq, url, dialog_id) {
	if (!dialog_id) var dialog_id = 'main_dialog';
	var dialog = create_dialog(dialog_id);

	jq.live('click', function() {
		add_params = $(this).attr('p'); 
		if (add_params) {
			if (url.match(/\?/))
				add_params = '&' + add_params;
			else
				add_params = '?' + add_params;
		} else {
			add_params = '';
		}

		getHTML(dialog, url + add_params, function() {
			dialog.prepend('<div class="jqmClose close-button"></div>').jqmShow();
		});
	
		return false;
	});
}

function close_dialog() {
	$('div.jqmClose:visible').click();
}

var indicator;
var indicator_count = 0;
function spi() {
	if (jQuery().achtung) {
		indicator_count++;
		if (indicator_count == 1)
			indicator = $.achtung({disableClose: true, message: 'Моля изчакайте', timeout: 0});
	}
}

function hpi() {
	if (jQuery().achtung) {
		indicator_count--;
		if (indicator_count == 0)
			indicator.achtung('close');
	}
}

function showMsg(type, msg) {
	if (type == 'error') {
		$.achtung({message: msg, className: 'achtungFail', timeout: 0});
	} else if (type == 'success') {
		$.achtung({message: msg, className: 'achtungSuccess', timeout: 5});
	} else {
		alert("Unknown error.");
	}
}

$.fn.serializeAnything = function() {
	var return_array = false;
	if (typeof(arguments) == "object" && arguments.length >= 1) {
		return_array = arguments[0];
	}
	
	var toReturn = [];
	var els = $(this).find(':input').get();
	$.each(els, function() {
		if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
			var val = $(this).val();
			if (return_array === false) {
				toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ));
			} else {
				toReturn.push({ name: this.name, value: val });
			}
		}
	});
	return (return_array === false) ? toReturn.join("&") : toReturn;
}

$.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = $.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
}

function getHTML(element, url, params, callback) {
	if (typeof url !== "string")
		return $.load(url);

	var off = url.indexOf(" ");
	if (off >= 0) {
		var selector = url.slice(off, url.length);
		url = url.slice(0, off);
	}

	var type = "GET";
	if (params) {
		if ($.isFunction( params )) {
			callback = params;
			params = null;
		} else if (typeof params === "object") {
			params = $.param( params );
			type = "POST";
		} else if (typeof params === "string") {
			type = "POST";
		}
	}

	spi();
	var req = $.ajax({
		url: url,
		type: type,
		dataType: "html",
		data: params,
		success: function(result, status, res) {
			hpi();
			if (result.substr(0, 1) === '{') {
				try {
					var obj = eval("(" + result + ")");
					if (obj.logged_out)
						session_expired();
					else
						showMsg('error', obj.err);
				} catch(e) {
					showMsg('error', 'error_parsing_ajax_result');
				}
				return false;
			}
			if (element && (status == "success" || status == "notmodified"))
				element.html(selector ? $("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g, "")).find(selector) : res.responseText);

			if (element && callback)
				element.each(callback, [res.responseText, status, res]);
			else if (callback)
				callback(res.responseText, status, res);
		}
	});

	return element;
}

function getJSON() {
	var args = Array.prototype.slice.call(arguments);
	var action = args.shift();
	var data = {};
	var callback = function() {};
	var method = 'get';
	var async = true;

	if (args.length >= 1 && (typeof args[0] === 'object' || typeof args[0] === 'string'))
		data = args.shift();
	
	if (args.length >= 1 && typeof args[0] === 'function')
		callback = args.shift();

	if (args.length >= 1 && typeof args[0] === 'string')
		method = args.shift();

	if (args.length >= 1 && typeof args[0] === 'boolean')
		 async = args.shift();

	spi();
	if (method === 'get') {
		if (async) {
			$.get(action, data, function(result) {
				hpi();
				if (result.logged_out) {
					session_expired();
					return false;
				}
				callback(result);
			}, 'json');
		} else {
			var v = $.ajax({
				url: action,
				async: false,
				"data": data,
				"dataType": "json"
			}).responseText;

			hpi();
			eval("var ret = " + v);
			return ret;
		}
	} else if (method === 'post') {
		$.post(action, data, function(result) {
			hpi();
			if (result.logged_out) {
				session_expired();
				return false;
			}
			callback(result);
		}, 'json');
	} else {
		hpi();
		showMsg('error', 'invalid_request_method');
		return false;
	}
}

function session_expired() {
	showMsg('error', 'session_expired');
	setTimeout(function(){ location.href = '/' }, 2000);
	//show_login(element, url, params, ( callback ) ? callback : function() {}, loadSafe);
}


