// JavaScript Document
/******************************************************************
@author: 		mohammed ahmed
@date: 			05.05.2007
@version: 		1.2
@comments:
mobox provides a friendly reploacement to the popup box window.
It add the window to the required page in the form of innerHtml.
It can also be used to display another page contents.

@licence: FREE. refernces are made where possible to third party code. 

*******************************************************************/

// variables
var opacityLevel 		= 5; 					// overlay background transparancy level.
var browserType 		= navigator.userAgent; 	// type of browser. i.e. MSIE or opera.

var indicator			= null;			//div
var indicatorID			= "indicator"	// div id
var indicatorImgPath 	= "images/indicator.gif"; 
var indicatorImgHtml 	= "<img src=\""+indicatorImgPath+"\" alt=\"Loading...\" style=\"width:128px;height:128px;\"/>";
var closeImgPath		="images/WhiteCircle.png";
var closeImgHtml		="<img src=\""+closeImgPath+"\" align=\"right\" width=\"14\" height=\"14\" border=\"0\" alt=\"close\" />";

var overlayBG			= null;			// div
var overlayBGID			= "overlayBG";	// div id

var box 				= null;			// div
var boxID 				= "mobox";		// div id
var boxFrame 			= null;			// div
var boxFrameID 			= "boxFrame";	// div id
var boxContents 		= null;			// div
var boxContentsID 		= "boxContents";// div id
var boxHeader			= null;			// div
var boxHeaderID			= "boxHeader";	// div id
var boxTitle			= null;			// div
var boxTitleID			= "boxTitle";	// div id
var boxAttr 			= "rel"; 		// html tag attribute that determins the box element.
var boxH 				= "250px";		// box deafult height.
var boxW 				= "400px";		// box default width.
var boxCloseOption 		= 1;			// default box closing option. available options: 0 on click anywhere in the box, 1 close button.
var boxCloseLinkID		= "closeBox";	// the <a> id 
var boxTitle 			= "mobox";		// default box title. please note, the title only appears if the box has a header
var displayHeader 		= true;			// display header to the box.
var boxHtmlTagType 		= "a";			// the html tag type that defines the box.
var boxType				= 0;			// default box type. 0= simple box with frame, 1 = window style, 2 = nifty box
var boxDimensions		= new Array();	// box width and height.


// on script loading, run the initiation method
window.onload=function (){
  initiation();
}



// add box relevant materials to the page.
function initiation(){	
	
	// get the box tag i.e. <a href=.... rel="mobox[123,321]">contents</a>
	var boxTags = getBoxTags(); // Array - list of the specific tags
	
	// do the following for each tag found
	for(var i=0; i< boxTags.length ; i++){		
		var boxTag = boxTags[i];
		
		// create click event listener
		boxTag.onclick = function() {
			boxDimensions = getBoxDimension(this);
			// create the box in the page.. only one box. 
			createBox(document.getElementsByTagName("body")[0],this);
			
			// set box objects
			box 		= document.getElementById(boxID);
			boxFrame 	= document.getElementById(boxFrameID);
			boxHeader 	= document.getElementById(boxHeaderID);
			boxTitle 	= document.getElementById(boxTitleID);
			boxContents = document.getElementById(boxContentsID);
			indicator	= document.getElementById(indicatorID);
			overlayBG	= document.getElementById(overlayBGID);
			
			showIndicator();
			applyOverlay();
			showBox(this);		
			hideIndicator();			
			window.onscroll = maintPos;
			window.onresize = maintPos;
			return false;
		};
	}
	
}

// create the box layout in the required area. i.e. in the page body tag.
function createBox(element, boxTag){
	// remove any existing mobox
	var tempBox = document.getElementById(boxID);
	if(tempBox != null) element.removeChild(tempBox);
	
	// get box type
	var boxOption;
	var type = getBoxType(boxTag);
	if(type == null) type = boxType; // use the default type if no type was specified
	type = parseInt(type);
	
	if(type != 0){
		if(type == 1){
			if(boxDimensions.length == 2) boxOption = 4; // this option provides similar layout to option 1, but with fixed size box.
			else boxOption = 1;
		}else if(type == 2){
			if(boxDimensions.length == 2) boxOption = 3; // this option provides similar layout to option 2, but with fixed size box.
			else boxOption = 2;
		}
	}else{
		boxOption = type;
	}
	
	// set box componenets
	var boxHtml = "";
	boxHtml = "<div id=\""+overlayBGID+"\" style=\"display:none;\"></div>"; // for graying out the page.
	boxHtml += "<div id=\""+indicatorID+"\" style=\"display:none;\">" +indicatorImgHtml+"</div>"; // where indicator image is displayed.
	switch(boxOption){
		case 1:
			// (TYPE 1) box size fit contents			
			boxHtml += "<table id=\""+boxFrameID+"\" style=\"display:none;\" border=\"0\" cellspacing=\"1\" cellpadding=\"0\" class=\"frame\">";
			boxHtml += "<tr id=\""+boxHeaderID+"\" style=\"display:none;\">";
			boxHtml += 	"<th id=\""+boxTitleID+"\" align=\"left\">&nbsp;</th>";
			boxHtml += 	"<th id=\"closeBoxCell\" align=\"right\"><a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">";
			boxHtml += 	closeImgHtml+"</a></th>";
			boxHtml += "</tr><tr>";	
			boxHtml += 	"<td colspan=\"2\">";
			boxHtml +=	"<div id=\""+boxContentsID+"\">";
			boxHtml += "<a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">Click here to close</a>";
			boxHtml += "</div></td></tr></table>";
			
		break;
		case 2: // (TYPE 2) box size fit contents
		/**
		 * DOES NOT SIZE TO FIT THE CONTENTS IN FIREFOX & IE7 & IE6.
		 * DOES NOT APPLY ROUND CORNERS IN IE7
		 */	
		 	boxHtml +=	"<div class=\"rBox\">"; 
			boxHtml += "<table id=\""+boxFrameID+"\" style=\"display:none;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td>"; 
			boxHtml +=	"<b class=\"rBoxTop\">";
			boxHtml +=	"<b class=\"r1\"></b>";
			boxHtml +=	"<b class=\"r2\"></b>";
			boxHtml +=	"<b class=\"r3\"></b>";
			boxHtml +=	"<b class=\"r4\"></b></b>";
			
							
			
			boxHtml +=	"<div class=\"rBoxHeader\" id=\""+boxHeaderID+"\" style=\"display:none;\">";
			boxHtml += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td id=\""+boxTitleID+"\">";
			boxHtml += "</td><td id=\"boxCloseCell\">";
			boxHtml += 	"<a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">";
			boxHtml += 	closeImgHtml+"</a>";
			boxHtml += "</td></tr></table>";			
			boxHtml +=  "</div>";
			
			boxHtml +=	"<div class=\"rBoxBody\" id=\""+boxContentsID+"\">Contents</div>";
			boxHtml +=	"<b class=\"rBoxBottom\">";
			boxHtml +=	"<b class=\"r4\"></b>";
			boxHtml +=	"<b class=\"r3\"></b>";
			boxHtml +=	"<b class=\"r2\"></b>";
			boxHtml +=	"<b class=\"r1\"></b></b>";			
			
			boxHtml += "</td></tr></table></div>";
		break;
		case 12: // BACKUP of case 2 (TYPE 2) box size fit contents
		/**
		 * DOES NOT SIZE TO FIT THE CONTENTS IN FIREFOX & IE7 & IE6.
		 * DOES NOT APPLY ROUND CORNERS IN IE7
		 */	
			boxHtml += "<table id=\""+boxFrameID+"\" class=\"rBox\" style=\"display:none;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td>"; 	
			boxHtml +=	"<b class=\"rBoxTop\">";
			boxHtml +=	"<b class=\"r1\"></b>";
			boxHtml +=	"<b class=\"r2\"></b>";
			boxHtml +=	"<b class=\"r3\"></b>";
			boxHtml +=	"<b class=\"r4\"></b></b>";
			
			boxHtml +=	"<div class=\"rBoxHeader\" id=\""+boxHeaderID+"\" style=\"display:none;\">";
			boxHtml += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td id=\""+boxTitleID+"\">";
			boxHtml += "</td><td id=\"boxCloseCell\">";
			boxHtml += 	"<a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">";
			boxHtml += 	closeImgHtml+"</a>";
			boxHtml += "</td></tr></table>";			
			boxHtml +=  "</div>";
			
			boxHtml +=	"<div class=\"rBoxBody\" id=\""+boxContentsID+"\">Contents</div>";
			boxHtml +=	"<b class=\"rBoxBottom\">";
			boxHtml +=	"<b class=\"r4\"></b>";
			boxHtml +=	"<b class=\"r3\"></b>";
			boxHtml +=	"<b class=\"r2\"></b>";
			boxHtml +=	"<b class=\"r1\"></b></b>";			
			
			boxHtml += "</td></tr></table>";
		break;
		case 3: // (TYPE 2) box size fixed with scroll bars if content is larger
			/**
			 * DOES NOT PROVIDE HORIZANTAL SCROLL BAR IN IE6
			 */
			boxHtml +=	"<div id=\""+boxFrameID+"\" class=\"rBox\" style=\"display:none;\">"; 
			boxHtml +=	"<b class=\"rBoxTop\">";
			boxHtml +=	"<b class=\"r1\"></b>";
			boxHtml +=	"<b class=\"r2\"></b>";
			boxHtml +=	"<b class=\"r3\"></b>";
			boxHtml +=	"<b class=\"r4\"></b></b>";
			
			boxHtml +=	"<div class=\"rBoxHeader\" id=\""+boxHeaderID+"\" style=\"display:none;\">";
			boxHtml += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td id=\""+boxTitleID+"\">";
			boxHtml += "</td><td id=\"boxCloseCell\">";
			boxHtml += 	"<a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">";
			boxHtml += 	closeImgHtml+"</a>";
			boxHtml += "</td></tr></table>";			
			boxHtml +=  "</div>";
			
			boxHtml +=	"<div class=\"rBoxBody\" id=\""+boxContentsID+"\">Contents</div>";
			
			boxHtml +=	"<b class=\"rBoxBottom\">";
			boxHtml +=	"<b class=\"r4\"></b>";
			boxHtml +=	"<b class=\"r3\"></b>";
			boxHtml +=	"<b class=\"r2\"></b>";
			boxHtml +=	"<b class=\"r1\"></b></b>";
			boxHtml +=	"</div>";
		break;		
		case 4: //(TYPE 1) box size fixed with scroll bars if content is larger
		/**
			 * DOES NOT PROVIDE HORIZANTAL SCROLL BAR IN IE6
			 */
			boxHtml +=	"<div id=\""+boxFrameID+"\" style=\"display:none;\">"; 			
			boxHtml +=	"<div id=\""+boxHeaderID+"\" style=\"display:none;\">";	
			boxHtml += "<table border=\"0\" cellspacing=\"1\" cellpadding=\"0\" class=\"frame\"  width=\"100%\">";
			boxHtml += "<tr>";
			boxHtml += 	"<th id=\""+boxTitleID+"\" align=\"left\">&nbsp;</th>";
			boxHtml += 	"<th id=\"closeBoxCell\" align=\"right\"><a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">";
			boxHtml += 	closeImgHtml+"</a></th>";
			boxHtml += "</tr></table>";				
			boxHtml +=  "</div>";					
			boxHtml +=	"<div class=\"boxContentsFrame\" id=\""+boxContentsID+"\">Contents</div>";		
			boxHtml +=	"</div>";
			
			break;
			
		default:
			boxHtml +=	"<div id=\""+boxFrameID+"\" style=\"display:none;\">"; // box frame. can be null if no frame is required by setting the stylesheet
			boxHtml += "<div id=\""+boxHeaderID+"\" style=\"display:none;\">";
			boxHtml += "<a id=\""+boxCloseLinkID+"\" href=\"javascript:void(null);\">Click here to close</a>";
			boxHtml += "<font id=\""+boxTitleID+"\" align=\"left\">&nbsp;</font></div>";		
			boxHtml +=	"<div id=\""+boxContentsID+"\">";// add start box content div
			
			boxHtml += "</div>";// close box content div tag
			boxHtml += "</div>";// close box fram div tag
	}
	
	// create the box
	var abox = document.createElement("div");
	abox.setAttribute("id",boxID);
	abox.style.display = 'block';
	abox.innerHTML = boxHtml;
	element.appendChild(abox);
}

// get the used boxs tags
function getBoxTags(){
	var array = new Array();
	var elements = document.getElementsByTagName(boxHtmlTagType);
	for (var i = 0; i < elements.length ; i++) {
		var element = elements[i];
		// check if it has the box used attribute
		if(element.getAttribute(boxAttr)){
			var attr = element.getAttribute(boxAttr);
			// check if the attribute calls the mobox
			if (attr.indexOf("mobox") != -1){
				array.push(element);
			}
		}
	}
	return array;
}

// show indicator
function showIndicator(){
	indicator.style.display="block";
	posToCenter(indicator);	
	indicator.onclick = function(){hideBox();hideIndicator();}
}

function hideIndicator(){
	indicator.style.display="none";
}

// apply overlay - grayout background
function applyOverlay(){
	overlayBG.style.opacity = 0;
	overlayBG.style.filter = 'alpha(opacity=0)';
	setBGOpacity = setOpacity;
	for (var i=0;i<=opacityLevel;i++) {setTimeout("setBGOpacity('overlayBG',"+i+")",70*i);} 		
	overlayBG.style.display = "block";
	var pagesize = new getPageSize();
	var scrollPos = new getScrollPos();
		
	if(browserType.indexOf("MSIE ") != -1) {overlayBG.style.width = pagesize.width+'px';} 	
	overlayBG.style.height = pagesize.height+scrollPos.scrollY+'px';
	
	hideIEselect();
}

function removeOverlay(){	
	overlayBG.style.display="none";
	showIEselect();
}

// show the box
function showBox(boxTag){
	// set box properties
	boxFrame.style.display = "";
	
	if(boxDimensions.length == 2){
		boxFrame.style.width = boxDimensions[0] +"px";
		boxFrame.style.height = boxDimensions[1] +"px";	
	}
	
	boxFrame.style.visibility = "hidden";
	posToCenter(boxFrame); 
	boxFrame.style.visibility = "visible";
	
	// display box header
	setBoxHeader(boxTag);
	boxHeader.style.display = "";
	var title = getBoxTitle(boxTag);
	boxTitle.innerHTML = title;
	
	boxContents.style.overflow = "auto";
	// clear contents before populating
	boxContents.innerHTML = "";	
	// get box contents
	
	setBoxContents(boxTag);	
	//alert(boxContents.scrollWidth+"x"+boxContents.scrollHeight);
	// set close box listeners
	document.getElementById(boxCloseLinkID).onclick = function(){hideBox();};
	if(boxCloseOption == 0){ boxContents.onclick = function(){hideBox();};}
}


function hideBox(){
	removeOverlay();
	boxFrame.style.display="none";
	// clear contents
	boxContents.innerHTML = "";
	window.onscroll = null;
}

/*
 * specify the contents of the box.
 * There are two ways: 
 * 1. reading from a file.
 * 2. reading from the contents within the html tag.
 *
 * @param: fileURL - this must be an http link. 
 * if null then the box contents will read from the defined variable boxContentHtml.
 */
function setBoxContents(boxTag){	
	var boxContentHtml = "";
	var fileUrl = boxTag.href;
	if(fileUrl == window.location){
		boxContentHtml = boxTag.innerHTML;
		boxContents.innerHTML = boxContentHtml;
	}else{
		var xmlHttpRequest = false;
		if(browserType.indexOf("MSIE 7") != -1){
			xmlHttpRequest = createXmlHttpRequestIE7(); // to be compatible with IE7
		}else{
			xmlHttpRequest = createXmlHttpRequest();
		}
		
	   if (xmlHttpRequest.overrideMimeType) {
		  xmlHttpRequest.overrideMimeType('text/xml');
		}	
		xmlHttpRequest.open('GET',boxTag.href,true);		
		xmlHttpRequest.onreadystatechange = function() {
			if(xmlHttpRequest.readyState == 4){				
				boxContentHtml = xmlHttpRequest.responseText;
				// Bug In  IE for box type 2. contents arenot set in the boxContents
				boxContents.innerHTML = boxContentHtml;						
			}
		}
		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		xmlHttpRequest.send(null);
	}
}

// set box dimension only if specified.
function getBoxDimension(boxTag){
	if(boxTag != null){
		var attr = boxTag.getAttribute(boxAttr); // i.e. mobox[210,320] width,higth
		var dimensions = attr.slice(attr.indexOf("[")+1,attr.indexOf("]")).split(/\,/);
		/*// set dimensions to the defaul if nothing is specified.
		if((dimensions == null)&&(dimensions.length < 2)){
			dimensions[0] = boxW ;
			dimensions[1] = boxH;
		}*/
		return dimensions;
	}
}

function setBoxHeader(){
	if(displayHeader == true) {boxHeader.style.display = "block";}
	else {boxHeader.style.display = "none";}
}

// get the box title from the used tag title attribute.
function getBoxTitle(boxTag){
	if(boxTag != null) return boxTag.getAttribute("title");
	return boxTitle; // return defalt value
}

function getBoxType(boxTag){
	var attr = boxTag.getAttribute(boxAttr); // i.e. mobox[210,320]&type=1
	var type = attr.split(/.*\&type=/);
	// in MSIE 7 array location starts from 0
	if(browserType.indexOf("MSIE") != -1) return type[0];
	return type[1];
}


posToCenter = function(elem) {
	var scrollPos = new getScrollPos();
	var pageSize = new getPageSize();
	var emSize = new getElementSize(elem);
	var x = Math.round(pageSize.width/2) - (emSize.width /2) + scrollPos.scrollX;
	var y = Math.round(pageSize.height/2) - (emSize.height /2) + scrollPos.scrollY;	
	elem.style.left = x+'px';
	elem.style.top = y+'px';	
}

getScrollPos = function() {
	var docElem = document.documentElement;
	this.scrollX = self.pageXOffset || (docElem&&docElem.scrollLeft) || document.body.scrollLeft;
	this.scrollY = self.pageYOffset || (docElem&&docElem.scrollTop) || document.body.scrollTop;
}

getPageSize = function() {
	var docElem = document.documentElement
	this.width = self.innerWidth || (docElem&&docElem.clientWidth) || document.body.clientWidth;
	this.height = self.innerHeight || (docElem&&docElem.clientHeight) || document.body.clientHeight;
}

getElementSize = function(elem) {
	this.width = elem.offsetWidth ||  elem.style.pixelWidth;
	this.height = elem.offsetHeight || elem.style.pixelHeight;
}

/*
 * Creating a cross-browser XMLHttpRequest
 * @author: Philip McCarthy - philmccarthy@gmail.com 
 */
function createXmlHttpRequest(){
	var xmlreq = null;
	// Create XMLHttpRequest object in non-Microsoft browsers
	if (window.XMLHttpRequest) {
		xmlreq = new XMLHttpRequest();
	} // Create XMLHttpRequest via MS ActiveX
	else if (window.ActiveXObject) {
		try {			
      		// Try to create XMLHttpRequest in later versions of Internet Explorer
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e1) {
				// Failed to create required ActiveXObject
				try {
					// Try version supported by older versions of Internet Explorer
					xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
					} 
					catch (e2) {
						// Unable to create an XMLHttpRequest with ActiveX
					}				
			}
	}
  return xmlreq;
}

/********************************************************
 Make this IE7 Compatible ;)
 http://ajaxian.com/archives/ajax-on-ie-7-check-native-first
*********************************************************/
function createXmlHttpRequestIE7() {
	var xmlhttp;
		/*@cc_on
	@if (@_jscript_version>= 5)
			try {xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
					try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
					catch (E) {xmlhttp = false;}
			}
	@else
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != "undefined") {
			try {xmlhttp = new XMLHttpRequest();} catch (e) {xmlhttp = false;}
	}
	return xmlhttp;
}
/************************************************************/
// hide select boxes -- known bug in MS IE6 when using layers
function hideIEselect(){
    if(browserType.indexOf("MSIE ") != -1)
    {
        var selects = document.getElementsByTagName("select");        
        for (var i = 0; i < selects.length ; i++){
            var select = selects[i];
            if(select != null)select.style.display='none';
        }        
    }
}

// show select boxes -- known bug in MS IE when using layers
function showIEselect(){
    if(browserType.indexOf("MSIE ") != -1)
    {
        var selects = document.getElementsByTagName("select");
        for (var i = 0; i < selects.length ; i++){
            var select = selects[i];
            if(select != null)select.style.display='block';
        }
    }
}

setOpacity = function (elemid,value) {
	var e = document.getElementById(elemid);
 	e.style.opacity = value/10;
 	e.style.filter = 'alpha(opacity=' + value*10 + ')';
}

maintPos = function() {
	var pagesize = new getPageSize();
	var scrollPos = new getScrollPos();

	if(browserType.indexOf("MSIE ") != -1) {overlayBG.style.width = pagesize.width+'px';} 

	if(browserType.indexOf("Opera/9") != -1) {overlayBG.style.height = document.body.scrollHeight+'px';}
	else {overlayBG.style.height = pagesize.height+scrollPos.scrollY+'px';}
	
	posToCenter(boxFrame);
	
}

