var selectsElements;
//used for show static contet as modal div
var dontDeleteModalContent=false;

var currentModalElement;
var currentModalTitle;
var modalWaitInfoShown = false;
//stote div ids displayed in modal window
var modalDivs = [];
//titles of modal window
var modalTitles= [];
//keeps infor is background blured or nor for every modal window
var blurStatus = [];
var modalErrors = [];
var modalMessages = [];
var modalHelpLinks = [];
var modalCenterWindow = [];
//Invoked in addition to closeModal function when modal window is closed.
var closeFunctions = new Array();
//keeps info about dimension of background for every modal div
var backgroundXY = new Array();
var modalWindowId = 'modalWindow';
var modalHeaderId = 'modalHeader';
var modalCenterActiveWindowdow = true;
//if true, background is not hidden when modal window is closed.
var keepBlur = false;
var bgBlur = 'bgBlur';


//show Static Div as Modal Div
function modalPopUp(successDiv, modalTitle ,blur, closeFunction, addModalButton){
    modalSemaphore = 0;
    if (blur == null){
    	blur == false;
    }
	showModalDiv(null, null, successDiv, modalTitle, null, closeFunction, blur);
	dontDeleteModalContent = true;
	modalShowContent(successDiv, null, null, null, addModalButton);
	showElement(successDiv);
}
//deserialize form but doesn't disable form attributes while waiting for respond
function submitModalEnabledForm(formName, successDiv, method, modalTitle){
	_showModalDiv(formName, method, null, null, successDiv, modalTitle);
}
//depracated, use showModalDiv
function quickAddDialog(url,params, successDiv, modalTitle, postFunction, closeFunction){
	showModalDiv(url,params, successDiv, modalTitle, postFunction, closeFunction);

}
//create a modal window without blured background
function showModalDivUnBlur(url,params, successDiv, modalTitle){
	showModalDiv(url,params, successDiv, modalTitle, null, null, false);
}
//basic function for displaying ajax request in modal window
function showModalDiv(url, params, successDiv, modalTitle, postFunction, closeFunction, blur, centerWindow){
	_showModalDiv(null, null, url, params, successDiv, modalTitle, postFunction, closeFunction, blur, centerWindow);
}
function _showModalDiv(formName, method, url, params, successDiv, modalTitle, postFunction, closeFunction, blur, centerWindow){
	if (modalSemaphore == 1) {  return;}
	dontDeleteModalContent = false;
	_initNewModalWindow(successDiv, modalTitle, closeFunction, blur, centerWindow);
	if (url != null){
			//ajax requests
		submitToUpdate(url,params, successDiv, null, postFunction, true);
		return;
	}
	if (formName != null){
		submitEnabledForm(formName, successDiv, method, true, true);
	}
}
//deprecated, use showModalDiv
function showAsModalDiv(url,params, successDiv, modalTitle, postFunction, closeFunction, blur){
	showModalDiv(url,params, successDiv, modalTitle, postFunction, closeFunction, blur);
}
//add new modalDivId, modal title and set modalDialogFlag
function _initNewModalWindow(modalDivId, modalTitle, closeFunction, blur, centerWindow){
	var modalSize = modalDivs.length;
	modalDivs[modalSize] = modalDivId;

	modalTitles[modalSize] = modalTitle != null ? modalTitle : ' ';
	blurStatus[modalSize] = blur != null ? blur : true;
	modalMessages.push(null);
	modalErrors.push(null);
	modalHelpLinks.push(null);
	modalCenterWindow.push(centerWindow != null ? centerWindow : true);

	closeFunctions[closeFunctions.length] = closeFunction;
	currentModalTitle = modalTitle;
	modalSemaphore = 1;
}
function modalGetActiveWindow(){
	if (modalDivs.length == 0) return null;
	return $(modalDivs[modalDivs.length-1]);
}
//creates header, title for modal div
function _prepareModalWindowContainer(modalContent, hideCloseLink, showHelp, addModalButton){

	if (hideCloseLink == null) hideCloseLink = false;
	if (showHelp == null) showHelp = false;
	var modalTitle = currentModalTitle;
	var title = modalTitle != null ? modalTitle : " &nbsp;";
	modalWindow = $(modalWindowId);
	if ($(modalWindowId) == null) {
		modalWindow = document.createElement('table');
		modalWindow.id = modalWindowId;
		modalWindow.className 	= 'modalContent';
		document.getElementsByTagName('body')[0].appendChild(modalWindow);
		modalWindow.cellSpacing = 0;
		modalWindow.setAttribute('cellpadding',3);
	}else{
		modalDeleteContent();
	}

	table = modalWindow; //document.createElement('table');;
	
	var rowIndex = 0;
	var row = table.insertRow(rowIndex++);
	var cell = row.insertCell(0);
	cell.innerHTML = title;
	focusA = document.createElement('a');
	focusA.id = modalWindowId+"_focus";
	focusA.href = "";
	cell.appendChild(focusA);
	cell.id = modalHeaderId;
	//cell.style.width = '99%;';
	row.style.cursor = 'move';
	row.className = "modalHeader";
	var colspan = 2;
	
	//prepare help link
	cell = row.insertCell(1);
	
	if (!hideCloseLink){
		//close modal link
		span = document.createElement('span');
		span.className = 'modalHeaderLink';
		span.innerHTML = '<a href="#" onclick="javascript: closeModal(); return false" title="Close" id="modalCloseLink_'+modalDivs.length+'">' +
		'<img src="'+contextPath+'/img/close_modal.png" alt="Close" class="modalCloseLink" /></a>';
		cell.appendChild(span);
		//colspan++;
	}
	
	span = document.createElement('span');
	span.className = 'modalHeaderLink';
	span.innerHTML = '<a href="#" onclick="javascript: modalHelpOpen(); return false" class="modalHelpLink" >' +
	'Help</a>';
	span.id = "modalHelLink_"+modalDivs.length;
	cell.appendChild(span);
	if (!showHelp){
		span.style.display = 'none';
	}

	
	row = table.insertRow(rowIndex++);
	
	cell = row.insertCell(0);
	cell.colSpan = colspan;
	div = document.createElement("div");
	div.id = modalWindowId+"_messageContainer";
	cell.appendChild(div);
	div = document.createElement("div");
	div.id = modalWindowId+"_errorContainer";


	cell.appendChild(div);

	row = table.insertRow(rowIndex++);
	cell = row.insertCell(0);
	cell.colSpan = colspan;
	cell.appendChild(modalContent);
	
	if (addModalButton){
		row = table.insertRow(rowIndex++);
		cell = row.insertCell(0);
		cell.colSpan = colspan;
		cell.innerHTML = '<div style="text-align:center;"><input type="button" class="buttons" name="ok" value="Ok" onclick="javascript:closeModal(true);  return false;"></div>';
	}
}
var dialogFunction;
function executeDialogFunction(){
	if (dialogFunction == null) return;
	try{
		dialogFunction();
	}catch(e){
	}
}
function dialogBlocker(message, title, postFunct, showCloseLink, buttonLabel){
	if (title == null) title = "Info";
	dialog(message, postFunct, title, 'blocker', showCloseLink, buttonLabel);
}
function dialogError(message, title, postFunct, showCloseLink, buttonLabel){
	if (title == null) title = "Error";
	dialog(message, postFunct, title, 'error', showCloseLink, buttonLabel);
}
function dialogMessage(message, title, postFunct, showCloseLink, buttonLabel){
	if (title == null) title = "Message";
	dialog(message, postFunct, title, 'message', showCloseLink, buttonLabel);
}
function dialogInfo(message, title, postFunct, showCloseLink, buttonLabel){
	if (title == null) title = "Info";
	dialog(message, postFunct, title, 'info', showCloseLink, buttonLabel);
}
function dialogInput(message, title, postFunct, showCloseLink, buttonLabel){
	if (title == null) title = "Info";
	dialog(message, postFunct, title, 'input', showCloseLink);
}
function dialogDelete(entity, name, postFunct, title){
	if (name != null) name = "'"+name+"'";
		else name = "";
	if (title == null) title = "Delete "+entity;
	dialog("Are you sure you want to delete "+entity+" "+ name+" ?", postFunct, title, 'delete');
}
function dialog(message, postFunct, title, dialogType, showCloseLink, buttonLabel){

	if (message == null) return;
	dialogFunction = postFunct;
	var divId = 'dialog';
	checkDiv(divId);
	if (title == null) title="&nbsp;";
	_initNewModalWindow(divId, title);
	var table = document.createElement('table');
	var row = table.insertRow(0);
	var cell = row.insertCell(0);
	var buttonNumber = 2;
	var rowsNumber = 1;
	if (showCloseLink){
		showCloseLink = true;
	}
	var firstButtonLabel  = "   Yes   ";
	var secondButtonLabel = "   No   ";

	if (buttonLabel != null){
		firstButtonLabel = buttonLabel;
	}
	if (dialogType == null){
		dialogType = 'delete';
	}
	var className = 'dialog  ';
	if (dialogType == 'delete'){
		className +='dialog_delete';
	}
	if (dialogType == 'info'){
		className += 'dialog_info';
	}
	if (dialogType == 'message' ){
		className += 'dialog_message';
		firstButtonLabel  = "   OK   ";
		buttonNumber = 1;
	}
	if (dialogType == 'error'){
		className += 'dialog_error';
		buttonNumber = 1;
	}
	if (dialogType == 'blocker'){
		className += 'dialog_message';
		showCloseLink = false;
		buttonNumber = 0;
	}
	if (dialogType == 'input'){
		buttonNumber = 1;
	}

	cell.width = "400px";
	cell.align="center";

	var div = document.createElement('div');
	div.className = className;
	div.innerHTML = message ;
	cell.appendChild(div);
	row = table.insertRow(rowsNumber);

	cell = row.insertCell(0);
	cell.align="center";

	if (buttonNumber == 2){
	cell.innerHTML = '<input type="button" class="buttons" name="ok" value="'+  firstButtonLabel  +'" onclick="javascript:executeDialogFunction(); closeModal(true); return false;" > '
	+'<div style="display:inline; width:100px" >&nbsp;</div> <input type="button" class="buttons" name="ok" value="'+  secondButtonLabel  +'" onclick="javascript:dialogFunction = null; closeModal(true); return false;">';
	}else if (buttonNumber == 1){
		cell.innerHTML = '<input type="button" class="buttons" name="ok" value="'+  firstButtonLabel  +'" onclick="javascript:executeDialogFunction(); closeModal(true);  return false;">';
	}else {
		cell.innerHTML = "";
	}
	if (dialogType == 'input'){
		className += 'dialog_input';
		row = table.insertRow(1);
		cell = row.insertCell(0);
		cell.innerHTML = "<input type='text' id='myDialogInput' style='width:200px;' onkeypress='wChatResp.inputNameSubmit(event)'/>"
		cell.align="center";
	}
	$(divId).appendChild(table);
	modalShowContent(divId, null, null, !showCloseLink);
}
//main Modal function
//creates modal container, blug background and plave div on center
//reverse - when modal window is closed and app need to show previous modal
//dontShowClose - if true, modal div doesn't show x link in upper right corner
function modalShowContent(elementId, dontCenterWindow, reverse, dontShowClose, addModalButton) {
	if (reverse == null) reverse = false;
	//if (modalDialogFlag == null) return;
	if (!reverse && modalDivs.length > 1){
	   var xy = new Array($(bgBlur).style.width, $(bgBlur).style.height);
	   //use later to restore bg dimens
	   backgroundXY.push(xy);
	}
	_hideSelectBoxes(elementId);
	modalWindowId = 'modalWindow_'+modalDivs.length;
	modalHeaderId = 'modalHeader_'+modalDivs.length;
	if (!reverse) {
		_prepareModalWindowContainer($(elementId), dontShowClose, null, addModalButton);
	}

	if (blurStatus[blurStatus.length-1]) {
		modalBlurBackground();
	}else{
		setZIndex($(bgBlur),-1);
	}
	/*if(modalCenterWindow[_positionWindowOnCenter.length-1]){
		addScrollEvent(function(){modalSetWindowOnCenter()});
	}  */
 	currentModalElement = modalWindowId;
	showElement(elementId);
	try{
		$(modalWindowId+"_focus").focus();
	}catch(e){
	}

	if (dontCenterWindow == null ||  dontCenterWindow == false)
		_positionWindowOnCenter($(modalWindowId));
	try{
		new Draggable(modalWindowId,
			{
				scroll: window,
				handle: $(modalHeaderId),
				revert: function(element){return false;},
				snap: function(x,y,draggable) {
					function constrain(n, lower, upper) {
						if (n > upper) return upper;
						else if (n < lower) return lower;
						else return n;
					}

					element_dimensions = Element.getDimensions(draggable.element);
					parent_dimensions = Element.getDimensions($('bgBlur'));//draggable.element.parentNode);
					return[
						constrain(x, 0, parent_dimensions.width - element_dimensions.width),
						constrain(y, 0, parent_dimensions.height - element_dimensions.height)];
				}
			}
		);

	} catch (e){
		//do nothing
	}
	if (!reverse){
	   _resetBackgroundSize();
	}else{
		var xy = backgroundXY.pop();
		//save background dimens
		$(bgBlur).style.width = xy[0];
		$(bgBlur).style.height = xy[1];
	}
	return false;
}
addResizeEvent(function(){
	modalSetWindowOnCenter();
	}
);
//window.onscroll = modalSetWindowOnCenter;
function modalSetWindowOnCenter(){
	if(modalWindowId != null && modalWindowId != 'modalWindow' && modalCenterActiveWindowdow && modalDivs.length > 0){
		//if(! _positionWindowOnCenter[_positionWindowOnCenter.length-1]) return;
		_positionWindowOnCenter($(modalWindowId));
		_resetBackgroundSize();
	}
}

function modalDeleteContent(){
	if (dontDeleteModalContent && modalDivs.length > 0){
		checkDiv('wpmHiddenContentDiv');
		hideElement(modalDivs[modalDivs.length-1]);
		$('wpmHiddenContentDiv').appendChild($(modalDivs[modalDivs.length-1]));
	}
	deleteRows('modalWindow_'+modalDivs.length);

}
function closeModals(){
	while(modalDivs.length > 0){
		closeModal();
	}
}
function closeModal(dontCenterWindow) {
	if (closeFunctions[closeFunctions.length-1] != null){
		eval("try{"+closeFunctions[closeFunctions.length-1]+'(); } catch(e){}');
	}
	modalSemaphore = 0;
	modalDeleteContent();
	if (modalDivs.length == 0) return;
	//modalDialogFlag = true;
	dontDeleteModalContent = false;
	modalSemaphore = 0;
	if (modalDivs.length == 1) {
		//modalDialogFlag = null;
		_showSelectBoxes();
		hideElement('modalWindow_'+modalDivs.length);
		if(keepBlur == false) {
			hideElement(bgBlur);
		}
		_descreaseModals();
	}else{
		Element.remove(modalWindowId);
		_descreaseModals();
		currentModalTitle = modalTitles[modalTitles.length-1];
		modalShowContent(modalDivs[modalDivs.length-1], dontCenterWindow, true);
	}

}

function modalBlurBackground(zIndexIncrement){

	_resetBackgroundSize();
	showElement(bgBlur);
	setZIndex($(bgBlur),zIndexIncrement);

}
 modalHideCloseLink = function(){
	hideElement('modalCloseLink_'+modalDivs.length);
}
 modalShowCloseLink = function(){
	showElement('modalCloseLink_'+modalDivs.length);
}
modalSetWindowTitle = function (title, length){
	var table = $('modalWindow_'+modalDivs.length);
	if (table == null) return;
	if (length != null){
		var addSufix = false;
		if (title.length > length) addSufix = true;
		title = title.substring(title, length);
		if (addSufix) title += '...';
	}
	table.rows[0].cells[0].innerHTML = title;
}




function setZIndex(oNode, increment){
	if ( oNode && oNode.style ) {
		with ( oNode.style ) {
			position = 'absolute';
		    //Niksa added
		    zIndex = modalGetActiveZIndex(increment);
		}
	}
}

function modalGetActiveZIndex(increment){
	if (increment == null)
		increment = 0;
	return 120000+ 1000 * (modalDivs.length + increment);
}

function modalShowLoading(){
	//not completed
	/*var zIndexIncrement = 1;
	setZIndex($('waitInformation'),zIndexIncrement+2);
	showElement('waitInformation')
	_positionWindowOnCenter($('waitInformation'));*/
	var zIndexIncrement = 2;
	modalBlurBackground(zIndexIncrement);
	_positionWindowOnCenter($('waitInformation'));
	setZIndex($('waitInformation'),zIndexIncrement);
	modalWaitInfoShown = true;
}
function modalHideLoading(){
	//closeModal();
	if (!modalWaitInfoShown) return;
	hideElement('waitInformation');
	if (modalDivs.length > 0){
		modalBlurBackground(-1);
	}else{
		hideElement(bgBlur);
	}
	modalWaitInfoShown = false;
}
function modalIsWindowOpen(){
	return (modalDivs.length > 0);
}
function modalHelpOpen(){
	var helpId = modalHelpLinks[modalHelpLinks.length - 1];
	if (helpId != null){
		showHelp(helpId);
	}
}
function modalHelpLinkId(id){
	modalHelpLinks[modalHelpLinks.length - 1] = id;
	showElement("modalHelLink_"+modalHelpLinks.length);
}

function _getSelectBoxes(){
	selectsElements = document.getElementsByTagName('select');
}
function _hideSelectBoxes(elementId){
	var sublings = getChildren($(elementId), true, 'input');
	if (! isIE7()) {
		if (selectsElements == undefined){
		_getSelectBoxes();}
		if (document.all){
			for (var i=0; i<selectsElements.length;i++){
				//selectsElements[i].style.display = 'none';
			}
 	}}
}
function _showSelectBoxes(){
	if (! isIE7()) {
		if (document.all){
			for (var i=0; i<selectsElements.length;i++)	{
				//selectsElements[i].style.display = '';
			}
		}
	}
}
function _resetBackgroundSize(){
	var bgWidth;
	var bgHeight;
	var win = getWindowDimensions();
	bgWidth = win.x;
	bgHeight = win.y;
	if($(bgBlur) != null){
		if (bgWidth < document.body.scrollWidth){
			$(bgBlur).style.width = document.body.scrollWidth;
		}else{
			$(bgBlur).style.width = bgWidth;
		}
		if (bgHeight < document.body.scrollHeight){
			$(bgBlur).style.height = document.body.scrollHeight;
		}else{
			$(bgBlur).style.height = bgHeight;
		}
	}
}
function _descreaseModals(){
	modalDivs.pop();
	modalTitles.pop();
	closeFunctions.pop();
	blurStatus.pop();
	modalErrors.pop();
	modalMessages.pop();
	modalHelpLinks .pop();
	modalCenterWindow.pop();
}
_positionWindowOnCenter = function( oNode ) {
    if ( typeof(oNode) == 'string' ) {
        oNode = $(oNode);
    }
	currentModalElement = oNode;
    var iDocX  = 0;
    var iWinY = 0;
    if ( typeof( window.innerWidth ) == 'number' ) {
        iDocX  = window.innerWidth;
        iWinY = window.innerHeight;
    } else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        iDocX  = document.documentElement.clientWidth;
        iWinY = document.documentElement.clientHeight;
    } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        iDocX  = document.body.clientWidth;
        iWinY = document.body.clientHeight;
    }


	var scroll = getWindowScroll();
	var scrollX = scroll.x;
	var scrollY = scroll.y;

	setZIndex(oNode);
	//setZIndex($(modalHeaderId));
    var oElementDimensions = Element.getDimensions(oNode);
    var iSetX = ( iDocX - oElementDimensions.width  ) / 2;
    var iSetY = ( iWinY - oElementDimensions.height ) / 2;// + scrollY;
    iSetX = ( iSetX < 0 ) ? 0 : iSetX;
    iSetY = ( iSetY < 0 ) ? 0 : iSetY;

	if ( oNode && oNode.style ) {
		with ( oNode.style ) {
			left = scrollX+ iSetX + "px";
			top  = scrollY +iSetY + "px";
			display = '';
		}
	}
};
