/*

	Parts of this code are based on "lightbox"

*/

/**
 * This is a temporary function to cover the period to rebuild all generateDialog calls to give a json object
 * as parameter in stead of separate parameters. For new dialog calls use the generateDialog function
 * 
 */
function generateDialogPrev(cThisFormID,cDialogName,cFormPageID,cID,cURL){
	
	/*
		cThisFormID: the name of the form from which this action is initiated
		cDialogName: the name of the dialog file to op
		cFormPageID: optional target form page id (formid)
		cID: optional ID which can be used to retrieve data in the dialog. Typically this param is populated by a href
		cURL: is used for situations where the dialog file is located outside the standard dialog folder (e.g. modules)
	*/
			
	var json = {"parentform": cThisFormID, "dialogid": cDialogName, "formid": cFormPageID, "id": cID, "dialogurl": cURL};
	
	generateDialog(json);
	
}

/**
 * 
 * 
 * @param object json {	
 * 		parentform: the name of the form from which this action is initiated
 *		dialogid: the name of the dialog file to load
 *		formid: optional target form page id (formid)
 *		id: optional ID which can be used to retrieve data in the dialog. Typically this param is populated by a href
 *		dialogurl: is used for situations where the dialog file is located outside the standard dialog folder (e.g. modules)
 *	}
 */
function generateDialog(json){

	if (!$("#overlay").length) {
		
		generateOverlay(json.dialogid);

		//Populate the dialog via AJAX
		generateDialogHTML(json);
		
	}
	
}


function generateOverlay(cDialogName){
	
	arrayPageSize = getPageSize();
	arrayPageScroll = getPageScroll();

	// Generate the overlay	
	var objBody = document.getElementsByTagName("body").item(0);
	var objOverlay = document.createElement('div');
	var cDivOverlayId = 'overlay';
	
	objOverlay.setAttribute('id',cDivOverlayId);
   	objOverlay.style.height = arrayPageSize[1] + 'px';
   	objOverlay.style.width = "100%";
	
	objBody.insertBefore(objOverlay, objBody.firstChild);

	document.getElementById(cDivOverlayId).style.display ='block';
	
	// Generate the Dialog
	var objDialog = document.createElement('div');
	//var cDivDialogId = 'dialog';

	objDialog.setAttribute('id','dialog');
	objDialog.setAttribute('className', 'dialog ' + cDialogName); /* IE */
	objDialog.setAttribute('class','dialog ' + cDialogName); /* FF */
	
	var objDialog = document.body.appendChild(objDialog);
	var nWidth = parseInt(getStyle(objDialog, "width"));
	var nHeight = "300";
	
	//objDialog.style.top = (arrayPageScroll[1] + ((arrayPageSize[4] - 35 - nHeight) / 2) + 'px');
	objDialog.style.left = (((arrayPageSize[0] - 20 - nWidth) / 2) + 'px');
		
	//cDivDialogIdString = String(cDivDialogId);
	document.getElementById("dialog").innerHTML = "<div id='dialog_content' class='disabled'>Loading...</div>";

	if ($.browser.msie && $.browser.version.substr(0,2) == "6.") {
		// In IE6 the z-index doesn't work on select elements those are still on top above the overlay.
		// So we mark those with a special class and disabled them
		// In the dialog close function we enable them and remove the class
		$('select:visible').addClass('IE6SelectZIndexBug');
		$('.IE6SelectZIndexBug').hide();
	}
}

function postprocessDialog(){
	
	var objDialog = document.getElementById("dialog");

	//Make scrollable tables scrollable
	var dialogWidth = $('#dialog').width();
	var tableHeight = 220;
	var rowcount = $('table.scrollable tr').size();
	if(rowcount > 10){
		$('table.scrollable').Scrollable(tableHeight,dialogWidth);
	}
	
	nDialogHeight = document.getElementById("dialog").clientHeight;
	nYPos = (arrayPageSize[3] - nDialogHeight)/2;
	if (nYPos < 0) nYPos = 0;
	objDialog.style.top = (arrayPageScroll[1]  + nYPos+ 'px');
	
	
	// Check for 'ESC' keypress
	document.onkeypress = getKey;
	
	// Set initial focus
	$("#dialog :input:text:visible:first").focus();
	
	ajaxFixFormButtons();
	
}

/**
 * 
 *
 * @param object json {	
 * 		parentform: the name of the form from which this action is initiated
 *		dialogid: the name of the dialog file to load
 *		formid: optional target form page id (formid)
 *		id: optional ID which can be used to retrieve data in the dialog. Typically this param is populated by a href
 *		dialogurl: is used for situations where the dialog file is located outside the standard dialog folder (e.g. modules)
 *	}
 */
function generateDialogHTML(json) {
	
	if(json.dialogurl){
		cData = "dialogurl="+json.dialogurl;
	} else {
		cData = "dialogid="+json.dialogid;
	}

	if(json.formid){
		cData += "&formid="+json.formid;
	}
	
	if(json.message){
		cData += "&message="+json.message;
	}
	
	if(json.id){
		cData += "&id="+json.id; //used by the dialog to retrieve information from the database based on this id
	}
	
	if(json.data){
		cData += "&data="+json.data; //used to pass data from ajax calls to the dialog
	}
	
	
	if (json.params) {
		cData += json.params;
	}
	
	if(json.parentform){
		
		if(document.forms[json.parentform] != 'undefined'){

			oForm = document.getElementById(json.parentform);	
		
			if(oForm.elements.length > 0){
		
				for (i = 0; i < oForm.elements.length; i++) {
					
					if (oForm.elements[i].type == "checkbox") {
						if (oForm.elements[i].checked == true) {
							cData += "&";
							cData += oForm.elements[i].name + "=" + oForm.elements[i].value;	
						}
					} else if (oForm.elements[i].type == "radio") {
						if (oForm.elements[i].checked == true) {
							cData += "&";
							cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
						}
									
					} else if ((oForm.elements[i].type != "button") && (oForm.elements[i].type != "submit")  && (oForm.elements[i].name != "formFields")) {
						cData += "&";
						cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
					} 
					
				}//for (i = 0; i < oForm.elements.length; i++)
				
			} //if(oForm.elements.length > 0)
		
		}
		
	} //if(json.parentform)
	
	$.ajax({
		url: "/functions/dialog_handler.php",
		dataType: "html",
		data: cData,
		success: function(html){

			$("#dialog_content").html(html);
			$("#dialog_content").show();
			
			if($("#dialog").data("onload")){
				eval($("#dialog").data("onload"));
			}
			
			$("#dialog").draggable({
				handle: "div.dialogHeader"
			});
			
			postprocessDialog();
			
		}
	});
	
}


//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}


// Listen for the key pressed by the user
function listenKey () {	document.onkeypress = getKey; }


// If ESC is pressed close the dialog
function getKey(e){
	
	 var kC  = (window.event) ? // MSIE or Firefox?
	 			event.keyCode : e.keyCode;
     var Esc = (window.event) ?
     			27 : e.DOM_VK_ESCAPE // MSIE : Firefox

     if(kC==Esc) {
        closeDialog();
     }

}


// Function to close the dialog and the overlay
function closeDialog(){
	$.ajax({url: "/functions/ajax/unset_session_form.php"});	
	$("#dialog").remove();
	$("#overlay").remove();
	document.onkeypress = '';
	if ($.browser.msie && $.browser.version.substr(0,2) == "6.") {
		$('.IE6SelectZIndexBug').show();
		$('.IE6SelectZIndexBug').removeClass('IE6SelectZIndexBugEnabled');
	}
}

// Retrieve style information set via css
function getStyle(oElm, strCssRule){

	/* This function retrieves style information that was set using css */
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}




function setDialogInitialFocus() {
	
	var objDialog = document.getElementById("dialog_content");
	var nodes = objDialog.getElementsByTagName("input");

	j = 0;
	for(var i = 0;i < nodes.length;i++) {
		
		if (nodes[i].type=="text") {
			
			if ((j == 1) && (nodes[i].name != "cSearch") && (nodes[i].name != "") && (nodes[i].name != "formGuid") ) {
				cID = nodes[i].id
				document.getElementById(cID).focus();
			}
			j++;			
		}
	}
	
}

function showBusy() {
	if(document.getElementById('busy')){
		oDiv = document.getElementById('busy');	
		oDiv.setAttribute('className', 'busyIcon'); /* IE */
		oDiv.setAttribute('class','busyIcon'); /* FF */
	}	
}

function hideBusy() {
	if(document.getElementById('busy')){
		oDiv = document.getElementById('busy');	
		oDiv.setAttribute('className', ''); /* IE */
		oDiv.setAttribute('class',''); /* FF */
	}	
}


function getSelectedValue(cForm,cField){
	
	// This function retrieves the formfields data (constraints string) and 
	// split the data into separate strings. If the specified cField is found
	// an exclamation mark is added or removed to the constraint. This will
	// enable or disable the field from being validates. 	
	
	var cFieldName=cField+"Field";

	for(var i = 0;i < document.forms[cForm].elements[cFieldName].length;i++) {
	
		if (document.forms[cForm].elements[cFieldName][i].checked==true) {
            return document.forms[cForm].elements[cFieldName][i].value;         
		}

	}

}
