var http_request = false;
var browser=navigator.appName;
var timerID = 0;
var slideShowStatus = "off";
var randomStatus = "off";
var previousImageChoice = -1;
var previousTabChoice = "client-tab";
var previousSubTabChoice = "documents-tab";
var currentScrollPosition;
var destinationScrollPosition;

var imageTemplateArray;
var docTemplateArray;

var halfWayPoint;
var increment = 1;
var accelerate = 3;
var increase;

var fadeArray = new Array();
var fadeAnimTimer = -1;
var opacityStep = 10; //lets keep this in even multiples of 100 to keep things easy

var expandArray = new Array();
var expandTimer = -1;
var expandMultiplyer = 1.2;

var myWidth;
var myHeight;
var myScrollTop;
var myScrollLeft;
var myScrollWidth;
var myScrollHeight;
var screenWidth;
var screenHeight;

var sectionElements;

var refreshImage = new Image();
refreshImage.src = "/pressroom/images/progress_bar2.gif";

var spacerImage = new Image();
spacerImage.src = "/pressroom/images/spacer.gif";

function makePOSTRequest(url, parameters) {
	//alert(parameters);
	http_request = false;
	
	if (window.XMLHttpRequest && browser!="Microsoft Internet Explorer") { // Mozilla, Safari,...
	  //alert("moz");
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
	  	//alert("win");
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
}

function alertContents() {
	http_request.readyState;
	if(http_request.readyState == 4) {
    	if(http_request.status == 200) {
			var imageTemplateReset = 0;
			var docTemplateReset = 0;
			//alert("--"+http_request.responseText+"--");
			if(browser=="Microsoft Internet Explorer") {
				XMLdoc = new ActiveXObject("Microsoft.XMLDOM");
				XMLdoc.async=false;
				XMLdoc.loadXML(http_request.responseText);
				sectionElements = XMLdoc.getElementsByTagName('section');
			}else{
				sectionElements = http_request.responseXML.getElementsByTagName('section');
			}
			
			//Check to see if response is a possible error thrown by the server
			if(sectionElements.length == 0) {
				if(http_request.responseText) {
					errorReporting(http_request.responseText);
				}
			}else{
				//alert(browser+" = "+sectionElements.length);
				for (var i=0;i<sectionElements.length;i++) {
					tagindex = getNodeValue(sectionElements[i],'name').indexOf("_|_");
					tagindex2 = getNodeValue(sectionElements[i],'name').indexOf("|_|");
					tagindex3 = getNodeValue(sectionElements[i],'name').indexOf("|-|");
					if(tagindex != -1) {
						tagindex = getNodeValue(sectionElements[i],'name').indexOf("|*|");
						if(tagindex != -1) {
							highlightThumb(getNodeValue(sectionElements[i],'data'), true);
						}else{
							highlightThumb(getNodeValue(sectionElements[i],'data'), false);
						}
					//Setting up of javascript array for use with images template system
					}else if(tagindex2 != -1) {
						if(imageTemplateReset == 0) {
							imageTemplateArray = new Array();
							imageTemplateReset++;
						}
						var clientID = getNodeValue(sectionElements[i],'name').substring((tagindex2+3),getNodeValue(sectionElements[i],'name').length);
						var imageID = getNodeValue(sectionElements[i],'data');
						imageTemplateArray.push(new Array(clientID,imageID));
					}else if(tagindex3 != -1) {
						if(docTemplateReset == 0) {
							docTemplateArray = new Array();
							docTemplateReset++;
						}
						var clientID = getNodeValue(sectionElements[i],'name').substring((tagindex3+3),getNodeValue(sectionElements[i],'name').length);
						var imageID = getNodeValue(sectionElements[i],'data');
						docTemplateArray.push(new Array(clientID,imageID));
					}else{
						//Write out data
						adddata(getNodeValue(sectionElements[i],'name'), getNodeValue(sectionElements[i],'data'));
					}
				} 
				//adddata("progress", '<img src="images/spacer.gif" width="136" height="10" />');
				//document.getElementById("progress").innerHTML = '<img src="images/spacer.gif" width="136" height="10" />';
			}
			document.getElementById("progress").style.display = "none";
		} else {
            alert('There was a problem with the request. http request status = '+http_request.status);
        }
    }else if(http_request.readyState == 1) {
		//adddata("progress", '<img src="images/progress_bar2.gif" width="136" height="10" />');
		//document.getElementById("progress").innerHTML = '<img src="images/progress_bar2.gif" width="136" height="10" />';
		progressPopout();
	}
}

function getNodeValue(obj,tag)
{
	return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}

function adddata(divname, data) {
   	//alert(divname);
	//alert("data= "+data);
	//var wrappingDiv = document.createElement('div');
  	//wrappingDiv.innerHTML = request.responseText;
  	//parentElement.appendChild(wrappingDiv);
	//startFade(divname, data);
	
	//document.getElementById(divname).innerHTML = data;
	so_clearInnerHTML(document.getElementById(divname));
	document.getElementById(divname).innerHTML = data;
	
	//Safari hack
	//window.resizeBy(1,1);
	//window.resizeBy(-1,-1);
}

function so_clearInnerHTML(obj) {
	// so long as obj has children, remove them
	while(obj.firstChild) obj.removeChild(obj.firstChild);
}

function errorReporting(errorText) {
	getSize();
	document.getElementById("errorout").style.height = myScrollHeight + "px";
	document.getElementById("errorout").style.width = myScrollWidth + "px";
	document.getElementById("errorout").style.display = "block";
	document.getElementById("error-container").style.top = (myScrollTop + 20) + "px";
	document.getElementById("error-container").style.left = 10 + "px";
	
	errorText = errorText.substr(0,1500) + "...";
	
	document.getElementById("error-text").innerHTML = errorText;
	document.getElementById("error-container").style.display = "block";
}

function errorClose() {
	document.getElementById("errorout").style.display = "none";
	document.getElementById("error-container").style.display = "none";
}

function progressPopout() {
	getSize();
	baseTop = (Math.floor(screenHeight/2) - Math.floor(10/2) + myScrollTop);
	baseLeft = (Math.floor(screenWidth/2) - Math.floor(136/2) + myScrollLeft);
	document.getElementById("progress").style.top = baseTop + "px";
	document.getElementById("progress").style.left = baseLeft + "px";
	document.getElementById("progress").style.display = "block";
}

function formPost(form_name, php_name, module_name) {
	if(!form_name) {
		return false;	
	}
	//alert('Form Request');
	var poststr = "";
	
	var item_object = "";
	
	var form_object = document.getElementById(form_name);
	
	for(i=0;i<form_object.elements.length;i++) {
		tagindex = form_object.elements[i].name.indexOf("-_-");
		if(tagindex != -1) {
			poststr += form_object.elements[i].name.substr(0,tagindex) + "=";
		}else{
			if(form_object.elements[i].name != "") {
				poststr += form_object.elements[i].name + "=";
			}
		}
		
		item_object = document.getElementById(form_object.elements[i].name);
		if(item_object == null) {
			//do nothing
		}else if(item_object.type == "hidden" || item_object.type == "text" || item_object.type == "textarea" || item_object.type == "password" || item_object.type == "button" || item_object.type == "submit"){
			//alert(form_object.elements[i].name + " = TEXT OR BUTTON = "+item_object.value);
      		tagindex = item_object.value.indexOf("/pressroom/");
			if(tagindex != -1) {
				newstring = item_object.value.replace(/\//g, "-");
				poststr += newstring + "&";
			}else{
				poststr += item_object.value + "&";
			}
		}else if(item_object.type == "checkbox"){
			//alert(form_object.elements[i].name + " = CHECKBOX = "+item_object.checked);
      		poststr += item_object.checked + "&";
      	}else if(item_object.type == "select-one"){
			//alert(form_object.elements[i].name + " = SELECTION = "+poststr);
      		poststr += item_object.options[item_object.selectedIndex].value + "&";
      	}
	}
	poststr += module_name + "=yes";
	//alert(poststr);
    makePOSTRequest(php_name, poststr);
}

function linkPost(action, php_name, module_name) {
	//alert('Link Request');
	poststr = "action=" + action + "&" + module_name + "=yes";
	if(module_name == "photogallery") {
		slideShow("off");
	}
	
	if(action == "admin") {
		highlightTab("admin-tab");
	}else if(action == "clients") {
		highlightTab("client-tab");
	}else if(action == "documentsList") {
		highlightSubTab("documents-tab");
	}else if(action == "imagesList") {
		highlightSubTab("images-tab");
	}
	makePOSTRequest(php_name, poststr);
}

function highlightTab(tabName) {
	off_object = document.getElementById(previousTabChoice);
	previousTabChoice = tabName;
	
	off_object.className="background-tab";
	
	on_object = document.getElementById(tabName);
	on_object.className="active-tab";
}

function highlightSubTab(tabName) {
	off_object = document.getElementById(previousSubTabChoice);
	previousSubTabChoice = tabName;
	
	off_object.className="background-tab";
	
	on_object = document.getElementById(tabName);
	on_object.className="active-tab";
}

function slideShow(action) {
	//var item_object = document.getElementById("slideshowcheckbox");
	//alert("slideshow = "+item_object.checked);
	//if(item_object.checked) {
	if(action == "on") {
		executeImageChange();
		adddata("slideshowbutton", '<input type="button" value="Turn Slideshow Off" onclick="javascript:slideShow(\'off\');" />');
		document.control4.forwardbutton.disabled=true;
		document.control1.backbutton.disabled=true;
		slideShowStatus = "on";
	}else{
		clearTimeout(timerID);
		adddata("slideshowbutton", '<input type="button" value="Turn Slideshow On" onclick="javascript:slideShow(\'on\');" />');
		document.control4.forwardbutton.disabled=false;
		
		if(randomStatus == "off") {
			document.control1.backbutton.disabled=false;
		}
		slideShowStatus = "off";
	}
}

function randomize() {
	var item_object = document.getElementById("randomcheckbox");
	if(item_object.checked) {
		poststr = "randomize=yes&photogallery=yes";
		document.control1.backbutton.disabled=true;
		randomStatus = "on";
	}else{
		poststr = "randomize=no&photogallery=yes";
		if(slideShowStatus == "off") {
			document.control1.backbutton.disabled=false;
		}
		randomStatus = "off";
	}
	
	makePOSTRequest("/pressroom/photogallery_stub.php", poststr);
}

function executeImageChange() {
	timerID = self.setTimeout("executeImageChange()", 4000)
	poststr = "forwardbutton=yes&photogallery=yes";
	makePOSTRequest("/pressroom/photogallery_stub.php", poststr);
}

function confirmation(message, formname, php, module) {
	var answer = confirm(message);
	if (answer){
		formPost(formname, php, module);
	}
}

function highlightThumb(imageNumber, noscroll) {
	thumb_object = document.getElementById("thumb"+imageNumber.toString());
	thumb_object.style.color="#000000";
	thumb_object.style.backgroundColor="#FFFFFF";
	thumb_object.style.border="thin solid #000000";
	
	if(previousImageChoice != -1) {
		thumb_object = document.getElementById("thumb"+previousImageChoice.toString());
		thumb_object.style.color="#FFFFFF";
		thumb_object.style.backgroundColor="#000000";
		thumb_object.style.border="thin solid #FFFFFF";
	}
	
	previousImageChoice = imageNumber;
	
	if(!noscroll) {
		var j = 'thumb' + imageNumber.toString();
		//var thepoint = document.getElementById(j).offsetLeft;
		//document.getElementById('thumbnail-container').scrollLeft = thepoint;
		currentScrollPosition = document.getElementById('thumbnail-container').scrollLeft;
		destinationScrollPosition = document.getElementById(j).offsetLeft-215;
		
		if(destinationScrollPosition < 0) {
				destinationScrollPosition = 0;
		}
		
		if(currentScrollPosition < destinationScrollPosition) {
			halfWayPoint = ((destinationScrollPosition - currentScrollPosition)/2) + currentScrollPosition;
			increase = 1;
		}else{
			halfWayPoint = ((currentScrollPosition - destinationScrollPosition)/2) + destinationScrollPosition;
			increase = 0;
		}
		
		increment = 1;
		
		self.setTimeout("scroller()", 50);
	}
}

function scroller() {
	var scrollkill = false;
	
	if(currentScrollPosition == destinationScrollPosition) {
		scrollkill = true;
	}
	
	if(increase == 1) {
		if(currentScrollPosition > destinationScrollPosition || scrollkill) {
			scrollkill = true;
		}else if(currentScrollPosition <= halfWayPoint) {
			increment += accelerate;
		}else{
			if(increment <= 1) {
				increment = 1;
			}else{
				increment -= accelerate;
			}
		}
		
		if(!scrollkill) {
			document.getElementById('thumbnail-container').scrollLeft = currentScrollPosition += increment;
		}
	}else{
		if(currentScrollPosition < destinationScrollPosition || scrollkill) {
			scrollkill = true;
		}else if(currentScrollPosition >= halfWayPoint) {
			increment += accelerate;
		}else{
			if(increment <= 1) {
				increment = 1;
			}else{
				increment -= accelerate;
			}
		}
		if(!scrollkill) {
			document.getElementById('thumbnail-container').scrollLeft = currentScrollPosition -= increment;
		}
	}
	
	if(!scrollkill) {
		self.setTimeout("scroller()", 50);
	}else{
	}
}

function pressInit() {
	//alert("INIT!!");
	poststr = "init=yes&pressroom=yes";
	makePOSTRequest("/pressroom/index.php", poststr);
}

function kill() {
	poststr = "killsession=yes";
	makePOSTRequest("/pressroom/index.php", poststr);
}

function panelopen(divid, divcontainer, expand) {
	userpanel = document.getElementById(divcontainer);
	
	//alert(divid+" -- "+divcontainer);
	//divcontainer is made up of the word "open" with the id number tacked onto the end
	idnumber = divid.substr(4, divid.length);
	collapsepanel = document.getElementById("collapse"+idnumber);
	//userpanelstate = collapsepanel.style.visibility;
	if(expand) {
		//userpanel.style.display="none";
		//collapsepanel.style.visibility="hidden";
		//panelExpander(collapsepanel, true, userpanel.offsetHeight); //enable for animated
		collapsepanel.style.height=userpanel.offsetHeight+"px"; //enable for non-animated
		adddata(divid, '<a href="javascript:panelopen(\''+divid+'\', \''+divcontainer+'\', false);">Close Panel</a>');
	}else{
		//userpanel.style.display="block";
		//collapsepanel.style.visibility="visible";
		//panelExpander(collapsepanel, false, userpanel.offsetHeight); //enable for animated
		collapsepanel.style.height=0; //enable for non-animated
		adddata(divid, '<a href="javascript:panelopen(\''+divid+'\', \''+divcontainer+'\', true);">Open Panel</a>');
		//if(divid.substr(0, 5) == "image") {
		//	linkPost("imagerefresh"+idnumber, "index.php", "pressroom");
		//}
	}
}

function defaultPropagate(counterID) {
	itemType = document.getElementById('itemtype-_-'+counterID).value;
	
	if(itemType == "doc") {
		docName = document.getElementById('docname-_-'+counterID).value;
		docDate = document.getElementById('docdate-_-'+counterID).value;
		docDescription = document.getElementById('docdescription-_-'+counterID).value;
		docCategory = document.getElementById('doclist-_-'+counterID).selectedIndex;
		docClient = document.getElementById('clientid-_-'+counterID).value;
		docEnabled = document.getElementById('docenabled-_-'+counterID).checked;
		
		for(i=0;i<docTemplateArray.length;i++) {
			docArray = docTemplateArray[i];
			tempClientID = docArray[0];
			tempImageID = docArray[1];
			defaultApply = document.getElementById('defaultapply-_-'+tempImageID).checked;
			
			if(tempClientID == docClient && defaultApply) {
				document.getElementById('docname-_-'+tempImageID).value = docName;
				document.getElementById('docdate-_-'+tempImageID).value = docDate;
				document.getElementById('docdescription-_-'+tempImageID).value = docDescription;
				document.getElementById('doclist-_-'+tempImageID).selectedIndex = docCategory;
				document.getElementById('docenabled-_-'+tempImageID).checked = docEnabled;
			}
		}
	}else if(itemType == "image") {
		//check to see if we have the pulldown list
		pulldown = false;
		if(document.getElementById('imagelist-_-'+counterID)) {
			pulldown = true;
		}
		
		imageCategory = "";
		action = "";
		
		imageName = document.getElementById('imagename-_-'+counterID).value;
		imageCredit = document.getElementById('imagecredit-_-'+counterID).value;
		imageDescription = document.getElementById('imagedescription-_-'+counterID).value;
		if(pulldown) {
			imageCategory = document.getElementById('imagelist-_-'+counterID).value;
			action = 'cancelimagecategory|'+imageCategory;
		}else{
			imageCategory = document.getElementById('catname-_-'+counterID).value;
			action = 'newimagecategory|'+imageCategory;
		}
		imageClient = document.getElementById('clientid-_-'+counterID).value;
		imageEnable = document.getElementById('docenabled-_-'+counterID).checked;
		
		for(i=0;i<imageTemplateArray.length;i++) {
			imageArray = imageTemplateArray[i];
			tempClientID = imageArray[0];
			tempImageID = imageArray[1];
			if(!document.getElementById('defaultapply-_-'+tempImageID)) {
				continue;
			}
			defaultApply = document.getElementById('defaultapply-_-'+tempImageID).checked;
			
			if(tempClientID == imageClient && defaultApply) {
				action += '|'+tempImageID;
				document.getElementById('imagename-_-'+tempImageID).value = imageName;
				document.getElementById('imagecredit-_-'+tempImageID).value = imageCredit;
				document.getElementById('imagedescription-_-'+tempImageID).value = imageDescription;
				//document.getElementById('imagelist-_-'+tempImageID).selectedIndex = imageCategory;
				document.getElementById('docenabled-_-'+tempImageID).checked = imageEnable;
			}
		}
		action += '|'
		linkPost(action, '/pressroom/index.php', 'pressroom');
	}
}

function selectAll(counterID, doApply, image) {
	tempClientID1 = document.getElementById('clientid-_-'+counterID).value;
	if(image) {
		for(i=0;i<imageTemplateArray.length;i++) {
			imageArray = imageTemplateArray[i];
			tempClientID2 = imageArray[0];
			tempImageID = imageArray[1];
			if(tempClientID2 == tempClientID1) {
				document.getElementById('defaultapply-_-'+tempImageID).checked = doApply;
			}
		}
	}else{
		for(i=0;i<docTemplateArray.length;i++) {
			docArray = imageTemplateArray[i];
			tempClientID2 = docArray[0];
			tempDocID = docArray[1];
			if(tempClientID2 == tempClientID1) {
				document.getElementById('defaultapply-_-'+tempDocID).checked = doApply;
			}
		}
	}
}

function changeEnable(containerName, idName) {
	item_object = document.getElementById(idName);
	container = document.getElementById(containerName);
	if(item_object.checked) {
		container.style.backgroundImage = "url(/pressroom/images/itemBackground.jpg)";
	}else{
		container.style.backgroundImage = "url(/pressroom/images/itemBackgroundDisabled.jpg)";
	}
}

function panelExpander(panelDiv, expand, maxHeight) {
	//is this panel already in motion
	divActive = false;
	arrayPos = 0;
	numItems = expandArray.length;
	for(i=0;i<numItems;i++) {
		if(expandArray[i][0] == panelDiv) {
			divActive = true;
			arrayPos = i;
			break;
		}
	}
	
	if(divActive) {
		expandArray[arrayPos][2] = expand;
	}else{
		//initialize the div name, the contents, direction (true=expand, false=contract), maxHeight, step
		expandArray.push(new Array(panelDiv, expand, maxHeight, 1));
	}
	if(expandTimer == -1) {
		expandTimer = setInterval("expandWorker()", 20);
	}
}

function expandWorker() {
	numItems = expandArray.length;
	if(numItems == 0) {
		clearInterval(expandTimer);
		expandTimer = -1;
	}else{
		for(i=0;i<numItems;i++) {
			setHeight(expandArray[i], i);
		}
	}
}

function setHeight(divArray, mainPos) {
	if(!divArray) {
		return;	
	}
	currentHeight = parseInt(divArray[0].style.height.substr(0, divArray[0].style.height.length-2));
	divArray[3] *= expandMultiplyer;
	if(divArray[1]) {
		currentHeight += divArray[3];
	}else{
		currentHeight -= divArray[3];
	}
	
	if(divArray[1]) {
		if(divArray[2] <= currentHeight) {
			expandArray.splice(mainPos, 1);
			currentHeight = divArray[2];
		}
	}else{
		if(currentHeight <= 0) {
			expandArray.splice(mainPos, 1);
			currentHeight = 0;
		}
	}
	divArray[0].style.height = currentHeight+"px";
}

function startFade(fadeDiv, newDivContents) {
	//initialize the div name, the contents, direction (0=fadeout, 1=fadein), opacity level(start at 100)
	fadeArray.push(new Array(fadeDiv, newDivContents, 0, 100));
	if(fadeAnimTimer == -1) {
		fadeAnimTimer = setInterval("fadeWorker()", 20);
	}
}

function fadeWorker() {
	numItems = fadeArray.length;
	if(numItems == 0) {
		clearInterval(fadeAnimTimer);
		fadeAnimTimer = -1;
	}else{
		for(i=0;i<numItems;i++) {
			setOpac(fadeArray[i], i);
		}
	}
}

function setOpac(divArray, mainPos) {
	if(!divArray) {
		return false;	
	}
	if(divArray[2] == 0) {
		if(divArray[3] == 0) {
			document.getElementById(divArray[0]).innerHTML = divArray[1];
			divArray[2] = 1;
		}else{
			divArray[3] -= opacityStep;
		}
	}else{
		divArray[3] += opacityStep;
	}
	document.getElementById(divArray[0]).style.opacity = divArray[3] / 100;
	document.getElementById(divArray[0]).style.filter = 'alpha(opacity=' + divArray[3] + ')';
	
	if(divArray[3] == 100) {
		fadeArray.splice(mainPos, 1);
	}
}

function getSize() {
	if (document.all) {
		// IE4+ or IE6+ in standards compliant 
		myWidth  = (document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.clientWidth;
		myHeight = (document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.clientHeight;
		myScrollTop = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		myScrollLeft = (document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
	} else {
		// Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
		myScrollTop = window.pageYOffset;
		myScrollLeft = window.pageXOffset;
	}
	
	// Core code from - quirksmode.org
    if (window.innerHeight && window.scrollMaxY) {	
        myScrollWidth = document.body.scrollWidth;
		myScrollHeight = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
		myScrollWidth = document.body.scrollWidth;
		myScrollHeight = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		myScrollWidth = document.body.offsetWidth;
		myScrollHeight = document.body.offsetHeight;
	}
	
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		screenHeight = window.innerHeight;
		screenWidth = window.innerWidth;
		
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		screenHeight = document.documentElement.clientHeight;
		screenWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		screenHeight = document.body.clientHeight;
		screenWidth = document.body.clientWidth;
	}
}
