// Adams shorthand js..
var d = document;
dId =  function(id){
	return d.getElementById(id);
}
dCss = function(id){
	return dId(id).style;
}
dTags = function(tagName, id){
	if(tagName == undefined){
		return false;
	} else {
		if(id == undefined){
			return d.getElementsByTagName(tagName);
		} else {
			return dId(id).getElementsByTagName(tagName);
		}
	}
}
dEnum = function(myObject){
	var temp = "";
	for(myItem in myObject){
		temp += myItem +": "+ myObject[myItem] + " // ";
	}
	alert(temp);
}

// function that makes the nav drop downs work.
/** DELETE? this was the drop downs used on the intermediate console **/
sfHover = function() {
	if(document.getElementById("nav1")){
		var sfEls = document.getElementById("nav1").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
	if(document.getElementById("nav2")){
		var sfEls = document.getElementById("nav2").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

// show hide menu...
menuSize = function(myAction){
	if(myAction == "showHide"){
		if((document.getElementById("menuContent").style.width == "") || (document.getElementById("menuContent").style.width != "0px")){
			document.getElementById("menuContent").style.width = "0px" ;
			document.getElementById("menuContent").style.overflow = "hidden" ;
			document.getElementById("menuSide").style.width = "5px" ;
			document.getElementById("contentSide").style.marginLeft = "25px" ;
			document.getElementById("twoColumns").style.backgroundPosition = "0px 0px";
		} else {
			document.getElementById("menuContent").style.width = "215px" ;
			document.getElementById("menuContent").style.overflow = "auto" ;
			document.getElementById("menuSide").style.width = "220px" ;
			document.getElementById("contentSide").style.marginLeft = "240px" ;
			document.getElementById("twoColumns").style.backgroundPosition = "215px 0" ;
		}
	}
}

//START: allow alpha transparencies in IE
function initAlphaBackgrounds(){
	if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
		window.attachEvent("onload", alphaBackgrounds);
	}
}
function alphaBackgrounds(){
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
	for (i=0; i<document.all.length; i++){
		var bg = document.all[i].currentStyle.backgroundImage;
		if (itsAllGood && bg){
			if (bg.match(/\.png/i) != null){
				var mypng = bg.substring(5,bg.length-2);
				document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+mypng+"', sizingMethod='scale')";
				document.all[i].style.backgroundImage = "url('/i/b.gif')";
			}
		}
	}
}
initAlphaBackgrounds();
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (version < 7)) // document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
if (window.attachEvent)
    window.attachEvent("onload", correctPNG);
    //FINISH: allow alpha transparencies in IE

function repositionIrBrowser(){
	// this repositions and rescales the editor to fit with the window size
	//var height = "400px";
	var height = "481px";
	var width = "800px";
	var left = "47px";
	var top = "130px";
	//var top = "220px";
	
	//var editorControl = document.getElementById("consoleEditor");
    //var fakeBody = document.getElementById("cContainer"); //the main scrolling element within editor mode.
	
	myBrowser.style.left = left; 
	myBrowser.style.top = top;
	myBrowser.style.height = height;
	myBrowser.style.width = width;
	repositionShade();
}

function repositionShade(){
	shadeWidth = document.body.scrollWidth; // shade is the 50% transparency
	shadeHeight = document.body.scrollHeight;
	myShade.style.height = shadeHeight;
	myShade.style.width = shadeWidth;
	
	var editorControl = document.getElementById("consoleEditor");
	if(editorControl){
	    myShade.style.position = "absolute";
	    myShade.style.height = document.body.clientHeight;
	}
}

// this is used by the editor (and other things) for custom formatters
function doGenericBrowser(action, url) {
    
    myBrowser = document.getElementById("browserFrame");
    
    if(action == "open") {
        shade("show");
        myBrowser.src = url;
        myBrowser.className = "browserOn";
		repositionIrBrowser();
		document.body.onresize = function(){
			repositionIrBrowser();
		}
    } else if (action == "close") {
        shade("hide");
		myBrowser.className = "browserOff";
		document.body.onresize = "";
		myBrowser.src = "about:blank";
    }
}

function doBrowser(doWhat, forWhat, selectedObject){
	// opens and closes the iframe and sticks the transparent shade onto stop users
	// interacting with the the cms while in the editor.
    var url = "";
    switch(forWhat) {
        case "image" :
            //if(selectedObject) {
			//    url = "/Utility/FindImageLibrary.ashx?ciid=" + selectedObject;
		    //} else {
    		//	url = "/imagelibrary/default.htm/imagebrowser";
		    //}
		    url = "/default.htm/imagebrowser";
            break;
        case "link" :
            url = "/default.htm/linkbrowser";
            break;
        case "externallink" :
            url = "/console/externallink.htm";
            break;
        case "table" :
            url = "/console/table.htm";
            break;
        case "code" :
            url = "/console/code.htm";
            break;
        case "markup" :
            url = "/console/markup.htm";
            break;
    }

	doGenericBrowser(doWhat, url);
}

function shade(show){
    var editorControl = document.getElementById("consoleEditor"); //Check if in edit mode
    if(!editorControl) {
	    myShade = document.getElementById("shader");
	}
	else {
	    myShade = document.getElementById("editorShader");
	}
	    
	if(show=="show"){
		myShade.style.display = "block";
		myShade.style.backgroundColor = "#000";
		myShade.style.left = "0px";
		myShade.style.top = "0px";
		myShade.style.filter = "alpha(opacity=50)";
		myShade.style.zIndex = "10001";
		hideSelects("hide");
	} else {
		myShade.style.display = "none";
		document.body.onresize = "";
		hideSelects("show");
	}
}
function hideSelects(show){
	if (window.attachEvent){
		var d = document.getElementsByTagName("select"); 
		for(i=0; i<d.length; i++){
			d[i].style.visibility = (show == "hide") ? "hidden" : "visible";
		}
	}
}
function createShortcut(doWhat){
	var shortcuts = document.getElementById("createNewShortcut").style;
	if(doWhat == "new"){
		shade("show");
		shortcuts.visibility = "visible";
		repositionShade();
		if (window.attachEvent) window.attachEvent("onresize", repositionShade);
	} else {
		shortcuts.visibility = "hidden";
		shade("hide");
	}
}
function placePlaceholderNav(){
	//repostions the right hand placeholder navigation to align with the top of the editor
	var editorTop = document.getElementById("consoleEditor").offsetTop; //get value of top of editor.
	var placeholderNav = document.getElementById("editorPlacholderNav");
	placeNavTop = placeholderNav.offsetTop + 12; //get top of placeholder nav
	var cine = document.getElementById("contentItemNavElement"); //parent in nav tree
	//TODO: adam - this is sometimes null (see http://console.irpublish.irdev.net/rnid/nef/lbt.htm/-/edit?wiz=1)
	if(cine != null) {
		cineBase = cine.offsetTop + cine.scrollHeight; //get value of bottom of parent in tree
		if(editorTop>cineBase){
			//if the editor is lower down the screen than the nav then adjust the nav
			placeholderNav.style.marginTop = editorTop - placeNavTop;
		}
	}
}

function fadeEditor(inOut){
	// this is the background changer in the editor at the moment it only moves from one
	// fixed colour to another, could be upgraded to go from any colour to any colour with
	// configurable times as this one is fixed.
	theBg = document.getElementById("consoleEditor").style;
	if(inOut == "in"){
		startR = currentR = startG = currentG = startB = currentB = 229;
		endR = endG = 255
		endB = 208;
		adjustR = (startR-endR)/8;
		adjustG = (startG-endG)/8;
		adjustB = (startB-endB)/8;
		whichFade = "in";
		fadeIn = window.setInterval(adjustEditorFade, 5);
	} else if (inOut == "out"){
		startR = currentR = startG = currentG = 255;
		startB = currentB = 208;
		endR = endG = endB = 229;
		adjustR = (startR-endR)/26;
		adjustG = (startG-endG)/26;
		adjustB = (startB-endB)/26;
		whichFade = "out";
		fadeOut = window.setInterval(adjustEditorFade, 20);
	}
}
function adjustEditorFade(){
	// subfunction for the fadeEditor()
	if(currentR != endR){
		currentR -= adjustR;
		currentG -= adjustG;
		currentB -= adjustB;
		colourString = "#" + Math.floor(currentR).toString(16) + Math.floor(currentG).toString(16) + Math.floor(currentB).toString(16);
		theBg.backgroundColor = colourString;
	} else {
		if(whichFade == "in"){
			window.clearInterval(fadeIn);
			fadeEditor("out");
		} else {
			window.clearInterval(fadeOut);
		}
	}
}

//HACK shouldn't be using a global....
var g_RowId;
var g_oldClassName;
function fadeRow(inOut){
	// this is the background changer in the editor at the moment it only moves from one
	// fixed colour to another, could be upgraded to go from any colour to any colour with
	// configurable times as this one is fixed.
	theBg = document.getElementById(g_RowId).style;
	if(inOut == "in"){
		g_oldClassName = document.getElementById(g_RowId).className;
		document.getElementById(g_RowId).className = "";
		startR = currentR = startG = currentG = startB = currentB = 229;
		endR = endG = 255
		endB = 208;
		adjustR = (startR-endR)/8;
		adjustG = (startG-endG)/8;
		adjustB = (startB-endB)/8;
		whichFade = "in";
		fadeIn = window.setInterval(adjustRowFade, 40);
	} else if (inOut == "out"){
		startR = currentR = startG = currentG = 255;
		startB = currentB = 208;
		endR = endG = endB = 229;
		adjustR = (startR-endR)/26;
		adjustG = (startG-endG)/26;
		adjustB = (startB-endB)/26;
		whichFade = "out";
		fadeOut = window.setInterval(adjustRowFade, 50);
	}
}
function adjustRowFade(){
	// subfunction for the fadeRow()
	if(currentR != endR){
		currentR -= adjustR;
		currentG -= adjustG;
		currentB -= adjustB;
		colourString = "#" + Math.floor(currentR).toString(16) + Math.floor(currentG).toString(16) + Math.floor(currentB).toString(16);
		theBg.backgroundColor = colourString;
	} else {
		if(whichFade == "in"){
			window.clearInterval(fadeIn);
			fadeRow("out");
		} else {
			window.clearInterval(fadeOut);
			document.getElementById(g_RowId).className = g_oldClassName;
		}
	}
}

function showShortcuts(){
	// top navigation function to show and position the shortcuts menu in the header.
	// had to use 3 divs because of the dodgy alpha png in the background
	thePanel = document.getElementById('myPanelOne');
	theList = document.getElementById('myShortcutsPanel');
	theFoot = document.getElementById('myPanelBottom');
	theTop = document.getElementById('shortcutsLink').offsetTop+32;
	theLeft = document.getElementById('shortcutsLink').offsetLeft;
	thePanel.style.top = theTop + "px";
	thePanel.style.left = theLeft + "px";
	theFoot.style.top = (theTop+thePanel.scrollHeight) + "px";
	theFoot.style.left = theLeft + "px";
	thePanel.style.visibility = "visible";
	theList.style.visibility = "visible";
	theFoot.style.visibility = "visible";
}

function hideShortcuts(){
	// hide the shortcuts menu from the header
	document.getElementById('myPanelOne').style.visibility = "hidden";
	document.getElementById('myShortcutsPanel').style.visibility = "hidden";
	document.getElementById('myPanelBottom').style.visibility = "hidden";
}

function showOtherItems(){
	// in the image browser this shows the dodgy drop down menu.
	// may need to improve it.
	document.getElementById("otherItems").style.display = "block";
	window.setTimeout(hideOtherItems,4000);
}

function hideOtherItems(){
	// in the image browser this hides the drop down menu
	document.getElementById("otherItems").style.display = "none";
}

function toggleDetail(showDetail) {
	var detail = document.getElementById("modeBoxDetailed");
	var simple = document.getElementById("modeBoxSimple");
	
	//shouldn't happen, but worth worrying about
	if(detail == null || simple == null) {
		return;
	}
	
	if(showDetail) {
		detail.style.display = "block";
		simple.style.display = "none";
		
		//delete cookie, if present
		document.cookie = "lockingsimple=;path=/;expires=" + new Date(1970, 3, 13).toGMTString();
	} else {
		detail.style.display = "none";
		simple.style.display = "block";
		
		//drop cookie
		document.cookie = "lockingsimple=true;path=/;expires=" + new Date(2070, 3, 13).toGMTString();
	}
}

// SWAP TABS IN STRUCTURE VIEW
function structureTab(whichTab){
	if(dId("stFolders")) {
		dCss("stFolders").backgroundColor = (whichTab=="stFolders") ? "#3366cc" : "#999999" ;
		dCss("folderItemsList").display = (whichTab=="stFolders") ? "block" : "none" ;
	}
	if(dId("stContent")) {
		dCss("stContent").backgroundColor = (whichTab=="stContent") ? "#3366cc" : "#999999" ;
		dCss("contentItemsList").display = (whichTab=="stContent") ? "block" : "none" ;
	}
	if(dId("stProperties")) {
		dCss("stProperties").backgroundColor = (whichTab=="stProperties") ? "#3366cc" : "#999999" ;
		dCss("propertiesArea").display = (whichTab=="stProperties") ? "block" : "none" ;
	}
	if(dId("stViews")) {
	    dCss("stViews").backgroundColor = (whichTab=="stViews") ? "#3366cc" : "#999999" ;
		dCss("viewsList").display = (whichTab=="stViews") ? "block" : "none" ;
	}
}

// ADVANCED Search, disable/enable input boxes.
function disableInputs(isDisabled){
	dId("startDate").disabled = (isDisabled) ? true : false;
	dId("endDate").disabled = (isDisabled) ? true : false;
	dId("dateTypes").disabled = (isDisabled) ? true : false;
	dCss("startDate").filter =  (isDisabled) ? "alpha(opacity=20)" : "alpha(opacity=100)";
	dCss("endDate").filter =  (isDisabled) ? "alpha(opacity=20)" : "alpha(opacity=100)";
	dCss("startDateLinkImage").filter =  (isDisabled) ? "alpha(opacity=20)" : "alpha(opacity=100)";
	dCss("endDateLinkImage").filter =  (isDisabled) ? "alpha(opacity=20)" : "alpha(opacity=100)";
}

//display saving graphic 
function showSaving(){
	dCss("savingDoc").display = "block";
	
	var editorControl = document.getElementById("consoleEditor");
	if(editorControl) {
	    dCss("savingDoc").top = (document.body.clientHeight/2) - (140/2);
	    dCss("savingDoc").left = (document.body.clientWidth/2) - (322/2);
	}
	else {
        dCss("savingDoc").top = (dId("consoleEditor").offsetTop+(dId("consoleEditor").scrollHeight)/2)-(dId("savingDoc").scrollHeight/2);
        dCss("savingDoc").left = (dId("consoleEditor").offsetLeft+(dId("consoleEditor").offsetWidth)/2)-(dId("savingDoc").offsetWidth/2);
	}
}
function hideSaving(){
	dCss("savingDoc").display = "none";
}
var lastSavedDate;
function startLastSaved(year,month,day,hours,minutes){
	lastSavedDate = new Date(year, month, day, hours, minutes);
	howLongSinceSaved();
	var checkDates = window.setInterval(howLongSinceSaved, 5000);
}
function howLongSinceSaved(){
	var currentDate = new Date();
	var dateDifference = parseInt((currentDate.valueOf() - lastSavedDate.valueOf())/60000);
	var minutes;
	var hours;
	var days;
	var outputText = "<em>Last saved ";
	if(dateDifference>0){
		days = Math.floor(dateDifference/(60*24));
		outputText += "<strong>";
		if(days>0){
			outputText += days + " day" + (days == 1 ? " " : "s ");
		}
		hours = Math.floor((dateDifference-(days*60*24))/60);
		if(hours>0){
			outputText += hours + " hour" + (hours == 1 ? " " : "s ");
		}

		// we need a leading zero on the minutes part of the date
		minutesPart = "0" + lastSavedDate.getMinutes().toString();
		minutesPart = minutesPart.substr(minutesPart.length-2);
		
		minutes = dateDifference-(days*60*24)-(hours*60);
		outputText += minutes + " minute" + (minutes == 1 ? " " : "s ") + "</strong>";
		outputText += " ago at " + lastSavedDate.getHours() + ":";
		outputText += minutesPart;
		if(currentDate.getDay() != lastSavedDate.getDay()) {
			outputText += " on " + whatDay(lastSavedDate.getDay()) + " ";
			outputText += lastSavedDate.getDate() + " ";
			outputText += whatMonth(lastSavedDate.getMonth()) + " ";
			outputText += lastSavedDate.getFullYear();
		} else {
			outputText += " today";
		}
		outputText += "</em>";
	} else {
		//date saved in the future
		outputText += "less than a minute ago</em>"
	}
	dId("lastSaved").innerHTML = outputText;
}
function whatDay(theDay){
	if(theDay == 0){
		return "Sunday";
	} else if (theDay == 1){
		return "Monday";
	} else if (theDay == 2){
		return "Tuesday";
	} else if (theDay == 3){
		return "Wednesday";
	} else if (theDay == 4){
		return "Thursday";
	} else if (theDay == 5){
		return "Friday";
	} else if (theDay == 6){
		return "Saturday";
	}
}
function whatMonth(theMonth){
	if(theMonth == 0){
		return "January";
	} else if (theMonth == 1){
		return "February";
	} else if (theMonth == 2){
		return "March";
	} else if (theMonth == 3){
		return "April";
	} else if (theMonth == 4){
		return "May";
	} else if (theMonth == 5){
		return "June";
	} else if (theMonth == 6){
		return "July";
	} else if (theMonth == 7){
		return "August";
	} else if (theMonth == 8){
		return "September";
	} else if (theMonth == 9){
		return "October";
	} else if (theMonth == 10){
		return "November";
	} else if (theMonth == 11){
		return "December";
	}
}

//extend the intrinsic Array object to simplify adding new elements
//returns the index of the new element
Array.prototype.add = function(obj) {
	this[this.length] = obj;
	return this.length-1;
}

//extend the intrinsic Array object to simplify removing elements
//returns a new array without the specified index - the old array is
//not destroyed.
Array.prototype.remove = function(index) {
	var newArray = new Array();
	
	for(var i=0; i<=this.length-1; i++) {
		if(index != i)
			newArray.add(this[i]);
	}
	
	return newArray;
}

function _cancelEvent (evt) {
    if(window.event) {
        window.event.returnValue = false;
    } else if(evt) {
        evt.preventDefault();
    }
}

ObjectType.Folder = 1;
ObjectType.Structure = ObjectType.Folder;
ObjectType.ContentItem = 2;

function ObjectType() {}

function ToggleRelatedDataDiv(divId, linkId)
{
    var relatedDiv = document.getElementById(divId);
    if(relatedDiv)
    {
        relatedDiv.className = relatedDiv.className == 'show' ? 'hide' : 'show';
        
        var link = document.getElementById(linkId);
        if(link)
        {
            link.innerHTML = relatedDiv.className == 'show' ? '<em>click to hide related data</em>' : '<em>click for related data</em>';
        }
    }
}