/*
*  Greasemonkey Include JS
*  Version 1.0.0
*  Author: Loz Archer (loz@the-pub.org)
*  Date: January 24th 2010
*  No warranty, use and distribute at will
*  
 *--------------------------------------------------------------------------*/

/* CONFIGURATION HERE /*

/* Map Environments to TeamSite servers */
var teamsiteServers = new Array();
teamsiteServers["www.mycompany.com"] = "teamsite-prod.mycompany.com";
teamsiteServers["www.anothersite.com"] = "teamsite-prod.mycompany.com";
teamsiteServers["test.mycompany.com"] = "test-teamsite.mycompany.com";


// JSONscriptRequest -- a simple class for making HTTP requests
// using dynamically generated script tags and JSON
function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl; 
	this.noCacheIE = (fullUrl.indexOf("?") > -1) ? "&" : "?";
	this.noCacheIE += "noCacheIE="+new Date().getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj);  
}

JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}

var debug = 0;

/* Links to the TeamSite commands / CGI script */
var editUrl = "/iw-cc/edit?vpath=";
var loginUrl = "/iw-cc/command/iw.ui";
var newformUrl = "/iw-cc/command/iw.ccpro.create_form?vpath=";

var checkDcrCgi = "/iw-bin/iw_cgi_wrapper.cgi/greasemonkey-checkdcr.cgi";
var checkLoginCgi = "/iw-bin/greasemonkey-checklogin.cgi";

var dcrPath = getMetadata('cms.path');
var newFormPath = getMetadata('cms.newform');

var tsServer = teamsiteServers[location.hostname];
var cgiCheckDcrUrl = "http://"+tsServer+checkDcrCgi;
var cgiCheckLoginUrl = "http://"+tsServer+checkLoginCgi;

if (debug) {
	alert (
		"tsServer = "+tsServer+"\n"+
		"dcrPath = "+dcrPath+"\n"
	);
}

if (tsServer && dcrPath) {
	checkLoginRequest = new JSONscriptRequest(cgiCheckLoginUrl);
	checkLoginRequest.buildScriptTag(); 
	checkLoginRequest.addScriptTag();
}

/*   CALLBACK FUNCTIONS   ********************************
*  These are invoked from the CGIs called within this script.
*
*/

function callback_checklogin(json){
	checkLoginRequest.removeScriptTag();
	if (debug) {
		alert ("Back from checklogin.cgi: "+json);
	}
	var loggedinStatus = eval('(' + json + ')');
	if (loggedinStatus.loggedin) {
		/*  fire off a request to a CGI to check the DCR exists, check locks,
		*  and display an EDIT / UNLOCK button as appropriate
		*  
		*  The callback function is callback_getstatus() below
		*/
		var pars = "action=getstatus&vpath="+dcrPath;
		var remoteUrl = cgiCheckDcrUrl +"?"+pars;
			
		checkDcrRequest = new JSONscriptRequest(remoteUrl);
		checkDcrRequest.buildScriptTag(); 
		checkDcrRequest.addScriptTag();		
	} else {
		createMenuBar();
		loginUrl = "http://"+tsServer+loginUrl;
		appendLink(loginUrl,"Login","Click to login to TeamSite","_blank");
		appendLink("","You are not logged in to TeamSite.  Login and then browse to this page again.","","");
	}
}


function callback_getstatus(json) {
	/*  This is a callback function from the CGI
	*  This function receives the DCR status as a JSON string, and then displays the "EDIT", "UNLOCK" and "Locked by..." links as approprate
	*/
	//alert("In callback function. JSON: "+json);
	
	if (debug) {
		alert (json);
	}
	var dcrState = eval('(' + json + ')');

	createMenuBar();
	if (dcrState.exists) {
		var editFormType = get_datatype(dcrPath);
		editUrl = "http://"+tsServer+editUrl+dcrPath;
		appendLink(editUrl,"Edit"+editFormType,"Click to edit this page in TeamSite","_blank");
		if (newFormPath) {
			var newFormType = get_datatype(newFormPath);
			newformUrl = "http://"+tsServer+newformUrl+newFormPath;
			appendLink(newformUrl,"New"+newFormType,"Click to create a new item","_blank");
		}
		var lockedByText = "";		
		if (dcrState.locked) {
			if (dcrState.lockedby == "self") {
				lockedByText = "Locked by you";
				appendLink("javascript:unlockDcr('"+dcrState.dcrPath+"')","Unlock","Click to unlock this DCR in TeamSite","");					openMenuBar() 
			} else 	{
				lockedByText = "Locked by "+dcrState.lockedby;				
			}
			if (lockedByText) {
				appendLink("",lockedByText,"","");
			}		
		}
	} else {
		appendLink("javascript:alert('Debug information: "+json+"')","The DCR for this page cannot be found automatically.","","");
	}	
	appendLink("javascript:hideMenuBar()","Close","Click to hide this toolbar","");		
	checkDcrRequest.removeScriptTag();
}

function get_datatype(vpath) {
	var datatypeRegex = new RegExp("templatedata/[^/]*/([^/]*)");
	var matches = datatypeRegex.exec(vpath);
	if (matches) {
		var datatype = matches[1];
		var initial = datatype.substr(0,1).toUpperCase();
		datatype = initial+datatype.substr(1,datatype.length-1);
		return " "+datatype;
	} else {
		return false;
	}
}

function callback_unlockdcr() {
	/*  This is a callback function from the CGI.  It reloads the page to remove the UNLOCK link.
	*  This may seem like poor-man's DHTML admittedly, but it has the effect of verifying that the DCR is indeed unlocked. */
	unlockDcrRequest.removeScriptTag();
	window.location.reload();
}

/*   BUTTON FUNCTIONS   ********************************
*  These are invoked by the user clicking on a button in the toolbar
*
*/


function unlockDcr(dcrPath) {
	/*  This function is called when the user clicks on the "UNLOCK" button
	*  It fires off an asynchronous request to the CGI to perform the unlock
	*  The callback function is callback_unlockdcr() below
	*/
	var pars = "action=unlockdcr&vpath="+dcrPath;
	var remoteUrl = cgiCheckDcrUrl +"?"+pars;
	//alert ("Calling "+remoteUrl);

	unlockDcrRequest = new JSONscriptRequest(remoteUrl);
	unlockDcrRequest.buildScriptTag(); 
	unlockDcrRequest.addScriptTag();
	
}


/*   MENU BAR FUNCTIONS   ********************************
*  Functions for controlling the DHTML menu bar
*
*/

var menuBarHeight = 19;
var menuBarBorderWidth = 1;
// var menuBarTabPosition = 980;  // right of the advert
var menuBarTabPosition = 125;  // left of the advert
var effectiveMenuBarHeight = menuBarHeight + menuBarBorderWidth*2;
var animationDelay = 5;  /* milliseconds */
var linkPadding = 15;
var isOpen = 0;

function appendLink (url,linktext,title,target) {
	/*  This function adds a link onto the end of the menuBar
	*/
	var link;
	if (url) {
		link = document.createElement('a');
		link.setAttribute("href", url);
		link.setAttribute("title", title);
		link.setAttribute("target", target);
		link.style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";
		link.style.fontSize = "11px";
		link.style.color = "#003366";
		link.style.fontWeight = "normal";
		link.style.cursor = "pointer";
	} else {
		link = document.createElement('span');
		link.style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";
		link.style.fontSize = "11px";
		link.style.color = "#003366";
		link.style.fontWeight = "bold";
	}
	var text = document.createTextNode(linktext);
	link.appendChild(text);
	var listItem = document.createElement('span');
	listItem.style.paddingLeft = linkPadding+"px";
	listItem.appendChild(link);			
	var menuBar = document.getElementById('greasemonkey-menuBar');
	menuBar.appendChild(listItem);
}

function createMenuBar() {
	var listYoffset = -2;
	
	/* Create the menuBar */
	var menuBar = document.createElement('div');
	menuBar.setAttribute("id", "greasemonkey-menuBar");
	menuBar.style.border = menuBarBorderWidth+"px black solid";
	menuBar.style.backgroundColor = "#eeeeee";
	menuBar.style.top = "-"+effectiveMenuBarHeight+"px";
	menuBar.style.left = "0px";
	menuBar.style.position = "absolute";
	menuBar.style.width = "100%";
	menuBar.style.lineHeight = "17px";
	menuBar.style.height = menuBarHeight+"px";
	document.getElementsByTagName("body").item(0).appendChild(menuBar);
	
	/* Create the menuBar tab */
	var menuBarTab = document.createElement('div');
	menuBarTab.setAttribute("id", "greasemonkey-menuBarTab");
	//menuBarTab.style.backgroundColor = "#eeeeee";
	menuBarTab.style.top = "0px";
	menuBarTab.style.left = menuBarTabPosition+"px";
	menuBarTab.style.position = "absolute";
	menuBarTab.style.width = "40px";
	menuBarTab.style.height = "40px";
	menuBarTab.onmouseover = new Function('openMenuBar()');
	menuBarTab.onclick = new Function('closeMenuBar()');
	document.getElementsByTagName("body").item(0).appendChild(menuBarTab);	
	menuBarTabImg = document.createElement('img');
	menuBarTabImg.setAttribute("src","http://"+tsServer+"/iw/greasemonkey-include-iwlogo.gif");
	menuBarTab.appendChild(menuBarTabImg);
	
	appendLink("", "TeamSite Tools:", "", "");
}

function openMenuBar() {
	if (!isOpen) {
		moveMenuBar(-effectiveMenuBarHeight,0);
	}
}

function hideMenuBar() {
	var menuBar = document.getElementById('greasemonkey-menuBar');
	var menuBarTab = document.getElementById('greasemonkey-menuBarTab');
	menuBar.style.visibility = "hidden";
	menuBarTab.style.visibility = "hidden";
	isOpen = 0;
}

function closeMenuBar() {
	var menuBar = document.getElementById('greasemonkey-menuBar');
	var menuBarTab = document.getElementById('greasemonkey-menuBarTab');
	menuBar.style.top = "-"+effectiveMenuBarHeight+"px";
	menuBarTab.style.top = "0px";
	isOpen = 0;
}

function moveMenuBar(startY, endY) {
	isOpen = 1;
	var menuBar = document.getElementById('greasemonkey-menuBar');
	var menuBarTab = document.getElementById('greasemonkey-menuBarTab');
	
	var newY = startY + 1;
	menuBar.style.top = newY+"px";
	menuBarTab.style.top = (newY+menuBarHeight+menuBarBorderWidth)+"px";
	if (endY > newY) {
		setTimeout('moveMenuBar('+newY+','+endY+')', animationDelay);
	}
}

function getMetadata(name) {
	var dataArray = document.getElementsByName(name);
	if (dataArray.length) {
		return dataArray[0].content;
	} else {
		return false;
	}
}
