/*********************************************

		<HELP id='thirdHelp' title='Third help' left='490' top='420' width='150' height='120' group='sampleTopics' maxDisplay='3'>
			This is the third help window
			<p><a href='#' onclick='parent.helpWindow.showNode("secondHelp")'>Previous</a></p>
		</HELP>



/**********************************************/



var helpWindow = {
	
		"allowCommonPopups" : null,
		"allowTourPopups" : null,
		"backgroundDiv" : null,
		"contentsDiv" : null,
		"popupWin" : null,  							// reference to the div containing the popup
		"disabled" : false,
		"doc" : null,
		"exitPopupOnBlur" : true,
		"height"  : 200,
    "isTourInProgress" : false,
		"nextto"	: null,
    "resize"	: true,
    "titleDiv" : null,
    "usageName"	 : new Array(),
    "usageCount" : new Array(),
    "width" : 300,
	
		"addHelp" : function (xmlNode) {
    	if (!helpWindow.popup) helpWindow.createWindow();
			var topNode = mainWindow.helpBoxes.selectSingleNode("HELPS");
			var newNodes = xmlNode.selectNodes("HELPS/*");
			for (var nn=0; nn<newNodes.length; nn++)
			{
				var oldNode = topNode.selectSingleNode("*[@id=\"" + newNodes[nn].getAttribute("id") + "\"]");
				if (oldNode) topNode.replaceChild(newNodes[nn].cloneNode(true), oldNode);
				else topNode.appendChild(newNodes[nn].cloneNode(true));
			}
		},

		"checkAllowCommon" : function() {
			if (!helpWindow.allowCommonPopups) 
			{
				var val = mainWindow.agt.preference(".//POPUPHELP/@showcommon");
				if (val) helpWindow.allowCommonPopups = (val.toLowerCase()=="true") ? true : false;
				else helpWindow.allowCommonPopups = true;				
			}
			return helpWindow.allowCommonPopups;
		},

		"checkAllowTour" : function() {			
			if (!helpWindow.allowTourPopups) 
			{
				var val = mainWindow.agt.preference(".//POPUPHELP/@showtour");
				if (val) helpWindow.allowTourPopups = (val.toLowerCase()=="true") ? true : false;
				else helpWindow.allowTourPopups = true;				
			}
			return helpWindow.allowTourPopups;			
		},
		
		/*************************************************************************************
		*    Possible results includ:
		*				 'yes' - I have already seend it
		*        'no'  - I said I didn't want to see it
		*        'ask' - either I've never had the option to see it or I said ask me later
		*************************************************************************************/
		"checkAllowStartupTour" : function(tourName) {

			var val = mainWindow.agt.preference(".//POPUPHELP/TOUR[@name='" + tourName + "']/@viewed");
			if (val=="" || val=="later") val = true;
			else val = false;
			return val;
		},
		


		"createWindow" : function() {

			if (!helpWindow.popupWin)
			{
				var txt = 
					'	<DIV class=rib-t>' +
					'		<DIV class=rib-b>' +
					'			<DIV class=rib-l>' +
					'				<DIV class=rib-r>' +
					'					<DIV class=rib-bl>' +
					'						<DIV class=rib-br>' +
					'							<DIV class=rib-tl>' +
					'								<DIV class=rib-tr>' +
					'									<DIV class="rpbtabbedmenu" id=helpWindowTitle style="width:99%;">' +
					'										<DIV class=xxpodtitledivbox id=savedsearches_titlebox ownerid="savedsearches">' +
					'											<SPAN class=podtitletext id=helpWindowTitleText>Title Text</SPAN>' +
					'											<SPAN class=podtitlebuttons>' +
					'												<A class=podclose title="Close Pod" href="#" onclick="helpWindow.hide()"></A>' +
					'											</SPAN>' +
					'											<SPAN style="CLEAR: both"></SPAN>' +
					'										</DIV>' +
					'									</DIV>' +
					'									<DIV class=podcontents id=helpWindowContents>Window Contents<br/></DIV>' +
					'								</DIV>' +
					'							</DIV>' +
					'						</DIV>' +
					'					</DIV>' +
					'				</DIV>' +
					'			</DIV>' +
					'		</DIV>' +
					'	</DIV>' +
					' <div id="arrowholder" style="left:90px; bottom: -29px;"></div>' ;
	

	
				//Create a container div 
				helpWindow.popupWin = helpWindow.popup.document = 
								new Element('div', { 'id':'helpinfopod', 'class':'infopod' })
								            .setStyles({'position': 'absolute'}).inject($(document.body));

				helpWindow.popupWin.innerHTML = txt;	

				// Create a background div that covers the entire page.  If the user 
				// clicks on this div then popup will close.  
				helpWindow.backgroundDiv = 
				        new Element('div', {'id':'helpinfoback', 'class':'infopodback',
				        						events: { 'click': function() { helpWindow.popup.hide(); } } })
				        						.setStyle('display', 'none')
				        						.inject($(document.body));


				//txt = "<div id='helpWindowTitleText'>Title text</div><br/><div id='helpWindowContents'>Contents</div>"
				//helpWindow.doc.body.innerHTML = txt;
				helpWindow.contentsDiv = $(helpWindow.popupWin.getElementById("helpWindowContents"));
				helpWindow.titleDiv = $(helpWindow.popupWin.getElementById("helpWindowTitleText"));
			}
		},

		"doTour_setPreference": function (tourName, view) {

			mainWindow.prefTools.init(top._agt.preferences, false);
			
			var pNode = top._agt.preferences;
			var phNode = pNode.selectSingleNode("POPUPHELP");
			if (!phNode) phNode = pNode.appendChild(pNode.ownerDocument.createNode(1, "POPUPHELP", pNode.namespaceURI));
			var tNode = phNode.selectSingleNode("TOUR[@name='" + tourName + "']");
			if (!tNode) 
			{ 
				tNode = phNode.appendChild(phNode.ownerDocument.createNode(1, "TOUR", pNode.namespaceURI));
				tNode.setAttribute("name", tourName);
			}
			tNode.setAttribute("viewed", view);
			
			mainWindow.prefTools.postData.postToHost();			
		},

		"doTour_Later": function(tourName) {
			helpWindow.doTour_setPreference(tourName, "later");				
			
			helpWindow.isTourInProgress = false;
			helpWindow.showNode('replaytour');
		},

		"doTour_No": function(tourName) {
			helpWindow.doTour_setPreference(tourName, "no");
			
			helpWindow.isTourInProgress = false;
			helpWindow.showNode('replaytour');
		},

		"doTour_Yes": function(tourName, stopIndex) {
			helpWindow.doTour_setPreference(tourName, "yes");
			helpWindow.tourStop(tourName, stopIndex);
		},

		"executeActions" : function (objNode, action, showError) {
			
			var actNodes = objNode.selectNodes("ACTION[@event='" + action + "']");
			for (var i=0; i<actNodes.length; i++)
			{
				try
				{
					eval(actNodes[i].text);
				}
				catch(e)
				{
					if (showError) alert(e);
				}
			}						
		},
		
		"hide": function() {
			if (helpWindow.popup) helpWindow.popup.hide();
			helpWindow.isTourInProgress = false;
		},

    "replaceTags" : function (str) {
   
      // If there aren't any tags, exit the function 
      if (str.test("{{")== false) return str; 

      // Check for login data tags
      if (str.test("{{logindata")==true)
      {
        if (podTools.loginDataXML == null) alert("You are trying to include logindata tags but have set podTools.loginDataXML to the login XML structure.")
        else {
          var cnt = true;
          while (cnt==true) {
            var match = str.match(/{{logindata\((\w+)\)}}/);
            if (match) {
            	if (match[1].toLowerCase() == 'password')
            	{
            		str = str.replace(match[0], mainWindow.agt.password);
            	}
            	else
            	{
	              var valNode = podTools.loginDataXML.selectSingleNode("//" + match[1]);
	              if (valNode) str = str.replace(match[0], valNode.text);
	              else str = str.replace(match[0], match[1] + " not found");
              }
            }
            else
              cnt=false;
          }
        }
      }

      // Check for object source tags (like agent photo)
      if (str.test("{{objsrc")==true)
      {
        if (podTools.loginDataXML == null) alert("You are trying to include logindata tags but have set podTools.loginDataXML to the login XML structure.")
        else {
          var cnt = true;
          while (cnt==true) {
            var match = str.match(/{{objsrc\((\w+)\)}}/);
            if (match) {
              var valNode = podTools.loginDataXML.selectSingleNode("//OBJECTS/@" + match[1].toUpperCase());
              if (valNode) str = str.replace(match[0], unescape(valNode.text));
              else str = str.replace(match[0], match[1] + " not found");
            }
            else
              cnt=false;
          }
        }
      }

			// Call a 
			if (str.test("{{function:")==true)
			{
        var cnt = true;
        while (cnt==true) {

					// var match = str.match(/{{function:(.*)\((.*)\)}}/);
					var match =  str.match(/{{function:((.*)\((.*)\))}}/);
					if(match)
					{
						var fullFunc = match[1];
						var funcName = match[2];
						var parmsName = match[3];
						
						var valNode = eval(fullFunc);
						str = str.replace(match[0], valNode);
					}
          else
            cnt=false;
        }
			}
      
      return str;
    },

    "show"    : function (posObj) { 
    	if (!helpWindow.popup.document) helpWindow.createWindow();
    	if (helpWindow.disabled) return;
			
    	helpWindow.popup.show(posObj);
    	//helpWindow.popup.show(helpWindow.left, helpWindow.top, helpWindow.width, helpWindow.height);
    	helpWindow.nextto = null;
    },
    
    "showNode" : function (id, t, l, nextToNodeName) {

    	if (!helpWindow.popup.document) helpWindow.createWindow();

    	if (helpWindow.disabled) return;
    	if (helpWindow.isTourInProgress==true) return;
  		if (helpWindow.checkAllowCommon()==false) return;
    	
    	var posObj = { 'nextTo':null, 'ptLoc':null, 'offsetLeft':null, 'offsetTop':null, 
    	            'height': null, 'width':null, 
    	            'arrowLoc':null, 'arrowSlide':null };
  		
  		helpWindow.titleDiv.innerHTML = "Help not found";
    	helpWindow.contentsDiv.innerHTML = "Unable to find help with id=" + id;

  		var hNode = mainWindow.helpBoxes.selectSingleNode("//*[@id=\"" + id + "\"]");
  		if (hNode)
  		{
				for (var uu=0; uu<helpWindow.usageName.length; uu++) if (helpWindow.usageName[uu].toUpperCase() == id.toUpperCase()) break;
				if (uu >= helpWindow.usageName)
				{
					helpWindow.usageCount[uu] = 0;
					helpWindow.usageName[uu] = id;
				}
  			if (hNode.getAttribute("maxDisplay"))
  			{
					if (parseInt(hNode.getAttribute("maxDisplay"), 10) <= helpWindow.usageCount[uu]) {helpWindow.hide(); return;}
  			}
				helpWindow.usageCount[uu]++;
  			if (hNode.getAttribute("title")) helpWindow.titleDiv.innerHTML = hNode.getAttribute("title");
  			else helpWindow.titleDiv.innerHTML = "";
  			if (hNode.getAttribute("height")) helpWindow.height = parseInt(hNode.getAttribute("height"), 10);
  			else helpWindow.height = 200;
  			if (hNode.getAttribute("width")) helpWindow.width = parseInt(hNode.getAttribute("width"), 10);
  			else helpWindow.width = 300;

  			helpWindow.contentsDiv.innerHTML = hNode.xml;

  			posObj.arrowLoc = hNode.getAttribute("arrow");
  			posObj.nextTo = hNode.getAttribute("nextto");
  			posObj.offsetTop = t ? t : hNode.getAttribute("top");
  			posObj.offsetLeft = l ? l : hNode.getAttribute("left");
  			posObj.height = helpWindow.height;
  			posObj.width = helpWindow.width;

				posObj.arrowSlide = hNode.getAttribute("arrowslide");
  		}
  		else debugger;

    	helpWindow.show(posObj);
    },

		/************************************************
		*    Begin Displaying a tour
		************************************************/
    "tour" : function(tourName, showStartup) {
 	
      if (!tourName) return;
  
      var tourStops = mainWindow.helpBoxes.selectNodes("//TOUR[@id=\"" + tourName + "\"]/STOP");
      if (tourStops.length == 0) return valetAlert("Unable to find the tour " + tourName);
      if (!helpWindow.popup.document) helpWindow.createWindow();
    
      var startIdx = 0;
      if (showStartup != true)
      	while (tourStops[startIdx] && tourStops[startIdx].getAttribute('startup')=='true') startIdx++;

			helpWindow.isTourInProgress = true;
      helpWindow.tourStop(tourName, startIdx);		//Display the first window
    },

    "tourStop"   : function (tourName, idx) {
    	
      var tourStops = mainWindow.helpBoxes.selectNodes("//TOUR[@id=\"" + tourName + "\"]/STOP");
      if (idx >= tourStops.length) {helpWindow.hide(); return;}
    	
    	var posObj = { 'nextTo':null, 'ptLoc':null, 'offsetLeft':null, 'offsetTop':null, 
    	            'height': null, 'width':null, 
    	            'arrowLoc':null, 'arrowSlide':null };

      
      /****************************************************************
      *   Check to see if the stop is defined as a child to the help node
      *   If it isn't look for a referenced help node
      **********************************************************************/
      var stopNode;
      stopNode = tourStops[idx].selectSingleNode("HELP");
			if(!stopNode)
			{
      	var uri = "//HELP[@id=\"" + tourStops[idx].getAttribute("refid") + "\"]";
      	stopNode = mainWindow.helpBoxes.selectSingleNode(uri);
      }
      
      
			if (!stopNode)
			{
				helpWindow.titleDiv.innerHTML = "Tour stop not found";
				helpWindow.height = 100;
				helpWindow.width = 200;
				helpWindow.contentsDiv.innerHTML = "The tour " + tourName + " contains a stop named " + 
					tourStops[idx].getAttribute("refid") + " which is not in helpBoxes.xml";
			}
			else
			{
  			if (stopNode.getAttribute("title")) helpWindow.titleDiv.innerHTML = stopNode.getAttribute("title");
  			else helpWindow.titleDiv.innerHTML = "";
  			if (stopNode.getAttribute("height")) helpWindow.height = parseInt(stopNode.getAttribute("height"), 10);
  			else helpWindow.height = 200;
  			if (stopNode.getAttribute("width")) helpWindow.width = parseInt(stopNode.getAttribute("width"), 10);
  			else helpWindow.width = 300;
  			posObj.arrowLoc = stopNode.getAttribute("arrow");
  			helpWindow.contentsDiv.innerHTML = stopNode.xml;
			}
			
			var isStartup = tourStops[idx].getAttribute("startup");
			if (isStartup == 'true')
			{
				var txt = "<br/><table cellpadding='2' cellspacing='0' class='textTable' style='background-color:#FFFF75;' width='90%' align='center'>";
					txt += "<td style='text-align:left;'><button style='width:50px' " +
								" onclick='helpWindow.doTour_Yes(\"" + tourName + "\", " + (idx+1) + "); return false;'>Yes</button></td>";
					txt += "<td style='text-align:left;'><button style='width:50px' " +
								" onclick='helpWindow.doTour_No(\"" + tourName + "\"); return false;'>No</button></td>";
					txt += "<td style='text-align:left;'><button style='width:80px' " +
								" onclick='helpWindow.doTour_Later(\"" + tourName + "\"); return false;'>Ask me later</button></td>";
				
				txt += "</tr></table>";
			}
			else
			{			
	      var startCnt = 0;
      	while (tourStops[startCnt] && tourStops[startCnt].getAttribute('startup')=='true') startCnt++;

				
				var txt = "<br/><table cellpadding='2' cellspacing='0' class='textTable' style='background-color:#FFFF75;' width='90%' align='center'>";
				if (idx - startCnt > 0)
				{
					txt += "<td style='text-align:left;'><a class='podshrinktab' href='#' " +
								" onclick='helpWindow.tourStop(\"" + tourName + "\", " + (idx-1) + "); return false;'></a></td>";
				}
				else txt += "<td>&#160;</td>";
				
				txt += "<td style='text-align:center;'>Tour Stop #" + (idx-startCnt+1) + " out of " + (tourStops.length - startCnt) + "</td>";
				if ((idx+1) < tourStops.length)
				{
					txt += "<td style='text-align:right;'><a class='podexpandtab' href='#' " +
								" onclick='helpWindow.tourStop(\"" + tourName + "\", " + (idx+1) + "); return false;'></a></td>";
				}
				else txt += "<td>&#160;</td>";
				
				txt += "</tr></table>";
			}
			helpWindow.contentsDiv.innerHTML += txt;
			helpWindow.height += 30;
			
			if (stopNode.getAttribute("nextto")) posObj.nextTo = stopNode.getAttribute("nextto");
			posObj.offsetTop = stopNode.getAttribute("top");
			if (!posObj.offsetTop) posObj.offsetTop = 0;
			posObj.offsetLeft = stopNode.getAttribute("left");
			if (!posObj.offsetLeft) posObj.offsetLeft = 0;


			posObj.height = helpWindow.height;
 			posObj.width = helpWindow.width;
			posObj.arrowSlide = stopNode.getAttribute("arrowslide");
			posObj.ptLoc = stopNode.getAttribute("ptloc");
  

			helpWindow.executeActions(tourStops[idx], "beforedisplay");
			helpWindow.show(posObj);
			helpWindow.executeActions(tourStops[idx], "afterdisplay");
    },

		/***********************************************************************************/

		"popup": {
			
			"isOpen": false,
			
			"document": null,
			
			"hide": function() {
				
				var doc = helpWindow.popup.document;
				if (doc) doc.setStyle('display', 'none');
				
				helpWindow.backgroundDiv.setStyle('display', 'none');
				
				helpWindow.popup.isOpen = false;
			},
			
			"show": function(posObj) {

				var doc = helpWindow.popup.document;
				var docCoord = doc.getCoordinates();

				var tranVals = { 'transition':false, 'oldLeft':null, 'oldTop':null, 'oldHeight':null, 'oldWidth':null, 
												 'newLeft': null, 'newTop':null, 'newHeight':null, 'newWidth':null }
				if (helpWindow.popup.isOpen)
				{
					tranVals.transition = true;
					tranVals.oldLeft = doc.left;
					tranVals.oldTop = doc.top;
					tranVals.oldHeight = doc.height;
					tranVals.oldWidth = doc.width;
				}

				// Make the pod visible
				if (doc) doc.setStyle('display', '');

				// enable the background.
				if (helpWindow.exitPopupOnBlur == true)
				{
					helpWindow.backgroundDiv.setStyle('display', '');
					myFx = new Fx.Style(helpWindow.backgroundDiv, 'opacity'); 
	 				myFx.set(.25);
				}

				/**************************************************************
				*     Find the point where the arrow should point
				**************************************************************/			
				var refEl;
				var refPoint = { 'x': null, 'y':null };

				if(posObj.nextTo && posObj.nextTo.toLowerCase()=="::tourlink") 
				{
					refEl = mainWindow.$('maximizedpod').getElement("a[class='podtourbtn']")
					var refElCoord = refEl.getCoordinates();
					refPoint.y = 33;
					refPoint.x = refElCoord.left - mainWindow.$('maximizedpod').getCoordinates().left - 7;
				}
				else
				{
					if (!posObj.nextTo) refEl = $(document.body);
					else refEl = $(posObj.nextTo);

					var refElCoord = refEl.getCoordinates();

				  if($type(posObj.ptLoc) != "string") posObj.ptLoc = "";
				  posObj.ptLoc = posObj.ptLoc.toLowerCase();
				  if (posObj.ptLoc.indexOf('t') >= 0) refPoint.y = refElCoord.top;
				  if (posObj.ptLoc.indexOf('m') >= 0) refPoint.y = refElCoord.top + parseInt(refElCoord.height / 2); 
				  if (posObj.ptLoc.indexOf('b') >= 0) refPoint.y = refElCoord.top + parseInt(refElCoord.height);
					if (!refPoint.y) refPoint.y = refElCoord.top;

				  if (posObj.ptLoc.indexOf('l') >= 0) refPoint.x = refElCoord.lrft;
				  if (posObj.ptLoc.indexOf('c') >= 0) refPoint.x = refElCoord.left + parseInt(refElCoord.width / 2); 
				  if (posObj.ptLoc.indexOf('r') >= 0) refPoint.x = refElCoord.left + parseInt(refElCoord.width);
					if (!refPoint.x) refPoint.x = refElCoord.left;
				}
			
				if (posObj.offsetLeft) refPoint.x = refPoint.x + parseInt(posObj.offsetLeft);
				if (posObj.offsetTop) refPoint.y = refPoint.y + parseInt(posObj.offsetTop);				  

				
				tranVals.newTop = refPoint.y;  //parseInt(refElCoord.top) + parseInt(top);
				tranVals.newLeft = refPoint.x;  //parseInt(refElCoord.left) + parseInt(left);
				tranVals.newHeight = posObj.height; 
				tranVals.newWidth = posObj.width;


//				if (height) helpWindow.contentsDiv.setStyle('height', height);
if (posObj.height) helpWindow.contentsDiv.setStyle('height', posObj.height - $('helpWindowTitle').getCoordinates().height - 13);

				var arrowDiv = $('arrowholder');
				arrowDiv.removeClass('rib-arb').removeClass('rib-art').removeClass('rib-arl').removeClass('rib-arr');
				arrowDiv.setStyle('left','').setStyle('right','').setStyle('top','').setStyle('bottom','');


if (!posObj.arrowSlide) posObj.arrowSlide = 50;
var arrowWidth = 25;
var arrowHeight = 30;
var arrowSlidePad = 15;
		
				if ($type(posObj.arrowLoc) != 'string') posObj.arrowLoc = 'R';
				posObj.arrowLoc = posObj.arrowLoc.substr(0,1).toUpperCase();
				docCoord = doc.getCoordinates(); // refetch the coordinates because we set the height 
				switch(posObj.arrowLoc)
				{
					case "N":
						arrowDiv.setStyles({'display':'none'});
						break;
					case "B":
						arrowDiv.addClass("rib-arb");
						var pos = parseInt(((posObj.width - arrowWidth - (2 * arrowSlidePad)) * posObj.arrowSlide/100)) + arrowSlidePad;
						arrowDiv.setStyles({'left': pos, 'display':''});
						
						tranVals.newTop = tranVals.newTop - posObj.height - arrowHeight;
						tranVals.newLeft -= pos;
						break;
					case "T":
						arrowDiv.addClass("rib-art");
						//var pos = parseInt((docCoord.width - 25) / 2);
						var pos = parseInt(((posObj.width - arrowWidth - (2 * arrowSlidePad)) * posObj.arrowSlide/100)) + arrowSlidePad;
						arrowDiv.setStyles({'left': pos, 'display':''});
						arrowDiv.setStyles({'top':  - 29 });

						tranVals.newLeft -= pos;
						break;
					case "L":
						arrowDiv.addClass("rib-arl");
						//var pos = parseInt((docCoord.height - 25) / 2);
						var pos = parseInt(((posObj.height - arrowWidth - (2 * arrowSlidePad)) * posObj.arrowSlide/100)) + arrowSlidePad;
						arrowDiv.setStyles({'top': pos, 'display':''});

						tranVals.newTop -= pos;
						break;
					case "R":
					default:
						arrowDiv.addClass("rib-arr");
						//var pos = parseInt((docCoord.height - 25) / 2);
						var pos = parseInt(((posObj.height - arrowWidth - (2 * arrowSlidePad)) * posObj.arrowSlide/100)) + arrowSlidePad;
						arrowDiv.setStyles({'top': pos, 'display':''});
						arrowDiv.setStyles({'right': '-29px', 'display':''});
						
						tranVals.newTop -= pos;
						tranVals.newLeft = tranVals.newLeft - posObj.width - arrowHeight;
						break;
				}
				
				if (tranVals.transition == true)
				{
					var myEffects = new Fx.Styles(doc, {duration: 200, transition: Fx.Transitions.linear});
					myEffects.start({
    				'width': tranVals.newWidth,
    				'height': tranVals.newHeight,
    				'top': tranVals.newTop,
    				'left':tranVals.newLeft
					});
				}
				else
				{

					if (!tranVals.newHeight || tranVals.newHeight===0) alert("Expected height missing in show()");

					var myEffects = new Fx.Styles(doc, {duration: 200, transition: Fx.Transitions.linear});
					myEffects.start({
    				'width': [150, tranVals.newWidth],
    				'height': [0, tranVals.newHeight],
    				'top': [200, tranVals.newTop],
    				'left': [200, tranVals.newLeft]
					});

					/*
					if (tranVals.newWidth) doc.setStyle('width', tranVals.newWidth);

					doc.setStyle('top', tranVals.newTop);
					doc.setStyle('left', tranVals.newLeft);
					*/					
				}
								
				helpWindow.popup.isOpen = true;
			}
		}
 };


