Function.prototype.clone=function(){
    return eval('['+this.toString()+']')[0];
};
Date.prototype.getUTCTotalMilliseconds = function() {
	return this.valueOf()-this.getTimezoneOffset()*60*1000;
};

var Common = function() {};

Common.TimeLine = function(url) {
	if(url === undefined) {
		TimeLine.request_end = new Date();
		console.log(
			url, ": ", 
			TimeLine.request_start.toLocaleTimeString() + "." + TimeLine.request_start.getMilliseconds(), "||", 
			p.getResponseHeader("START"), "||",
			p.getResponseHeader("END"), "||",
			p.getResponseHeader("TOTAL"), "||",
			TimeLine.request_end.toLocaleTimeString() + "." + TimeLine.request_end.getMilliseconds()					
		);				
	}else{
		TimeLine.request_start = new Date();
	}
};

$(function($) {
	var elm = $("<pre></pre>");

	function show_error(txt) {
		if (Common.Connector.modalError === undefined) {
			var html = $("#message_box").clone().show();
			html.find("span").html(txt);
			html.find("input").hide();
			html.find("[name='reset']").show().click(function(){
				window.location.reload();
				$.fn.colorbox.close;
			});
			Common.Connector.modalError = $.fn.colorbox({
				transition: "none", 
				html: html,
				onClosed: function() { Common.Connector.modalError = undefined; }
			});
		}
	}
	
	
	Common.Connector = function(url, events) {
		var _events = $.extend({
				onStart: function() { },
				onCompleted: function(response, callback) { callback.call(this, response); }
			}, events);
		
		this.Post = function(method, data, callback) {
			var _this = this;
			function _callback(response) {
				if (response && response.IsLogged === false) {
					document.location = response.RedirectUrl;
				} else if (response && response.ServerError == true) {
					show_error("<pre>Internel Server Error</pre>");
				} else {
					_events.onCompleted.call(_this, response, callback);
				}
			}

			if (method !== undefined) {
				this.method = method;
				this.data = data;
				this.callback = callback;
			}
			
			_events.onStart.call(this);		
			$.post(url + this.method, $.toJSON(this.data), _callback, "json");
		};
	};

	Common.status_loading = new function() {
		var count = 0;
		var elm = $("#loading");
		this.show = function() {
			count++;
			elm.show();
		}
		this.hide = function() {
			count--;
			if(count <= 0) {
				count = 0;
				elm.hide();
			}
		}
	};
	
	elm.ajaxError(function(event, request, settings) {
		if (Common.Connector.modalError === undefined) {
			var msg;
			if (request.status == 200) {
				return;
			} else if (request.status == 0) {
				msg = 'You are currently offline.\n Please check your network connection.';
			} else {
				msg = 'Internel Server Error.';
			}
			show_error(msg);
		}
	});
	elm.ajaxStart(function() {
		Common.status_loading.show();
	});
	elm.ajaxStop(function() {
		Common.status_loading.hide();
	});	
});
