/**
*   JavaScript functions for controlling the application frames.  
*/
/*
//this function includes all necessary js files for the application  
function include(file)  
{  
  
  var script  = document.createElement('script');  
  script.src  = file;  
  script.type = 'text/javascript';  
  script.defer = true;  
  
  document.getElementsByTagName('head').item(0).appendChild(script);  
  
}  
  
// include any js files here   
include('/adsonline/js/ajax.js');  
*/

// global variables
var lastProjectId;
var lastMenuOption;
var recursionHack = false;

/**
*   Project display
*/

function setProjectDisplay(projectId, projectName, projectNumber, status) {
   
    //alert("projectId: " + projectId + " lastProjectId: " + lastProjectId);
   
    if (projectId == "" || projectId == "0") {
        return;
    }
    if (projectId == null) {
    	if (lastProjectId == null){
    		return;
    	}
    	projectId = lastProjectId;
        
    	//alert("Using last projectId: " + lastProjectId);
    }

    
    if (!lastProjectId) {
        lastProjectId = projectId;
    }

    // right navigation project display functions
    var funcName = "div-" + projectId;
   
    var lastFuncName = "div-" + lastProjectId;

    // if the right div is undefined, try to reload the frame, so that new projects are picked up
    if (top.frames.right.document.getElementById(lastFuncName) != null) {
        top.frames.right.document.getElementById(lastFuncName).style.display="none"
    }
    if (top.frames.right.document.getElementById(funcName) == null && !recursionHack) {
    	recursionHack = true;	// prevent infinite recursion
        top.frames.right.location.replace('/adsonline/sideProjectNav.do');
        return;
    }   
    recursionHack = false;
    
    //alert(funcName + " frame doc: " + top.frames.right.document.getElementById(funcName));
    if(status) {
        var n=status=="Schematic Design"?0:status=="Design Development"?1:status=="Contract Documents"?2:status=="Out to bid"?3:status=="Contract Admin"?4:5;
        top.frames.right.document.getElementsByName("div-projects")[n].style.display='block';
    }
    top.frames.right.document.getElementById(funcName).style.display="block"

    // change image
    var imageName = "image-" + projectId;
    var lastImageName = "image-" + lastProjectId;
    if (top.frames.right.document.getElementById(lastFuncName) != null) {
        top.frames.right.document[lastImageName].src = "/adsonline/images/icn-projbook-close.gif";
    }
    top.frames.right.document[imageName].src = '/adsonline/images/icn-projbook-open.gif';

	// make selected project bold
	var project = "a-" + funcName;
	var prevProject = "a-" + lastFuncName;
    if (top.frames.right.document.getElementById(prevProject) != null) {
		top.frames.right.document.getElementById(prevProject).style.fontWeight = "normal";
	}
	top.frames.right.document.getElementById(project).style.fontWeight = "bold";

    // change table background
    var tdName = "td-" + projectId;
    var lastTdName = "td-" + lastProjectId;
    //if (top.frames.right.document.getElementById(lastFuncName) != null) {
    //    top.frames.right.document.getElementById(lastTdName).style.backgroundColor="#cccccc";
    //}
    //top.frames.right.document.getElementById(tdName).style.backgroundColor="white";

    // change the title in the top navigation
    if (projectName != null){
       top.frames.topfrm.document.getElementById('projectName').innerHTML='PROJECT NAME: ' + projectName;
    }

    if (projectNumber != 'null'){
       top.frames.topfrm.document.getElementById('projectNumber').innerHTML='|PROJECT NUMBER: '+ projectNumber;
    }else{
       top.frames.topfrm.document.getElementById('projectNumber').innerHTML='|PROJECT NUMBER: --';
    }
	
	// highlight an option
	var	option = null;
	var		ourUrl = top.frames.center.location.toString();
	
	if (lastMenuOption){
		// IE?
		try {
			lastMenuOption.style.backgroundColor = "white";
		} 
		catch (e){
			// IE Sucks indeed alert(e.message);
		}
	}
	if (ourUrl.indexOf('showProjectManagement') >= 0){
		option	= "mgmt-" + funcName;
	}
	else if (ourUrl.indexOf('sheet') >= 0){
		option	= "ws-" + funcName;
		option  = null;		// nah, no highlight for this
	}
	else if (ourUrl.indexOf('schedule') >= 0){
		option	= "sched-" + funcName;
	}
	else if (ourUrl.indexOf('spec') >= 0){
		option	= "spec-" + funcName;
	}
	else if (ourUrl.indexOf('attachmentEdit') >= 0){
		option	= "attedit-" + funcName;
	}
	else if (ourUrl.indexOf('att') >= 0){
		option	= "att-" + funcName;
	}
	else {
		option	= "info-" + funcName;
	}
	//alert(ourUrl + " option: " + option);
	
	if (option != null){
		option = top.frames.right.document.getElementById(option);
		if (option != null){
			lastMenuOption = option;
			//option.style.backgroundColor = "#A3C380";
		}
	}

    lastProjectId = projectId;
    
    updateProjectMenu();
}

var	currentOpenedItems = new Array();

/**
 * Make project menu parents open or close.
 * @param openThis - a parent menu id to toggle or null to open "current opened items"
 */
function updateProjectMenu(openThis){
	var	bAdd = true;
	//alert('updateProjectMenu: ' + openThis);
	// if non-null, add/remove in array
	if (openThis != null){
		for (var i=0; i<currentOpenedItems.length; i++){
			if (currentOpenedItems[i] == openThis){
				currentOpenedItems.splice(i,1);	// remove element
				bAdd = false;
				adjustParentItem(openThis, false);
				break;
			}
		}
		if (bAdd){
			currentOpenedItems[currentOpenedItems.length] = openThis;
		}
	}
	else {
		bAdd = false;
	}
	// iterate and open all currently opened items
	for (var i=0; i<currentOpenedItems.length; i++){
		adjustParentItem(currentOpenedItems[i], true);
	}

        
//	return bAdd;
}

function adjustParentItem(itemId, bOpen){
	//alert(itemId + " bOpen: " + bOpen);

	// get the elements of interest
	//var		img = top.frames.right.document.getElementById(itemId + "-img");
	var		sub = top.frames.right.document.getElementById(itemId + "-sub");

	//img.width   = "9";
	//img.height  = "9";
	//img.border  = "0";
	if (!bOpen){
		//img.src = "/adsonline/images/plus-orange.gif";
		//img.alt = "Expand";
		sub.style.display = "none";
		sub.style.visibility = "hidden";
	}
	else {
		//img.src = "/adsonline/images/minus-orange.gif";
		//img.alt = "Collapse";
		sub.style.display = "block";
		sub.style.visibility = "visible";
	}
}

/**
*   User display
*/
var lastUserId;
function setUserDisplay(userId, refresh) {
    if (!lastUserId) {
        lastUserId = userId;
    }

    // display functions
    var funcName = "div-" + userId;
    var lastFuncName = "div-" + lastUserId;

    if (refresh) {
        top.frames.right.location.replace('/adsonline/sideUserNav.do');
    }

    // if the right div is undefined, try to reload the frame, so that new projects are picked up
//    if (top.frames.right.document.getElementById(funcName) == null) {
  //      top.frames.right.location.replace('/adsonline/sideUserNav.do');
    //}   
    if (top.frames.right.document.getElementById(lastFuncName) != null) {
        top.frames.right.document.getElementById(lastFuncName).style.display="none"
    }
    if (top.frames.right.document.getElementById(funcName) != null) {
        top.frames.right.document.getElementById(funcName).style.display="block"
    }

    // change image
    var imageName = "image-" + userId;
    var lastImageName = "image-" + lastUserId;
    if (top.frames.right.document[lastImageName] != null) {
        top.frames.right.document[lastImageName].src = "/adsonline/images/icn-user-close.gif";
    }
    if (top.frames.right.document[imageName] != null) {
        top.frames.right.document[imageName].src = '/adsonline/images/icn-user-open.gif';
    }

    // change table background
    var tdName = "td-" + userId;
    var lastTdName = "td-" + lastUserId;
    //if (top.frames.right.document.getElementById(lastTdName) != null) {
    //    top.frames.right.document.getElementById(lastTdName).style.backgroundColor="#cccccc";
    //}
    //if (top.frames.right.document.getElementById(tdName) != null) {
    //    top.frames.right.document.getElementById(tdName).style.backgroundColor="#dddddd";
    //}
    lastUserId = userId;
}


function openDocument(baseURI, cname){
	var		elt = null;
	for (var i=0; i<document.forms.WorksheetPageForm.elements.length; i++){
		if (document.forms.WorksheetPageForm.elements[i].name == cname){
			elt = document.forms.WorksheetPageForm.elements[i];
			break;
		}
	}
	
	if (elt){
		var   v = "";
		if (elt.options) v = getSelectedOption(elt).value;
		else			 v = elt.value;
		if (v && v.length > 0){
			var uri = baseURI + v;		//encodeURIComponent(v);
			var win = window.open(uri, "docwin",
				"location=no,resizable,toolbar=no,width=800,height=600,menubar=no,scrollbars=yes,left=80,top=80");
			//alert(uri);
		} else {
			alert("Please select a document to view; only some catalog products have accompanying documents (the list may be empty).");
		}
	} else {
		alert("No such control: " + ctrlId);
	}
	
}


var __note = null;

function savePopup(emailField, field, newField, user, formID, propID)
{
	var date = new Date();
        var st=date.getFullYear();
        var M=date.getMonth()+1;
        st += ((M.toString().length<2) ? "-0" : "-") + M.toString();
        var d=date.getDate();
        st += ((d.toString().length<2) ? "-0" : "-") + d.toString();
        var h=date.getHours();
        var m=date.getMinutes();
        var s=date.getSeconds();
        st += ((h.toString().length<2) ? " 0" : " ") + h.toString();
        st += ((m.toString().length<2) ? ":0" : ":") + m.toString();
        st += ((s.toString().length<2) ? ":0" : ":") + s.toString();
        var text = field.value +"\r\n\036"+st.toString()+", "+user+newField.value+"\r\n";
	__note.inputNode.value = text;
	if(__note.inputNode.value.length == 0) {
		__note.imageNode.src = getPopupIcon(false);
	} else {
		// Check the issue flag
		var issueFlagName =  propID ;
		var issFlag = document.forms[formID].elements[issueFlagName];
		issFlag.checked = true;
		__note.imageNode.src = getPopupIcon(true);
	} // if

	i2=0;
	maxItems=emailField.options.length;
	for (i=0;i<maxItems;i++) {
		if (emailField.options[i].selected==true) {
			emailID='noteEmails['+ i2 +']';
			document.forms[formID].elements[emailID].value=emailField.options[i].value;
			i2++;
		}
	}

	document.forms[formID].elements['noteEmailID'].value=propID;

    // TEB 8-23-04
	//closeNote(__note);
    closePopup(field);
	document.forms[formID].submit();
} // savePopup

function closePopup(field)
{
    //alert("closePopup field: " + field);
	closeNote(__note);
	AfterCloseAll();
} // closePopup

function closeNote(__note)
{
	__note.style.visibility = "hidden";
	if(__note.inputNode != null)
	{
		__note.inputNode.parentNode.removeChild(__note);
		__note.inputNode = null;
	}
	__note = null;
} // closeNote

function popUp(formID, propID, imageNode, user)
{
	var noteNewtNode="";
	var noteInputNode=document.forms[formID].elements[ propID ];
	// JM 4/9/05 - needed?
	BeforeFirstOpen();
	if(__note != null)
	{
		closeNote(__note);
	} // if
	__note = document.createElement("DIV");

	// Hide it while it's being generated
	__note.style.visibility = "hidden";
	noteInputNode.parentNode.appendChild(__note);
	__note.imageNode = imageNode;
	__note.inputNode = noteInputNode;
	// Style sheets not being picked up here for some reason, assigning via jscript
	__note.style.position = "absolute";
	__note.style.backgroundColor = "#ffffff";
	__note.style.borderTop    = "#efefef solid 2px";
	__note.style.borderLeft   = "#efefef solid 2px";
	__note.style.borderBottom = "black solid 2px";
	__note.style.borderRight  = "black solid 2px";
	__note.style.padding      = "5px";

	var len=noteEmails.length;
	emailSelect='<select id="tempNoteEmails" name="tempNoteEmails" MULTIPLE SIZE=3>';
	for(neIdx=0;neIdx<len;neIdx++) {
		emailSelect+='<option value="' + noteEmails[neIdx] + '">' + noteEmails[neIdx] + '</option>';
	}
	emailSelect+='</select>';

	__note.innerHTML = "<span id='__notePrompt'>Issue Notes:</span>" +
		"<center><div><textarea readonly='readonly' id='popupField' cols='70' rows='8'>" +
		noteInputNode.value + "</textarea></div>"+
		"<div><textarea id='newField' cols='70' rows='3'>" +
		noteNewtNode + "</textarea></div>&nbsp;"+
                "<div> Select users to receive an email of this note:<br>" +
		emailSelect + "</div>&nbsp;<div>" +
		"<input id='__noteSaveButton' type='button' onclick='savePopup(tempNoteEmails, popupField,newField,\""+user+"\", \""+formID+"\",\""+propID+"\")' value='Save'>" +
		"<input type='button' onclick='closePopup(popupField)' value='Close'>" +
		"</div></center>";

	// Set the size perfectly
	var pField = document.getElementById("popupField");
 	var pNewField = document.getElementById("newField");
	var pEmailSel = document.getElementById("tempNoteEmails");
	var sButton = document.getElementById("__noteSaveButton");
	var nSpan = document.getElementById("__notePrompt");
	__note.style.width = new String(pField.offsetWidth + 10);
 	__note.style.height = new String(pField.offsetHeight + 42+10 + pNewField.offsetHeight + nSpan.offsetHeight + sButton.offsetHeight + pEmailSel.offsetHeight);
	// Make it viewable
	__note.style.visibility = "visible";
}

function BeforeFirstOpen()
{
   if (HideArray) {
      var H_A,H_Al,H_El,i;
		var Nav4=0;
		var DomYes=1;
      H_A=HideArray;
      H_Al=H_A.length;
      for (i=0;i< H_Al;i++)
        {       
            if(document.getElementById(H_A[i])) //when i reached 28, it's null???
		{
        // H_El=Nav4?form.document.layers[H_A[i]]:DomYes?form.document.getElementById(H_A[i]).style:form.document.all[H_A[i]].style;
			// JM 4/9/05 - changed from form ref to straight doc.   
			//H_El=Nav4?form.document.layers[H_A[i]]:DomYes?form.document.getElementById(H_A[i]).style:form.document.all[H_A[i]].style;
			H_El=Nav4?document.layers[H_A[i]]:DomYes?document.getElementById(H_A[i]).style:document.all[H_A[i]].style;
			H_El.visibility="hidden";
		}
        }
    }
}

function AfterCloseAll()
{
	var Nav4=0;
	var DomYes=1;
   if(HideArray){
      var H_A,H_Al,H_El,i;
      H_A=HideArray;
      H_Al=H_A.length;
      //alert("AfterCloseAll");
      for (i=0;i<H_Al;i++){
        if(document.getElementById(H_A[i])) //when i reached 28, it's null???
            {
			// JM 4/9/05 - changed from form ref to straight doc.   
         //H_El=Nav4?form.document.layers[H_A[i]]:DomYes?form.document.getElementById(H_A[i]).style:form.document.all[H_A[i]].style;
         H_El=Nav4?document.layers[H_A[i]]:DomYes?document.getElementById(H_A[i]).style:document.all[H_A[i]].style;
         H_El.visibility="visible"
            }
	}
    }
}

var comparedKeys     = new Array();
var comparedProducts = new Array();
var numCompared = 0;

function resetComparedProducts(){
	comparedKeys     = new Array();
	comparedProducts = new Array();
	numCompared = 0;
}

function modifyComparedProducts(mfgId, prodGroupId, prodId, bAdd){
	if (!bAdd){
		comparedProducts[prodId] = null;
		for (var i=0; i<comparedKeys.length; i++){
			if (comparedKeys[i] == prodId){
				comparedKeys[i] = null;
				if ($('mod-'+prodId)){
					$('mod-'+prodId).checked = false;
				}
				break;
			}
		}
		numCompared--;
	} else {
		comparedKeys[numCompared] = prodId;
		var		arr = comparedProducts[prodId] = new Array();
		var		tbl = document.getElementById("pdi-"+prodId);
		var 	img = document.getElementById("pii-"+prodId);
		for (var i=0; i<tbl.rows.length; i++){
			var  name = tbl.rows[i].cells[0].innerHTML;
			var value = tbl.rows[i].cells[1].innerHTML;
			arr[name] = {mfgId: mfgId, prodGroupId: prodGroupId, value: value, img: img?img.src:null};
		}
		numCompared++;
	}
	var vcText = document.getElementById("vcText");
	vcText.innerHTML = "(" + numCompared + ")";
}

function viewCompared(){
	var		div = document.getElementById("comparedProducts");
	var		tbl = document.getElementById("tblComparedProducts");
	var		 tr = tbl.rows[0];
	var		 td;
	while (tbl.rows.length > 0) tbl.deleteRow(0);
	var     idx = 0;
	
	// build row 0 which is product images
	tr			= tbl.insertRow(0);
	td			= tr.insertCell(0);
	td.innerHTML = "<b>PROPERTIES</b>";
	td.width    = "140px";
	var	nProds = 0;
	var  props = new Array();
	// want MFG/MODEL/SERIES first
	props[props.length] = "MANUFACTURER";
	props[props.length] = "MODEL";
	props[props.length] = "SERIES";
	props[props.length] = "ARTICLE";
	
	for (var i=0; i<comparedKeys.length; i++)
	{
		var   pid = comparedKeys[i];
		if (pid == null) continue;		// has been removed
		var  pr = comparedProducts[pid];		// array
		td		= tr.insertCell(nProds+1);
		td.width = "200px";
		var img = pr["MODEL"].img;
		var html = img ? ("<img src='" + img + "' width='120'>") : "";
		html	+= "<br/>";
		html	+= "<a href=\"javascript:window.document.SelectProductForm.mfgID.value='" + pr["MANUFACTURER"].mfgId + "';" +
				" window.document.SelectProductForm.productID.value='" + pid + "'; " +
				" window.document.SelectProductForm.productGroupID.value='" + pr["MANUFACTURER"].prodGroupId + "';" + 
				" catalogSubmit(window.document.SelectProductForm); void 0;\"" + 
				" class='greenSmall'>" +
				//"<img src='/adsonline/company/adsonline/images/NewAds_PlusButton.gif' alt='' width='13' height='13' border='0' align='top' hspace=1>" +
				"Add To My Project</a>";
		html	+= "&nbsp;&nbsp;";
		html	+= "<a href=\"javascript:modifyComparedProducts(null,null,'" + pid + "',false);" +
				"UI.showHide('comparedProducts', false); viewCompared(); void 0;\">Remove Product</a>";
		
		td.innerHTML = html;
		td.align = "center";
		td.valign = "middle";
		
		nProds++;

		for (var p in pr)
		{
			// hack around prototype adding stuff to arrays
			if ((typeof pr[p]) == "function" || pr[p].toString().indexOf("_") == 0) continue;
			if (props.indexOf(p) < 0) props[props.length] = p;
		}
	}
	
	// other rows for properties
	for (var x=0; x<props.length; x++){
		tr	= tbl.insertRow(x+1);
		if ((x%2)==0) tr.style.backgroundColor = "f5f5f5";
		else		  tr.style.backgroundColor = "e1e1e1";
		td  = tr.insertCell(0);		// row label
		td.innerHTML = props[x];
		td.valign = "top";
		for (var c=0; c<nProds; c++){
			td = tr.insertCell(c+1);
		}
	}
	// fill 'em up
	var		cell=1;		// cell index
	for (var i=0; i<comparedKeys.length; i++)
	{
		var pid = comparedKeys[i];
		if (pid == null){
			continue;
		}
		var pr = comparedProducts[pid];		// array
		for (var x=0; x<props.length; x++){
			var name = props[x];	// pr[x].name;
			if (!pr[name]) continue;
			var  val = pr[name].value;
			tr		 = tbl.rows[x+1];
			td		 = tr.cells[cell];
			td.innerHTML = val;
			td.valign = "top";
		}
		cell++;
	}
	div.style.width	  = (168*tbl.rows[0].cells.length)+"px";
	//div.style.display = "block";
	UI.showHide(div, true);
}
