/** Global MooTools additions **/
Element.implement({
	getSiblings: function(match) {
		return this.getParent().getChildren(match).erase(this);
	}
});

function slidemessage(flashmsg) {
	var msgfx = new Fx.Slide(flashmsg, {duration:800});
	msgfx.hide().slideIn().chain(function(){
    	this.slideOut.delay(2000, this);
	}).chain(function(){
		flashmsg.setStyle('display', 'none');
	});
}

/**
 * Generate a random string
 * @param string_length
 * @return
 */
function bifrontend_randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

/**
 * Take an existing window and inject the window controls (such as close)
 * @param ucontenWindowID ID of window attaching to. Used for events, but not accessed directly
 * @param windowControlBar object (not yet in DOM)
 * @return beefed up windowControlBar element
 */
function blueInkFrontEnd_attachContentWindowControls(ucontentWindowID, windowControlBar)
{
	var closeLink = new Element('a', {'id' : ucontentWindowID + '_controls_closeWindow', 'href' : '#', 'class' : 'blueInkFrontEnd_closeWindow', 'text' : 'close', 'style' : 'float: right'});
	closeLink.addEvent('click', function(event) {blueInkFrontEnd_destroyContentWindow(ucontentWindowID)});
	closeLink.inject(windowControlBar);

	return windowControlBar;
}

/**
 * Open an unobtrusive content window overlay
 * @param contentData (object) {'url':'/aurl', 'text':'sometextorhtml'}, (string) text
 * @param wheight (int) height of window (string) auto
 * @param wwidth (int) width of window (string) auto
 * @param forced_id (string) override auto generation of ids by setting a manual one instead
 * @return window ID
 */
function blueInkFrontEnd_addContentWindow(contentData, wheight, wwidth, forced_id)
{
	var contentWindowEl;
	var windowSubContent;
	var windowControlBar;
	var ucontentWindowID;
	if (forced_id == null) {
		var radString = bifrontend_randomString(6);
		ucontentWindowID = 'blueInkFrontEnd_contentWindow_' + radString;
	} else {
		ucontentWindowID = forced_id;
	}
	//TODO:make an option
	blueInkFrontEnd_fadeBackground(80);

	if (!document.body.hasChild(ucontentWindowID)) {
		contentWindowEl = new Element('div', {'id' : ucontentWindowID, 'class' : 'overlaypage blueInk_contentWindow'});
		//contentWindowEl = $(ucontentWindowID);
		windowControlBar = new Element('div', {'id' : ucontentWindowID + '_controls', 'class' : 'blueInk_contentWindow_controls'});
		windowSubContent = new Element('div', {'id' : ucontentWindowID + '_content', 'class' : 'blueInk_contentWindow_content'});
		windowControlBar = blueInkFrontEnd_attachContentWindowControls(ucontentWindowID, windowControlBar);

		windowControlBar.inject(contentWindowEl);
		windowSubContent.inject(contentWindowEl);
		contentWindowEl.injectInside(document.body)
	} else {
		contentWindowEl = $(ucontentWindowID);
		windowControlBar = $(ucontentWindowID+'_controls');
		windowSubContent = $(ucontentWindowID+'_content');
	}
	//determine content data
	var contentText = false;
	var contentUrl = false;
	if (typeof(contentData) == 'string') {
		contentText = contentData;
	} else if (typeof(contentData) == 'object') {
		if (contentData.text !== undefined) {
			contentText = contentData.text;
		} else {
			contentText = '';
		}
		if (contentData.url !== undefined) {
			contentUrl = contentData.url;
		}
	}
	//reset
	contentWindowEl.setStyles({
		'display': 'block',
		'top': window.getScrollTop() + window.getHeight()/2 -100,
		'height': wheight,
		'left': window.getWidth()/2 - 250,
		'width': wwidth,
		'padding': '5px'
	});
	windowSubContent.set('text', contentText);
	//http request
	if (contentUrl !== false) {
		blueInkFrontEnd_httpRequest(contentUrl, windowSubContent);
	}
	return ucontentWindowID;
}

/**
 * Destroy an open window instance
 * @param ucontentWindowID
 * @return true | false (window doesn't exist)
 */
function blueInkFrontEnd_destroyContentWindow(ucontentWindowID)
{
	if (document.body.hasChild(ucontentWindowID)) {
		$(ucontentWindowID).removeEvents();
		$(ucontentWindowID).fade(0).destroy();
		blueInkFrontEnd_restoreBackground();
		return true;
	} else {
		return false;
	}
}

/**
 * Fade the background out or in to given value (0 to 100).
 * This is done via an illusion.
 * @param fade_to (percent, 0 to 100)
 * @return
 */
function blueInkFrontEnd_fadeBackground(fade_to)
{
	if (fade_to === null || fade_to > 100) {
		fade_to = 80;
	} else if (fade_to < 0) {
		fade_to = 0;
	} else {
		//calculate fade based on fade_to in reference to what the background should be, not the overlay
		fade_to = 100 - fade_to;
	}
	fade_to = fade_to/100;
	var suboverlay;
	if (!document.body.hasChild('ddoverlay')) {
		suboverlay = new Element('div', {'id': 'ddoverlay'}).injectInside(document.body).setStyles({
			'height': window.getScrollSize().y,
			'opacity': 0
		});
	} else {
		suboverlay = $('ddoverlay');
	}
	//lock interface
	if (fade_to !== 0) {
		loginformshowing = true;
	} else {
		loginformshowing = false;
	}
	suboverlay.fade(fade_to);
	//return
	return;
}

/**
 * Unfade the background
 * @return
 */
function blueInkFrontEnd_restoreBackground(force)
{
	if (force && document.body.hasChild('ddoverlay')) {
		$('ddoverlay').setStyles({'opacity' : 0});
		loginformshowing = false;
		return true;
	}
	return blueInkFrontEnd_fadeBackground(100);
}

/**
 * Sends a background http request (ajax)
 * @param url (string)
 * @param update_container (element)
 * @param process_returned_javascript (bool)
 * @param onComplete Callback (function) (defaults to injection of html in options{'update':'theelement'} if set and callback is null)
 * @return
 */
function blueInkFrontEnd_httpRequest(url, update_container, process_returned_javascript, onCompleteCallback)
{
	if (process_returned_javascript == null) {
		process_returned_javascript = false;
	}
	var request = new Request.HTML({
		update: update_container,
		evalScripts: process_returned_javascript,
		onComplete: function(rtree, relements, rhtml, rjscript){
			if (typeof(onCompleteCallback) !== 'undefined'){
				onCompleteCallback(rtree, relements, rhtml, rjscript);
			}
		}
	}).get(url);
}

function hidesmallform()
{
	var suboverlay = $('ddoverlay');
	var subformpage = $('overlaypage');
	loginformshowing = false;
	subformpage.setStyle('display', 'none');
	suboverlay.fade(0);
	$$('.item object,.item embed').each(function(obj) {
		obj.setStyle('visibility', 'visible');
	});
}
var loginformshowing;
function showloginform(timedout, removeoverlay) {
	$$('.item object,.item embed').each(function(obj) {
		obj.setStyle('visibility', 'hidden');
	});
	if (document.body.hasChild('sfloader')) {
		$('sfloader').setStyle('display', 'none');
	}
	var suboverlay;
	if (!document.body.hasChild('ddoverlay')) {
		suboverlay = new Element('div', {'id': 'ddoverlay'}).injectInside(document.body).setStyles({
			'height': window.getScrollSize().y,
			'opacity': 0
		});
	} else {
		suboverlay = $('ddoverlay');
	}
	if (!suboverlay.getStyle('opacity')) {
		suboverlay.fade(0.8);
	}
	var subformpage = $('overlaypage');
	subformpage.setStyles({
		'display': 'block',
		'top': window.getScrollTop() + window.getHeight()/2 -100,
		'height': 200,
		'left': window.getWidth()/2 - 250,
		'width': 500
	});
	if ($('user_login') != null) {
		$('user_login').focus();
	}
	if (timedout != null) {
		new Element('p', {
			'class': 'error',
			'text' : 'For your security, you have been logged out due to inactivity.'
		}).inject($('blueink-login-box'), 'top');
	}
	new Element('input', {
		'type': 'hidden',
		'name': 'data[extra][v2inline]',
		'value': cakeurl
	}).injectInside(subformpage.getElement('form'));
	$$('.item-cancel').each(function(cancelbutton){
		cancelbutton.addEvents({
			'click': function(e) {
				hidesmallform();
			}
		});
	});
	document.addEvent('keydown', function(event) {
		if (event.key == 'esc') $$('.item-cancel')[0].fireEvent('click');
	});
	subformpage.getElement('form').addEvent('submit', function(e){
		subformpage.setStyle('display', 'none');
		new Element('div', {'id': 'sfloader'}).injectInside(document.body).set('text', 'logging in...').setStyles({
			'display': 'block',
			'top': 100,
			'left': window.getWidth()/2 - 200
		});
	});
}
window.addEvent('domready', function() {
	$$('.message').each(slidemessage);
	loginformshowing = false;
	document.addEvent('keydown', function(e){
		if ($('adminmenu') == null && !loginformshowing && e.control && e.shift && e.key == 'l') {
			e.stop();
			loginformshowing = true;
			showloginform();
		}
	});
});

