//
// Helper javascript functions
//

// Main Window Opener
//
// Window Options, - set up the size of windows
//
//
//


// Absolute references to popups.
function getEcsRoot() { 
  var arr = ("" + document.location).split("/");
  return "/" + arr[3];
}

function getCieQuoteRootUrl() {
  return g_CIEQUOTE_URL;
}



function windowOptions(url, winName) {
  var opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=700,height=500,left=20,top=40';

	// Dashboard sizing.    
    if (url.indexOf("dash") != -1  || url.indexOf("sm_home/home.htm") != -1 || url.indexOf("cs_home/home.htm") != -1) {
      opts = 'location=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes,width=800,height=600,left=20,top=40';
    } 
    
    else if (url.indexOf("/enduser/list/accounts") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    }    
    else if (url.indexOf("/enduser/list/contacts") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    }  
    else if (url.indexOf("/enduser/list/accounts/save_to_folder") != -1) {
       opts = 'resizable=yes,toolbar=no,scrollbars=no,height=300,width=400,left=100,top=75';
    }
    else if (url.indexOf("/enduser/documents/account/entity_search") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=450,height=600,left=400,top=40';
    } 
    else if (url.indexOf("/enduser/documents/account_contact") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=700,left=20,top=40';
    } 
    else if (url.indexOf("/enduser/documents/accountfolder") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    } 
    else if (url.indexOf("/enduser/documents/account") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    } 
    else if (url.indexOf("/enduser/documents/activity") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    } 
    else if (url.indexOf("/enduser/documents/agent") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    } 
    else if (url.indexOf("/enduser/documents/cms") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=810,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/contact_email") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/contact") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=900,height=600,left=20,top=40'; 
    }
     else if (url.indexOf("/enduser/documents/download") != -1) {
      opts = 'resizable=yes,toolbar=yes,scrollbars=yes,width=350,height=500,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/employee") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=350,height=500,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/fulfillment_folder/") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=650,height=700,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/fulfillment/enclosure_search") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=650,height=600,left=400,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/fulfillment/") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=650,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/interaction") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/inquiry") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/letterrequest") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/opportunity") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/quotes") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40';
    }
    else if (url.indexOf("/enduser/documents/product") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/query") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    else if (url.indexOf("/enduser/documents/routing_ticket") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=850,height=600,left=20,top=40'; 
    }


    // Marketing
    else if (url.indexOf("/marketing/") != -1) {
      opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    }
    
    // Sales Admin
    else if (url.indexOf("/sales_admin/fulfillment/marketing_pieces") != -1) {
		opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=600,height=600,left=470,top=50'; 
    }
    else if (url.indexOf("/sales_admin/users/securitygroup/modify_i") != -1) {
		opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=600,height=600,left=470,top=50'; 
    }
    else if (url.indexOf("/sales_admin/users/user_accounts/modify_i") != -1) {
		opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=600,height=600,left=470,top=50'; 
    }
    else if (url.indexOf("/sales_admin/") != -1) {
		opts = 'resizable=yes,toolbar=no,scrollbars=yes,width=800,height=600,left=20,top=40'; 
    } 
    
    // Downloadable 
    else if (url.indexOf("/fs") != -1 || url.indexOf("file://") != -1 || url.indexOf("download/") || url.indexOf(".csv")) {
      opts = 'location=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes,width=800,height=800,left=60,top=40'; 
    } else if ( url.indexOf("/enduser/list/marketing_view") != -1 || url.indexOf("file://") != -1) {
	opts = 'location=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes,width=800,height=800,left=60,top=40';
    }


    // bounce to new site
    else if ( url.indexOf("http://") != -1 || url.indexOf("https://") != -1 ) {
      opts = 'location=yes,menubar=yes,resizable=yes,toolbar=yes,scrollbars=yes,width=800,height=600,left=20,top=40';
    }
    
    // Info and Help //
    else if ( url.indexOf("/about/") != -1 ) {
      opts = 'resizable=yes,toolbar=no,scrollbars=no,width=500,height=440,left=200,top=200';
    }

  return opts;
}


// Main Window Opener - note winName can't have spaces in it.
function stWinOpen(url_in, winName, opts_in) {
//    var opts = windowOptions(url_in, winName);
//    var url = fnGetSessionUrl(url_in);
    
    // Pop the win
//   alert('in winopen ' + winName);
//   var opp = window.open(url,winName,opts);
//var opp = window.open(url, winName);  //  commented out to remove pop up
	 window.location = url_in;		// added by Ken Wilson
}



function stWinFocus() {
  window.focus();
}


function stWinClose() {
    //window.close();
}
function stWinCloseParentReload() {
    stWinParentReload();
    stWinClose();
}


function isValidWindow(win) {
   return win != null  && "" + win.location != "undefined" && "" + win.location != "";
}

function stWinParentReload() {
   if (isValidWindow(window.opener)) {
      window.opener.location.reload( true );
   }
}

function stWinCloseParentSubmit(formName) {
   if (isValidWindow(window.opener)) {
	 window.opener.document.forms[formName].submit();
   }
   
   stWinClose();
}


function stWinReload() {
   if (isValidWindow(window)) {
      window.location.reload( true );
   }
}


function getDocumentsRootUrl() {
  return getEcsRoot() + "/enduser/documents";
}

function getListRootUrl() {
  return getEcsRoot() + "/enduser/list";
}

function getEnduserRootUrl() {
  return getEcsRoot() + "/enduser";
}

function getFramesRootUrl() {
  return getEcsRoot() + "/common/frames";
}

function getAdminRootUrl() {
  return getEcsRoot() + "/admin";
}

function getSalesAdminRootUrl() {
  return getEcsRoot() + "/sales_admin";
}


function getCommerceAdminRootUrl() {
  return getEcsRoot() + "/system/commerce";
}

function getSalesAdminDocumentsRootUrl() {
  return getSalesAdminRootUrl() + "/documents";
}

function getSystemAdminRootUrl() {
  return getEcsRoot() + "/system";
}


function getTerritoryRootUrl() {
  return getEcsRoot() + "/territory";
}

function getMarketingRootUrl() {
  return getEcsRoot() + "/marketing";
}

function getImagesRootUrl() {
  return getEcsRoot() + "/images";
}

 // used to disable all elements on a form
 function disableForm(formName) {
      for (var i = 0; i < document.forms[formName].elements.length; i++) {
	  document.forms[formName].elements[i].disabled = true;
      }		 
    }

function openPop(sUrlBase) {
	openPop(500, 680);
}
function openPop(sUrlBase, height, width) {
	var win="defaultWin";
	var url = sUrlBase;
    var opts = windowOptions(url, win);
	var opp = stWinOpen(url, win, opts);
}

function popPlaceholder(sText) {
	var win="Placeholder";
	var opp = stWinOpen("", win, "resizable=yes,toolbar=no,scrollbars=yes,height=50,width=400,left=400,top=400");
	opp.document.open();
	opp.document.write('<html><title>Popup Placeholder</title><LINK REL=STYLESHEET TYPE=text/css HREF=../../../css/ecs.css>');
        opp.document.write('<body bgcolor=#FFFFFF><form name=flip>');
  	opp.document.write('<font class="notetext">' + sText + '</font></body><p><input name="Close" value="Close" type=button onclick="javascript:window.close();"></html>');
}



// selects the appropriate value for the MainTop frame
function fnMainTopSelect(sID, sHtm, sDefault) {
	var frameMT = document;
	var frameMT = parent.MainTop;
        if ("undefined" != "" + frameMT) {
            frameMT.location.replace(sHtm);
        }
}

// used to change image arrows in the MainTop tables
function fnMainBotSelect(sID, sHtm, sDefault) {
	var frameMT = parent.MainBot;
        if ("undefined" != "" + frameMT) {
            frameMT.location.replace(sHtm);
	}
}

// Turn on/off the image arrow.
//var sImg_old = -1;
//if (document.images) {
//  Arrowon = new Image();
//  Arrowon.src = "../../../images/arrowon.gif";
//  Arrowoff = new Image();
//  Arrowoff.src = "../../../images/arrowoff.gif";
//}

function fnUpdateImageArrow(sID_in, bOn) {
   if ("undefined" == "" + document.images[sID_in]) { return; }

   if (!bOn) {
   // turn off the image.
    document.images[sID_in].src = Arrowoff.src
    } else {
    // turn on the image
    document.images[sID_in].src = Arrowon.src
    }
}

function fnUpdateImageArrow1(sImg, sImg) {
	// Now set up the image below.
	if (sImg_old != -1) {
		fnUpdateImageArrow(sImg_old, false);
	}
	fnUpdateImageArrow(sImg, true);
	sImg_old = sImg;
}


// selects the appropriate value for the LeftNavBot frame
function fnLeftNavBotSelect(sImg, sHtm, sID) {
	var frameLNT = document;
	var frameLNT = parent.LeftNavBot;
	var url = sHtm + "?CONTEXT_ID=" + sID;
	frameLNT.location.replace(url);

	fnUpdateImageArrow1(sImg_old, sImg);
}

// selects the appropriate value for the LeftNavBot frame
function fnDetailSelect(sImg, sHtm, sID) {
	
	var frameLNT = document;
	var url = sHtm + "?CONTEXT_DETAIL_ID=" + sID;
	frameLNT.location.replace(url);
	
	// Now set up the image below.
	if (sImg_old != -1) {
		fnUpdateImageArrow(sImg_old, false);
	}
	fnUpdateImageArrow(sImg, true);
	sImg_old = sImg;
}


// selects the appropriate value for the LeftNavTop frame
function fnLeftNavTopSelect(sID, sHtm, sDefault) {
	
	var frameLNT = document;
	var frameLNT = parent.LeftNavTop;
	frameLNT.location = sHtm;
	
}


// selects the appropriate value for the right frame in the enduser modules.
function fnRightFrameSelect(sImg, sHtm, sID) {
	var frameRF = document;
	var frameRF = parent.frame_right;
	var url = sHtm + "?CONTEXT_ID=" + sID;
	frameRF.location.replace(url);

	fnUpdateImageArrow1(sImg_old, sImg);
}



// Truncate the string and replace with elipsis
// Make the string no longer than 15 chars.
// ie.  Joint Chiefs of Staff
//      Joing Chiefs ...
function fnTruncate2(s_in, len, bElipse) {   
   var s = s_in;
   var result;
   var lastIdx = 0;   
   var bDone = s.length <= len;
   for (;bDone == false;) {
        var idx = s.lastIndexOf(" ");
        if (idx == -1) {
           s = s.substring(0, len);
           bDone = true;
           continue;
        }
        var s1 = s.substring(0, idx );
//        document.write("<li> orig :[" + s + "] now :[" + s1 + "]");
        s = s1;
        bDone = (s.length <= len);
   }

     result = s;
     if (bElipse != null && bElipse) {
       result +=  "...";
     }
//  document.write("<li> returning : " + result);
  return result;
}

function fnTruncate(s) {   
   return fnTruncate2(s, 15, true);
}




// selects the appropriate value for the right frame in the enduser modules.
function openRightFrame(url) {
	var frameRF = document;
	var frameRF = parent.frame_right;
	frameRF.location.replace(url);
}

function fnOpenRequestDetail( id ) {
		openDetails2(getDocumentsRootUrl() + "/fulfillment/details.htm", "FormLetter." + id, getOid(), 620,450);
}

function fnOpenDirectMail( id ) {
		openDetails2(getDocumentsRootUrl() + "/fulfillment_folder/details.htm", "FormLetter." + id, getOid(), 620,450);
}

function fnOpenFulfillmentNew( parentoid ) {
		openDetails2(getDocumentsRootUrl() + "/fulfillment/new_i.htm", "", parentoid, 620, 450);
	}

function fnOpenFulfillmentList( oid ) {
		openDetails2(getDocumentsRootUrl() + "/fulfillment/list.htm", oid, oid, 620, 450);
	}
	
// opens details file in new window.
function openDetails(page,id) {
   var opp = stWinOpen(page, id,'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=700,left=20,top=40');
}

// opens Enduser help file in new window
 function openHelp() {
 var helpframe = popWin("helpwin", "./help.htm", 760,400,"no", "no", "no", "no", "no", "yes",  "yes", "no");
}

function fnOpenEnduser() {	
  stWinOpen(getEnduserRootUrl() + "/documents/sales_dashboard/home.htm", "ecs_enduser");
}
function fnOpenSalesMgr() {	
  stWinOpen(getFramesRootUrl() + "/salesmgr/frameset.htm", "ecs_enduser");
}
function fnOpenMarketing() {	
  stWinOpen(getFramesRootUrl() + "/marketing/frameset.htm", "ecs_enduser");
}

function fnOpenAdmin() {	
  stWinOpen(getSalesAdminRootUrl() + "/admin_frames.htm", "ecs_admin");
}
function fnOpenSalesAdmin() {	
  stWinOpen(getSalesAdminRootUrl() + "/admin_frames.htm", "ecs_admin");
}

function fnOpenMarketingAdmin() {	
  stWinOpen(getMarketingRootUrl() + "/marketing_frames.htm", "ecs_marketing_admin");
}

function fnOpenWorkflowAdmin() {	
  stWinOpen(getMarketingRootUrl()  + "/marketing_frames.htm", "ecs_marketing_admin");
}

function fnOpenTerritoryAdmin() {	
  stWinOpen(getTerritoryRootUrl() + "/territory_frames.htm", "ecs_territory_admin");
}

function fnAddModulesFolder(level_0) {
   // Other Modues	
   level_om = insFld(level_0, gFld("<font class='leftlinkbold'>Other Modules</font>", "", imageSettingsDefault));

insDoc(level_om, gLnk('frame_left', "<font class=leftlink><font class=leftlink>Enduser</font>", "javascript:fnOpenEnduser();", imageSettingsDefault))
insDoc(level_om, gLnk('frame_left', "<font class=leftlink><font class=leftlink>Sales Admin</font>", "javascript:fnOpenSalesAdmin();", imageSettingsDefault))
insDoc(level_om, gLnk('frame_left', "<font class=leftlink><font class=leftlink>Marketing Admin</font>", "javascript:fnOpenMarketingAdmin();", imageSettingsDefault))
insDoc(level_om, gLnk('frame_left', "<font class=leftlink><font class=leftlink>Territories Admin</font>", "javascript:fnOpenTerritoryAdmin();", imageSettingsDefault))
}

// opens Admin Help main frameset (hhstart.htm) in new window
 function openAdminHelp() {
 var helpframe = popWin("helpwin", "../docs/admin/hh_start.htm", 850,600,"no", "no", "no", "no", "no", "yes",  "yes", "no");
}

// opens Marketing help file in new window
 function openMktgHelp(bookmark) {
 var helpframe = popWin("helpwin", "../../../docs/marketing_admin/right.htm" + bookmark, 400,400,"yes", "no", "no", "no", "no", "yes",  "yes", "no");

}

//This function (pop) opens a daughter-window in the center of the screen
function popWin(windowName, loc, w, h, setToolbar, setLocation, setDirectories, setStatus, setMenubar, setScrollbars, setResizable, setCopyhistory)
{

	// Determine pop-up position to center on screen
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/25 : 0;

	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',toolbar='+setToolbar+',location='+setLocation+',directories='+setDirectories+',status='+setStatus+',menubar='+setMenubar+',scrollbars='+setScrollbars+',resizable='+setResizable+',copyhistory='+setCopyhistory+''

	stWinOpen(loc, windowName, settings);
}

function nothing() {
}


// Write out a stylized error message
// displays error messages, based on the form element for errors.

function writeError1(formName, varName) {
  var errorString = document.forms[formName].elements[varName].value;
  writeError2(errorString);
}
function writeError2(errorString) {
  var errors = errorString.split("|");
  if (errorString != "" && errors.length > 0) {
  	  document.getElementById('ecsErrors').style.display="block";
	  document.writeln('<ul>');
	  for (var i=0;i < errors.length;i++) {
		  document.writeln('<li>');
		  document.writeln(errors[i]);
	  }
	  document.writeln("</ul>");
  }
}

function writeError(formName) {
  writeError1(formName, 'errors');
}


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
	if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
		document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
	else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);


function fnOpenView(sUrl) {
	fnOpenView(sUrl,  "ViewWin");
}

function fnOpenView(sUrl, sWinId) {
      var vFrame = stWinOpen(sUrl,sWinId,'resizable=yes,toolbar=no,scrollbars=no,height=390,width=550,left=100,top=75');
}


// selects the appropriate value for the LeftNavTop frame
function fnGoToAccountDetails(id) {	
  openAccount(id);
}


// selects the appropriate value for the LeftNavTop frame
function fnGoToContactDetails(id) {	
  openContact(id);
}

function doNothing() {}

function openTreeControl(relativeUrl) {
  popWin("treecontrol", relativeUrl + "tree_control/menu_frames.html", 750, 500, "yes", "no", "no", "no", "no", "yes", "yes", "no");
}


function getSearchId() {
  return "";
}

function getOid() {
  return "";
}

function getParentOid() {
  return "";
}

function fnGetUrl(sUrlBase, oid, parent_oid, urlArgs) {
	
	var q = "?";
	var win="defaultWin";
	var url = sUrlBase;
        if ("" + urlArgs != "undefined" && "" + urlArgs != "") {
           url += q + urlArgs;
           q = "&";
        }

	if ("" + oid != "undefined") {
	 url = url + q +  "oid=" + oid;
//	 win = "" + oid;
	 q = "&";
        }
	if ("" + parent_oid != "undefined") {
	  url = url + q + "parent_oid=" + parent_oid;
	  q = "&";
//	  win = "" + parent_oid;
        }	

	// Add the search criteria.
	var srch = getSearchId();
	if (srch != "") { 
 	   url = url + q + "search_id=" + srch;
           q = "&";
        }
	return url;
}

function fnGetWinName(sUrlBase, oid, parent_oid) {
  var i = sUrlBase.lastIndexOf("/") + 1;
  var len = sUrlBase.length;
//  alert("lenght for: " + sUrlBase + " is: " + len);
  //alert("grab substring: " + i + " end= " + len);
  var sName = sUrlBase.substring(i, len);
//  alert("have substring" + sName);
  var s0 = sName.split(".");
  var a0 = s0.join("_");
  //alert(a0);
  
 
  var name = (oid + "." +  parent_oid).split(".");
  var s1 = a0 + "_" + name.join("_");
  var a1 = s1.split("*");
  var s2 = a1.join("_");
  return s2;  
}

// opens details file in new window.
function openDetails1(sUrlBase, oid, winWidth, winHeight, winLeft, winTop) { 
  openDetails2(sUrlBase, oid, undefined, winWidth, winHeight, winLeft, winTop);
}

function openDetails2(sUrlBase, oid, parent_oid, winWidth_in, winHeight_in, winLeft_in, winTop_in) {
	var winWidth = 500;
	var winHeight = 500;
	var winLeft = 20;
	var winTop = 20;
	if ("" + winHeight_in != "undefined") {
	    winWidth = winWidth_in;
	    winHeight = winHeight_in;
	    winLeft = winLeft_in;
	    winTop = winTop_in;
        }

	
	var url = fnGetUrl(sUrlBase, oid, parent_oid, "NAV_SELECTED=tab.home", false);
	var win = fnGetWinName(sUrlBase, oid, parent_oid);
  
//	var opp = stWinOpen(url, win, 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=' + winHeight + ',width=' + winWidth + ',850,left=20,top=40');
	document.location=url;
}

function openDocumentWindowWithArgs(sUrlBase, oid, parent_oid, sargs, winWidth_in, winHeight_in, winLeft_in, winTop_in) {
	var winWidth = 850;
	var winHeight = 650;
	var winLeft = 20;
	var winTop = 20;
	if ("" + winHeight_in != "undefined") {
	    winWidth = winWidth_in;
	    winHeight = winHeight_in;
	    winLeft = winLeft_in;
	    winTop = winTop_in;
        }

	if ( sargs != "" ) {
		sargs += "&NAV_SELECTED=tab.home";
	} else {
		sargs = "NAV_SELECTED=tab.home";
	}

	var url = fnGetUrl(sUrlBase, oid, parent_oid) + "&" + sargs;
	var win = fnGetWinName(sUrlBase, oid, parent_oid);
//	alert("opening url in window: " + win + " for oid: " + oid + "  : " + url );
  
	var opp = stWinOpen(url, win, 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=' + winHeight + ',width=' + winWidth + ',850,left=20,top=40');
}

function closeDetails() {
	stWinClose();
}
function closeWindow() {
	stWinClose();
}
var undefined;

// display date on _main pages.

function curDate() {
 var d = new Date()
 var ampm = d.getHours()
 if(ampm < 12) { 
 ampm = " A.M."
 }
 else if(ampm >= 12) {
  ampm = " P.M."
   }
 var addzero = d.getMinutes()
 if (addzero <= 9) {
 addzero = ("0" + addzero)
 }
 var convertMil = d.getHours()
 if (convertMil >= 13) {
 convertMil = (convertMil - 12)
 }


 document.write(d.getMonth() + 1)
 document.write("/");
 document.write(d.getDate())
 document.write("/")
 document.write(d.getFullYear() + " ")
 document.write(convertMil + ":");
 document.write(addzero)
 document.write(ampm)
 }


///////////////////////// POP UP FUNCTIONS /////////////////////////////////////


//////////////////// Functions to popup the new opportunity stuff.

// This is temporary to get the popup to work
function openOpportunity(id) {
	openDetails1(getDocumentsRootUrl() + "/opportunity/details.htm", "Opportunity." + id, 800,600);
}

function openOpportunityModify(id) {
	openDetails1(getDocumentsRootUrl() + "/opportunity/modify_i.htm", "Opportunity." + id, 750,600);
}

function openCase(id) {
	openDetails1(getDocumentsRootUrl() + "/cms/details.htm", "Case." + id, 810,600);
}

function openAgentDup(dupTrigger) {
	openDetails1(getDocumentsRootUrl() + "/agent/account_dups.htm", 810,600);
}


function openOpportunityNewForAccount(id) {
	openDetails2(getDocumentsRootUrl() + "/opportunity/new_i.htm", "", "Account." + id, 700,600);
}

function openOpportunityNewForAccountWithArgs(id, args) {
	openDocumentWindowWithArgs(getDocumentsRootUrl() + "/opportunity/new_i.htm", "", "Account." + id, args, 750,520);
}


function openCaseNewForAccount(id) {

//	openDetails2(getDocumentsRootUrl() + "/cms/newcase_i.htm", "Case.NEW", "Account." + id, 850,600);
openDetails2(getDocumentsRootUrl() + "/cms/new_i.htm", "Case.NEW", "Account." + id, 850,600);
}

////////////////////// end opportunity

function popParentSearch() {
	var win="parentSearch";
	var url = getDocumentsRootUrl() + "/account/entity_search.htm";

        var height=600;
        var width = 400;
	var opp = stWinOpen(url, win, 'resizable=yes,toolbar=no,scrollbars=yes,height=' + height + ',width=' + width + ',left=40,top=40');
}

////////////////// Functions to popup the new account stuff.

function openAccount(id) {
	openDetails1(getDocumentsRootUrl() + "/account/details.htm", "Account." + id, 780,600,20,20);

}

function openSalesTeam(id) {
	openDetails1(getSalesAdminRootUrl() + "/users/salesteams/modify_i.htm", "UserAccount." + id, 780,600,20,20);

}

function openOrganizationRef(id) {
	openDetails1(getSalesAdminRootUrl() + "/users/organization/details.htm", "OrganizationRef." + id, 780,600,20,20);
}


function openAccountContactList(id) {
	openDetails1(getDocumentsRootUrl() + "/account/contacts.htm", "Account." + id, 780,600,20,20);

}

function openItem(objkey) {
	var sUrl;
	
	sUrl    = getMarketingRootUrl() + "/products/products/details.htm?oid=ItemMasterRef." + objkey;

	var ri = stWinOpen(sUrl, 'ItemNew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=600,width=850,left=20,top=20');
}

function openRoutingInfo(objid, objkey) {
	var sUrl;
	var sObject;
	
	sObject = "parent_oid=" +objid + "." + objkey;	
	sUrl    = getDocumentsRootUrl() + "/routing_ticket/list.htm?oid=RoutingTicket.NEW&" + sObject;

	var ri = stWinOpen(sUrl, 'RINew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=400,width=650,left=20,top=20');
}


function openRoutingInfoModify(sUrl) {
	var sUrl;
	sUrl    = getDocumentsRootUrl() + "/routing_ticket/modify_i.htm?oid="  + sUrl;
	var ri = stWinOpen(sUrl, 'RINew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=600,width=850,left=20,top=20');
}

function openAccountOrganizationTree(id) {
	openDetails1(getDocumentsRootUrl() + "/account/entity.htm", "Account." + id, 780,600,20,20);

}

function openContactNew(sUrl, parentObj) {
	   var s = fnGetUrl(sUrl, "Contact.NEW", parentObj, "");
		var opp = stWinOpen(s, 'ContactNew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=860,width=780,left=20,top=0');
}

function openAddressNew(sUrl, parentObj) {
	   var s = fnGetUrl(sUrl, "Address.NEW", parentObj, "");
		var opp = stWinOpen(s, 'AddressNew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=860,width=780,left=20,top=0');
}

function openAccountNew(sUrl) {
	   var s = fnGetUrl(sUrl, "Account.NEW", "", "");
		var opp = stWinOpen(s, 'AccountNew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=700,width=780,left=20,top=0');
}


function openAccountModify() {
		var opp = stWinOpen('../../documents/account_contact/modify_account.htm', 'AccountNew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=700,width=780,left=20,top=0');
}


//////////////////// end account

//////////////////// start account folder

function openAccountFolder(id) {
	openDetails1(getDocumentsRootUrl() + "/accountfolder/details.htm", "AccountFolder." + id, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}


function openAccountFolderNew() {
		var opp = stWinOpen('../../documents/accountfolder/new_i.htm', 'AccountNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

//////////////////// end account folder

//////////////////// start contact folder

function openDocumentFolder(id) {
	openDetails1(getDocumentsRootUrl() + "/folders/details.htm", "DocumentFolder." + id, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}


function openDocumentFolderNew(objType) {
	    var surl = "../../documents/folders/new_i.htm?parent_oid=DocumentTypeRef." + objType;
		var opp = stWinOpen(surl, 'FolderNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

//////////////////// end account folder


/////////////// Functions to popup the new contact stuff.

// This is temporary to get the popup to work
function openContact(id) {	
  openDetails1(getDocumentsRootUrl() + "/contact/details.htm", "Contact." + id, 780,600);
}

function openAddress(id) {	
  openDetails1(getDocumentsRootUrl() + "/address/details.htm", "Address." + id, 780,600);
}


function openAddressParentOid(id, poid) {	
  openDetails2(getDocumentsRootUrl() + "/address/details.htm", "Address." + id, poid,780,600);
}


function openAccountContactNew() {
		var opp = stWinOpen('../../documents/account_contact/new_i.htm', 'ContactNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=720,left=40,top=40');
}

function openLetterRequest(id) {
  openDetails1(getDocumentsRootUrl() + "/letterrequest/details.htm", "Form." + id);
}


function openLetterRequestNewForContact(oid) {
  openDetails1(getDocumentsRootUrl() + "/letterrequest/new_i.htm", "", oid);
}



////////////// Functions to popup the new employee stuff.

function openEmployee(id) {
  openDetails1(getDocumentsRootUrl() + "/employee/details.htm", "EmployeeRef." + id, 0, 0);
}

function openEmployeeByUserAccount(id) {
  openDetails1(getDocumentsRootUrl() + "/employee/details.htm", "UserAccount." + id, 0, 0);
}

function openEmployeeAdmin(id) {
  openDetails1(getSalesAdminRootUrl() + "/users/employees/details.htm", "EmployeeRef." + id, 740, 600);
}

function openEmployeeNew() {
   openDetails1(getSalesAdminRootUrl() + "/users/employees/new_i.htm", "EmployeeRef.new", 740, 600);
}

function openOrganizationNew() {
   openDetails1(getSalesAdminRootUrl() + "/users/organization/new_i.htm", "OrganizationRef.new", 740, 600);
}
function openLocationNew() {
   openDetails1(getSalesAdminRootUrl() + "/users/locations/new_i.htm", "LocationRef.new", 740, 600);
}
function openLocationRef(id) {
   openDetails1(getSalesAdminRootUrl() + "/users/locations/details.htm", "LocationRef." + id, 740, 600);
}
function openEmployeeNew(parentoid) {
   openDetails2(getSalesAdminRootUrl() + "/users/employees/new_i.htm", "EmployeeRef.new", parentoid, 740, 600);
   
}


function openTaxZoneRefNew() {
   openDetails1(getCommerceAdminRootUrl() + "/taxzones/new_i.htm", "TaxZoneRef.new", 740, 600);
}
function openTaxZoneRef(id) {
   openDetails1(getCommerceAdminRootUrl() + "/taxzones/details.htm", "TaxZoneRef." + id, 740, 600);
}

function openTaxCodeRefNew() {
   openDetails1(getCommerceAdminRootUrl() + "/taxcodes/new_i.htm", "TaxCodeRef.new", 740, 600);
}
function openTaxCodeRef(id) {
   openDetails1(getCommerceAdminRootUrl() + "/taxcodes/details.htm", "TaxCodeRef." + id, 740, 600);
}

function openTaxClassRefNew() {
   openDetails1(getCommerceAdminRootUrl() + "/taxclasses/new_i.htm", "TaxClassRef.new", 740, 600);
}
function openTaxClassRef(id) {
   openDetails1(getCommerceAdminRootUrl() + "/taxclasses/details.htm", "TaxClassRef." + id, 740, 600);
}


/////////////// end employee

//////////// Functions to popup the new activity stuff.

// This is temporary to get the popup to work
 function openActivity(id) {
  openActivityModify(id);
  //  openDetails1(getDocumentsRootUrl() + "/activity/details.htm", "Tasks." + id, 620,500);
 }

// This method exists because the default is "modify" 
function openActivityDetails(id) {
   if (id.indexOf("Tasks.") == -1) {
     id = "Tasks." + id;
   }
   openDetails1(getDocumentsRootUrl() + "/activity/details.htm", id, 620,500);
 }
 
 function openActivityModify(id) {
  openDetails1(getDocumentsRootUrl() + "/activity/modify_i.htm", "Tasks." + id, 620,650);
 }

// This is temporary to get the popup to work
 function openInquiry(id) {
  openDetails1(getDocumentsRootUrl() + "/inquiry/inquiry_to_opportunity.htm", "Inquiry." + id, 620,470);
 }

 function openAutoCreateInquiryRef(id) {
  openDetails1(getMarketingRootUrl() + "/system/autoinq/details.htm", "AutoCreateInquiryRef." + id, 620,450);
 }


function openActivityNew() {
		var opp = stWinOpen('../../documents/activity/new_i.htm', 'ActivityNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

function openActivityNewByTimeSlot(tStart, tEnd) {
		var opp = stWinOpen('../../documents/activity/new_i.htm?tS=' + tStart + '&tE=' + tEnd, 'ActivityNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

///////////////// end activity

////////////// Functions to popup the new interaction stuff.
function openNewFulfillment() {      
//        alert(getDocumentsRootUrl() + "/fulfillment/new_i.htm" + " oid = " + getOid());
       	openDetails2(getDocumentsRootUrl() + "/fulfillment/new_i.htm", "FormLetter.NEW", getOid(), 780,600,20,20);
}

function openNewEmailForContact(contactUuid) {
   return openNewEmailForContactAndParent(contactUuid, getOid())
}

function openNewEmailForContactAndParent(contactUuid, parentUuid) {
   if (contactUuid == null) {
      contactUuid = getOid();
   }

    return openDetails2(getDocumentsRootUrl() + '/contact_email/email.htm', contactUuid, parentUuid, 625, 500);
}

// This is temporary to get the popup to work
function openInteraction(id) {
  openDetails1(getDocumentsRootUrl() + "/interaction/details.htm", "Interactions." + id, 620,450);
}

function openInteractionNew(contactOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/interaction/new_i.htm?oid=" + contactOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'InteractionNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	

function openProfileContact(contactOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/contact/profile_i.htm?oid=" + contactOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'ContactProfile', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	

function openProfileInquiry(inquiryOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/inquiry/qualify.htm?oid=" + inquiryOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'InquiryProfile', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	

function openProfileCase(caseOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/cms/profile_i.htm?oid=" + caseOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'CaseProfile', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	

function openProfileOpportunity(opportunityOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/opportunity/profile_i.htm?oid=" + opportunityOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'OpportunityProfile', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	
function openProfileCompany(opportunityOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/parent_company/profile_i.htm?oid=" + opportunityOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'CompanyProfile', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	

function openProfileAccount(accountOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/account/profile_i.htm?oid=" + accountOid + "&parent_oid=" + parentOid;
	var opp = stWinOpen(sUrl, 'AccountProfile', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	

function openRegisterLead(contactOid) {
	var sUrl = getDocumentsRootUrl() + "/contact/registerlead_i.htm?oid=" + contactOid;
	var opp = stWinOpen(sUrl, 'InteractionNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	


function openInteractionNewByOpportunity(id) {
		var opp = stWinOpen('../../documents/interaction/interactions_i.htm', id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

/////////////// end interaction

function openUser(id) {
		var opp = stWinOpen('../../documents/user/details.htm', id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

function openUserNew() {
		var opp = stWinOpen('../../documents/user/user_i.htm', 'UserNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}


/////////////// end user


////////////// Functions to popup the new products stuff.

// This is temporary to get the popup to work
function openProduct(id) {
		var opp = stWinOpen('../../documents/opportunity/products.htm', id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

function openProductNew() {
		var opp = stWinOpen('../../documents/opportunity/products_i.htm', 'ProductNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

/////////////// end products
function openScoreNew() {
	    var surl = getMarketingRootUrl() + "/placements/document_score/new_i.htm";
		var opp = stWinOpen(surl, 'documentScore', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}


////////////// Functions to popup the new service request stuff.

// This is temporary to get the popup to work
function openServiceRequest(id) {
		var opp = stWinOpen('../../documents/servicerequest/details.htm', id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

function openServiceRequestNew() {
		var opp = stWinOpen('../../documents/servicerequest/servicerequest_i.htm', 'SRNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

/////////////// end service request

// function to open popups not in the documents directory

function openMyInbox(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

function openMyFolder(id) {
		var opp = stWinOpen('../../documents/accountfolder/details.htm?oid=AccountFolder.' + id, id, 'resizable=yes,toolbar=nos,scrollbars=yes,height=250,width=500,left=40,top=20');
}

function openDocQueues(id) {
		var opp = stWinOpen('./queues.htm', id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}

function openQuery(id) {
		var opp = stWinOpen(getMarketingRootUrl() + '/query/defs/details.htm', id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}
function openQueryDetails(id) {
		var opp = openDetails1(getDocumentsRootUrl() + '/query/details.htm', "QueryRef." + id, 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}


///////////////////////  Adam's functions

// function openInteractionNewByOpportunity(id) {
//     return openDetails2(getDocumentsRootUrl() + "/interaction/new_i.htm", "Interaction.new", // "Opportunity." + id);
// }

function openInteractionNewByContact(id) {
    return openDetails2(getDocumentsRootUrl() + "/interaction/new_i.htm", "Interaction.new", "Contact." + id);
}

function openInteractionNewByInteraction(id) {
    return openDetails1(getDocumentsRootUrl() + "/interaction/new_i.htm", "Interaction.new" + id);
}

function openCompany(id) {
    return openDetails1(getDocumentsRootUrl() + "/parent_company/details.htm", "OrganizationRef." + id);
}


function openActivityNewByOpportunity(id) {
    return openDetails2(getDocumentsRootUrl() + "/activity/new_i.htm", "Activity.new", "Opportunity." + id);
}
function openActivityNewByContact(id) {
    return openDetails2(getDocumentsRootUrl() + "/activity/new_i.htm", "Activity.new", "Contact." + id);
}

function openActivityNewByActivity(id) {
    return openDetails2(getDocumentsRootUrl() + "/activity/new_i.htm", "Activity.new", "Contact." + id);
}
function openActivityNew(contactUuid, parentUuid) {
    return openDetails2(getDocumentsRootUrl() + "/activity/new_i.htm", contactUuid, parentUuid, 600, 550);
}


function openOpportunityNewByAccount(accountid) {
    return openDetails2(getDocumentsRootUrl() + "/opportunity/new_i.htm", "Opportunity.new", "Account." + accountid);
}

// Pop-up screens for Marketing Administration Menus

function openLocations(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openSizes(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openFrequencies(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openMediaTypes(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openResponseMethods(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openCostTypes(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openPlacements(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=450,width=600,left=170,top=50');
}

function openPlacement(id) {
   openDetails1(getMarketingRootUrl() + '/placements/placements/details.htm', 'PlacementRef.' + id, 750,500);
}



function openDataDefaults(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openLeadTypes(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}

function openValidationLibrary(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=no,height=400,width=600,left=170,top=110');
}

function openValidationPreferences(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=no,height=450,width=600,left=170,top=50');
}

function openValidationDefaults(id) {
		var opp = stWinOpen('./details.htm', id,'resizable=yes,toolbar=no,scrollbars=yes,height=400,width=600,left=170,top=110');
}


////////////////////////////



// Print current page.
function printPage(text){
	text=document
	print(text)
}


// Checks to see if a checkbox is selected for a given form and checkbox field name
// If an alert message is passed, then the message is displayed if the checkbox is not selected
function isCheckboxSelected(formName, checkboxName, alertMessage) {
  // Make sure at least one document key is checked	
  for (var i = 0; i < document.forms[formName].elements.length; i++) {
	if (document.forms[formName].elements[i].name == checkboxName &&
		document.forms[formName].elements[i].checked == true) {
	  return true;
	}
  }

  if (alertMessage != null && alertMessage.length > 0) {
	alert(alertMessage);
  }
  return false;
}

function isMultipleCheckboxSelected(formName, checkboxName, alertMessage, minSelected) {
  // Make sure at least one document key is checked	
  var idx = 0;
  for (var i = 0; i < document.forms[formName].elements.length; i++) {
	if (document.forms[formName].elements[i].name == checkboxName &&
		document.forms[formName].elements[i].checked == true) {
          idx ++;
	  if (idx >= minSelected) {
             return true;
          }
	}
  }

  if (alertMessage != null && alertMessage.length > 0) {
	alert(alertMessage);
  }
  return false;
}


function fnToggleCheckboxes(formName) {
  var aform = document.forms[formName];
    var c;
    for(var i = 0; i < aform.elements.length; i++) {
        c = aform.elements[i];
        if (c.type == "checkbox") {
            if (!c.checked) {
                c.checked = true;
            }
            else {
                c.checked = false;
            }
        }
    }
}

function fnUnCheckAllCheckboxes(formName) {
  var aform = document.forms[formName];
    var c;
    for(var i = 0; i < aform.elements.length; i++) {
        c = aform.elements[i];
        if (c.type == "checkbox") {
            if (c.checked) {
                c.checked = false;
            }
        }
    }
}

function fnCheckAllCheckboxes(formName) {
  var aform = document.forms[formName];
    var c;
    for(var i = 0; i < aform.elements.length; i++) {
        c = aform.elements[i];
        if (c.type == "checkbox") {
	    c.checked = true;
        }
    }

}

// Submits the current open nodes
function fnSetCurrentOpenNodes(formName) {
  var nodeElement = indexOfEntries[0];
  var i = 1;
  var openNodes = "";
  while (nodeElement != null) {		
	if (i > 1 && nodeElement.isOpen != null && nodeElement.isOpen == true) {
	  if (openNodes == "") {
		openNodes = (i - 1);
	  } else {
		openNodes += "," + (i - 1);
	  }
	}
	nodeElement = indexOfEntries[i];
	i++;
  }
//  alert('here: ' + openNodes);
  document.forms[formName].elements["current_open_nodes"].value=openNodes;
}

function fnSubmitTreeMenu(currentLevel) {
  var formName = "menuInfo";
  fnSetCurrentOpenNodes(formName);
  if (currentLevel != null) {
	document.forms[formName].elements["load_level"].value=currentLevel;
  }
  document.forms[formName].submit();
}


function isBlankOrNull(value) {
	if (value == null || value == '') {
		return true;
	}
	return false;
}

function openDocumentForModify(oid) {
   var name  = oid.split(".");

   switch (name[0]) {
   case "RoutingTicket": openRoutingInfoModify(oid);
	break;
   case "Tasks": openActivityModify(name[1]);
	break;
   case "AutoCreateInquiryRef": openAutoCreateInquiryRef(name[1]);
	break;
   default: alert("openDocumentForModify : Document Not Supported! " + oid);  
   }
}

function openDocument(oid) {
   var name  = oid.split(".");

   switch (name[0]) {
   case "Account": openAccount(name[1]); 
	break;
   case "Case": openCase(name[1]); 
	break;
   case "Contact": openContact(name[1]);
	break;
   case "DocumentFolder": openDocumentFolder(name[1]);
	break;
   case "Inquiry": openInquiry(name[1]);
	break;
   case "Opportunity": openOpportunity(name[1]);
	break;
   case "RoutingTicket": openRoutingInfoModify(oid);
	break;
   case "EmployeeRef": openEmployee(name[1]);
	break;
   case "UserAccount": openEmployeeByUserAccount(name[1]);
	break;
   case "Tasks": openActivity(name[1]);
	break;
   case "Inquiry": openInquiry(name[1]);
	break;
   case "FormLetter": fnOpenRequestDetail(name[1]);
	break;	
   case "Order": fnOpenOrder(name[1]);
	break;		
   case "Quote": fnOpenQuote(name[1]);
	break;			
   case "AutoCreateInquiryRef": openAutoCreateInquiryRef(name[1]);
	break;
   case "OrganizationRef": openCompany(name[1]);
	break;
   default: //alert("openDocument() - Document type Not Supported! " + oid);
   }

}    




// New functions for security

function getAdminDocumentsRootUrl() {
  return getEcsRoot() + "/admin/documents";
}
function getAdminRootUrl() {
  return getEcsRoot() + "/admin";
}

function getSalesAdminRootUrl() {
  return getEcsRoot() + "/sales_admin";
}

function openEcsPermission(id) {
	openDetails1(getAdminDocumentsRootUrl() + "/permission/details.htm", "EcsPermission." + id, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

function openEcsPermissionNew() {
   var opp = stWinOpen(getAdminDocumentsRootUrl() + '/permission/new_i.htm', 'Permission_new', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}
    

function openEcsPrincipal(id) {
	openDetails1(getAdminDocumentsRootUrl() + "/securitygroup/details.htm", "EcsPrincipal." + id, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

function openEcsPrincipalNew() {
   var opp = stWinOpen(getAdminDocumentsRootUrl() + '/securitygroup/new_i.htm', 'Principal_new', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}
 

function openEcsProtectedUrl(id) {
	openDetails1(getAdminDocumentsRootUrl() + "/protectedurl/details.htm", "EcsProtectedUrl." + id, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

function openEcsProtectedUrlNew() {
   var opp = stWinOpen(getAdminDocumentsRootUrl() + '/protectedurl/new_i.htm', 'ProtectedUrl_new', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}


// Product Profile URLs    
function openPPProductCategoryRef1(oid) {
	openDetails1(getAdminRootUrl() + '/system/productcategories/details.htm', oid, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

function openPPProductCategoryRef(id) {
	openPPProductCategoryRef1("PPProductCategoryRef." + id);
}

function openPPProductCategoryRefNewByParent(parentOid) {
    return openDetails2(getAdminRootUrl() + '/system/productcategories/new_i.htm', "PPProductCategoryRef.new", parentOid);
}

function openPPProductCategoryRefNew() {
    return openDetails2(getAdminRootUrl() + '/system/productcategories/new_i.htm', "PPProductCategoryRef.new", "");
}

// Product Profile URLs    
function openPPMfgRef1(oid) {
	openDetails1(getAdminRootUrl() + '/system/manufacturers/details.htm', oid, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

function openPPMfgRef(id) {
	openPPMfgRef1("PPMfgRef." + id);
}

function openPPMfgRefNew() {
    return openDetails2(getAdminRootUrl() + '/system/manufacturers/new_i.htm', "PPMfgRef.new", "");
}


// Product Profile URLs    
function openPPProduct(oid) {
	openDetails1(getDocumentsRootUrl() + '/productprofile/details.htm', oid, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

function openPPProductNewByAccount(account_oid) {
    return openDetails2(getDocumentsRootUrl() + '/productprofile/new_i.htm', "", "Account." + account_oid);
}


// Analyses
function openRBAnalysisNew() {
    return openDetails2(getDocumentsRootUrl() + '/analysis/new_i.htm', "", "");
}

// Product Profile URLs    
function openRBAnalysis(oid) {
	openDetails1(getDocumentsRootUrl() + '/analysis/details.htm', oid, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
}

// Open a proxy dashboard with the calendar, etc.
function openDashboard(userAccountId) {
       	openDetails1(getDocumentsRootUrl() + "/dashboard/cal_day.htm", userAccountId, 780,600,20,20);
}

// Get the form elements as a CSV
function formEleValuesToCSV(form_name, ele_name) {
  var arrV = new Array();
  var ele = document.forms[form_name].elements[ele_name];

  if (ele == null) {
  } else if (ele.value != null) {
	  if ( ele.checked == true ) {
		  arrV[arrV.length] = ele.value;
	  }
  } else if (ele.length != null) {
     for (var i = 0; i < ele.length; i++) {
		 if ( ele[i].checked == true ) {
			 arrV[arrV.length] = ele[i].value;
		 }
     }
  } 
  return arrV.join(",");
}

// 
// Convert a  formname, and a checkbox form var into an array of the values
// Replaces "formEleValuesToCSV " above.  Essentially the same, but also returns null
// if no var is found.
// 
// a.  If there is no such form var, return null.
// b.  If there are one or more checkboxes, but none selected, return an empty array.
// c.  Otherwise, return an array of all the selected checkboxes.
// 
function fnCheckboxesToJSArray(formName, formVar) {
 var ele_array = document.forms[formName].elements[formVar];
 var key_array = new Array();
 if (ele_array == null) {
    return null;
 }

 if (ele_array.length == null) {
   var cb = ele_array;
   if (cb.checked) {
      key_array[key_array.length] = ele_array.value;
   }
 } else {
   for (var idx = 0; idx < ele_array.length; idx++) {
     var cb = ele_array[idx];
     if (cb.checked) {
       key_array[key_array.length] = cb.value;
     }
   }
 }
 return key_array;
}

function fnGoToOrganizationRefDetails(obj) {
}


  function openFolderContents(folderKey, documentTypeKey) {

	if ( documentTypeKey == 7000 ) {
		openDetails2(getListRootUrl() + "/accounts/folder_contents.htm",  "DocumentFolder." + folderKey, "DocumentFolder." + folderKey, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
	}
   
	if ( documentTypeKey == 7007 ) {
		openDetails2(getListRootUrl() + "/contacts/folder_contents.htm", "DocumentFolder." + folderKey,"DocumentFolder." + folderKey, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
	}

	if ( documentTypeKey == 6003 ) {
		openDetails2(getListRootUrl() +"/users/details.htm", "DocumentFolder." + folderKey,"DocumentFolder." + folderKey, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
	}	
          
  }

  function openFolderDocument(folderKey, documentTypeKey) {
	if ( documentTypeKey == 7000 ) {
		openDetails2(getListRootUrl() + "/accounts/details.htm",  "DocumentFolder." + folderKey, "DocumentFolder." + folderKey, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
	}
   
	if ( documentTypeKey == 7007 ) {
		openDetails2(getListRootUrl() + "/contacts/details.htm", "DocumentFolder." + folderKey,"DocumentFolder." + folderKey, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
	}

	if ( documentTypeKey == 6003 ) {
		openDetails2(getListRootUrl() +"/users/details.htm", "DocumentFolder." + folderKey,"DocumentFolder." + folderKey, 'resizable=yes,toolbar=no,scrollbars=yes,height=600,width=780,left=60,top=20');
	}	
          
  }


// 
// Format - dd-MMM-yyyy
// 

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");


function fnFormatDate(d, fmt) {
   var s = "N/A";
   if (d == null ) {
     return s;
   }
   
   if (fmt == null) {
     fmt = "HH:mm";
   } 

   var curr_date = d.getDate();
   var curr_month = d.getMonth();
   var curr_year = d.getFullYear();
   var dHr =  d.getHours();
   var dM = d.getMinutes();
   var sM;
   if (dM < 10) {
     sM = "0" + dM;
   } else {
     sM = "" + dM;
   }

   switch (fmt) {
   case 'HH:mm':  { 
      if (dHr == 0) {
         s = "12:" + sM + "a";
	} else       if (dHr > 12) {
         s = "" + (dHr - 12) + ":" + sM + "p";
      }  else {
         s = "" + (dHr ) + ":" + sM + "a";
      }
      break;
   }
   case 'dd-MMM-yyyy': {
      s = curr_date + "-" + m_names[curr_month].substr(0,3) + "-" + curr_year;   
      break;
   }
   }
   return "" + s;  
}
function startclock() {
	var thetime=new Date();
	var nhours=thetime.getHours();
	var nmins=thetime.getMinutes();
	var nsecn=thetime.getSeconds();
	var nday=thetime.getDay();
	var nmonth=thetime.getMonth();
	var ntoday=thetime.getDate();
	var nyear=thetime.getYear();
	var AorP=" ";
	var WelcomeText=" ";
	
	if (nhours>=12){
	    AorP="PM";
	    WelcomeText="Good Afternoon";
	} else {
	    AorP="AM";
	    WelcomeText="  Good Morning";
	}
	if (nhours>=18){
	    WelcomeText="  Good Evening";
	}
	if (nhours>=13)
	    nhours-=12;
	
	if (nhours==0)
	   nhours=12;
	
	if (nsecn<10)
	 nsecn="0"+nsecn;
	
	if (nmins<10)
	 nmins="0"+nmins;
	
	if (nday==0)
	  nday="Sun";
	if (nday==1)
	  nday="Mon";
	if (nday==2)
	  nday="Tue";
	if (nday==3)
	  nday="Wed";
	if (nday==4)
	  nday="Thu";
	if (nday==5)
	  nday="Fri";
	if (nday==6)
	  nday="Sat";
	
	nmonth+=1;
	
	if (nyear<=99)
	  nyear= "19"+nyear;
	
	if ((nyear>99) && (nyear<2000))
	 nyear+=1900;
	
	if (nmonth==1)
	  nmonth="Jan";
	if (nmonth==2)
	  nmonth="Feb";
	if (nmonth==3)
	  nmonth="Mar";
	if (nmonth==4)
	  nmonth="Apr";
	if (nmonth==5)
	  nmonth="May";
	if (nmonth==6)
	  nmonth="Jun";
	if (nmonth==7)
	  nmonth="Jul";
	if (nmonth==8)
	  nmonth="Aug";
	if (nmonth==9)
	  nmonth="Sep";
	if (nmonth==10)
	  nmonth="Oct";
	if (nmonth==11)
	  nmonth="Nov";
	if (nmonth==12)
	  nmonth="Dec";
	// document.clockform.clockspot.value=nhours+":"+nmins+" "+AorP+"  "+nday+",  "+ntoday+"-"+nmonth+"-"+nyear;
	document.forms[0].clockspot.value=nday+",  "+ntoday+"-"+nmonth+"-"+nyear+"   "+nhours+":"+nmins+" "+AorP;
//	document.forms[0].clockwelcome.value=WelcomeText + " ";
	setTimeout('startclock()',5000);
} 

function ecsSetTopTab(ecsTabRef) {
	if (null != parent.frames['frame_top']) {
		if (null != parent.frames['frame_top'].ecsUpdateTab) {
  			parent.frames['frame_top'].ecsUpdateTab(ecsTabRef);
  		}
  	}
  	if (null != parent.frames['frame_right']) {
  		parent.frames['frame_right'].focus();
  	}
}
function ecsDisableTab(ecsTabRef) {
	var ecsTabLink = 'tablink' + ecsTabRef;
	if (null != document.forms['form0']) {
		if (document.forms['form0'].elements[ecsTabLink] != null) {
			document.forms['form0'].elements[ecsTabLink].value = "disable";
		} else {
			alert("Warning - " + ecsTabLink + " does not exist as a tabset link form variable!");
		}
	}
}		

// always focus the window on running.
stWinFocus();

function openFulfillmentNew(contactOid, parentOid) {
	var sUrl = getDocumentsRootUrl() + "/fulfillment/new_i.htm?parent_oid=" + contactOid + "," + parentOid;
	var opp = stWinOpen(sUrl, 'FulfillmentNew', 'resizable=yes,toolbar=no,scrollbars=yes,height=500,width=720,left=40,top=40');
}	


function openContactInteractions(id) {
  var sUrl = getDocumentsRootUrl() + "/contact/interactions.htm?oid=" + id + "&parent_oid=" + id;
  var ri = stWinOpen(sUrl, 'cI', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=400,width=650,left=20,top=20');
}

function openContactActivities(id) {
  openDetails1(getDocumentsRootUrl() + "/contact/activities.htm", id, 620,450);
}

function openContactInbox(id) {
  openDetails1(getDocumentsRootUrl() + "/contact/activity.htm", id, 620,450);
}

function openContactOpportunities(id) {
  openDetails1(getDocumentsRootUrl() + "/contact/opportunities.htm", id, 620,450);
}

function openRoutingTicketNew(oid) {
	var sUrl;
	
	sUrl    = getDocumentsRootUrl() + "/routing_ticket/list.htm?oid=RoutingTicket.NEW&parent_oid=" + oid;
	var ri = stWinOpen(sUrl, 'RINew', 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=400,width=650,left=20,top=20');
}

function saveContactToFolder(ids) {
  var contactKey = ids.split(".");
  var sUrl = getListRootUrl() + "/contacts/save_to_folder.htm?contact_key=" + contactKey[1] + "&oid=" + ids;
  openPop( sUrl );
}


function saveAccountToFolder(ids) {
  var accountKey = ids.split(".");
  var sUrl = getListRootUrl() + "/accounts/save_to_folder.htm?account_key=" + accountKey[1] + "&oid=" + ids;
  openPop( sUrl );
}

function openCaseForContact(oid) {
  var sUrl = getDocumentsRootUrl() + "/cms/new_i.htm?oid=Case.NEW&parent_oid=" + oid;
  openPop( sUrl );
}

function openOpportunityForContact(oid) {
  var sUrl = getDocumentsRootUrl() + "/opportunity/new_i.htm?oid=Opportunity.NEW&parent_oid=" + oid;
  openPop( sUrl );
}

function openQuoteNewForContact(oid) {
 //http://localhost:8080/cons/pages/go.do?pageName=QuoteNew1.Page&actionCode=newData&contactUuid=Contact.19185599&uuid=Quote.new
//  var sUrl = getCieQuoteRootUrl() + "/pages/go.do?pageName=QuoteNew1.Page&actionCode=newData&contactUuid=" + oid + "&uuid=Quote.new"
  var sUrlArgs = "pageName=QuoteNew1.Page&actionCode=newData&contactUuid=" + oid + "&uuid=Quote.new"
  var sUrl = getDocumentsRootUrl() + "/download/goCie.htm?" + sUrlArgs;  
  
  openExternalUrl( sUrl );
}

/**
 *  Now, supports only inquiries - someday more types??? See QuoteNewAction.java in ciequote_admin
 */
function openQuoteNewForParent(oid) {
 //http://localhost:8080/cons/pages/go.do?pageName=QuoteNew1.Page&actionCode=newData&contactUuid=Contact.19185599&uuid=Quote.new
//  var sUrl = getCieQuoteRootUrl() + "/pages/go.do?pageName=QuoteNew1.Page&actionCode=newData&contactUuid=" + oid + "&uuid=Quote.new"
  var sUrlArgs = "pageName=QuoteNew1.Page&actionCode=newData&parentUuid=" + oid + "&uuid=Quote.new";
  var sUrl = getDocumentsRootUrl() + "/download/goCie.htm?" + sUrlArgs;  
  openExternalUrl( sUrl );
}


function openQuote(quoteKey) {
  var sUrl = getDocumentsRootUrl() + "/download/goCie.htm?uuid=Quote." + quoteKey;
//  alert('going ' + sUrl);
  openExternalUrl( sUrl);
}

function openOrder(orderKey) {
//  var sUrl = getCieQuoteRootUrl() + "/pages/go.do?pageName=OrderEdit.Page&uuid=Order." + orderKey;
  var sUrl = getDocumentsRootUrl() + "/download/goCie.htm?uuid=Order." + orderKey;
  openExternalUrl( sUrl);
}

function fnOpenOrder(orderKey) {
	openOrder(orderKey);
}

function fnOpenQuote(quoteKey) {
	openQuote(quoteKey);
}

function submitForm(evt) {
 //  alert("submitting form :" );
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = target.form;
    form.submit();
    return true;   
}

function submitViaEnter(evt) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = target.form;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);

    if (charCode == 13 || charCode == 3) {
      submitForm(evt);
    }
    return true;
}

function getNavSetContextWithOid(shref, tabid, histgroupid ) {
	var sep = "?";
	if (shref.indexOf("?") != -1) {
	  sep = "&";
	 }
	var is_Oid = getOid();
	// alert (is_Oid);
	if (is_Oid != "") {  // kw added to prevent empty Oid  30-Jul-08
		var goref = shref + sep + "oid=" + getOid() + '&NAV_SELECTED=' + tabid;
	} else {
		var goref = shref + sep + 'NAV_SELECTED=' + tabid;
	}
	// aad - 04-Jun-08 - added histgroupid to keep the pages together under one group. 
	// See STPageViewHistory for the 
	if (histgroupid != null) {
		goref += "&hgrp=" + histgroupid;
	}
	return goref;
}

function navSetContextWithOid( shref, tabid, histgroupid ) {
	var goref = getNavSetContextWithOid( shref, tabid, histgroupid );
	stWinLoc(goref);
}

function navSetContextWithParentOid( shref, tabid ) {
	var sep = "?";
	if (shref.indexOf("?") != -1) {
	  sep = "&";
	 }
	 
	var goref = shref + sep + "oid=" + getOid() + "parent_oid=" + getParentOid() + '&NAV_SELECTED=' + tabid;
	stWinLoc(goref);
}

function navSetContextWithParentOidOnly( shref, tabid ) {
	var sep = "?";
	if (shref.indexOf("?") != -1) {
	  sep = "&";
	 }
	 
	var goref = shref + sep +  "parent_oid=" + getParentOid() + '&NAV_SELECTED=' + tabid;
	alert(goref);
	stWinLoc(goref);
}

function navSetContext( shref, tabid ) {
	var sep = "?";
	if (shref.indexOf("?") != -1) {
	  sep = "&";
	 }
	 
	var goref = shref + sep +"NAV_SELECTED=" + tabid;			// changed 07/26/08 kw
	stWinLoc(goref);
}

function navSetContextSetOid( shref, tabid, oid ) {
	var goref = shref + "?oid=" + oid +"&TOPNAV_SELECTED=" + tabid;
	stWinLoc(goref);
}

function navSetContextSetParentOid( shref,  parentoid , tabid) {
	var goref = shref + "?parent_oid=" + parentoid +"&TOPNAV_SELECTED=" + tabid;
	stWinLoc(goref);
}
function navSetContextWithNoOid( shref, tabid ) {  // this function should only be used by TOPNAV
	// navSetContext(shref, tabid);			// changed 07/26/08 kw
	var sep = "?";
	if (shref.indexOf("?") != -1) {
	  sep = "&";
	 }
	 
	var goref = shref + sep +"TOPNAV_SELECTED=" + tabid + "&NAV_SELECTED=tab.home";
	stWinLoc(goref);
}

 function navSearch() {
    var bAccount = document.forms['quickSearchForm'].elements["topNavAccountName"].value != "";
    var bContact = document.forms['quickSearchForm'].elements["topNavLastName"].value != "" || document.forms['quickSearchForm'].elements["topNavFirstName"].value != "" ;
 	if ( bAccount || bContact)  {
 		
		if ( document.forms['quickSearchForm'].elements["topNavFirstName"].value != "" ) {
			document.forms['quickSearchForm'].elements["topNavFirstName"].value = document.forms['quickSearchForm'].elements["topNavFirstName"].value + "%";
		}
		
		if ( !bContact) {
			// IE6 admin_sales screens get error from here on.....
			// document.forms['form3'].elements["topNavAccountName"].value=document.forms['quickSearchForm'].elements["topNavAccountName"].value;
			// document.forms['form3'].submit();
			
			// somehow this fixes it..... but does not make sense!!!!!! IE is aweful
			document.forms[2].elements["topNavAccountName"].value=document.forms['quickSearchForm'].elements["topNavAccountName"].value;
			document.forms[2].submit();
		} else {
			if ( bContact && !bAccount ) {
 				// IE6 admin_sales screens get error from here on.....
				// document.forms['form2'].elements["topNavLastName"].value=document.forms['quickSearchForm'].elements["topNavLastName"].value;	
				// document.forms['form2'].elements["topNavFirstName"].value=document.forms['quickSearchForm'].elements["topNavFirstName"].value;
				// document.forms['form2'].submit();
				
 				// somehow this fixes it..... but does not make sense!!!!!! IE is aweful
				document.forms[1].elements["topNavLastName"].value=document.forms['quickSearchForm'].elements["topNavLastName"].value;	
				document.forms[1].elements["topNavFirstName"].value=document.forms['quickSearchForm'].elements["topNavFirstName"].value;
				document.forms[1].submit();
			} else {	
 				// IE6 admin_sales screens get error from here on.....
 				// statement: document.forms['form1'] ....returned object is null or does not exsist 
				// document.forms['form1'].elements["topNavAccountName"].value=document.forms['quickSearchForm'].elements["topNavAccountName"].value;
				// document.forms['form1'].elements["topNavLastName"].value=document.forms['quickSearchForm'].elements["topNavLastName"].value;	
				// document.forms['form1'].elements["topNavFirstName"].value=document.forms['quickSearchForm'].elements["topNavFirstName"].value;
				// document.forms['form1'].submit();
				
 				// somehow this fixes it..... but does not make sense!!!!!! IE is aweful
				document.forms[0].elements["topNavAccountName"].value=document.forms['quickSearchForm'].elements["topNavAccountName"].value;
				document.forms[0].elements["topNavLastName"].value=document.forms['quickSearchForm'].elements["topNavLastName"].value;	
				document.forms[0].elements["topNavFirstName"].value=document.forms['quickSearchForm'].elements["topNavFirstName"].value;
				document.forms[0].submit();
			}					
		} 
 	}
 }

 function navQuoteSearch() {
    var bAccount = document.forms['quickQuoteSearchForm'].elements["topNavFormQuoteAccountName"].value != "";
    var bQuoteKey = document.forms['quickQuoteSearchForm'].elements["topNavFormQuoteNumber"].value != "";

   if ( bAccount || bQuoteKey)  {
		if ( bQuoteKey) {
			document.forms['form44'].elements["QuoteKey"].value=document.forms['quickQuoteSearchForm'].elements["topNavFormQuoteNumber"].value;
			document.forms['form44'].submit();
		} else {
			if ( bAccount ) {
				document.forms['form44'].elements["AccountName"].value=document.forms['quickQuoteSearchForm'].elements["topNavFormQuoteAccountName"].value;
				document.forms['form44'].submit();
			} 					
		} 
 	}
 }

 function navOrderSearch() {
    var bAccount = document.forms['quickOrderSearchForm'].elements["topNavFormOrderAccountName"].value != "";
    var bOrderKey = document.forms['quickOrderSearchForm'].elements["topNavFormOrderNumber"].value != "";

   if ( bAccount || bOrderKey)  {
		if ( bOrderKey) {
			document.forms['form55'].elements["OrderKey"].value=document.forms['quickOrderSearchForm'].elements["topNavFormOrderNumber"].value;
			document.forms['form55'].submit();
		} else {
			if ( bAccount ) {
				document.forms['form55'].elements["AccountName"].value=document.forms['quickOrderSearchForm'].elements["topNavFormOrderAccountName"].value;
				document.forms['form55'].submit();
			} 					
		} 
 	}
 }


function fnGetSessionUrl(url_in) {
	
	// Session id is already in the url.
	if (url_in.indexOf("jsession" != -1)) {
		return url_in;
	}
	
	var arr = url_in.split("?");
	var url = url_in + SEMATREE_sessionId;
	if (arr.length == 1) {
		url = url_in + SEMATREE_sessionId;
	} else if (arr.length == 2) {
	 	url = arr[0] + SEMATREE_sessionId + "?" + arr[1];
	 }
	 return url;
}

//  function fnGetSessionUrl(url_in) {
// 	var arr = url_in.split("?");
// 	var url = url_in;
// 	var sName = fnGetSessionIdName();
// 	if ( url_in.indexOf( sName ) < 0 ) {
// 		url = url_in + SEMATREE_sessionId;
// 		if (arr.length == 1) {
// 			url = url_in + SEMATREE_sessionId;
// 		} else if (arr.length == 2) {
// 		 	url = arr[0] + SEMATREE_sessionId + "?" + arr[1];
// 		 }
//	}
//	 return url;
//  }


function stWinLoc(url_in) {
	var url = fnGetSessionUrl(url_in);
	window.location.href = url;
}

// Open Parent functions
function openContactParent(id) {	
  openDetails1Parent(getDocumentsRootUrl() + "/contact/details.htm", "Contact." + id, 780,600);
}

function openAccountParent(id) {	
  openDetails1Parent(getDocumentsRootUrl() + "/account/details.htm", "Account." + id, 780,600);
}

function openDetails1Parent(sUrlBase, oid, winWidth, winHeight, winLeft, winTop) { 
  openDetails2Parent(sUrlBase, oid, undefined, winWidth, winHeight, winLeft, winTop);
}

function openDetails2Parent(sUrlBase, oid, parent_oid, winWidth_in, winHeight_in, winLeft_in, winTop_in) {
	var winWidth = 500;
	var winHeight = 500;
	var winLeft = 20;
	var winTop = 20;
	if ("" + winHeight_in != "undefined") {
	    winWidth = winWidth_in;
	    winHeight = winHeight_in;
	    winLeft = winLeft_in;
	    winTop = winTop_in;
        }

	
	var url = fnGetUrl(sUrlBase, oid, parent_oid, "NAV_SELECTED=tab.home", false);
	var win = fnGetWinName(sUrlBase, oid, parent_oid);
  
//	var opp = stWinOpen(url, win, 'resizable=yes,toolbar=no,scrollbars=yes,status=yes,height=' + winHeight + ',width=' + winWidth + ',850,left=20,top=40');
	parent.document.location=url;
}


// always focus the window on running.
stWinFocus();
 
// Calendar JavaScript
	function fnDateChanged(calendar, date) {
		var inputField = fnGetDateInputField();
		var dest = document.getElementById(inputField);
		if ( calendar.dateClicked ) {
			dest.value = date;
			calendar.callCloseHandler();
		}
	}
	
	function fnCloseCalendar(calendar) {
		calendar.hide();
	}
	
	function fnOpenCalendar(inputField, id) {
		var cal = new Calendar(0, new Date(), fnDateChanged, fnCloseCalendar);
		fnSetDateInputField(inputField);
		cal.create();
		cal.setDateFormat( fnGetCalendarDateFormat() );
		cal.showAtElement(document.getElementById(id));
	}

	function fnOpenCalendarDateTime(inputField, id) {
		var cal = new Calendar(0, new Date(), fnDateChanged, fnCloseCalendar);
		fnSetDateInputField(inputField);
		cal.showsTime = true;
		cal.create();
		cal.setDateFormat( fnGetCalendarDateTimeFormat() );
		cal.showAtElement(document.getElementById(id));
	}
 function previousPg(pgs){
 history.go(pgs)
 }

// Open an external url in a new window.
//
function openExternalUrl(url, winName) {

	var root = getEcsRoot();
	if (url.indexOf(root) == 0) {
		// Do nothing.
    } else if (url.indexOf('http://') != 0 && url.indexOf("/" != 0)) {
       url = "http://" + url;
    }
//  ie doesn;t like commas in winname,so ripped win name
    //   alert('in openExternalUrl ' + url);
	window.open(url);
}


// Pops a new window, (or tab)
// Used for downloading files.
//
function downloadFile(url) {

	var root = getContextRoot();
	if (url.indexOf(root) == 0) {
		// Do nothing.
    } else if (url.indexOf('http://') != 0 && url.indexOf("/" != 0)) {
       url = "http://" + url;
    }
//  ie doesn;t like commas in winname,so ripped win name
    //   alert('in openExternalUrl ' + url);
	window.open(url);
}

