// Get page height and width
var pageHeight, pageWidth;

function getPageDimensions() {
	pageHeight = window.innerHeight
	|| (document.documentElement ? document.documentElement.clientHeight : undefined)
	|| (document.body ? document.body.clientHeight : undefined);

	pageWidth = window.innerWidth
	|| (document.documentElement ? document.documentElement.clientWidth : undefined)
	|| (document.body ? document.body.clientWidth : undefined);
}

Event.observe(window, "load", getPageDimensions, false);
Event.observe(window, "resize", getPageDimensions, false);

// Save page and pointer X/Y positions
var pointerX;
var pointerY;
var pageX;
var pageY;
var useIframeHack = true;

function position(e) {

	pointerX = Event.pointerX(e);
	pointerY = Event.pointerY(e);

	positionWindow();

	if(typeof(cbPosition) != 'undefined') {
		cbPosition();
	}

	if(pageStarted) {

		moveInfo();
		moveLoading();

	}

}

function positionWindow() {

	pageX = Try.these ( function() { return window.pageXOffset; }, function() { return undefined;})
			|| Try.these ( function() {	return document.documentElement.scrollLeft; }, function() { return undefined;})
			|| Try.these ( function() {	return document.body.scrollLeft; }, function() { return undefined;})
			|| 0;

	pageY = Try.these ( function() {	return window.pageYOffset; },function() { return undefined;})
				|| Try.these ( function() {return document.documentElement.scrollTop; }, function() {return undefined;})
				|| Try.these (function() {	return document.body.scrollTop;	}, function() { return undefined;})
				|| 0;
}

Event.observe(document, "mouseover", position, false);
Event.observe(document, "mousemove", position, false);


function loading() {

	if(pageErrors != null) {
		showErrors(pageErrors);
	}

	if(pageMessage != null) {
		showMessage(pageMessage);
	}

}

window.addToStart(loading);

/*
 * Info messages
 */
function showInfo(message, size) {

	var info = $('infoBox');

	if(info) {

		info.innerHTML = message;

		if(typeof(size) == 'undefined') {
			size = null;
		} else {
			size += 'px';
		}

		info.setStyle('width', size);

		moveInfo();

		Element.show('infoBox');

	}

}

function hideInfo() {
	var info = $('infoBox');

	if(info != null) {
		Element.hide('infoBox');
	}

}

function moveInfo() {

	var info = $("infoBox");

	if (info && info.getStyle("display") !== "none") {
		info.style.left = Math.min(pointerX + 5, pageWidth - $("infoBox").getWidth()) + "px";
		info.style.top = pointerY + 25 + "px";
	}
}


/*
 * Boxes
 */
var boxes = 0;
var boxesIds = new Array();

function showBox(id, options) {

	if(options === undefined) {
		options = { };
	}

	hideInfo();

	if(id == getCurrentBox()) {
		hideCurrentBox();
	}

	if(boxes <= 0) {
		showBackground();
	}

	if(typeof(options.y) != 'undefined') {
		if(options.y == 'pointer') {
			y = pointerY - 30;
		} else {
			y = options.y;
		}
	} else {
		positionWindow();
		if(typeof(pageY) == 'undefined') {
			y = 0;
			options.scroll = true;
		} else {
			y = pageY + 100;
		}
	}

	if(y != null) {
		moveBox(id, y);
	}

	if(typeof(options.scroll) != 'undefined' && options.scroll) {
		window.scrollBy(0, Math.max(y - 100, 0));
	}


	Element.setStyle(id, {
		'zIndex': boxes + 2000,
		'position': 'absolute'
	});

	Element.show(id);

	if(typeof($(id).hacked) == 'undefined') {
		iFrameHack(id);
	}

	replaceBox(id);

	boxes++;
	boxesIds[boxesIds.length] = id;

	eval('try { '+ id.ucFirst() +'.show(typeof(options.show) != \'undefined\' ? options.show : { }); } catch(e) { }');

	if(typeof(cbShowBox) != 'undefined') {
		cbShowBox(id);
	}

	//hide elements that could make a bad display (flash over popup...)
	hideElementsOnPopup();

	return false;
}

// will hide elements with
// - the class '.hide-on-popup'
// - the class 'hide-flash-on-popup' AND an possible flash element (<object> markup)
// - the class 'hide-iframe-on-popup' AND an iframe element
// usefull for hide flash ads that stay over popups
function hideElementsOnPopup() {

	var elementsToHide = $$('.hide-on-popup', '.hide-flash-on-popup object', '.hide-flash-on-popup embed', '.hide-iframe-on-popup iframe');
	elementsToHide.each(
		function(myElement) {
			// hide element
			myElement.setStyle({visibility: 'hidden'});
		}
	);
}

// will show elements that were hidden by hideElementsOnPopup()
function showElementsOnPopup() {

	// show hidden elements only if no more oppened popups
	if(boxes < 1) {
		var elementsToShow = $$('.hide-on-popup', '.hide-flash-on-popup object', '.hide-flash-on-popup embed', '.hide-iframe-on-popup iframe');
		elementsToShow.each(
			function(myElement) {
				// show element
				myElement.setStyle({visibility: 'visible'});
			}
		);
	}
}

function iFrameHack(id) {

	if(useIframeHack) {

		var destinedElement = $(id);
		var savedContent = destinedElement.innerHTML;
		destinedElement.innerHTML = '<iframe scrolling="noscroll" allowtransparency="true" style="overflow: hidden; display: block; position:relative; width:100%; height:100%; background-color: transparent;z-index:10" frameborder="no" src="/media/sowcle/image/shapes/void.html"></iframe>'+
						'<div style="position:absolute; top:0px; left:0px; width:100%;z-index:11">'+ savedContent +'</div>';
		destinedElement.hacked = true;
		if($(id.replace(/Box/, 'Content'))) {
			destinedElement.style.height = destinedElement.childNodes[1].offsetHeight+"px";
		}

	}

}


function replaceBox(id) {
	if(document.getElementById(id).parentNode.tagName.toLowerCase() != 'body') {
		$(id).savedParent = $(id).parentNode;
		document.body.appendChild(document.getElementById(id));
		$(id).style.position = 'absolute';

	}
}


function resizeBox(id, size) {
	Element.setStyle(id, { 'width': size +'px' });
}


function moveBox(id, positionY) {

	var element = $(id);
	var elementWidth = Element.getStyle(id, 'width');
	getPageDimensions();

	if(elementWidth != '' && elementWidth != null) {
		size = elementWidth.substr(0, elementWidth.length - 2);
	} else {
		size = 600;
	}

	element.style.left = ((pageWidth - size) / 2) + 'px';

	if(typeof(positionY) != 'undefined') {
		element.style.top = positionY + 'px';
	} else {
		if(isNaN(pointerY)) {
			var position = 100;
		} else {
			var position = Math.max(100, pointerY - 100);
		}
		element.style.top = position + 'px';
	}

}

function hideBox(id) {

	var idPosition = null;

	for(var i = boxesIds.length - 1; i >= 0; i--) {
		if(boxesIds[i] == id) {
			idPosition = i;
		}
	}

	if(idPosition == null) {
		return;
	}

	boxes--;
	boxesIds[idPosition] = null;

	if(boxes <= 0) {
		hideBackground();
	}

	Element.hide(id);

	if($(id).savedParent) {
		$(id).savedParent.appendChild($(id));
	}

	if(typeof(contentTutorial) != 'undefined' && contentTutorial.currentTutorial != null) {
		contentTutorial.currentclose();
	}

	hideInfo();

	eval('try { '+ id.ucFirst() +'.hide(); } catch(e) { }');

	if(typeof(cbHideBox) != 'undefined') {
		cbHideBox(id);
	}

	//unhide elements that were hidden on popup opening
	showElementsOnPopup();

	return false;

}

function hideCurrentBox() {

	if(boxes <= 0) {
		return false;
	}

	for(var i = boxesIds.length - 1; i >= 0; i--) {
		if(boxesIds[i] != null) {
			return hideBox(boxesIds[i]);
		}
	}

}

function getCurrentBox() {
	return boxesIds[boxes - 1];
}

/*
 * Loading message
 */
var loadingDefault = null;

function showLoading(text) {
	$('loading').style.zIndex = 9999; //**tempFix
	if(loadingDefault == null) {
		loadingDefault = $('loading').innerHTML;
	}
	if(typeof(text) == 'undefined') {
		text = loadingDefault;
	}
	$('loading').innerHTML = text;
	Element.show('loading');
	moveLoading();
}

function moveLoading() {

	var loading = $('loading');

	if(loading && loading.getStyle('display') !== 'none') {

		loading.style.left = pointerX +'px';
		loading.style.top = (pointerY + 20) +'px';

	}

}

function hideLoading() {
	Element.hide('loading');
}

/*
 * Handle background
 */

function showBackground() {

	Element.show('background');

	if(typeof(cbShowBackground) != 'undefined') {
		cbShowBackground();
	}

}

function hideBackground() {

	Element.hide('background');

	if(typeof(cbHideBackground) != 'undefined') {
		cbHideBackground();
	}

}

/*
 * Handle errors
 */

function showErrors(errors) {

   	// Hide message box
	hideMessage();

	$('errorsBox').innerHTML = errors;
	$('errorsBox').style.overflow = "hidden";
	$('errorsBox').hacked = true;
	showBox('errorsBox', { move: true });
	iFrameHack('errorsBox');
}

function showInternalError() {
	showErrors(internalError);
}

function hideErrors() {
	hideBox('errorsBox');
}

/*
 * Handle messages
 */
function showMessage(message) {

	// Hide error box
	hideErrors();

	new Element.scrollTo('global');
	$('messageBox').hacked = true;
	$('messageBox').innerHTML = message;
	$('messageBox').style.overflow = "hidden";

	showBox('messageBox', { y: 200 });
	iFrameHack('messageBox');
}

function hideMessage() {
	hideBox('messageBox');
}

var lastPage;
var lastParams;
var lastLocation = document.location.href;

var ajaxCurrentRequests = 0;

Ajax.JSON = function(callback, options) {

	if(options === undefined) {
		options = { };
	}

	showLoading(options.loadingMessage);

	if(callback.prepare) {
		callback.prepare();
	}

	callback.params = callback.buildParameters();

	lastPage = callback.page;
	lastParams = callback.params;

	var ajaxOptions = {
		"method": callback.method,
		"onSuccess": function(request) {
			ajaxCurrentRequests--;
			hideLoading();
			if(typeof(arguments.page) != 'undefined') {
				this.page = arguments.page;
			}
			if(typeof(callback.onBeforeHandle) != 'undefined') {
				callback.onBeforeHandle(request);
			}
			callback.handleSuccess(request);
			if(typeof(callback.onAfterHandle) != 'undefined') {
				callback.onAfterHandle(request);
			}
		},
		"onFailure": function(request) {
			ajaxCurrentRequests--;
			hideLoading();
			if(typeof(callback.onBeforeHandle) != 'undefined') {
				callback.onBeforeHandle(request);
			}
			callback.handleFailure(request);
			if(typeof(callback.onAfterHandle) != 'undefined') {
				callback.onAfterHandle(request);
			}
		}
	};

	if(callback.method.toLowerCase() == 'post') {
		ajaxOptions.postBody =  callback.params;
	} else {
		ajaxOptions.parameters = callback.params;
	}

	ajaxCurrentRequests++;

	new Ajax.Request(callback.page, ajaxOptions);

	return false;

}

var CommonAjax = {

	method: "post",
	arguments: null,
	params: null,
	object: null,

	initialize: function(arguments) {
		if(typeof(arguments) != 'undefined') {
			if(typeof(arguments.page) != 'undefined') {
				this.page = arguments.page;
			}
			if(typeof(arguments.id) != 'undefined') {
				this.id = arguments.id;
			}
			if(typeof(arguments.raise) != 'undefined') {
				this.raise = arguments.raise;
			}
			if(typeof(arguments.params) != 'undefined') {
				this.params = arguments.params;
			}
			if(this.construct) {
				this.construct(arguments);
			}
			this.arguments = arguments;
		} else {
			if(this.construct) {
				this.construct();
			}
		}
	},

	/* Build parameters */
	buildParameters: function() {

		if(this.parameters) {
			this.params = this.parameters();
		} else if(this.params == null) {

			var formId;

			if(this.arguments != null && typeof(this.arguments.form) != 'undefined') {
				formId = this.arguments.form;
			} else {
				formId = this.id;
			}


			var form = $(formId);

			if(form) {
				this.params = '';
				var formattedElements = form.serialize(true);
				for(key in formattedElements) {
					if(typeof(formattedElements[key]) == 'string') {
						var nameForSite = key;
						if(key.match('^'+ formId)) {
							nameForSite = key.substr(formId.length).lcFirst();
						}

						this.params += nameForSite+'='+formattedElements[key].urlEncode()+'&';
					}
				};
			} else {
				this.params = '';
			}

		}

		if(this.params.substr) {
			return this.params;
		}

		for(var param in this.params) {

			if(this.params[param] == null) {
				this.params[param] = getField(this.id + param.ucFirst());
			}

		}

		var out = new Array();

		for(var param in this.params) {

			var outParam = param +'=';
			var value = this.params[param];

			switch(typeof(value)) {

				case 'number' :
					outParam += value.toString();
					break;

				case 'boolean' :
					outParam += value ? '1' : '0';
					break;

				case 'string' :
					outParam += value.urlEncode();
					break;

			}

			out.push(outParam);

		}

		return out.join('&');

	},

	/* Handle success request  */
	handleSuccess: function(request) {

		var content = request.responseText;

		if(projectMode === 'debug') {

			var regex = '\<div id\=\"debugPage\" name\=\"([0-9]+)\" style\=\"display\: none\"\>(.*)\<\/div\>$';
			var debug = content.match(regex);

			if(debug) {
				debugToolbarAdd(debug[2]);
				content = content.substitute(debug[0], '');
			}

		}

		try {

			this.object = content.evalJSON(true);

			if(projectMode === 'debug' && debug) {
				debugToolbarContents[debug[1]] = this.object;
			}

		}
		catch(e) {

			this.object = false;

			if(projectMode === 'debug') {

				var debugId = "debug-message-"+ Math.random();

				var html = '';
				var htmlAction = '<a href="" onclick="$(&quot;'+ debugId +'&quot;).hide(); return false;">hide</a>';

				html += '<div style="font-weight: bold" id="'+ debugId +'">';
				html += '<span style="color: red">Critical error found ('+ htmlAction +'):</span> ';
				html += content;
				html += '</div>';

				debugToolbarAdd(html);
				debugToolbarBigger();

			}

		}

		if(this.object != false) {

			if(typeof(this.object.redirection) != "undefined") {
				document.location.href = this.object.redirection;
				return;
			}
			
			if(typeof(this.handleErrors) != "undefined") {
				var test = this.handleErrors(this.object);
			} else {
				var test = this._handleErrors(this.object);
			}

			if(test) {
			} else {
				if(typeof(this.execute) != "undefined") {
					this.execute(this.object);
				}

				if(this.showTutorial != undefined) {
					this.showTutorial();
				} else {
					this._showTutorial();
				}

				if(typeof(this.handleMessage) != "undefined") {
					this.handleMessage(this.object);
				} else {
					this._handleMessage(this.object);
				}
			}

		} else {

			// The server answer is empty, do nothing
			if(request.responseText == '') {

				if(typeof(this.handleEmpty) != "undefined") {
					this.handleEmpty();
				} else {
					this._handleEmpty();
				}

			}
			// JSON is malformed
			else {

				if(typeof(this.handleJSON) != "undefined") {
					this.handleJSON();
				} else {
					this._handleJSON();
				}

			}
		}

	},

	/* Handle failure request  */
	handleFailure: function(request) {

		showInternalError();
		if(this.error) {
			this.error();
		}

	},

	/* Show error box if needed */
	_handleErrors: function(object) {
		if(object.errorsText && object.errorsText.length > 0) {

			if(typeof(this.interaction) != 'undefined') {
				$("message-"+ this.interaction).innerHTML = '';
				$("errors-"+ this.interaction).innerHTML = object.errorsText;
			} else if(typeof(this.raise) != 'undefined') {
				raise(this.raise, object.errorsText);
				raiseTimeout = typeof(this.raiseTimeout) != 'undefined' ? this.raiseTimeout : 10;
				if(raiseTimeout != null) {
					unraise(this.raise, 10);
				}
			} else {
				showErrors(object.errorsText);
			}
			return true;
		}

		return false;

	},

	/* Empty response */
	_handleEmpty: function() {
	},

	/* Invalid JSON */
	_handleJSON: function() {
		showInternalError();
	},

	/* Show message box if needed */
	_handleMessage: function(object) {

		if(object.messageText && object.messageText.length > 0) {

			if(typeof(this.interaction) != 'undefined') {
				$("message-"+ this.interaction).innerHTML = object.messageText;
				$("errors-"+ this.interaction).innerHTML = '';
			} else if(typeof(this.raise) != 'undefined') {
				raise(this.raise, object.messageText);
				raiseTimeout = typeof(this.raiseTimeout) != 'undefined' ? this.raiseTimeout : 10;
				if(raiseTimeout != null) {
					unraise(this.raise, 10);
				}
			} else {
				showMessage(object.messageText);
			}

			return true;
		}

		return false;

	},

	/* Put content */
	content: function() {
		if(typeof(this.object.content) != 'undefined') {
			$(this.id +'Content').innerHTML = this.object.content;
		}
	},

	/* Reset form */
	reset: function() {
		$(this.id).reset();
	},

	/* Hide form interface */
	hide: function() {
		hideBox(this.id + 'Box');
	},

	/* Reload current page */
	reload: function (params) {

		var destination = lastLocation;

		if(destination.indexOf('#') != -1) {
			destination = destination.substr(0, destination.indexOf('#'));
		}

		if(destination.indexOf('?') == -1) {
			destination += '?';
		}

		if(typeof(params) != 'undefined') {
			destination += '&'+ params;
		}

		document.location.href = destination;

	},

	_showTutorial: function() {
		var contentTutorial = this.contentTutorial || window.contentTutorial;

		if(this.tutorial && contentTutorial) {
			contentTutorial.display(this.tutorial, { highlightId: this.highlightId });
		}
	}

}




var raises = new Array();

function raise(id, content) {
	
	if(typeof(raises[id]) == 'undefined') {
		raises[id] = null;
	}
	
	var needClear = (raises[id] != null);
	
	if(needClear) {
		clearTimeout(raises[id]);
		raises[id] = null;
	}
	
	if($(id)) {
	
		$(id).innerHTML = '<div>'+ content +'</div>';
		
		if(needClear == false) {
			
			Effect.SlideDown(id, { duration: 0.5 });
			
		}
		
	}
	

}

function unraise(id, delay) {
	
	if(raises[id] == null) {
		if(typeof(delay) == 'undefined') {
			doUnraise(id);
		} else {
			raises[id] = setTimeout("doUnraise('"+ id +"')", delay * 1000);
		}
	}

}

function doUnraise(id) {
	if($(id) && $(id).visible() == true) {
		Effect.SlideUp(id, { duration: 0.5 });
	}
	raises[id] = null;
}
