/////////////////////////////////////////////////////////////////
//Project:	Grades
//Author:	Nikos Tsiligaridis
//Version:	1.0
/////////////////////////////////////////////////////////////////

var g_app_name = "Praxis GSK";
/////////////////////////////////////////////////////////////////
// jQuery custom
/////////////////////////////////////////////////////////////////
jQuery.fn.center = function(b_animate)
{
	if(typeof b_animate == "undefined")
		b_animate = false;

	this.css("position", "absolute");

	var top = ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px";
	var left = ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px";

	if(b_animate)
	{
		this.animate({top: top, left: left}, 300);
	}
	else
	{
		this.css("top", top);
		this.css("left", left);
	}
}

/////////////////////////////////////////////////////////////////
// Request and load content into a container (load() alternative)
/////////////////////////////////////////////////////////////////
jQuery.fn.load_content = function(url, extra_data, method, success_callback, b_loading_show, b_generic_handler)
{
	var _this = this;

	ajax_load_content(url, extra_data, method, function(data, status, obj_http, b_success)
												{
													if(b_success)
														_this.html(data);

													if(typeof success_callback == "function")
														success_callback(data, status, obj_http, b_success);
												}, b_loading_show, b_generic_handler);
}

/////////////////////////////////////////////////////////////////
// Request table contents and append to tables body
/////////////////////////////////////////////////////////////////
jQuery.fn.load_table_content = function(url, extra_data, success_callback)
{
	var table_body = this.find("tbody");
	var pagination = this.next(".pagination_cont");

	table_body.hide();
	pagination.hide();

	// Get table column count for colspan
	var colspan = this.find("th").length;

	// Create empty row with spinner
	table_body.html("<tr class=\"tr_loader\"><td colspan=\"" + colspan + "\"></td></tr>");

	ajax_load_content(url, extra_data, "get", function(obj_json, status, obj_http, b_success)
									{
										if(typeof obj_json.data == "undefined" && b_success) // TEMP FIX???
											dialog("error", null, "Παρουσιάστηκε σφάλμα κατά τη φόρτωση του πίνακα.", ["ok"], null);

										table_body.html(obj_json.data);
										pagination.html(obj_json.pagination);

										if(typeof success_callback == "function")
											success_callback(obj_json);
									}, false, true);
	table_body.fadeIn();
	pagination.fadeIn();
}

/////////////////////////////////////////////////////////////////
// Get max val() of all elements
/////////////////////////////////////////////////////////////////
jQuery.fn.get_max_val = function()
{
	var max = 0;
	this.each(function()
	{
		var obj = $(this);

		if(obj.val() > max)
			max = obj.val();
	});

	return max;
}

/////////////////////////////////////////////////////////////////
// indexOf for IE
/////////////////////////////////////////////////////////////////
if(!Array.indexOf)
{
	Array.prototype.indexOf = function(arr)
	{
	    for(var i=0; i<this.length; i++)
	    {
	        if(this[i]==arr)
	            return i;
	    }
	    return -1;
	}
}

/////////////////////////////////////////////////////////////////
// indexOf for IE
/////////////////////////////////////////////////////////////////
Array.prototype.remove_val = function(val)
{
	while(1)
	{
		var index = this.indexOf(val);

		if(index == -1)
			break;

		this.splice(index, 1);
	}
}

/////////////////////////////////////////////////////////////////
// Simultaneous fadeout and slideup
/////////////////////////////////////////////////////////////////
jQuery.fn.fade_slide_up = function()
{
	this.animate({ height: 'toggle', opacity: 'toggle' }, 'slow');
}

/////////////////////////////////////////////////////////////////
// Generic dialog box
/////////////////////////////////////////////////////////////////
function dialog(type, title, content, buttons, callback)
{
	var dlg = $("#dialog");

	var icon_ok = "templates/images/icon_check_big.png";
	var icon_error = "templates/images/icon_x_big.png";
	var icon_info = "templates/images/icon_info_big.png";

	// Decide icon
	if(type == "ok")
		dlg.find(".dialog_icon img").attr("src", icon_ok);
	else if(type == "error")
		dlg.find(".dialog_icon img").attr("src", icon_error);
	else
		dlg.find(".dialog_icon img").attr("src", icon_info);

	// Set title
	if(title == null)
		dlg.find(".dialog_title").text(g_app_name);
	else
		dlg.find(".dialog_title").text(title);

	// Set content
	dlg.find(".dialog_content").html(content);

	// Clone a button to use as template
	var btn_tpl = dlg.find(".dialog_buttons input:first-child").clone();

	// Empty buttons div
	var dlg_buttons = dlg.find(".dialog_buttons");
	dlg_buttons.html("");

	// Build buttons
	for(btn in buttons)
	{
		btn = buttons[btn];
		var btn_clone = btn_tpl.clone();

		switch(btn)
		{
		case "ok":
			btn_clone.click(function(){if(typeof callback == "function")callback("ok");dlg.hide();});
			btn_clone.attr("name", "btn_ok").attr("value", "Εντάξει").appendTo(dlg_buttons);
			break;
		case "cancel":
			btn_clone.click(function(){if(typeof callback == "function")callback("cancel");dlg.hide();});
			btn_clone.attr("name", "btn_cancel").attr("value", "Άκυρο").appendTo(dlg_buttons);
			break;
		case "yes":
			btn_clone.click(function(){if(typeof callback == "function")callback("yes");dlg.hide();});
			btn_clone.attr("name", "btn_yes").attr("value", "Ναί").appendTo(dlg_buttons);
			break;
		case "no":
			btn_clone.click(function(){if(typeof callback == "function")callback("no");dlg.hide();});
			btn_clone.attr("name", "btn_no").attr("value", "Όχι").appendTo(dlg_buttons);
			break;
		case "continue":
			btn_clone.click(function(){if(typeof callback == "function")callback("continue");dlg.hide();});
			btn_clone.attr("name", "btn_continue").attr("value", "Συνέχεια").appendTo(dlg_buttons);
			break;
		case "close":
			btn_clone.click(function(){if(typeof callback == "function")callback("close");dlg.hide();});
			btn_clone.attr("name", "btn_close").attr("value", "Κλείσιμο").appendTo(dlg_buttons);
			break;
		}
	}

	// Center, display
	dlg.center();
	dlg.fadeIn("fast");
}

/////////////////////////////////////////////////////////////////
// Show loading wnd
/////////////////////////////////////////////////////////////////
function loading_show()
{
	var loading = $("#wnd_loading");

	loading.center();
	loading.show();
}

/////////////////////////////////////////////////////////////////
// Hide loading wnd
/////////////////////////////////////////////////////////////////
function loading_hide()
{
	$("#wnd_loading").hide();
}

/////////////////////////////////////////////////////////////////
// Submit form ajax wrapper
/////////////////////////////////////////////////////////////////
function ajax_form_submit(form_id, method, url, extra_data, success_callback, b_loading_show, b_generic_handler)
{
	if(typeof b_loading_show == "undefined")
		b_loading_show = true;
	if(typeof b_generic_handler == "undefined") // Run generic success handler by default
		b_generic_handler = true;

	var form = $("#" + form_id);
	var form_data = form.serialize();

	if(form.length < 1)
	{
		alert("Form not found.");
		return false;
	}

	if(typeof extra_data != "undefined")
	{
		for(k in extra_data)
			form_data += "&" + k + "=" + extra_data[k];
	}
	form_data += "&ajax=1";

	$.ajax({cache: false,
			data: form_data,
			dataType: "application/json",
			error: ajax_on_error,
			complete: ajax_on_complete,
			type: method,
			url: url,
			success: function(data, status, obj_http)
						{
							var b_success = true;

							// Handle data too?
							if(b_generic_handler)
							{
								var ret = ajax_generic_response_handler(data);

								data = ret.data;
								b_success = ret.b_success;
							}

							// Has callback?
							if(typeof success_callback == "function")
								success_callback(data, status, obj_http, b_success);
						}
			});

	return true;
}

/////////////////////////////////////////////////////////////////
// Submit common ajax request
/////////////////////////////////////////////////////////////////
function ajax_load_content(url, extra_data, method, success_callback, b_loading_show, b_generic_handler)
{
	if(typeof extra_data == "undefined")
		extra_data = "";
	if(typeof b_loading_show == "undefined")
		b_loading_show = true;
	if(typeof b_generic_handler == "undefined") // Run generic success handler?
		b_generic_handler = true;
	if(typeof method == "undefined" || method == null)
		method = "get";

	if(b_loading_show)
		loading_show();

	var extra_data_str = "ajax=1";
	if(typeof extra_data != "undefined" && extra_data != null)
	{
		for(k in extra_data)
			extra_data_str += "&" + k + "=" + extra_data[k];
	}

	$.ajax({cache: false,
			data: extra_data_str,
			dataType: "text/html",
			error: ajax_on_error,
			complete: ajax_on_complete,
			type: method,
			url: url,
			success: function(data, status, obj_http)
					{
						var b_success = true;

						// Handle data too?
						if(b_generic_handler)
						{
							var ret = ajax_generic_response_handler(data);

							data = ret.data;
							b_success = ret.b_success;
						}

						// Has callback?
						if(typeof success_callback == "function")
							success_callback(data, status, obj_http, b_success);

						loading_hide();
					}
			});
}

/////////////////////////////////////////////////////////////////
// Generic ajax response handler
/////////////////////////////////////////////////////////////////
function ajax_generic_response_handler(data)
{
	try
	{
		var b_success = true;
		var obj_json = $.parseJSON(data);

		if(obj_json.type == "message")
		{
			dialog(obj_json.msg_type, obj_json.title, obj_json.content, ["ok"], null);

			if(obj_json.msg_type == "error")
				b_success = false;
		}

		return {data: obj_json, b_success: b_success};
	}
	catch(err)
	{
		return {data: data, b_success: true};
	}
}

/////////////////////////////////////////////////////////////////
// Ajax default handler: error
/////////////////////////////////////////////////////////////////
function ajax_on_error(obj_http, status, error)
{
	alert("error");
	dialog("error", "Σφάλμα", "Παρουσιάστηκε κάποιο σφάλμα. Παρακαλώ ξαναδοκιμάστε σε λίγο.", "ok");
}

/////////////////////////////////////////////////////////////////
// Ajax default handler: req complete (with or without errors
/////////////////////////////////////////////////////////////////
function ajax_on_complete(obj_http, status)
{}


/////////////////////////////////////////////////////////////////
// Window class
/////////////////////////////////////////////////////////////////
function wnd(id, b_modal, callback_on_close)
{
	var _this = this;

	// If id empty or already exists
	if(id.length == 0 || $("#wnd_" + id).length > 0)
		return false;

	// Called when closed
	this.callback_on_close = callback_on_close;

	// Properties
	this.id = "wnd_" + id;
	this.b_modal = b_modal ? true : false;

	// If modal, create lightbox
	if(this.b_modal)
		this.obj_lightbox = new lightbox(id);

	// Clone html
	this.obj = $("#window").clone().attr("id", this.id);
	this.obj.appendTo("body");

	// Set zindex and ++
	this.obj.css("z-index", wnd.last_zindex);
	wnd.last_zindex += 2;

	// Set onclick event for close button
	this.obj.find(".window_close").click(function()
											{
												_this.hide();


												if(typeof _this.callback_on_close != "undefined")
													_this.callback_on_close();

												_this.destroy();
											});
}
// Keeps track of current z-index max val
wnd.last_zindex = 10000;

wnd.prototype.load_url = function(url, success_callback)
{
	var callback = null;
	var _this = this;

	if(typeof success_callback == "function")
		callback = success_callback;

	ajax_load_content(url, null, "get", function(data, status, obj_http, b_success)
									{
										if(typeof callback == "function")
											response = callback(data, status, obj_http);

										if(b_success)
										{
											_this.content(data);
											_this.show();
										}
									}, true, true);
}

wnd.prototype.content = function(content)
{
	$("#" + this.id + " .window_content").html(content);
}

wnd.prototype.show = function(b_fade)
{
	if(this.b_modal)
	{
		this.obj_lightbox.set_zindex(this.obj.css("z-index") - 1);
		this.obj_lightbox.show();
	}
	this.obj.center();
	this.obj.fadeIn();
}

wnd.prototype.hide = function(success_callback)
{
	if(this.b_modal)
		this.obj_lightbox.hide();
	this.obj.fadeOut(400, success_callback);
}

wnd.prototype.destroy = function()
{
	var _this = this;

	this.hide(function(){_this.obj.find(".window_content").empty();});
}

/////////////////////////////////////////////////////////////////
// Lightbox class
/////////////////////////////////////////////////////////////////
function lightbox(id)
{
	// If id empty or already exists
	if(id.length == 0 || $("#lightbox_" + id).length > 0)
		return false;

	// Properties
	this.id = "lightbox_" + id;

	// Create lightbox
	$("body").append("<div id=\"" + this.id + "\" class=\"lightbox\"></div>")

	this.obj = $("#" + this.id);
}

lightbox.prototype.show = function(b_fade)
{
	if(b_fade)
		$("#" + this.id).fadeIn();

	else
		$("#" + this.id).show();
}

lightbox.prototype.set_zindex = function(zindex)
{
	this.obj.css("z-index", zindex);
}

lightbox.prototype.hide = function(b_fade)
{
	if(b_fade)
		$("#" + this.id).fadeOut();
	else
		$("#" + this.id).hide();
}

/////////////////////////////////////////////////////////////////
// Autocomplete
/////////////////////////////////////////////////////////////////
function on_autocomplete_select(event, ui)
{
	if(ui.item.value == -1)
		return false;
	else
	{
		window.location = "products.php?mode=prd_view&prd_id=" + ui.item.value;
		return false;
	}
}

function on_autocomplete(request, response)
{
	var _this = this;
	if(typeof this.cached == "undefined")
		this.cached = new Array;

	if(request.term in (this.cached))
	{
		response(this.cached[request.term]);
		return;
	}

	$.ajax({
			url: "ajax_search.php",
			dataType: "json",
			data: "mode=search&keyword=" + request.term,
			success: function(data)
					{
						_this.cached[request.term] = data;
						response(data);
					}
			});
}


/////////////////////////////////////////////////////////////////
// Open cat browser
/////////////////////////////////////////////////////////////////
function cat_browser_open(callback)
{
	if(typeof this.wnd_browser == "undefined")
		this.wnd_browser = new wnd("cat_browser", true);

	this.wnd_browser.load_url("cat_browser.php?callback=" + callback);
}
