ie  = (document.all && document.getElementById);
ns = (!document.all && document.getElementById);
				
// Set defaults if no settings provided in Theme file
function checkModuleSettings() {
	if (!closeButton) 			{ closeButton 			= "100000winclose.gif"; 		}
	if (!minimiseButton) 		{ minimiseButton 		= "100000winmin.gif"; 			}
	if (!unloadedCloseButton) 	{ unloadedCloseButton 	= "100000winclosegrey.gif"; 	}
	if (!maximiseButton) 		{ maximiseButton 		= "100000winmax.gif"; 			}
	if (!borderColor) 			{ borderColor 			= "#0668ED"; 					}
	if (!titleTextColor) 		{ titleTextColor 		= "#0668ED"; 					}
	if (!borderWidth) 			{ borderWidth 			= "5"; 							}
	if (!borderColorMinimised)	{ borderColorMinimised	= "#000099";					}
	if (!resizeBGColor)			{ resizeBGColor			= "#EEEEEE";					}
	if (!resizeTextColor)		{ resizeTextColor		= "#AAAAAA";					}
	if (!minimisedWidth)		{ minimisedWidth		= "200";						}
	}
	
function newModule(wtitle,wx,wy,wwidth,wheight,turl,minimised,embed,modexclusive,iframeSecurity) {

	checkModuleSettings(); // see above function

	var tdiv = "div"+modules;
	var txt;
	var num;
	var rnd = (Math.round((Math.random()*3)+1));

	if (!wx) {
		pleft = (Math.round((Math.random()*(document.body.clientWidth-wwidth-10))+10)); // 10 = offset left
		}
	else {
		pleft = wx;
		}
	if (!wy) {
		ptop = (Math.round((Math.random()*(document.body.clientHeight-wheight-25))+25)); // 25 = offset top
		}
	else {
		ptop = wy;
		}

	if (moduleHeaderImage) {
		headerBGColor = "";
		}	
		
	if (minimised == "Y" && embed != "Y") {
		loadURL = defaultPage;
		useButton = '/desktop/images/'+unloadedCloseButton;
		}
	else {
		loadURL = turl;
		useButton = '/desktop/images/'+closeButton;
		}
		
	if (embed == "Y") {
		totalEmbeddedModules++; // Used to stop gaps in minimised tiles
		}
		
	if (permanentBorders == "Y" && embed != "Y") {
		defaultBorderWidth = borderWidth;
		barVisibility = "visible";
		paddiv = '17px';
		}
	else {
		defaultBorderWidth = "0";
		barVisibility = "hidden";
		paddiv = '0px';
		}
	if (iframeSecurity == "Y") {
		iframeSecurity = "security=\"restricted\"";
		}
	else {
		iframeSecurity = "";
		}
		
	if (wwidth == "max") {
		wwidth = screen.width - pleft;
		}
	if (wheight == "max") {
		wheight = screen.height - ptop;
		}
		
	txt = '<div id="div'+modules+'" class="rwindow" style="top: '+ptop+'px; left: '+pleft+'px; width: '+wwidth+'px; height: '+wheight+'px; z-index: '+topfocus+'; background-color: '+bgColor+'; filter:alpha(opacity='+moduleOpacityMax+'); border: '+defaultBorderWidth+'px solid '+borderColor+'; border-top: 0px;" onClick="setzIndex(\'div'+modules+'\');" onmousedown="setLocks(\'lock\',\''+modules+'\');prepareResize(\'indiv'+modules+'\',\'hidden\');" onmouseup="setLocks(\'unlock\',\''+modules+'\');prepareResize(\'indiv'+modules+'\',\'visible\'); saveDivSettings(\''+modules+'\');" onMouseOut="setOpacity(\''+modules+'\',\'hide\');clearTimeout(timeOut);" onMouseOver="setzIndex(\'div'+modules+'\');setOpacity(\''+modules+'\',\'show\');clearTimeout(timeOutOpacity[\''+modules+'\']);waitTime(\'showBorder\',\''+modules+'\');">';
	//txt += ' <div id="txt'+modules+'" class="resizetextdiv" style="background-color:'+resizeBGColor+';color:'+resizeTextColor+';">resizing</div>';
	txt += ' <div id="bar'+modules+'" class="winbar" style="visibility:'+barVisibility+';background-image: url(\'/desktop/images/'+moduleHeaderImage+'\');background-color:'+headerBGColor+';z-index:'+topfocusbar+';" onmousedown="prepareMove(\''+modules+'\',\'hidden\');" onmouseup="unprepareMove(\''+modules+'\',\'visible\');" handlefor="div'+modules+'" title="Drag & Drop using the Title Bar when not minimised. Drag borders to resize.">';
	txt += '  <img id="resize'+modules+'" name="resize'+modules+'" src="/desktop/images/'+minimiseButton+'" width="15" height="17" border="0" alt="" onClick="resizeWindow(\''+modules+'\');" style="cursor: hand;"><img id="delete'+modules+'" name="delete'+modules+'" src="'+useButton+'" width="15" height="17" border="0" alt="" onClick="deleteWindow(\''+modules+'\',\'unbind\');" style="cursor: hand;">';
	txt += ' </div>';
	txt += ' <div id="indiv'+modules+'" class="ifrdiv" style="height:100%;padding-top:'+paddiv+';">';
	txt += '  <iframe id="t'+modules+'" name="t'+modules+'" src="'+loadURL+'" '+iframeSecurity+' class="ifr" scrolling="auto" frameborder="0" onLoad="setzIndex(\'div'+modules+'\');maximiseModule(\''+modules+'\');" allowTransparency="true"></iframe>';
	txt += ' </div>';
	txt += ' <div id="title'+modules+'" class="titlediv" style="float:left;visibility:'+barVisibility+';color:'+titleTextColor+';z-index:'+topfocustitle+';" onmousedown="prepareMove(\''+modules+'\',\'hidden\');" onmouseup="unprepareMove(\''+modules+'\',\'visible\');" handlefor="div'+modules+'">'+wtitle+'</div>';
	txt += '</div>';
	
	//This is where we set the containers that are used to hold the minimised window, if not embedded
	if (embed != "Y") {
		containertxt = '<div id="container'+modules+'" class="container" style="position:relative;height:19px;width:100%;z-index:-2;"></div>';
		containerTop = containerTop + 19;
		}

	num = modules;
	modSolo[num] = modexclusive;	// Stores module SOLO setting (N or Y)
	originalHREF[num] = turl;		// Store authors URL of module
	currentHREF[num] = loadURL;		// Store current URl of module
	winStatus[num] = minimised;		// Store initial minimised setting (from author or cookie)
	saveWidth[num] = wwidth;		// Store width setting (from author or cookie)
	saveHeight[num] = wheight;		// Store heigh setting (from author or cookie)
	saveLeft[num] = wx;				// Store left setting (from author or cookie)
	saveTop[num] = wy;				// Store top setting (from author or cookie)
	embeddedModules[num] = embed;	// Save embed setting (used in function showBorder)
	modules++;
	
	if (pleft > 720) {
		pleft = pleft - 710;
		}
	if (ptop > 200) {
		ptop = ptop - 190;
		}
	pleft = pleft + gapleft;
	ptop = ptop + gaptop;
	
	// Following two referenced divs must be output before this is called
	document.getElementById("pg").innerHTML = document.getElementById("pg").innerHTML + txt;
	if (embed != "Y") {
		document.getElementById("containers").innerHTML = document.getElementById("containers").innerHTML + containertxt;
		}
	if (minimised == "Y" && embed != "Y") {		
		resizeWindow(num);
		delWin = "Y"; // force Close Button function to prevent maximiseModule() function
		}
		
	topfocus = topfocus+3;
	topfocusbar = topfocus+1;
	topfocustitle = topfocus+2;
	
	}
	
//Timeout function used to delay border appearance on modules so if mouse is just pasing over
// the clearTimeOut function is called (above)
function waitTime(func,param) {
	if (!mouseAlreadyOver) {
		timeOut = setTimeout(func+"('"+param+"')", 250); // 1 second = 250
		}
	}
	
// Set flag on initial load to prevent minimised modules from maximising (iframe onLoad function)
function loadComplete(func,param) {
	themeLoaded = "Y";
	setzIndex('div1');
	}
	
// Called from iframe "onLoad" to detect when user invoked target call is made to the frame from another
function maximiseModule(num) {
	var twindow = 'div'+num;
	var divH = document.getElementById(twindow).offsetHeight;
	// delWin indicates if X button has been used to resize
	if (divH == minimisedHeight && delWin != "Y" && themeLoaded == "Y") {
		userInvokedMaximise = "Y";
		resizeWindow(num);
		userInvokedMaximise = "N";
		}
	delWin = "N"; // reset for next call
	}
	
// Opacity toggle for modules, called from outer module div (above) (settings from Theme file)
function setOpacity(num,type) {
	var twindow = 'div'+num;
	var divH = document.getElementById(twindow).offsetHeight;
	if (divH == minimisedHeight && type == 'hide') { // minimised, cover with opacity
		document.getElementById(twindow).style.filter= 'alpha(opacity='+moduleOpacityMin+')';
		}
	else if (type == 'hide') { // maximised, make opaque (mouseOut)
		timeOutOpacity[num] = setTimeout("makeOpaque('"+num+"')", 1000); // 1 second = 250
		}
	else {  // remove opacity layer to allow view (mouseOver)
		document.getElementById(twindow).style.filter= 'alpha(opacity=100)';
		}
	}
// Set a time delay for making a module display opaque on mouseout (called from setOpacity()
function makeOpaque(num) {
	var twindow = 'div'+num;
	document.getElementById(twindow).style.filter= 'alpha(opacity='+moduleOpacityMax+')';
	}
	
// Opacity toggle settings for info buttons, called from online.php (settings from Theme file)
function setButtonOpacity(num,type) {
	var timage = 'button'+num;
	if (type == 'hide') { // minimised, cover with opacity
		document.getElementById(timage).style.filter= 'alpha(opacity='+moduleOpacityMax+')';
		}
	else {  // moused over
		document.getElementById(timage).style.filter= 'alpha(opacity=100)';
		}
	}
	
//Lock down other Divs while moving to stop wandering mouse syndrome!
function setLocks(type,divid) {	
	var winiAsString;
	if (type == "lock") {		
		for (var wini=1;wini<parseFloat(modules);wini++) {
			winiAsString = 'div'+wini+'';
			document.getElementById(winiAsString).disabled = true; // lock each
			if (winiAsString != divid) {
				document.getElementById('div'+divid).disabled = false; // lock all except this
				}
			}
		}
	else {
		for (var wini=1;wini<parseFloat(modules);wini++) {
			winiAsString = wini+'';
			document.getElementById("div"+winiAsString).disabled = false; // lock each
			}
		}
	}

function prepareMove(divid,makediv) {
    var tdiv = 'indiv'+divid;
	var twindow = 'div'+divid;
	var divH = document.getElementById(twindow).offsetHeight;
	if (divH > minimisedHeight) {
		document.getElementById(tdiv).style.visibility = makediv;
		document.onmousedown = moveme_onmousedown;
		document.onmouseup = moveme_onmouseup;
		document.onmousemove = moveme_onmousemove;
		}
	}
	
function unprepareMove(divid,makediv) {
	var tdiv = 'indiv'+divid;
	var twindow = 'div'+divid;
	var divH = document.getElementById(twindow).offsetHeight;
	if (divH > minimisedHeight) {
		document.getElementById(tdiv).style.visibility = makediv;	
		document.onmousedown = doDown;
		document.onmouseup = doUp;
		document.onmousemove = doMove;
		}	
	}

// Save new Module positions on user move into cookie
function saveDivSettings(divid) {
	var outerdiv = 'div'+divid;
	var divMinim = winStatus[divid]; // minimised setting
	if (divMinim == 'N') { // not minimised, so store current user settings
		var divW = document.getElementById(outerdiv).offsetWidth;
		var divH = document.getElementById(outerdiv).offsetHeight;
		var divL = document.getElementById(outerdiv).style.left;
		var divT = document.getElementById(outerdiv).style.top;
		}
	else { // minimised, so store user settings prior to being mimimised
		var divW = saveWidth[divid];
		var divH = saveHeight[divid];
		var divL = saveLeft[divid];
		var divT = saveTop[divid];
		}
		
	//alert('savescheme.php?win='+divid+'&t='+divT+'&l='+divL+'&w='+divW+'&h='+divH+'&m='+divMinim,'ifr');
	window.open('/desktop/savescheme.php?win='+divid+'&t='+divT+'&l='+divL+'&w='+divW+'&h='+divH+'&m='+divMinim,'ifr');
	}
	
//Called when X button on module clicked
function deleteWindow(num,action) {
	var twindow = "div"+num;
	var inwindow = "indiv"+num;
	var containerdiv = "container"+num;
	var thisframe = 't'+num;
	var closeButtonDiv = 'delete'+num;
	var divH = document.getElementById(twindow).offsetHeight;	
	if (action == 'delete') {
		if (confirm("Are you sure you want to close & delete this Window?")) { // UNUSED Hide and remove window
			document.getElementById(inwindow).style.visibility = 'hidden';
			document.getElementById(containerdiv).style.visibility = 'hidden';
			document.getElementById(twindow).style.visibility = 'hidden';
			pleft = pleft - gapleft;
			ptop = ptop - gaptop;
			}
		}
	else if (divH != minimisedHeight && action == 'unbind') {
		if (confirm("This will navigate away from the current URL and minimise the window to save memory. You will be returned to the initial default URL when you maximise the window. Do you wish to continue?")) { // Empty window and minimise
			document.getElementById(thisframe).src = defaultPage;
			document.getElementById(closeButtonDiv).src = '/desktop/images/'+unloadedCloseButton;
			//window.open(defaultPage,thisframe);
			currentHREF[num] = '';
			resizeWindow(num);
			}
		}
	else if (divH == minimisedHeight && action == 'unbind') {
		if (confirm("This will navigate away from the current URL to save memory and minimise the window. You will be returned to the initial default URL when you maximise the window. Do you wish to continue?")) { // Empty window and minimise
			document.getElementById(thisframe).src = defaultPage;
			document.getElementById(closeButtonDiv).src = '/desktop/images/'+unloadedCloseButton;
			//window.open(defaultPage,thisframe);
			currentHREF[num] = '';
			}
		}
	delWin = "Y";
	}
	
function prepareResize(divid,makediv) {
    var tdiv = divid;
	document.getElementById(tdiv).style.visibility = makediv;
	}
	
function resizeWindow(num) {
	var twindow = "div"+num;
	var tbarwin = "bar"+num;
	var ttitlewin = "title"+num;
	var tcontainer = "container"+num;
	var thisframe = 't'+num;
	var closeButtonDiv = 'delete'+num;
	var resizeButtonDiv = 'resize'+num;
	var titleWidth = parseInt(minimisedWidth);
	var minL = document.getElementById('containers').style.left;
	var divW = document.getElementById(twindow).offsetWidth;
	var divH = document.getElementById(twindow).offsetHeight;
	var divL = document.getElementById(twindow).style.left;
	var divT = document.getElementById(twindow).style.top;	
	//Calculate whether to tile minimised windows up or down
	if (tileMinimisedFrom == "Top" || tileMinimisedFrom == "top") { // Tile minimised top down
		topAdjust = parseInt(1+(num-1)*19);
		var minT = parseInt(document.getElementById('containers').style.top) + topAdjust;
		}
	else { // Tile minimised bottom up (totalModulesExpected from online.php)
		topAdjust = parseInt(19*(num-totalEmbeddedModules-1));
		var minT = parseInt(document.getElementById('containers').style.top) + 
				   parseInt((totalModulesExpected-totalEmbeddedModules)*19) - 19 - topAdjust;
		}	
	if (divH == minimisedHeight) { // restore
		winStatus[num] = 'N';
		if (showOneModule == "Y") { // minimise all but this
			for (var wini=1;wini<parseFloat(modules);wini++) {
				if (winStatus[wini] == 'N' && (wini < num || wini > num)) {
					resizeWindow(wini); // minimise
					}
				}
			}
		if ((!currentHREF[num] || currentHREF[num] == defaultPage) && userInvokedMaximise == "N") {
			currentHREF[num] = originalHREF[num];
			//document.getElementById(thisframe).src = originalHREF[num];
			window.open(originalHREF[num],thisframe);
			}
		document.getElementById(twindow).style.width = saveWidth[num];
		document.getElementById(twindow).style.height = saveHeight[num];
		document.getElementById(twindow).style.left = saveLeft[num];
		document.getElementById(twindow).style.top = saveTop[num];
		document.getElementById(twindow).style.zIndex = '100';
		document.getElementById(twindow).style.borderLeft = '5px solid '+borderColor;   // set to color of rwindow border
		document.getElementById(twindow).style.borderRight = '5px solid '+borderColor;  // set to color of rwindow border
		document.getElementById(twindow).style.borderBottom = '5px solid '+borderColor; // set to color of rwindow border
		document.getElementById(tbarwin).style.cursor = 'move';
		document.getElementById(ttitlewin).style.cursor = 'move';
		document.getElementById(closeButtonDiv).src = '/desktop/images/'+closeButton;
		document.getElementById(resizeButtonDiv).src = '/desktop/images/'+minimiseButton;
		//document.getElementById(ttitlewin).style.width = saveWidth[num]+'px';
		if (modSolo[num] == "Y") {
			setSolo('maximise',num); // hide other windows if this is a runSolo module
			}
		removeFocus();
		showBorder(num);
		}
	else { // minimise
		saveWidth[num] = divW;
		saveHeight[num] = divH;
		saveLeft[num] = divL;
		saveTop[num] = divT;
		winStatus[num] = 'Y'; // Set minimised? (yep!)
		document.getElementById(tbarwin).style.visibility = 'visible';
		document.getElementById(tbarwin).style.cursor = 'hand';	
		document.getElementById(ttitlewin).style.cursor = 'hand';	
		document.getElementById(ttitlewin).style.visibility = 'visible';
		//document.getElementById(ttitlewin).style.width = titleWidth+'px';
		document.getElementById(twindow).style.height = minimisedHeight+'px';
		document.getElementById(twindow).style.width = minimisedWidth+'px';		
		document.getElementById(twindow).style.left = minL;		
		document.getElementById(twindow).style.top = minT;
		document.getElementById(twindow).style.zIndex = '0';
		document.getElementById(twindow).style.borderLeft = '0px solid '+borderColorMinimised;
		document.getElementById(twindow).style.borderRight = '0px solid '+borderColorMinimised;
		document.getElementById(twindow).style.borderBottom = '0px solid '+borderColorMinimised;
		document.getElementById(resizeButtonDiv).src = '/desktop/images/'+maximiseButton;
		if (modSolo[num] == "Y") {
			setSolo('minimise',num); // hide other windows if this is a runSolo module
			}
		removeFocus();
		}
	setOpacity(num,'hide');
	saveDivSettings(num);
	}
	
function setSolo(rtype,num) {
	for (var wini=1;wini<parseFloat(modules);wini++) {
		var tdiv = 'div'+wini;
		var idiv = 'indiv'+wini;
		if (document.getElementById(tdiv).offsetHeight > minimisedHeight && wini != parseInt(num) && 
			rtype == "maximise" && embeddedModules[wini] != "Y") {
			document.getElementById(tdiv).style.visibility = 'hidden'; // hide modules
			document.getElementById(idiv).style.visibility = 'hidden'; // hide modules
			}
		else if (document.getElementById(tdiv).offsetHeight > minimisedHeight && wini != parseInt(num) && 
				 rtype == "minimise" && embeddedModules[wini] != "Y") {
			document.getElementById(tdiv).style.visibility = 'visible'; // hide modules
			document.getElementById(idiv).style.visibility = 'visible'; // hide modules
			}
		}
	}
	
// remove all window focuses by hiding borders
function removeFocus() { 
	for (var wini=1;wini<parseFloat(modules);wini++) {
		strval = wini+'';
		hideBorder(strval);
		}
	}
	
function showBorder(thisWin) {	
	//Lock other modules first
	setzIndex("div"+thisWin);
	mouseAlreadyOver = "Y";
	if (winStatus[thisWin] == 'N') { // not minimised
		// first, hide borders of all modules
		removeFocus();
		currentWindowFocus = thisWin;
		if (allowModuleDrag == 'enabled' && embeddedModules[thisWin] != "Y") {
			var tbarwin = 'bar'+thisWin;
			var ttitlewin = 'title'+thisWin;
			var tmaindiv = 'div'+thisWin;
			var tresizediv = 'div'+thisWin;
			var tindivdiv = 'indiv'+thisWin;
			document.getElementById(tbarwin).style.visibility = 'visible';
			document.getElementById(ttitlewin).style.visibility = 'visible';
			document.getElementById(tmaindiv).style.borderLeft = borderWidth+'px solid '+borderColor;
			document.getElementById(tmaindiv).style.borderRight = borderWidth+'px solid '+borderColor;
			document.getElementById(tmaindiv).style.borderBottom = borderWidth+'px solid '+borderColor;
			document.getElementById(tresizediv).style.backgroundColor = resizeBGColor;
			document.getElementById(tindivdiv).style.paddingTop = '17px';
			}
		}
	}
	
function hideBorder(thisWin) {
	mouseAlreadyOver = "";
	if (winStatus[thisWin] == 'N' && permanentBorders != "Y") { // not minimised & permanent borders not set
		var tbarwin = 'bar'+thisWin;
		var ttitlewin = 'title'+thisWin;
		var tmaindiv = 'div'+thisWin;
		var tresizediv = 'div'+thisWin;
		var tindivdiv = 'indiv'+thisWin;
		document.getElementById(tbarwin).style.visibility = 'hidden';
		document.getElementById(ttitlewin).style.visibility = 'hidden';
		document.getElementById(tmaindiv).style.borderLeft = '0px'+' solid '+borderColor;
		document.getElementById(tmaindiv).style.borderRight = '0px'+' solid '+borderColor;
		document.getElementById(tmaindiv).style.borderBottom = '0px'+' solid '+borderColor;
		document.getElementById(tresizediv).style.backgroundColor = '';
		document.getElementById(tindivdiv).style.paddingTop = '0px';
		}
	}
	
function setzIndex(tdiv) {
	topfocus = topfocus + 3;
	topfocusbar = topfocus+1;
	topfocustitle = topfocus+2;
	document.getElementById(tdiv).style.zIndex = topfocus;	
	}

//Drag and drop code: http://javascript.internet.com/navigation/drag-and-drop-menu.html
N = (document.all) ? 0 : 1;
var ob;
var over = false;

function MD(e) {
if (over)
{
if (N) {
ob = document.getElementById(selecteddiv);
X=e.layerX;
Y=e.layerY;
return false;
}
else {
ob = document.getElementById(selecteddiv);
ob = ob.style;
X=event.offsetX;
Y=event.offsetY;
}
}
}

function MM(e) {
if (ob) {
if (N) {
ob.style.top = e.pageY-Y;
ob.style.left = e.pageX-X;
}
else {
ob.pixelLeft = event.clientX-X + document.body.scrollLeft;
ob.pixelTop = event.clientY-Y + document.body.scrollTop;
return false;
      }
   }
}

function MU() {
ob = null;
}

if (N) {
document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
}

//document.onmousedown = MD;
//document.onmousemove = MM;
//document.onmouseup = MU;

