

// VERSION_XX

var theLaunchedWindow;

//the 2 vars below are required because of strange boolean interpretation errors on br-pt systems
var verdadeiro = true;
var falso = false;

var OnEnterDelegate = "";
function captureEnter(enterEvent)
{    
	if (enterEvent.keyCode == 13 || enterEvent.which == 13)
	{
	    if(OnEnterDelegate.length > 0)
	    {
	        var ClickedObj = document.getElementById(unescape(OnEnterDelegate));
	        ClickedObj.click();		    
		}

		return false; // return false so the screen doesn't do anything
	}
	return true;
}		
		
function getXMLValue(xml,node)
{
	//sampel: <Email>nathanj@infograph.com</Email>
	//sample: <Company>IGC</Company><UserID></UserID><Email>nathanj@infograph.com</Email>
	nodeStartElem = "\x3C" + node + "\x3E"
	nodeEndElem = "\x3C/" + node + "\x3E"
	nodeStartLen = nodeStartElem.length //add length for start and end
	nodeStartPos = xml.indexOf(nodeStartElem)
	
	if(nodeStartPos > -1){
		nodeStartPos += nodeStartLen
		nodeEndPos = xml.indexOf(nodeEndElem)	
		if(nodeEndPos > -1){
			return xml.substring(nodeStartPos,nodeEndPos)
		}else{return ""}
	}else{return ""}
}
// gives indexOf functionality to an array
function ArrayIndexOf(v,n)
{
  n = (n==null)?0:n; 
  var m = this.length;
  for(var i = n; i < m; i++)
  {
    if(this[i] == v)
       return i;
  }     
  return -1;
}

function globalTrimString(str, trimChar)
{
    if(!trimChar)
        trimChar = "\\s"; // escaped space 
 
 	var RegExpStart = "/^" + trimChar + "+/g";   
	var RegExpEnd = "/" + trimChar + "+$/g";   
	 
    return str.replace(eval(RegExpStart),'').replace(eval(RegExpEnd),'');
	
	// return str.replace(/^\s+/g,'').replace(/\s+$/g,'');   
}

function bustFrames() 
{
	if (top.location.href != self.location.href)
		top.location.href=self.location.href	
}
function showOrHideDiv(the_div,showDiv,divType)
{
	var the_style = document.getElementById(the_div).style;
	if(showDiv) //show
		the_style.display=divType;
	else //hide
		the_style.display="none";	
}
function getCookie(name)
{
	var dcookie = document.cookie; 
	var cname = name + "=";
	var clen = dcookie.length;
	var cbegin = 0;
	while (cbegin < clen) 
	{
		var vbegin = cbegin + cname.length;
	    if (dcookie.substring(cbegin, vbegin) == cname)
	    { 
			var vend = dcookie.indexOf (";", vbegin);
	        if (vend == -1) vend = clen;
				return unescape(dcookie.substring(vbegin, vend));
	    }
	    cbegin = dcookie.indexOf(" ", cbegin) + 1;
	    if (cbegin == 0) 
	        break;
	}
	return null;
}
function setCookie(cName, cVal)
{
	var exp = new Date();// set up cookie expiration
	var oneYearFromNow = exp.getTime() + (365*24*60*60*1000);
	exp.setTime(oneYearFromNow);
    var cookie_date = exp.toGMTString();
	document.cookie = cName + "=" + cVal + ";expires=" + cookie_date;
}
function deleteCookie(cName)
{
	document.cookie = cName + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getLastSegment(str,delimiter)
{
	delimPos = str.lastIndexOf(delimiter)
	return str.substring(0,delimPos)
}

//Alert: This method will open a new window every time!
//function launchWindow(url,width,height)
//{
  
//   if(width == 0)
//		width = screen.availWidth
	
//	if(height == 0)
//		height = screen.availheight
	
//	theLaunchedWindow = window.open(url.replace(/#/g,"%23"),"","scrollbars,resizable,status=0,width=" + width + ",height=" + height);

//}

function randomString() 
{
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var rString = '';
	
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		rString += chars.substring(rnum,rnum+1);
	}
	
	return rString;
}


function launchWindow(url,width,height,windowname)
{   
   if(!windowname)
   {      
     //will allow each window to pop a new window.
     windowname = randomString();     
   }
   
   if(!width)
		width = screen.availWidth;
	
    if(!height)
		height = screen.availheight;
		
	theLaunchedWindow = window.open(url.replace(/#/g,"%23"),windowname,"scrollbars,resizable,status=0,width=" + width + ",height=" + height);
}
		
function containsInvalidChars(str)
{
	var badChars = /[\\\/:*?"<>|]/
	if(badChars.test(str))
	{
		return true;
	}
	else
	{
		return false;
	}
}
function remoteCall(url,async,returnPage)
{
	var httpRequest;
	try
	{
		httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); //1st choice
	}
	catch(e)
	{
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); //2nd (and last) choice
	}
			
	httpRequest.open("GET",url,async); //3rd param designates whether this is an asynchronous http call
	httpRequest.send();
	if(!async && returnPage)
		return httpRequest.responseText;
	else
	    return ""
	    
	httpRequest = null;
}

function remotePost(url,async,returnPage,postData)
{
	var httpRequest;
	try
	{
		httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); //1st choice
	}
	catch(e)
	{
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); //2nd (and last) choice
	}
			
	httpRequest.open("POST",url,async); //3rd param designates whether this is an asynchronous http call
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader("Content-length", postData.length);
    httpRequest.setRequestHeader("Connection", "close");
	try
	{
		httpRequest.send(postData);
	}
	catch(e)
	{
		//do nothing
	}

	if(!async && returnPage)
		return httpRequest.responseText;
	else
	    return ""
	    
	httpRequest = null;
}

function containsDBCS(str)
{
    for(i=0;i<str.length;i++)
    {
        if(str.charCodeAt(i) > 255)
        {
	        return true;
        }
    }
    return false;
}

// START - Loading spinner javascripts
function showPleaseWait(left, top)
{
	if(document.getElementById("DIVPleaseWait"))
	{
		document.getElementById("DIVPleaseWait").style.display = "";
		if(left)
		    document.getElementById("DIVPleaseWait").style.posLeft = left;
		if(top)    
		    document.getElementById("DIVPleaseWait").style.posTop = top;
		document.getElementById("DIVPleaseWait").style.position = "absolute";
	}
}

function hidePleaseWait()
{
	if(document.getElementById("DIVPleaseWait"))
	{
		document.getElementById("DIVPleaseWait").style.display = "none"
	}
}

function StartSpinner(btnName, clientFunction)
{
    if(btnName.length > 0)
    {
        if(document.getElementById(btnName))
        {
            document.getElementById(btnName).onmouseover="";
	        document.getElementById(btnName).onmouseout="";
	        document.getElementById(btnName).className='button-dead';
	        if(document.getElementById(btnName + 'Spinner'))
	        {
	            document.getElementById(btnName + 'Spinner').style.display='';
	        }
	    }
	}
	
	var fx = unescape(clientFunction);
	var returnVal = null;
	
	// this function always returns false so make sure we return false below
	if(fx.toLowerCase().indexOf("return false") != -1)
	{
        fx = fx.replace(/return false;/i, "");
        fx = fx.replace(/return false/i, "");
	    returnVal = false;
	}
	else if(fx.toLowerCase().indexOf("return true") != -1)
	{
        fx = fx.replace(/return true;/i, "");
        fx = fx.replace(/return true/i, "");
	    returnVal = true;
	}
	
	fx = fx.replace(/return;/i, ""); // remove any returns so we don't error on the eval()
	fx = fx.replace(/return/i, "");
	
	if(returnVal == null) // no return, must get return from fx return
	{
	    returnVal = eval(fx);
	}
	else
	{
	    eval(fx);	    
	}
	
	if(!returnVal && btnName.length > 0) // function didn't pass/don't go anywhere
	{
	    if(document.getElementById(btnName))
	    {
	        // set back to the standard settings
	        document.getElementById(btnName).onmouseover="this.className='button-over';"
	        document.getElementById(btnName).onmouseout="this.className='button';"
	        document.getElementById(btnName).className='button';
	        if(document.getElementById(btnName + 'Spinner'))
	        {
	            document.getElementById(btnName + 'Spinner').style.display='none';	    
	        }
	    }
	}
	return returnVal;
	
}
// END - Loading spinner javascripts





// START - component art JS add ons

// variables for client side templates
var loadingTemplateText = 'Loading...';
var sliderTemplateText1 = 'Page ';
var sliderTemplateText2 = ' of ';    
        
var treeNodesTreeView; // global reference to the current TreeView

// event called when a tree node is collapsed
function TreeView_onNodeCollapse(sender, eventArgs, alwaysAddSub, IsDefaultFolder, sessionID)
{   
    var selectedNode = eventArgs.get_node();
    
    // make async call to update that this folder has been opened/closed
    var url = "Integration/WebSvcAPI/Utility.asmx/TrackUserFolderStatus?SessionID=" + sessionID + "&FolderID=" + selectedNode.getProperty("nodeID") + "&IsOpen=false&IsDefaultFolder=" + IsDefaultFolder;
        
    remoteCall(url, true, "");
}

// event called when a tree node is expanded
function TreeView_onNodeExpand(sender, eventArgs, alwaysAddSub, IsDefaultFolder, sessionID, delegateFunc)
{   
    var selectedNode = eventArgs.get_node();

    // make sure it hasn't already been opened and that it is not the root
    if(selectedNode.getProperty("opened") != "true" && selectedNode.ID != "Node_0") 
    {
        treeNodesTreeView.beginUpdate();   
        
        removeDeadNodes(selectedNode); // kill all the dead nodes in the node we are going to add the child nodes
        
        buildTreeViewNodes(selectedNode, false, alwaysAddSub, delegateFunc);
        
        treeNodesTreeView.endUpdate();
        
        var nodeID = selectedNode.getProperty("nodeID");
        
        //if(folderHasChildren(nodeID)) // only keep track of folders that have children
        //{
        
            // make async call to update that this folder has been opened/closed
            var url = "Integration/WebSvcAPI/Utility.asmx/TrackUserFolderStatus?SessionID=" + sessionID + "&FolderID=" + selectedNode.getProperty("nodeID") + "&IsOpen=true&IsDefaultFolder=" + IsDefaultFolder;
            remoteCall(url, true, "");
        //}
    }
}

function removeDeadNodes(selectedNode)
{
    var i;
    // loop through and kill any "dead" nodes
    var children = selectedNode.get_nodes();
    
    for (i=0; i<children.get_length(); i++)
    {
        if(children.getNode(i).getProperty("dead")) // dead child node
        {
            children.getNode(i).remove();
        }
    }
}

// on init load up the first level deep of nodes
function initTreeView(treeView, alwaysAddSub, delegateFunc)
{
    treeNodesTreeView = treeView; // make global ref to the treeview
    
    showPleaseWait();
    
    treeNodesTreeView.beginUpdate();
    
    // load up the root nodes to begin with
    buildTreeViewNodes(treeNodesTreeView.findNodeById("Node_0"), true, alwaysAddSub, delegateFunc);
    
    treeNodesTreeView.endUpdate();
    
    hidePleaseWait();
}    

// builds one level deep of nodes in a tree with the specified selectedNode. The data is taken from the data previously loaded into the client hash tables from the server.
function buildTreeViewNodes(selectedNode, isRoot, alwaysAddSub, delegateFunc)
{
    if(isRoot)
        parentNodeID = 0; // root node should always have a zero parentNodeID
    else    
        parentNodeID = selectedNode.getProperty("nodeID");
        
  
// alert("selectedNode = " + selectedNode + ",   parentNodeID = " + parentNodeID + ", hashFolderIDs[parentNodeID]= " + hashFolderIDs[parentNodeID]);
    
    
    if((hashFolderIDs[parentNodeID] && hashFolderNames[parentNodeID]) || hashFileNames[parentNodeID])
    { 
        removeDeadNodes(selectedNode);         
   
        selectedNode.setProperty("opened", "true"); // build out the selected node
    }    
    
    if(hashFolderIDs[parentNodeID] && hashFolderNames[parentNodeID])    
    {
        var arrIDs = hashFolderIDs[parentNodeID].split("|"); // get the children IDs
        var arrNames = hashFolderNames[parentNodeID].split("|"); // get the children node HTML
        var i, nodeID;
        var newNode, deadNode, delegateFuncExec;
               
        for(i=0; i<arrIDs.length; i++)
        {
            nodeID = arrIDs[i];
            newNode = new ComponentArt.Web.UI.TreeViewNode();          
            newNode.set_text(arrNames[i]);
            newNode.set_id("Node_" + nodeID); 
            newNode.setProperty("nodeID", nodeID);
            newNode.setProperty("opened", "false");              
            selectedNode.get_nodes().add(newNode);    
                       
             // we need a dead node so that a "+" shows up next to the folders - only if the node has children or if it is specified to ALWAYS have one
            if(folderHasChildren(nodeID) || alwaysAddSub || hashFileNames[nodeID])
            {
                deadNode = new ComponentArt.Web.UI.TreeViewNode(); 
                deadNode.setProperty("dead", "true");
                deadNode.setProperty("ImageUrl", "spinner.gif");                
                newNode.get_nodes().add(deadNode);                 
            }
        }

        if(delegateFunc.length > 0) // execute the delegate on the current node
        {
            delegateFuncExec = delegateFunc.replace("[ID]", parentNodeID);
            delegateFuncExec = delegateFuncExec.replace("[SELECTED_NODE]", "selectedNode");

            eval(delegateFuncExec);            
        }
    }
    
    if(hashFileNames[parentNodeID])
    {        
        var arrFiles = hashFileNames[parentNodeID].split("|"); // get the files
        
        for(i=0; i<arrFiles.length; i++)
        {
            newNode = new ComponentArt.Web.UI.TreeViewNode();          
            newNode.set_text(arrFiles[i]);
            newNode.set_imageUrl("spacer.gif");
            newNode.set_imageWidth(1);
            newNode.set_imageHeight(1);
            //newNode.set_id("Node_" + nodeID); 
            //newNode.setProperty("nodeID", nodeID);
            //newNode.setProperty("opened", "false");              
            selectedNode.get_nodes().add(newNode);
        }
    }
    
    // in the case where we are at the root and there are no nodes at all, add a single "create new" node so you can start adding nodes
    if(delegateFunc.length > 0)
    {
        if(isRoot && !hashFolderIDs[parentNodeID])
        {
            delegateFuncExec = delegateFunc.replace("[ID]", parentNodeID);
            delegateFuncExec = delegateFuncExec.replace("[SELECTED_NODE]", "selectedNode");

            eval(delegateFuncExec);
        }
    }
    
}


function folderHasChildren(nodeID)
{
    if(hashFolderIDs[nodeID])
        return true;
    else
        return false;
}        

// opens up all folders that have been previously loaded into the clientside tree
function ExpandFolders()
{
    var deleg = "expandOpenedTreeNodes([PARENT_ID])";
    var i;
    var arrIDs = hashFolderIDs[0].split("|");

    treeNodesTreeView.beginUpdate();
    
    for(i=0; i<arrIDs.length; i++)
        recurseTreeNodesChildren(deleg, arrIDs[i], treeNodesTreeView);
        
    treeNodesTreeView.endUpdate();		   
}

// collapses all the folders and the re-opens the root element so that all the first level folders are displayed
function CollapseFolders()
{
    treeNodesTreeView.collapseAll();
    
    // open up the root
    var selectedNode = treeNodesTreeView.findNodeById("Node_0");
    selectedNode.set_expanded(true);
}

// expands tree nodes that have already been loaded into the tree
function expandOpenedTreeNodes(nodeID)
{
    var selectedNode = treeNodesTreeView.findNodeById("Node_" + nodeID);
    // only expand a node if it has been previously opened   
    if(selectedNode.getProperty("opened"))
    {
        //selectedNode.expand();
        selectedNode.set_expanded(true);           
    }
}


// loads up a tree's nodes with previously opened node ids
var arrNodeSequenceToLoad; // array used to hold the sequence of nodes that have to be loaded to get to the target node
var arrNodesPreviousBuilt = new Array(); // array used to hold nodes that have already been built so we don't keep building them

function preLoadTree(arrNodeIDsToLoad, alwaysAddSub, delegateFunc)
{   
   treeNodesTreeView.beginUpdate();
   
    if(arrNodeIDsToLoad.length > 0)
    {
        showPleaseWait();
        
        var i, j, selectedNode;       
       
        for(i=0; i<arrNodeIDsToLoad.length; i++)
        {
            arrNodeSequenceToLoad = new Array(); // create a new array to hold the parent sequence
            findFirstLevelNodeID(arrNodeIDsToLoad[i]); // get all the parents of the child until we get to the root node (Node_0)
        
            for(j=arrNodeSequenceToLoad.length-1; j>=0; j -= 1) // we have to go backwards to load from the parent down to the child
            {
                selectedNode = treeNodesTreeView.findNodeById("Node_" + arrNodeSequenceToLoad[j]);

                // build out the selected node
                if(selectedNode && ArrayIndexOf(arrNodesPreviousBuilt, arrNodeSequenceToLoad[j]) < 0)
                { 
                   if(selectedNode.getProperty("opened") != "true") 
                   {
                        buildTreeViewNodes(selectedNode, false, alwaysAddSub, delegateFunc); // build out the node in memory

                        if(folderHasChildren(arrNodeSequenceToLoad[j])) // only open the node if it has valid children nodes
                            expandOpenedTreeNodes(arrNodeSequenceToLoad[j]); // expand the node that was just built
                    }        
                }
                
                arrNodesPreviousBuilt[arrNodesPreviousBuilt.length]=arrNodeSequenceToLoad[j]; // track this node so we don't try to build again
            }
        }
    
       hidePleaseWait();
    }
    
    treeNodesTreeView.endUpdate();
}    

// find a first level node (node whose parent is Node_0) so we can build out the node from there
function findFirstLevelNodeID(childNodeID)
{    
    var parentID = hashChildParent[childNodeID];           

    if(childNodeID != 0 && childNodeID == parseInt(childNodeID)) // make sure we don't have a root for a parent (hashChildParent[childNodeID] == 0)
    {       
        arrNodeSequenceToLoad[arrNodeSequenceToLoad.length] = childNodeID; // track the child ID in the sequence       
        findFirstLevelNodeID(parentID); // get the parent of the parent  
    }
}

// recursively walks a treeview and calls a delegate function on each node that is found 
function recurseTreeNodesChildren(delegateFunc, parentID, treeView)
{
    if(treeView)
        treeNodesTreeView = treeView;

    var selectedNode = treeNodesTreeView.findNodeById("Node_" + parentID);
    var ID, i, delegateFuncExec;
    var children = selectedNode.get_nodes();
            
    for (i=0; i<children.get_length(); i++)
    {
        if(children.getNode(i).ID.indexOf("Node_") >= 0)
        {
            ID = children.getNode(i).ID.replace("Node_", "");

            // create the actual delegate defintion            
            if(delegateFunc.length > 0)
            {
                delegateFuncExec = delegateFunc.replace("[ID]", ID);
                delegateFuncExec = delegateFuncExec.replace("[PARENT_ID]", parentID);
                eval(delegateFuncExec); //execute the delegate
            }
            
            // recurse on childrend nodes
            recurseTreeNodesChildren(delegateFunc, ID);          
        }
    }
}

// END - component art JS add ons



// START - thumbnail bg color function and tracking

var lastCellID = "";	
var BGSelected = "#ffd76b"; // selected item color
var BGDefault = "#e9e9ee"; // default item color
var BGCheckedOut = "#cc0033"; // checked out item color
function cellBGColor(id, color, isCheckedOut) 
{
    //change cell bgcolor to highlight clicked thumbnail or link
    if(document.getElementById(id))
    {
        if(lastCellID != id)
        {
		    swapBGColor(id, color);
			
		    lastCellID = id; // remember the last one that was swapped
			
		    if(isCheckedOut)
		        lastCellIDCheckedOut = true;
		    else
		        lastCellIDCheckedOut = false;				    
		}    
	}
}


function swapBGColor(id, color)
{
    if(document.getElementById(id))
    {
		document.getElementById(id).style.backgroundColor = color;
		
		if(lastCellID != "") //change previously highlighted cell bgcolor back to default
		{				        
		   document.getElementById(lastCellID).style.backgroundColor = eval("typeof(" + lastCellID + "CheckedOut)") == "undefined" ? BGDefault : BGCheckedOut;					    
		}
	}	
}

function trim(inputString) 
{
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

// END - thumbnail bg color function and tracking
//-->
