cAPI = function() {

	this.init = function() {

//		$.getScript(JS_LIBS_URL + 'libs/sifr-config.js');

		API.includes();
		
		$.getScript(JS_LIBS_URL + 'libs/jquery/jquery.scrollTo-min.js');
		$.getScript(JS_LIBS_URL + 'libs/jquery/hotkeys.js');
		$.getScript(JS_LIBS_URL + 'libs/jquery/form.js');

//		console.log(ACL_ADMIN);

		API.editing = '';
		API.button = '';
		API.menuTimer = '';
		API.maxZ = 500;
		API.idGen = 1;
		API.mx = 0;
		API.my = 0;
		API.delta = 0;

		$.SetImpromptuDefaults({
					prefix: 'impromptu',
					show: 'slideDown',
					opacity: 0.8
		});

		$.ajaxSetup({
			type: "POST"
		});

		API.control();

		$('<div id="systemWorking">&nbsp;</div>').appendTo(document.body);
//		$('#systemWorking').html('<p class="aCenter" style="margin-top: 200px;"><img alt="" src="' + WWW_ROOT + 'themes/images/loading.gif"/></p>');
		$('<img id="throbber" src="' + WWW_ROOT + 'themes/images/throbber.gif"/>').appendTo("#container");
		$('#throbber').css({
			'position' : 'absolute',
			'display' : 'none',
			//'left' : (($(document).width() / 2) - 16) + 'px',
			'left' : '48%',
			'top' : '530px',
			'z-index' : '1000'
			//'top' : (($(document).height() / 2) - 16) + 'px'
		});
		 $("#throbber").ajaxStart(function(){
				 $(this).fadeIn();
 		});
		 $("#throbber").ajaxStop(function(){
				 $(this).fadeOut();
 		});

		o = new API.createElement('div', API.AJAXTarget = 'AJAXTarget', 'absolute', 0, 50, 500, 200, 10);
		o.innerHTML = '&nbsp;';
		o.style.backgroundColor = 'white';
		o.style.border = '1px solid black';
		o.style.overflow = 'hidden';
		o.style.display = 'none';
		document.body.appendChild(o);

//		console.log(DOCUMENT_BASE);

		_hsh = window.location.hash;
		_hsh = _hsh.substr(0, 1);
		if (_hsh != '#') {
			//window.location.hash = '#/'+LANG_SHORTCUT+'/index.html';
		}
		
//		setTimeout(function(){API.editElement('id_23');}, 2000);
		$.Lightbox.domReady();
		
	};

	this.control = function() {

		if (typeof $.hotkeys == 'undefined' || typeof $().mousewheel == 'undefined') {
			setTimeout(function(){API.control();}, 100);
			return;
		};

		API.mousemove();

		$(document.body).mousewheel(function(event, delta) {
			API.mx = event.pageX;
			API.my = event.pageY;
			API.delta = delta || 0;
		});
		if (APL_LOGGED != 'YES') $.hotkeys.add('Ctrl+l',function (){
			$.getScript(WWW_ROOT + 'js/admin/core.login.js');
		});

		if (getCookie('API_mouse') == 'yes') {
			$.getScript(JS_LIBS_URL + 'admin/API.mouse.js');
		} else {
			$.hotkeys.add('Ctrl+m',function (){
				$.getScript(JS_LIBS_URL + 'admin/API.mouse.js');
			});
		}
		$.hotkeys.add('f5',function (){
			$('#systemWorking').fadeIn();
			window.location.reload();
		});
		$.hotkeys.add('Ctrl+f5',function (){
			$('#systemWorking').fadeIn();
			window.location.reload();
		});
		$.hotkeys.add('Ctrl+r',function (){
			$('#systemWorking').fadeIn();
			window.location.reload();
		});
		$.hotkeys.add('Ctrl+q',function (){
			window.location.replace('?logout');
		});
	};

	this.includes = function() {
		if (SEO_ADMIN == 1) {
			$.getScript(JS_LIBS_URL + 'admin/SEO.js');
			$.getScript(JS_LIBS_URL + 'admin/CMS.js');
		}
		if (ACL_ADMIN == 1) {
			$.getScript(JS_LIBS_URL + 'admin/gacl.js');
		}
		if (LAYOUT_ADMIN == 1) {
			$.getScript(JS_LIBS_URL + 'admin/layout.js');
		}
	};

	this.mousemove = function() {
		$(document).bind('mousemove', function(e){
			API.mx = e.pageX;
			API.my = e.pageY;
		});
	};
};

cAPI.prototype.throbber = function(id) {
		if (!id) return;
		if (document.getElementById(id)) $('#' + id).html('<p class="aCenter" style="margin-top: 25px;"><img alt="" src="' + WWW_ROOT + 'themes/images/throbber.gif"/></p>');
};

cAPI.prototype.addElement = function(id) {
	var url = WWW_ROOT + 'admin/addElement/';
	_id = $('#' + id).parent().attr('id');
	if (_id == '') _id = $('#' + id).parent().parent().attr('id');
	var pars = '_target_id=' + _id;
	$.post(url, pars, function(data, textStatus) {
		$('#' + id).after('<div class="db" id="' + data + '"></div>');
		$('#' + id).remove();
		id = data;
		API.editElement(id);
	});
};

cAPI.prototype.editElement = function(id) {
	$('.placeholder').remove();
	content = API.storage = $('#' + id).html();

	_id = $('#' + id).parent().attr('id');
	if (_id == '') _id = $('#' + id).parent().parent().attr('id');
	if (content.indexOf('<!--PH-->') != -1) {
		content = content.substr(content.lastIndexOf('<!--PH-->') + 9);
		if (_id == 'buildings_list') {
			content = $("#buildings_list a[rel='" + id + "']").text() + '|||' + content;
		}
		$('#' + id).html(content);
	};
	tinyMCE.execCommand('mceAddControl', false, id);
};

cAPI.prototype.saveElement = function(ed) {
		var content = ed.getContent(); //-> get the processed content
	var editAreaId = ed.id; //-> get the id of the editor in a multiple editor environment, so you can handle the right editor area after the server response
	API.editAreaId = editAreaId;
//	content = content.replace(/\+/g, "&#43");
//	content = content.replace(/\\/g, "&#92");
	if (content.indexOf('<!--PH-->') != -1) content = content.substr(content.indexOf('<!--PH-->') + 9);
	content = encodeURIComponent(content);
	var url = WWW_ROOT + 'admin/saveElement/?id=' + editAreaId;
	var pars = editAreaId + '=' + content;
	$.post(url, pars, function(data, textStatus) {
		tinyMCE.execCommand('mceRemoveControl', false, editAreaId);
		$('#' + editAreaId).html(data);
		API.attachPlaceholder('#' + API.editAreaId);

		_id = $('#' + editAreaId).parent().attr('id');
		if (_id == '') _id = $('#' + editAreaId).parent().parent().attr('id');
		if (_id == 'buildings_list') {
			window.location.reload();
		}
	});
};

cAPI.prototype.attachPlaceholder = function(id){
	return;
	$(id).prepend('<div rel="' + $(id).id + '" class="placeholder none" style="background: transparent; position: absolute; top: 0px; left: 0px; width: ' + $(id).width() + 'px; height: ' + $(id).height() + 'px; border: 1px dotted black;">&nbsp;</div><!--PH-->');
	$(id).hover(function(){
		$(this).children('div[rel=\'' + $(id).id + '\']').fadeIn();
	}, function(){
		$(this).children('div[rel=\'' + $(id).id + '\']').fadeOut();
	});
};

cAPI.prototype.cancelElement = function(ed) {
	var editAreaId = ed.id;
	tinyMCE.execCommand('mceRemoveControl', false, editAreaId);
	$('#' + editAreaId).html(API.storage);
};

cAPI.prototype.createElement = function(element, id, position, x, y, w, h, zindex) {
	if (document.getElementById(id)) $('#' + id).remove();
	el = document.createElement(element);
	el.id = id;
	el.setAttribute('id', id);
	el.style.position = position;
	if (x < 0) {
		el.style.right = (0 - x) + 'px';
	} else {
		el.style.left = x + 'px';
	}
	if (y < 0) {
		el.style.bottom = (0 - y) + 'px';
	} else {
		el.style.top = y + 'px';
	}
	if (w == 0) {
		el.style.width = 'auto';
	} else {
		el.style.width = w + 'px';
	}
	if (h == 0) {
		el.style.height = 'auto';
	} else {
		el.style.height = h + 'px';
	};
	el.style.visibility = 'visible';
	el.style.display = 'block';
	el.style.zIndex = zindex;
	return el;
};

cAPI.prototype.ParseInt = function(s) {
	var ret = parseInt(s);
	return (isNaN(ret) ? 0 : ret);
};

cAPI.prototype.getBrowserInfo = function() {
		this.ver = navigator.appVersion;
		this.agent = navigator.userAgent;
		this.dom = document.getElementById ? 1 : 0;
		this.opera5 = this.agent.indexOf("Opera 5") > -1;
		this.opera = this.agent.indexOf("Opera") > -1;
		this.ie5 = (this.ver.indexOf("MSIE 5") > -1 && this.dom && !this.opera5) ? 1 : 0;
		this.ie6 = (this.ver.indexOf("MSIE 6") > -1 && this.dom && !this.opera5) ? 1 : 0;
		this.ie7 = (this.ver.indexOf("MSIE 7") > -1 && this.dom && !this.opera5) ? 1 : 0;
		this.ie4 = (document.all && !this.dom && !this.opera5) ? 1 : 0;
		this.ie = this.ie5 || this.ie6 || this.ie7;
		this.mac = this.agent.indexOf("Mac") > -1;
		this.ns6 = (this.dom && parseInt(this.ver) >= 5) ? 1 : 0;
		this.ns4 = (document.layers && !this.dom) ? 1 : 0;
		this.bw = (this.ie7 || this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5);
		return this;
};

cAPI.prototype.getPageInfo = function() {
		if (API.ParseInt(API.maxZ) < 100) API.maxZ = 100;
		this.x1 = 0;this.y1 = 0;
		this.x2 = (API.browser.ie7)?document.documentElement.clientWidth:(API.browser.ns6) ? innerWidth : document.body.clientWidth;
		this.y2 = (API.browser.ie7)?document.documentElement.clientHeight:(API.browser.ns6) ? innerHeight : document.body.clientHeight;
		this.x50 = Math.round(this.x2 / 2);
		this.y50 = Math.round(this.y2 / 2);
};

cAPI.prototype.stylize = function(o) {
		o.style.backgroundColor = 'white';
		o.style.border = '1px solid black';
		o.style.padding = '0px';
		o.style.margin = '0px';
		o.style.fontSize = '7pt';
		o.style.fontFamily = 'Verdana';
		o.style.overflow = 'hidden';
		return o;
};

var API = new cAPI();

$(function() {
	API.init();
});

Array.prototype.serializeC = function (){
	 var temp = '';
	 for(var vars in this){
			if(!(this[vars] instanceof Function)){
				 temp += vars + ':' + this[vars] + ',';
			}
	 }
	 return temp;
	 return temp.substr(0, temp.length - 1);
};

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};


function serialize( mixed_value ) {
		// http://kevin.vanzonneveld.net
		// +   original by: Arpad Ray (mailto:arpad@php.net)
		// +   improved by: Dino
		// %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
		// %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
		// *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
		// *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
		// *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
		// *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'

		var _getType = function( inp ) {
				var type = typeof inp, match;
				if (type == 'object' && !inp) {
						return 'null';
				}
				if (type == "object") {
						if (!inp.constructor) {
								return 'object';
						}
						var cons = inp.constructor.toString();
						if (match = cons.match(/(\w+)\(/)) {
								cons = match[1].toLowerCase();
						}
						var types = ["boolean", "number", "string", "array"];
						for (key in types) {
								if (cons == types[key]) {
										type = types[key];
										break;
								}
						}
				}
				return type;
		};
		var type = _getType(mixed_value);
		var val, ktype = '';

		switch (type) {
				case "function":
						val = "";
						break;
				case "undefined":
						val = "N";
						break;
				case "boolean":
						val = "b:" + (mixed_value ? "1" : "0");
						break;
				case "number":
						val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
						break;
				case "string":
						val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
						break;
				case "array":
				case "object":
						val = "a";
						/*
						if (type == "object") {
								var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
								if (objname == undefined) {
										return;
								}
								objname[1] = serialize(objname[1]);
								val = "O" + objname[1].substring(1, objname[1].length - 1);
						}
						*/
						var count = 0;
						var vals = "";
						var okey;
						for (key in mixed_value) {
								ktype = _getType(mixed_value[key]);
								if (ktype == "function" && ktype == "object") {
										continue;
								}

								okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
								vals += serialize(okey) +
												serialize(mixed_value[key]);
								count++;
						}
						val += ":" + count + ":{" + vals + "}";
						break;
		}
		if (type != "object" && type != "array") val += ";";
		return val;
};

function getAbsolutePosition(element) {
		var r = { x: element.offsetLeft, y: element.offsetTop };
		if (element.offsetParent) {
			var tmp = getAbsolutePosition(element.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
		}
		return r;
};


	/**
	 * Retrieve the coordinates of the given event relative to the center
	 * of the widget.
	 *
	 * @param event
	 *   A mouse-related DOM event.
	 * @param reference
	 *   A DOM element whose position we want to transform the mouse coordinates to.
	 * @return
	 *    A hash containing keys 'x' and 'y'.
	 */
/*	function getRelativeCoordinates(event, reference) {
		var x, y;
		event = event || window.event;
		var el = event.target || event.srcElement;

		if (!window.opera && typeof event.offsetX != 'undefined') {
			// Use offset coordinates and find common offsetParent
			var pos = { x: event.offsetX, y: event.offsetY };

			// Send the coordinates upwards through the offsetParent chain.
			var e = el;
			while (e) {
				e.mouseX = pos.x;
				e.mouseY = pos.y;
				pos.x += e.offsetLeft;
				pos.y += e.offsetTop;
				e = e.offsetParent;
			}

			// Look for the coordinates starting from the reference element.
			var e = reference;
			var offset = { x: 0, y: 0 }
			while (e) {
				if (typeof e.mouseX != 'undefined') {
					x = e.mouseX - offset.x;
					y = e.mouseY - offset.y;
					break;
				}
				offset.x += e.offsetLeft;
				offset.y += e.offsetTop;
				e = e.offsetParent;
			}

			// Reset stored coordinates
			e = el;
			while (e) {
				e.mouseX = undefined;
				e.mouseY = undefined;
				e = e.offsetParent;
			}
		}
		else {
			// Use absolute coordinates
			var pos = getAbsolutePosition(reference);
			x = event.pageX  - pos.x;
			y = event.pageY - pos.y;
		}
		// Subtract distance to middle
		return { x: x, y: y };
};*/
