var circuit = "";
var project = "";
var username = "";
var gifAsPipe = new Image();
gifAsPipe.src = "images/lm_single_pixel_gif.gif";

function confirmDelete() {
	return confirm('Are you sure you want to DELETE this item?');
}
function loadDelete() {
	if ( document.getElementsByTagName ) {
		var theLinks = document.getElementsByTagName('a');
		for ( a = 0 ; a < theLinks.length ; a++ ) {
			if ( theLinks[a].className == 'delete' ) {
				theLinks[a].onclick = confirmDelete;
			}
		}
	}
}
/* all scripts designed and (c) Mike Ritchie */
function loadFormFocus(){
	if ( document.forms.length > 0 ) {
		focused = false;
		for ( f = 0 ; f < document.forms.length ; f++ ) {
			for( i = 0 ; i < document.forms[f].elements.length ; i++ ) {
				if ( document.forms[f].elements[i].type == 'text' || document.forms[f].elements[i].type == 'textarea' ) {
					document.forms[f].elements[i].focus();
					focused = true;
					break;
				}
			}
			if ( focused ) {
				break;
			}
		}
	}
}

/* keyboard event handlers for Internet Explorer and Mozilla */
function loadKeyChecker(){
	if ( !document.all ) {
		window.captureEvents (Event.KEYDOWN);
		window.onkeydown=keyCheckMoz;
	}
}

function keyCheck(){
	if (window.event.ctrlKey) {
	    /* Let me copy dammit */
	} else if ( event.keyCode ) doKey(event.keyCode);
}

function keyCheckMoz(evt){
	if (evt.ctrlKey) {
		/* Let me copy dammit */
	} else if ( evt.which ) doKey(evt.which);
}

var unrun = true;
function doKey(thiskey){
	var ckey = 67; /* "c" */
	var fkey = 70; /* "f" */
	var curup = 38; /* "cursor up" */
	var curdown = 40; /* "cursor down" */
	var curleft = 37; /* "cursor left" */
	var curright = 39; /* "cursor right" */
	var dkey = 68; /* "d" */
	if ( unrun ) {
		switch (thiskey){
			case ckey:
				circuitname = prompt('Enter the alias for this circuit (ESC to cancel):','');
				circuitpath = prompt('Enter the path for this circuit, off of \'home\':','home/'+circuitname);
				if ( circuitname != null && circuitpath != null ) {
					window.location = 'index.cfm?fuseaction=project.doaddcircuit&project='+project+'&circuitname='+circuitname+'&circuitpath='+circuitpath+'&access=public';
				}
				break;
			case fkey:
				faname = prompt('Enter the fully resolved name for this fuseaction (ESC to cancel)','');
				if (faname != null) {
					if ( faname.indexOf('.') == -1 ) {
						faname = prompt('Please enter the circuit name for this fuseaction',circuit) + '.' + faname;
					}
					window.location = 'index.cfm?fuseaction=thiscircuit.doaddfa&project='+project+'&faname='+faname;
				}
				break;
			case curup:
			case curdown:
			case curleft:
			case curright:
			case dkey:
				if ( project.length > 0 ) window.location = 'index.cfm?fuseaction=project.keynav&project='+project+'&cursor='+thiskey;
				break;
			/*default :
				alert(thiskey);
				break;*/
		}
		if ( !document.all ) unrun = false;
	} else unrun = true;
}

/* drag and drop events for Internet Explorer and now Mozilla! w00t! */
var dragitem = "";
var dropitem = "";
var dragging = false;

function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
} 

function loadDragDrop() {
	var alltags = document.all ? document.all : document.getElementsByTagName("*"); 
	var found = false;
	for ( i = 0 ; i < alltags.length ; i++ ) { 
		found = false;
		if ( alltags[i].className == "dragable" || alltags[i].className == "dragdropable" ) {
			addEvent( alltags[i] , 'mousedown' , registermousedown , false );
			addEvent( alltags[i] , 'mousemove' , registerdragstart , false );
			found = true;
		}
		if ( alltags[i].className == "dropable" || alltags[i].className == "dragdropable" ) {
			addEvent( alltags[i] , 'mouseover' , registermouseover , false );
			addEvent( alltags[i] , 'mouseout' , registermouseout , false );
			addEvent( alltags[i] , 'mouseup' , registerdrop , false );
			found = true;
		}
		if ( !found ) {
			addEvent( alltags[i] , 'click' , canceldrag , false );
			addEvent( alltags[i] , 'mouseup' , canceldrag , false );
		}
	} 
}

function registermousedown() {
	dragging = true;
}
function registerdragstart() {
	if ( dragging && dragitem.length == 0 ) {
		dragitem = ( this.id ) ? this.id : window.event.srcElement.id;
		if (document.selection)
			document.selection.empty();
		else if (window.getSelection)
			window.getSelection().removeAllRanges();
	}
}
function registermouseover() {
	if ( dragging ) {
		dropitem = ( this.id ) ? this.id : window.event.srcElement.id;
		if ( this.className )
			this.className = "dropable_hover";
			else window.event.srcElement.className = "dropable_hover";
	}
}
function registermouseout() {
	if ( dragging ) {
		if ( this.className )
			this.className = "dropable";
			else window.event.srcElement.className = "dropable";
		dropitem = "";
	}
}
function registerdrop() {
	dragging = false;
	if ( dragitem.length != 0 && dropitem.length != 0 ) {
		document.location.href='index.cfm?fuseaction=project.dragdrop&project=' + project + '&src=' + dragitem + '&target=' + dropitem;
	}
}
function canceldrag() {
	dragitem = "";
	dropitem = "";
}

/* drawer persistence through "gif as pipe" */
function remember(drawername) {
	gifAsPipe.src="index.cfm?fuseaction=secured.rememberdrawers&username="+username+"&drawername="+drawername;
}
function drawer(e) {
	var target = null;
	if ( window.event && window.event.srcElement ) {
		target = window.event.srcElement;
	} else if ( e && e.target ) {
		target = e.target;
	}
	if ( !target ) return;
	while ( target != document.body && target.nodeName.toLowerCase() != 'dt' )
		target = target.parentNode;
	if ( target.nodeName.toLowerCase() != 'dt' ) return;
	theDL = target.parentNode;
	theDL.className = ( theDL.className == 'drawer-open' ) ? 'drawer-closed' : 'drawer-open';
	remember(theDL.id);
}
function loadDrawers() {
	if ( document.getElementsByTagName ) {
		theDTs = document.getElementsByTagName('dt');
		for ( d = 0 ; d < theDTs.length ; d++ ) {
			thisDT = theDTs[d];
			if ( thisDT.parentNode.className == 'drawer-open' || thisDT.parentNode.className == 'drawer-closed' ) {
				thisDT.onclick = drawer;
				thisDT.title = "Click to hide/reveal links in this group";
			}
		}
	}
}

/* AJAX circuit and fuseaction links */
var useAJAX = "never";
var ajaxTested = false;

var loadXMLDoc = function(theObject) {
	theObject.req = false;
    url = theObject.href.split('#')[0];
	url += '&method=js';
	/* branch for native XMLHttpRequest object */
    if ( window.XMLHttpRequest && ( useAJAX == "always" || ( useAJAX == "sometimes" && document.getElementById('useAJAX').checked == true ) ) ) {
    	try {
			theObject.req = new XMLHttpRequest();
        } catch(e) {
			theObject.req = false;
        }
    /* branch for IE/Windows ActiveX version */
    } else if ( window.ActiveXObject  && ( useAJAX == "always" || ( useAJAX == "sometimes" && document.getElementById('useAJAX').checked == true ) ) ) {
       	try {
        	theObject.req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		theObject.req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		theObject.req = false;
        	}
		}
    } else {
		/* allow the original link click for non-AJAX */
		return true;
	}
	if ( theObject.req ) {
		theObject.req.onreadystatechange = function() {
			processReqChange(theObject);
		}
		theObject.req.open("GET", url, true);
		theObject.req.send("");
		/* cancel the original click for AJAX */
		return false;
	}
}
function processReqChange(theObject) {
    /* only if req shows "loaded" and "OK" */
    if ( theObject.req.readyState == 4 ) {
		if ( theObject.req.status == 200 ) {
	        /* ...processing statements go here... */
			if ( typeof theObject.id != 'undefined' && document.getElementById ) {
				id = theObject.id;
				if ( typeof document.getElementById(id).parentNode.originalHTML == 'undefined' && document.getElementById(id).parentNode.getElementsByTagName('UL').length > 0 ) {
					openedContent = document.getElementById(id).parentNode.getElementsByTagName("UL")[0];
					if ( openedContent.parentNode.tagName.toUpperCase() == "DIV" )
						openedContent = openedContent.parentNode;
					openedContent.parentNode.removeChild(openedContent);
					document.getElementById(id).parentNode.opened = false;
					return;
				}
				document.getElementById(id).parentNode.originalHTML = ( typeof document.getElementById(id).parentNode.originalHTML != 'undefined' ) ? document.getElementById(id).parentNode.originalHTML : document.getElementById(id).parentNode.innerHTML;
				document.getElementById(id).parentNode.opened = ( typeof document.getElementById(id).parentNode.opened != 'undefined' ) ? ( document.getElementById(id).parentNode.opened==false ) : true;
				if ( document.getElementById(id).parentNode.opened ) {
					if ( document.getElementById(id).parentNode.originalHTML.toLowerCase().indexOf('<ol>') > -1 ) {
						document.getElementById(id).parentNode.getElementsByTagName('SPAN')[0].innerHTML += theObject.req.responseText;
					} else {
						theObject.replacedtext = document.getElementById(id).parentNode.innerHTML + theObject.req.responseText;
						document.getElementById(id).parentNode.innerHTML = theObject.replacedtext;
					}
					loadDragDrop();
				} else {
					document.getElementById(id).parentNode.innerHTML = document.getElementById(id).parentNode.originalHTML;
				}
			}
	    } else {
	        alert("There was a problem retrieving the XML data:\n" +
	            theObject.req.status);
	    }
	}
}
var ajaxReq;
function loadAJAXTest(theURL) {
	ajaxReq = false;
    /* branch for native XMLHttpajaxRequest object */
    if ( window.XMLHttpRequest ) {
    	try {
			ajaxReq = new XMLHttpRequest();
        } catch(e) {
			ajaxReq = false;
        }
    /* branch for IE/Windows ActiveX version */
    } else if ( window.ActiveXObject ) {
       	try {
        	ajaxReq = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		ajaxReq = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		ajaxReq = false;
        	}
		}
    }
	if ( ajaxReq ) {
		ajaxReq.onreadystatechange = processajaxReqChange;
		ajaxReq.open("GET", theURL, true);
		ajaxReq.send("");
	}
}
function processajaxReqChange() {
    /* only if ajaxReq shows "loaded" */
    if (ajaxReq.readyState == 4) {
        /* only if "OK" */
        if (ajaxReq.status == 200) {
            /* ...processing statements go here... */
			oUser = eval("(" + ajaxReq.responseText + ")");
			useAJAX = oUser.useAJAX;
			ajaxTested = true;
			if ( useAJAX == "sometimes" ) {
				if ( document.getElementById ) {
					document.getElementById('tabbar').innerHTML +=
						'<form><input type="checkbox" name="useAJAX" id="useAJAX" value="always" /> Use AJAX<'+'/form>';
				}
			}
		} else {
            alert("There was a problem retrieving the XML data:\n" +
                ajaxReq.statusText);
        }
    }
}
window.onload = function() {
	if ( document.getElementsByTagName ) {
		theBody = document.getElementsByTagName('body')[0];
		arProps = theBody.id.split('_');
		username = arProps[0];
		project = arProps[1];
		circuit = arProps[2];
		if ( typeof event != 'undefined' && project.length > 0 )
			addEvent( theBody, 'keydown', keyCheck , false );
	}
	loadDelete();
	loadFormFocus();
	if ( project.length > 0 && project.length > 0 ) loadKeyChecker();
	loadDragDrop();
	loadDrawers();
	if ( project.length > 0 ) loadAJAXTest("index.cfm?fuseaction=secured.xmluser");
	document.getElementById('loading').style.display = 'none';
}
