// public variables
gPopupIsShown = false;

// private script variables
var gReturnFunc;
var gHideSelects = false;
var gTabIndexes = new Array();
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME","SELECT");
var gTimerFunc;
var gButtons;

// function: init popup
function initPopUp() {

// adds a new divs to the body
	var body = $$('body')[0];
	var popcont = new Element('div');
	var popmask = new Element('div');
	popmask.id = 'popupMask';
	popcont.id = 'popupContainer';
	popcont.innerHTML = '' +
		'<div id="popupInner">' +
		'<div id="popupTitleBar">' +
		'<div id="popupTitle"></div>' +
		'<div id="popupControls">' +
		'<a href="javascript:void(0);" onclick="hidePopWin(false);"><span>Close</span></a>' +
		'</div>' +
		'</div>' +
		'<div id="popUpContent" style="width:100%;height:100%;background-color:transparent;margin:10px 10px 10px 10px;" width="100%" height="100%">' +
		'</div>' +
		'<div id="popupButtonBar" align="center">' +
		'</div>' +
		'</div>';
	body.grab(popcont, 'top');
	body.grab(popmask, 'top');
	
// do some additional settings
	gHideSelects = true;
}

// function: show the buttons according to what command has come
function showButtons(buttonDiv, buttons) {
	switch (buttons) {

	case "done cancel":
		buttonDiv.innerHTML = '<table width="100%" style="border-top: 1px solid #AAAAAA;"><tr><td align="left">' +
		'<button onclick="window.parent.hidePopWin(true)">Done</button>' +
		'</td><td align="right">' +
		'<button onclick="window.parent.hidePopWin(false)">Cancel</button>' +
		'</td></tr></table>';
		break;

	default:
		buttonDiv.innerHTML = '';
		break;
	}
	gButtons = buttons;
}

// function: show the popup
function showPopWin(title, content, width, height, fireFunc, returnFunc, buttons) {
	gPopupIsShown = true;
	disableTabIndexes();
	$("popupTitle").innerHTML = title;
	showButtons($('popupButtonBar'), buttons);
	var titleBarHeight = parseInt($("popupTitleBar").offsetHeight, 10);
	var buttonBarHeight = parseInt($("popupButtonBar").offsetHeight, 10);
	$("popupContainer").style.width = width + "px";
	$("popupContainer").style.height = (height+titleBarHeight) + "px";
	centerPopWin(width, height);
	$("popupContainer").style.opacity = '1.0';
	$("popupContainer").style.filter = 'alpha(opacity=100)';
	$("popupMask").style.display = 'block';
	var opt = {
		mode: "vertical"
	}
	var myFx = new Fx.Reveal("popupContainer", opt);
	myFx.reveal();
	$("popUpContent").innerHTML = content;
	gReturnFunc = returnFunc;
	if (fireFunc != null) {
		fireFunc();
	}
	if (gHideSelects == true) {
		hideSelectBoxes();
	}

// install a timer to check if a form has been submitted
	var myCheckFunc = function() {
		var formsobj = $$('form');												// catch all forms
		for (i = 0; i < formsobj.length; i++) {									// loop trough all document's editors
			var parents = formsobj[i].getParents('#popUpContent');				// search children of popup
			if (parents.length > 0) {											// found
				var submitResult = formsobj[i].retrieve('formsubmitresult');	// retrieve submit result
				if (submitResult) {												// form was succesfully submitted !
					$clear(gTimerFunc);											// clear timer
					submitResult = false;
					formsobj[i].store('formsubmitresult', submitResult);		// clear also flag
					var myCloseFunc = function() {
						hidePopWin(true);
					}
					myCloseFunc.delay(1500);									// hide popup after a while
				}
			}
		}
	}
	gTimerFunc = myCheckFunc.periodical(200);
}

// function: center the popup on various events
function centerPopWin(width, height) {
	if (gPopupIsShown == true) {
		if (width == null || isNaN(width)) {
			width = $("popupContainer").offsetWidth;
		}
		if (height == null) {
			height = $("popupContainer").offsetHeight;
		}
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		var scLeft,scTop;
		if (self.pageYOffset) {
			scLeft = self.pageXOffset;
			scTop = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			scLeft = document.documentElement.scrollLeft;
			scTop = document.documentElement.scrollTop;
		} else if (document.body) {
			scLeft = document.body.scrollLeft;
			scTop = document.body.scrollTop;
		}
		$('popupMask').style.width = $$('body')[0].scrollWidth + 'px';
		$('popupMask').style.height = $$('body')[0].scrollHeight + 'px';
		var titleBarHeight = parseInt($("popupTitleBar").offsetHeight, 10);
		var topMargin = scTop + ((fullHeight - (height+titleBarHeight)) / 2);
		if (topMargin < 0) {
			topMargin = 0;
		}
		$("popupContainer").style.top = topMargin + "px";
		$("popupContainer").style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
	}
}

// function: hide the popwin once the job is done
function hidePopWin(callReturnFunc) {

// check if we need confirmation or not here
	if ((gButtons == "done cancel") && (!callReturnFunc)) {
		var res = confirm("You are about to cancel your modifications. Are you sure you want to abandon ? If you click Cancel, you can then click Done to store your changes.");
		if (!res) {
			return;
		}
	}

// eventually destroy any open timer
	$clear(gTimerFunc);

// before destroy anything, better we call the update function...
	if (callReturnFunc == true && gReturnFunc != null) {
		gReturnFunc();
	}

// we have to delete all CKEditor objects that were created in the popup...
	var ckeditors = $$('*').filter('.cke_skin_kama');				// catch content declarations of CKE
	for (i = 0; i < ckeditors.length; i++) {						// loop trough all document's editors
		var parents = ckeditors[i].getParents('#popupContainer');	// search children of popup
		if (parents.length > 0) {									// found
			var editor = ckeditors[i].getAllPrevious('textarea');	// search textareas just previously declared
			delete CKEDITOR.instances[editor[0].name];				// delete those instances
		}
	}

// do the rest of the job
	gPopupIsShown = false;
	restoreTabIndexes();
	$('popupMask').style.display = 'none';
	var container = new Fx.Reveal($("popupContainer"));
	container.dissolve();
	if (gHideSelects == true) {
		displaySelectBoxes();
	}
}

// function: tab key trap
function keyDownHandler(e) {
    if (gPopupIsShown && ((e.keyCode == 9) || (e.which == 9))) {
		return(false);
	}
}

// function: disable tab indexes
function disableTabIndexes() {
	var i = 0;
	for (var j = 0; j < gTabbableTags.length; j++) {
		var tagElements = document.getElementsByTagName(gTabbableTags[j]);
		for (var k = 0 ; k < tagElements.length; k++) {
			gTabIndexes[i] = tagElements[k].tabIndex;
			tagElements[k].tabIndex="-1";
			i++;
		}
	}
}

// function: restore tab indexes
function restoreTabIndexes() {
	var i = 0;
	for (var j = 0; j < gTabbableTags.length; j++) {
		var tagElements = document.getElementsByTagName(gTabbableTags[j]);
		for (var k = 0 ; k < tagElements.length; k++) {
			tagElements[k].tabIndex = gTabIndexes[i];
			tagElements[k].tabEnabled = true;
			i++;
		}
	}
}

// function: hides all select boxes
function hideSelectBoxes() {
	for(var i = 0; i < document.forms.length; i++) {
		for(var e = 0; e < document.forms[i].length; e++){
			if(document.forms[i].elements[e].tagName == "SELECT") {
				document.forms[i].elements[e].style.visibility="hidden";
			}
		}
	}
}

// function: display all select boxes
function displaySelectBoxes() {
	for(var i = 0; i < document.forms.length; i++) {
		for(var e = 0; e < document.forms[i].length; e++){
			if(document.forms[i].elements[e].tagName == "SELECT") {
			document.forms[i].elements[e].style.visibility="visible";
			}
		}
	}
}

/**
 * X-browser event handler attachment and detachment
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}

/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/ *
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 * Gets the full width/height because it's different for most browsers.
 */
function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 
	return window.undefined; 
}

function getViewportWidth() {
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
	return window.undefined; 
}

// do some global settings here
if (!document.all) {
	document.onkeypress = keyDownHandler;
}
initPopUp();
addEvent(window, "resize", centerPopWin);
window.onscroll = centerPopWin;

