/********************************************************************************

Description: This is the JavaScript that will validate the form data in Moxi. 

*********************************************************************************/

// Constants
    var util_kNotFound = -1;
    var util_klowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
    var util_kuppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_";
    var util_kdigits = "0123456789"
    var util_kuppercaseHex =  "ABCDEF";
    var util_kowercaseHex =  "abcdef";
    var util_kuserNameMin = 7;
    var util_kuserNameMax = 64;
    var util_kcsruserNameMin = 4;
    var util_kcsruserNameMax = 30;
    var util_kcsrpassWordMin = 6;
    var util_kcsrpassWordMax = 30;
    var util_kpassWordMin = 6;
    var util_kpassWordMax = 64;
    var util_kfirstNameMin = 1;
    var util_kfirstNameMax = 64;
    var util_klastNameMin = 1;
    var util_klastNameMax = 64;
    var util_kdeviceNicknameMin = 1;
    var util_kdeviceNicknameMax = 64;
    var util_kminIntValue = -Math.pow(2,31);
    var util_kmaxIntValue = Math.pow(2,31) - 1;
    var util_kZipLenMin = 5;
    var util_kZipLenMax = 9;
    var util_kPhoneLen = 10; 
    var util_kAnswerLen = 255; 
    var util_kAddressLine1Len = 100;
    var util_kAddressLine2Len = 100;
    var util_kAddressCityLen = 100;
    var util_kBookmarkTitleLength = 1000;
    var util_kBookmarkURLLength = 1000;
    var cursorXCord; //click x coordinate
    var cursorYCord; //click y coordinate
    var strNoError = "";
    var m_event = null;
    var objCompareForm;
    var bHasForm=null;
    var changeLineupZip = "";
    var strVisible="visible";
    var strHidden="hidden";
    var ie = document.all; //ie
    var aob = document.getElementById && !document.all; //firefox and othersC
    var ajaxState = 0;
    var INITSTATE       = 1;
    var SUCCESSSTATE    = 2;
    var ERRORSTATE      = 3;
    var COMPLETESTATE   = 4;
    var arRecord = null;
    var arobjRecording = new Array();
    var getRecordingURL = null;
    var aryShowTimes;
    
   
   
/* 
==============================================================================
                  Utilities
==============================================================================
*/  

	String.prototype.trim = function()
	{
		return this.replace(/^\s+|\s+$/g,"");
	}


	function  validateURL(p_strURL)
	{
		// Note that this is only checking that the url begins
		//   with http/s:// and contains legal characters.
	    var url1 = /^https?:\/\/[A-Za-z0-9-\.\/:\_\?\&\=]+$/
	    
		return( util_kNotFound != stringTrim(p_strURL).search(url1) );
	}


/*
==============================================================================

                    DVR AJAX functions 

 ==============================================================================
 */

  
    function hideObject() 
    { 
      document.getElementById("dvrpopup").style.visibility= "hidden"; 
    }

   

	function showObject()
	{
	   var objTopLeft     = document.getElementById('overlaytopleft');
	   var objBottomLeft  = document.getElementById('overlaybottomleft');
	   var objTopRight    = document.getElementById('overlaytopright');
	   var objBottomRight = document.getElementById('overlaybottomright');
	   
       //local variable
       var arrowYOffset = 50; //Accomodate for the arrow pointer. This has dependencies on location
       var arrowYPosition = 115;
       var viewableHeight = document.documentElement.scrollHeight
       var topScrollHeight = document.documentElement.scrollTop
       var ObjDVRPopup  = document.getElementById('dvrpopup').style;
       var outX = false;
       var outY = false;
       var inX = false;            
       var inY = false;
       var screenHeight;
       var screenWidth;
       var popupWidth;
       var popupHeight;

	   //hide all arrows
       if(objTopLeft != 'undefined' && objTopLeft != undefined)
	       objTopLeft.className="arrow_off";
       if(objBottomLeft != 'undefined' && objBottomLeft != undefined)
	       objBottomLeft.className="arrow_off";
       if(objTopRight != 'undefined' && objTopRight != undefined)
	       objTopRight.className="arrow_off";
       if(objBottomRight != 'undefined' && objBottomRight != undefined)
	       objBottomRight.className="arrow_off";
       
       //Setup our variables
	   if (ie) 
	   { 
     	 popupWidth   = parseInt(ObjDVRPopup.width);
     	 popupHeight  = parseInt(ObjDVRPopup.clientHeight);
     	 screenWidth  = parseInt(document.body.clientWidth);
         screenHeight = parseInt(document.body.clientHeight);
 	   } 
	   else if (aob) 
	   { 
	     screenWidth  = parseInt(window.innerWidth);
         screenHeight = parseInt(window.innerHeight);
	     popupHeight  = parseInt(ObjDVRPopup.clientHeight);
         popupWidth   = parseInt(ObjDVRPopup.width);
       } 

       //if the popup hangs over the right of the  screen let's reposition it
       // so the user can see it
       if((popupWidth + cursorXCord) > screenWidth)
       {       
          ObjDVRPopup.left = (cursorXCord - popupWidth)+"px";
          outX=true;
       }
       else
       {
          ObjDVRPopup.left = cursorXCord+"px"; 
          inX=true;
       }
         
       //if the popup hangs over the top or bottom of the screen let's reposition it
       // so the user can see it
       if((popupHeight + cursorYCord) > viewableHeight)
       {
          outY=true;
          ObjDVRPopup.top = (((cursorYCord-popupHeight)+topScrollHeight)+ arrowYOffset)+"px";
       }
       else
       {
          inY=true;
          ObjDVRPopup.top = ((cursorYCord+topScrollHeight)-arrowYOffset)+"px";  
       }
       
	   //Put the arrow in the right place  
	   if(inX && inY)
	   {
       		if(objTopLeft != 'undefined' && objTopLeft != undefined)
	          objTopLeft.className="arrow_on";
	   }
	   else if(outX && outY)
	   {
       	   if(objBottomRight != 'undefined' && objBottomRight != undefined)
       	   {
	         objBottomRight.className="arrow_on";
	         document.getElementById('rightarrow').style.top= (popupHeight-arrowYPosition)+"px";
	       }
	   }
	   else if(outX && inY)
	   {
       	   if(objTopRight != 'undefined' && objTopRight != undefined)
	         objTopRight.className="arrow_on"; 
	   } 
	   else if(inX && outY)
	   {
       	   if(objBottomLeft != 'undefined' && objBottomLeft != undefined)
       	   {
	         objBottomLeft.className="arrow_on";     
	         document.getElementById('leftarrow').style.top= (popupHeight-arrowYPosition)+"px";
	       }
	   }
     
       //Scroll into position if needed
       document.getElementById('dvrpopup').scrollIntoView(true);
 
       //well let's see it
       ObjDVRPopup.visibility = "visible";
   }
    
	function checkDate(strDate)
  	{
	  if(strDate != "null" && strDate != "")
	  { 
	       //parser date formatted as yyyymmddThh:mm:ss
	       var arDate = strDate.split(":");
	       var strmins = arDate[1].substring(0,2);
	       var strYear = arDate[0].substring(0,4)
	       var strMonth = (arDate[0].substring(4,6))-1
	       var strDay = arDate[0].substring(6,8)
	       var strHour = arDate[0].substring(9,11);
	       var iHour = parseInt(trimLeadingZeros(strHour));

          //make new selected date object      
	      var selected = new Date();
	      selected.setYear(strYear);
	      selected.setMonth(strMonth);
	      selected.setDate(strDay);
	      selected.setHours(iHour);
	      selected.setMinutes(strmins);

	      //get the current time    
	      var now = new Date();
         
	      //If the current time is greater than the selected time return false
	      if(now.getTime() > selected.getTime())
	         return false;
	    }
      //must be okay     
      return true;
  	}
    
	function isDateBeforeNow(strDate)
  	{
  	    // This method assumes the date is in the recording format
  	    //    e.g. 20080808T190000 UTC
  	    var  bDateBeforeNow = false;
  	    
	    if (strDate != "null")
	    { 
	    	// parse date
	       	var strYear  = strDate.substring(0,4)
	       	var strMonth = (strDate.substring(4,6))-1
	       	var strDay   = strDate.substring(6,8)
	       	var strHour  = strDate.substring(9,11);
	       	var strMins  = strDate.substring(11,13);
	       	var strSecs  = strDate.substring(13);

         	// make input date object in UTC     
	      	var dDate = new Date(Date.UTC(strYear,strMonth,strDay,strHour,strMins,strSecs));
	      	var tTime = dDate.getTime();

	      	// get the current time in UTC    
	      	var now = new Date();
	      	var tNow = now.getTime();
         
	      	// If the selected time is <= the current time return true
	      	if (tTime <= tNow)
	         	bDateBeforeNow = true;
	    }

      	return bDateBeforeNow;
  	}
  
	function mypopup(strURL,strWidth)
 	{
	   mywindow = window.open(strURL,"mywindow","resizable=1,location=1,status=1,scrollbars=1,width="+strWidth);
 	}
 	 
	function getMapParameters(p_params)
  	{
      	var mParameters = new Array();
      	var aryParams = p_params.split("&");
     
         for(i = 0;i < aryParams.length;i++)
	     {
	       var aryTmp = aryParams[i].split("=");
	       mParameters[aryTmp[0]]= aryTmp[1];
	     }
	  	return mParameters;
  	}
 
  
  	function findMatchingProgram(station,channel,airdate)
  	{
      	var showAirDate = station+"_"+channel+"-"+airdate;
      	var objRecording = arobjRecording;

	    for(var j = 0;j < objRecording.length; j++)
	    {
	      var startRecordTime = objRecording[j].startTime;
	      var endDate  = objRecording[j].endTime;
	
	      if(objRecording[j].station == station && objRecording[j].channel+objRecording[j].subchannel  == channel)
	      {
		      if(date2Millis(airdate) <= date2Millis(startRecordTime) &&  date2Millis(startRecordTime) < date2Millis(endDate))
		      {
		          var arryRecordTime = startRecordTime.split('T');
		          var hour = arryRecordTime[1].substring(0,2);
		          var min = arryRecordTime[1].substring(2,4);
		          var sec = arryRecordTime[1].substring(4,6);
		                	            
		          return arryRecordTime[0]+"T"+hour+":"+min+":"+sec;
		      }
		  }  
	    
        return null;
      }
  	}
    
    function date2Millis(dbDateFormat)
    {
        
        var iYear  = dbDateFormat.substr(0,4);
        var iMonth = dbDateFormat.substr(4,2);
        var iDay   = dbDateFormat.substr(6,2);
        var iHour  = dbDateFormat.substr(9,2);
        var iMin   = dbDateFormat.substr(11,2);
        var iSec   = dbDateFormat.substr(13,2);
       
        var dDate = new Date(iYear,iMonth-1,iDay,iHour,iMin,iSec);
        
        return dDate.getTime();
   
      
    }
   
  function trimLeadingZeros(s)
   {
     while (s.substr(0,1) == '0' && s.length>1)
     { 
        s = s.substr(1,9999); 
     }
     return s;
  }
   
	function getProgramDetails(pars,e,state,url,enddate,p_bShowStatus,p_bNextProgram) 
    {
        var mParams = getMapParameters(pars);
        if (typeof(mParams["cancel"]) != "undefined")
        {
	        // find matching program in our updated cache
	        var recordStartID = findMatchingProgram(mParams["stationID"], trimLeadingZeros(mParams["channelnumber"]), mParams["airdate"].replace(/:/g,""));
       
	        if(recordStartID != null)
	            pars += "&recordtime="+recordStartID
        }

      // check against time
      if (checkDate(enddate) || p_bNextProgram)
      {
       pars = pars + "&state=" + state
       
       if (p_bNextProgram)
       		pars += "&nextprogram="+p_bNextProgram;
       		
       // see if there is a tab value to be added to the params
       var  eTabForm = document.getElementById("fmrfilter");
       
       if ((eTabForm != null) && (typeof(eTabForm) != "undefined"))
       {
       		pars += "&tab=" + eTabForm.tab.value;
       		
       		// If this is the topshows tab, get the selected type.
       		if (eTabForm.tab.value == "topshows")
       		{
       			var  eType = document.frmTopShows.viewedscheduled;
       			
       			if (eType[0].checked)
       				pars += "&view=viewed";
       			else if (eType[1].checked)
       				pars += "&view=scheduled";
       		}
       }
       
       var currentScrollTop = document.documentElement.scrollTop
       var bShow = (e == null)? true : false;
       
       if(!bShow)
       {
           cursorXCord  = e.clientX; //set click x coordinate
           cursorYCord  = e.clientY; //set click y coordinate
       }
        
       advAJAX.get({
    	url: url+"&"+pars ,
   		onInitialization : function() 
   		{
       	 	/* Show distractor dialog */
       	 	ajaxState = INITSTATE;
       	 	if(bShow)
       	 	{
              document.getElementById("dvrpopup").style.visibility = "hidden";
              adjustView(document.getElementById("tv_listings_wait"))
        	}
        	if (p_bNextProgram)
        	{
              document.getElementById("dvrpopup_topshows").style.visibility = "visible";
              adjustView(document.getElementById("tv_listings_wait_topshows"))
        	}
    	},
      	onSuccess : function(obj) 
      	{
       		/* Set layer content to data received from server */
    		document.getElementById("dvrpopup").innerHTML = obj.responseText;
       		ajaxState = SUCCESSSTATE;
  		},
    	onError : function(obj) 
    	{
            if (obj.status == 1000)
            {
                // The session has timed out.  Redirect.
    	        var  xmldoc = obj.responseXML;
                var  errorRecord = xmldoc.getElementsByTagName('pageexpired');
                var  strRedirect = errorRecord.item(0).getAttribute("redirecturl");
               
       	        top.document.location.href=strRedirect;
            }
            else
           	    alert("Error: " + obj.status + ": " + obj.responseText);
            ajaxState = ERRORSTATE;
	    },
    	onFinalization : function() 
    	{
	        /* After all operations we show hidden layer */
	        document.getElementById("tv_listings_wait").style.visibility = "hidden";
	         
    		if (ajaxState != ERRORSTATE)
    		{
		        //check for record status
		        var objElemRecord   = document.getElementById("scheduled_record");	
		        var objElemCancel   = document.getElementById("scheduled_cancel");
	    	    var objElemSeries   = document.getElementById("scheduled_series");	
	    	    var numElemCancel   = document.getElementById("number_canceled_shows");
    	     
		        if(objElemRecord != 'undefined' && objElemRecord != undefined)
		        {
		          var scheduleElement = objElemRecord.value;
		          var objScheduleElement = document.getElementById(scheduleElement);
		          var tmp_arScheduledProperties = scheduleElement.split("_");
		          var tmp_arScheduledProperties2 = tmp_arScheduledProperties[1].split("-");
		          var strStatus = "future";
		           
	              if (isDateBeforeNow(tmp_arScheduledProperties2[1]))
	                  strStatus = "recording";
	                   
		          //turn on the image for "scheduled" or "recording"
		          if (p_bShowStatus)
		          {
			         if (objScheduleElement != 'undefined' && objScheduleElement != undefined)
			         {
			          	  if (strStatus == "future")
			          	  	  objScheduleElement.className="state_scheduled";
			          	  else
			          	  	  objScheduleElement.className="state_recording";
			         }
		          }
		           
		          //update our javascript record schedule cache
		          addtoRecordArray(tmp_arScheduledProperties[0],tmp_arScheduledProperties2[0],
		                           tmp_arScheduledProperties2[1],strStatus)
		        }
		        if(objElemCancel != 'undefined' && objElemCancel != undefined)
		        {
		          //turn off the image for cancelled
		          var scheduleElement = objElemCancel.value;
		          if (p_bShowStatus)
		          	  document.getElementById(scheduleElement).className="state_notscheduled";
		           
		          //update our javascript record schedule cache
		          removeRecordArray(scheduleElement ,"removed")
		        }
		        if(objElemSeries != 'undefined' && objElemSeries != undefined)
		        {
		          //update series by polling device
		          seriesUpdate();
		        }
		        if(numElemCancel != 'undefined' && numElemCancel != undefined)
		        {
		          //turn off the image for all cancelled shows
		          var iNum = numElemCancel.value;
		          
		          for (var i = 0; i < iNum; i++)
		          {
		            var objElem = document.getElementById("scheduled_cancel" + i);
		        	 if(objElem != 'undefined' && objElem != undefined)
		        	 {
			          var scheduleElement = objElem.value;
			          var obj = document.getElementById(scheduleElement);
			          
		        	   if(p_bShowStatus && obj != 'undefined' && obj != undefined)
			              obj.className="state_notscheduled";
			          
			          //update our javascript record schedule cache
			          removeRecordArray(scheduleElement ,"removed")
			        }
			      }
		        }
	         
		        if(bShow)
		        {
		        	adjustView(document.getElementById("dvrpopup"));
		        }
		        else
		        {
		          if (p_bNextProgram)
		          {
		              // Turn off the distractor and restore the scroll location.
		              document.getElementById("dvrpopup_topshows").style.visibility = "hidden";
		              document.getElementById("tv_listings_wait_topshows").style.visibility = "hidden";
	                  window.scroll(0,currentScrollTop);     
		          }
		          showObject();
		        }
		    }
            ajaxState = COMPLETESTATE;
        }
       });
      }
      else
      {
        document.getElementById("dvrpopup").style.visibility = "hidden";
        alert("This show has ended, please select a new time");
      }
    }
    
    function adjustView(objPopupWidget)
    {
           //local variable
	       var topScrollHeight = document.documentElement.scrollTop
	       var topoffset = "300px";
	       var screenHeight;
	       var screenWidth;
	       var popupWidth;
	       var popupHeight;
	       var ObjDVRPopup  = objPopupWidget.style;
	     
	      
	      //Setup our variables
		  if (ie) 
		  { 
	    	 popupWidth   = parseInt(objPopupWidget.style.width)/2;
	    	 popupHeight  = parseInt(objPopupWidget.clientHeight)/2;
	    	 screenWidth  = parseInt(document.body.clientWidth)/2;
	         screenHeight = parseInt(document.body.clientHeight)/2;
		  } 
		  else if (aob) 
		  { 
		     screenWidth  = parseInt(window.innerWidth)/2;
	         screenHeight = parseInt(window.innerHeight)/2;
		     popupHeight  = parseInt(objPopupWidget.clientHeight)/2;
	         popupWidth   = parseInt(objPopupWidget.style.width)/2;
	      } 
	
	      //Center the distractor dialogs
	      ObjDVRPopup.left = (screenWidth-popupWidth) +"px"; 
	      ObjDVRPopup.top = topoffset;  
	      objPopupWidget.style.visibility = "visible";
	      
	      //Move the scollbar to the middle
	      window.scroll(0,topScrollHeight/2);     
         
    
    }
    
    function adjustView2(p_strPopupWidget)
    {
    	adjustView(document.getElementById(p_strPopupWidget));
    }
     
// String methods  
/*
==============================================================================

                    General utility and "Is" functions 

 ==============================================================================
 */

// ----------------------------------------------------------------------------

    function util_IsDefined( TheValue )
    {
        return( (typeof( TheValue ) != typeof( "" ))  &&  (null != TheValue) );
    }
    
// ----------------------------------------------------------------------------
// This function checks to see if the "Value" is  
// within the "Minvalue" and "MaxValue" inclusively.

    function util_InRange( MinValue, Value, MaxValue )
    {
        return( util_IsDefined( Value )  &&   (MinValue <= Value  &&  Value <= MaxValue) );
    }
    
// ----------------------------------------------------------------------------
// This function checks if the input string is empty. Used only in the other utility functions below

    // Check whether string s is empty.
	function util_isEmpty(s)
	{
		var strTrimmed = stringTrim(s);
		
	    return ((strTrimmed == null) || (strTrimmed.length == 0));
	}	

// ----------------------------------------------------------------------------
// This function checks if the input string is empty. NOTE IT IS EXACT THE SAME AS THE ABOVE FUNCTION
// BUT RETURNS FALSE INSTEAD OF TRUE IF THE CONDITION IS MET.  THIS IS TO MAINTAIN CONSISTENCY IN THE 
// FUNCTIONS AT THE BOTTOM OF THE PAGE.  THE ABOVE FUNCTIN IS USED WITHIN THE OTHER UTILITY FUNCTIONS
// DIRECTLY BELOW 

    // Check whether string s is empty.
	function util_isEmpty2(s)
	{
		var strTrimmed = stringTrim(s);

	    if ((strTrimmed == null) || (strTrimmed.length == 0)) return false;
		return true;
	}		
	
// ----------------------------------------------------------------------------
// Tests that characters of string s are all in bag.
	function util_isInBag (s, bag)
	{   
		var strTrimmed = stringTrim(s);
		var i;
    	for (i = 0; i < strTrimmed.length; i++)
    	{   
        	var c = strTrimmed.charAt(i);
        	if (bag.indexOf(c) == util_kNotFound) return false;
    	}

        return true;
	}		
	

	
// ----------------------------------------------------------------------------
// Tests required characters of string s are all in bag.
	function util_isRequiredInBag (s, bag)
	{   
		var strTrimmed = stringTrim(s);
		var i;
    	for (i = 0; i < strTrimmed.length; i++)
    	{   
        	var c = strTrimmed.charAt(i);
        	if (bag.indexOf(c) != util_kNotFound) return true;
    	}

        return false;
	}			
    
// ----------------------------------------------------------------------------
// This function checks to see if the "str" is valid.
    function util_validChars(str,other)
    {		
		var validChars = util_klowercaseLetters + util_kuppercaseLetters + other + util_kdigits;
		if (!util_isInBag(str, validChars)) return false;
		else return true;
    }
    
// ----------------------------------------------------------------------------
// This function checks to see if the "str" is valid hexidecimal.
    function util_validHex(str)
    {		
       var validChars = util_kuppercaseHex + util_kowercaseHex + util_kdigits;
	   if (!util_isInBag(str, validChars)) return false;
	   else return true;
    }    
	
// ----------------------------------------------------------------------------
// This function checks to see if the "str" is a valid integer.
// If other is empty, str must be a positive integer.
// Set other to '-' to allow both negative and positive integers.
    function util_isInteger(str,other)
    {	
    	var  bValid = false;
    		
		if (util_isInBag(str,util_kdigits + other) &&
		    (parseInt(str) >= util_kminIntValue)   &&
		    (parseInt(str) <= util_kmaxIntValue))
		    bValid = true;
		
		return bValid;
    }
	
// ----------------------------------------------------------------------------
// This function checks to see if the "str" or username is valid.
// Note that the username must be valid email address.
    function util_userName(str)
    {		
		var strTrimmed = stringTrim(str);
		var other = "_-."
		var validChars = util_klowercaseLetters + util_kuppercaseLetters + other + util_kdigits;
		
		if (util_isEmpty(strTrimmed)) return true;
		if (!util_InRange(util_kuserNameMin,strTrimmed.length,util_kuserNameMax)) return false;
		if (!util_IsEmail(strTrimmed)) return false;
		else return true;
    }
    
// ----------------------------------------------------------------------------
// This function checks to see if the "str" or nickname is valid.
    function util_NickName(str)
    {		
		var other = "_-.' &"
		var validChars = util_klowercaseLetters + util_kuppercaseLetters + other + util_kdigits;
		
		if (!util_validChars(str,validChars)) return false;
		if (util_isEmpty(str)) return true;
		if (!util_InRange(util_kdeviceNicknameMin,str.length,util_kdeviceNicknameMax)) return false;
		
		else return true;
    }
    
        
// ----------------------------------------------------------------------------
// This function checks to see if the "str" or password is valid.
    function util_passWord(str)
    {
		var strTrimmed = stringTrim(str);
		var validChars = util_klowercaseLetters + util_kuppercaseLetters + util_kdigits;
		
		if (util_isEmpty(strTrimmed)) return true;
		if (!util_InRange(util_kpassWordMin,strTrimmed.length,util_kpassWordMax)) return false;
		else if (!util_isInBag(strTrimmed, validChars)) return false;
		else return true;
    }
    
// ----------------------------------------------------------------------------
// This function checks to see if the "str" or password is valid.
    function util_csrpassWord(str)
    {
		var strTrimmed = stringTrim(str);
        var other = "_-.`~!@#$%^&*()"
        var validChars = util_klowercaseLetters + util_kuppercaseLetters + util_kdigits + other;
        var requirednonAlpha = other + util_kdigits;
        var requiredDigits = util_kdigits;
        
        if (util_isEmpty(strTrimmed)) return true;
        if (!util_InRange(util_kpassWordMin,strTrimmed.length,util_kpassWordMax)) return false;
        if (!util_isRequiredInBag(strTrimmed, requirednonAlpha)) return false;
        if (!util_isRequiredInBag(strTrimmed, requiredDigits)) return false;
        else if (!util_isInBag(strTrimmed, validChars)) return false;
        else return true;
    }
    
// ----------------------------------------------------------------------------  
// This function compares 2 strings   
    function StrCompare( Str1, Str2 )
    {
		return (Str1 == Str2 ? true : false);
    }   	

// This function compares 2 strings   
    function StrCompareIgnoreCase( Str1, Str2 )
    {
		return (Str1.toLowerCase() == Str2.toLowerCase() ? true : false);
    }   	
 
// ----------------------------------------------------------------------------  
// This function trims whitespace from the string  
    function stringTrim(p_strTrim) 
    {
    	var strTrimmed = p_strTrim;
    	
    	if ((strTrimmed != null) && (strTrimmed.length > 0))
    	{
	        //Match spaces at beginning and end of text and replace with null strings
	        strTrimmed = p_strTrim.replace(/^\s+/,'').replace(/\s+$/,'');
	    }
	    
	    return (strTrimmed);
    }

// ----------------------------------------------------------------------------
//  This function checks that an email string is formatted correctly.
//  
//  /^\s*\S+@\S+.\S+\s*$/ - the email pattern
//
//   ^   - Starting from beginning of the input string
//   \s* - followed by any leading white space characters
//   \S+ - followed by 1 or more non-white space characters
//   @   - followed by a single "@" character
//   \S+ - followed by 1 or more non-white space characters
//   \.  - followed by a single "." character
//   \S+ - followed by 1 or more non-white space character
//   \s* - followed by any trailing white space characters
//   $   - to the end of the input string.

    function util_IsEmail(EmailStr)
    {
	  if (!util_validChars(EmailStr,"_-@.")) 
	  {
	  	return false
	  }
	  if (!util_isEmpty(EmailStr))
      {
        return( util_kNotFound != EmailStr.search( /^\s*\S+@\S+\.\S+\s*$/ ) );
      }
      else{return true;}
	}

// ----------------------------------------------------------------------------    
// This function validates the zip code if it exists.  
    function validate_zip(str)
    {
        var j = 0;
        var otherLetter = "-";
        var validChars = util_kdigits + otherLetter;
        var bValid = false;
        var strTrimmed = stringTrim(str);
      
        if (util_isEmpty(strTrimmed) || (strTrimmed == " "))
            bValid = true;
        else
        {
	        if (util_isInBag(strTrimmed, validChars))
            {
                for (var i=0; i<strTrimmed.length; i++)
                {
                  if (util_isInBag(strTrimmed.charAt(i), util_kdigits)) j++;
                }
                if (j == util_kZipLenMin || j == util_kZipLenMax) 
                    bValid = true;
            }
        }

        return bValid;
    }    
	
// ----------------------------------------------------------------------------
	// Check a phone number
   
	function util_checkPhone(str)
	{ 
	        
	    var  strTrimmed = str.replace(/\s+/,'').replace(/\s+/,'');
	    var  j=0;
	    var  otherLetter = "-.()";
	    var  validChars = util_kdigits + otherLetter;
	    if (util_isEmpty(strTrimmed))  return true;
		if (strTrimmed!=" ")
		{
		    if (!util_isInBag(strTrimmed, validChars)) return false;
				
		        for (var i=0;i<strTrimmed.length;i++)
		        {
		          if (util_isInBag(strTrimmed.charAt(i), util_kdigits)) j++;
		        }
		    if (j != util_kPhoneLen) return false;
		
		    else return true;
		} else{return true;}
	}

// ----------------------------------------------------------------------------
// strip a phone number of punctuation
   
	function util_stripPhone(str)
	{ 
	    var s = str.replace(/\s+/,'').replace(/\s+/,'');
	    var removeChars = "-.()";
		for(i=0;i < removeChars.length;i++)
		{      
		 s = s.split(removeChars.charAt(i)).join("");
	    }
           	
	    return s;
	}		


// ----------------------------------------------------------------------------	

    function jsInitPage(p_bHasForm)
    {
       bHasForm = p_bHasForm
        if(bHasForm)
          objCompareForm = new formValueValidator();
    }

	//use this object for the form comparison validition
	function formValueValidator()
	{
        
	  
	    var formArray = new Array();
	    this.loaded = loadFormArray(formArray)
	
	   
	}
	
	
	//Load all the form elements in an associative array using name=value as key=value	
	function loadFormArray(formArray)
	{
	  
	   	 for(i=0; i<document.forms[0].elements.length; i++)
	  	 {
	  	     formArray[document.forms[0].elements[i].name]=document.forms[0].elements[i].value;
	 	 }
	  
	  return formArray;
	} 
	
	/*
	Check the form against the saved form array
	    bHasForm = true:  if changed isDirty true
        bHasForm = false: isdirty true
        bHasForm = null:  Not evaluating isDirty false
    */
	function isDirtyForm()
	{
	 
	  var isDirtyTemp = false;
	 if(bHasForm)
	 { 
	 
	    var formArray = objCompareForm.loaded
	    for(i=0; i<document.forms[0].elements.length; i++)
	    {
           if(formArray[document.forms[0].elements[i].name] != document.forms[0].elements[i].value)
	       {
		      isDirtyTemp = true;
			  break;
		   }
		
	    }
	    return isDirtyTemp;
	  }
	  else if(bHasForm != null)
	  {
	     return true;
	  }
	  else
	  {
	     return false;
	  }

	}

 
 /* my moxi menu*/
 var disappeardelay=250  //menu disappear speed onMouseout (in miliseconds)
var hidemenu_onclick="yes" //hide menu when user clicks within menu?

/////No further editting needed

var ie4=document.all
var ns6=document.getElementById&&!document.all

if (ie4||ns6)
document.write('<div id="dropmenudiv" class="menudiv" onMouseover="clearhidemenu()" onMouseout="dynamichide(event)"></div>')

function getposOffset(parentTab, offSetType)
{
	var totaloffset;
	
	if(offSetType=="left")
	  totaloffset = parentTab.offsetLeft;
	else
	  totaloffset = parentTab.offsetTop
	
	var parentPos=parentTab.offsetParent;
	
	while (parentPos !=null)
	{
		
		if(offSetType=="left")
		 totaloffset=totaloffset+parentPos.offsetLeft
		else
		 totaloffset=totaloffset+parentPos.offsetTop;
		 
		parentPos=parentPos.offsetParent;
	}
	return totaloffset;
}


function showhide(obj, e, menuwidth)
{
	if (ie4||ns6)
		dropmenuobj.style.left=dropmenuobj.style.top="-500px"
		
	if (menuwidth!="")
	{
		dropmenuobj.widthobj=dropmenuobj.style
		dropmenuobj.widthobj.width=menuwidth
	}
	if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
		obj.visibility="visible"
	else if (e.type=="click")
		obj.visibility="hidden"
}

function iecompattest()
{
   return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge)
{
	var edgeoffset=0
	if (whichedge=="rightedge")	
	{
		var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
		dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
		if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
			edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
	}
	else
	{
		var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
		var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
		dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
		if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
		{ //move up?
			edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
			if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
				edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
	    }
	}
	return edgeoffset
}

function populatemenu(objMenuIndex)
{
	if (ie4||ns6)
		dropmenuobj.innerHTML=objMenuIndex.join("")
	
}


function dropdownmenu(obj, e, objMenuIndex, menuwidth)
{

	if (window.event) event.cancelBubble=true
	else if (e.stopPropagation) e.stopPropagation()
	clearhidemenu()
	
	if(document.getElementById)
	  dropmenuobj= document.getElementById("dropmenudiv")
	else
	  dropmenuobj= dropmenudiv
	
	populatemenu(objMenuIndex)

	if (ie4||ns6)
	{
		showhide(dropmenuobj.style, e,  menuwidth)
		dropmenuobj.x=getposOffset(obj, "left")
		dropmenuobj.y=getposOffset(obj, "top")
		dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
		dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
	}

	return clickreturnvalue()
}

function clickreturnvalue(){

}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}

function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}

function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}

if (hidemenu_onclick=="yes")
document.onclick=hidemenu
/* end my moxi menu*/ 
	
/*

==============================================================================

                    Moxi messages functions

 =============================================================================
 */  

<!-- Begin
    var bHaveErrors = false;
    
    function  showError(p_strMessage)
    {
       alert(unescape(p_strMessage));
    }
    
    
    function showMessage(p_strMessage, 
                         p_bError,
                         p_wFocus,
                         errorid) 
    {
    
        if (!bHaveErrors && p_bError)
        {
            var errorObj = document.getElementById(errorid)
        	errorObj.innerHTML = p_strMessage;
        	errorObj.style.display = "block";
        	if (p_wFocus != null)
        		p_wFocus.focus();
            bHaveErrors = p_bError;
        }
    }


    function showMessageAndNavigate(p_strMessage,
                                    p_strURL)
	{
		alert(p_strMessage);
		top.location.href = p_strURL;
	}                                    
    
    
    function showHelp(p_bShow)
	{
  	    if(p_bShow)
 	       document.getElementById("help").style.visibility = "visible";  	    
 	    else
           document.getElementById("help").style.visibility = "hidden"; 
	}                                    

    function showCancelMessage(p_strMessage, 
                               p_strURL) 
    {
		if(isDirtyForm())
		{
			var bOK = confirm(p_strMessage);
			
			if (bOK)
				top.location.href = p_strURL;
		}
		else
			top.location.href = p_strURL;
    }


    function confirmDeviceRemove(p_strURL)
    {
    	// The input message has a string to be replaced by the value of the selected object.
    	//   Get the string to stuff in the message.
    	var  oObject = document.getElementById('deviceid');
    	var  strValue = oObject[oObject.selectedIndex].value;
        
        top.location.href = p_strURL + strValue;
    }

// ----------------------------------------------------------------------------
// Validate user data.
    function validate_userdata(p_fForm) 
    {  
        //reset/hide all
        document.getElementById("erroremail").style.display = "none";
		document.getElementById("erroremailconfirm").style.display = "none";
		document.getElementById("errorpassword").style.display = "none";
		document.getElementById("errorconfirmpassword").style.display = "none";
		document.getElementById("erroranswer").style.display = "none";
    
        bHaveErrors = false;

        if (util_isEmpty(p_fForm.email.value))
            showMessage(saErrors[11],true,p_fForm.email,"erroremail");
        else if (!util_userName(p_fForm.email.value)) 
            showMessage(saErrors[16],true,p_fForm.email,"erroremail");

        else if (util_isEmpty(p_fForm.emailconfirm.value))                    
            showMessage(saErrors[11],true,p_fForm.emailconfirm,"erroremailconfirm");
        else if (!util_IsEmail(p_fForm.emailconfirm.value))                   
            showMessage(saErrors[16],true,p_fForm.emailconfirm,"erroremailconfirm");
        else if (!StrCompareIgnoreCase(p_fForm.email.value,p_fForm.emailconfirm.value)) 
            showMessage(saErrors[12],true,p_fForm.emailconfirm,"erroremailconfirm");

        else if (util_isEmpty(p_fForm.password.value))
            showMessage(saErrors[0],true,p_fForm.password,"errorpassword");
        else if (!util_passWord(p_fForm.password.value)) 
            showMessage(saErrors[1],true,p_fForm.password,"errorpassword");

        else if (util_isEmpty(p_fForm.passwordconfirm.value))                       
            showMessage(saErrors[0],true,p_fForm.passwordconfirm,"errorconfirmpassword");
        else if (!util_passWord(p_fForm.passwordconfirm.value))                     
            showMessage(saErrors[1],true,p_fForm.passwordconfirm,"errorconfirmpassword");
        else if (!StrCompareIgnoreCase(p_fForm.password.value,p_fForm.passwordconfirm.value)) 
            showMessage(saErrors[2],true,p_fForm.passwordconfirm,"errorconfirmpassword");
            
        else if (util_isEmpty(p_fForm.answer.value))                       
            showMessage(saErrors[23],true,p_fForm.answer,"erroranswer");
        else if (!util_InRange(1,stringTrim(p_fForm.answer.value).length,util_kAnswerLen))
            showMessage(saErrors[31],true,p_fForm.answer,"erroranswer");
        
        return (!bHaveErrors);
    }
    
      function validate_userdetails(p_fForm) 
    {  
        //reset/hide all
        document.getElementById("erroremail").style.display = "none";
		document.getElementById("erroremailconfirm").style.display = "none";
		document.getElementById("errorpassword").style.display = "none";
		document.getElementById("errorconfirmpassword").style.display = "none";
		document.getElementById("erroranswer").style.display = "none";
    
        bHaveErrors = false;

        if (util_isEmpty(p_fForm.email.value))
            showMessage(saErrors[11],true,p_fForm.email,"erroremail");
        else if (!util_userName(p_fForm.email.value)) 
            showMessage(saErrors[16],true,p_fForm.email,"erroremail");

        else if (util_isEmpty(p_fForm.emailconfirm.value))                    
            showMessage(saErrors[11],true,p_fForm.emailconfirm,"erroremailconfirm");
        else if (!util_IsEmail(p_fForm.emailconfirm.value))                   
            showMessage(saErrors[16],true,p_fForm.emailconfirm,"erroremailconfirm");
        else if (!StrCompareIgnoreCase(p_fForm.email.value,p_fForm.emailconfirm.value)) 
            showMessage(saErrors[12],true,p_fForm.emailconfirm,"erroremailconfirm");

       
        else if (!util_passWord(p_fForm.password.value)) 
            showMessage(saErrors[1],true,p_fForm.password,"errorpassword");

       
        else if (!util_passWord(p_fForm.passwordconfirm.value))                     
            showMessage(saErrors[1],true,p_fForm.passwordconfirm,"errorconfirmpassword");
        else if (!StrCompareIgnoreCase(p_fForm.password.value,p_fForm.passwordconfirm.value)) 
            showMessage(saErrors[2],true,p_fForm.passwordconfirm,"errorconfirmpassword");
            
        else if (util_isEmpty(p_fForm.answer.value))                       
            showMessage(saErrors[23],true,p_fForm.answer,"erroranswer");
        else if (!util_InRange(1,stringTrim(p_fForm.answer.value).length,util_kAnswerLen))
            showMessage(saErrors[31],true,p_fForm.answer,"erroranswer");
        
        return (!bHaveErrors);
    }
    

// ----------------------------------------------------------------------------
// Validate account data.
    function validate_accountdata(p_fForm) 
    {  
        bHaveErrors = false;

        //reset/hide all
        document.getElementById("errorfirstname").style.display="none";
        document.getElementById("errorlastname").style.display="none";
        document.getElementById("erroraddress1").style.display="none";
        document.getElementById("erroraddress2").style.display="none";
        document.getElementById("errorcitystatezip").style.display="none";
        document.getElementById("errorphone").style.display="none";
       	if(typeof(errorcellphone1) != "undefined" )
        	document.getElementById("errorcellphone1").style.display="none";
       	if(typeof(errorcellphone2) != "undefined" )
        	document.getElementById("errorcellphone2").style.display="none";

        if (util_isEmpty(p_fForm.firstname.value))                           
        	showMessage(saErrors[4],true,p_fForm.firstname,"errorfirstname");
        else if (!util_validChars(p_fForm.firstname.value,"_-' .&*") ||             
		         !util_InRange(util_kfirstNameMin,stringTrim(p_fForm.firstname.value).length,util_kfirstNameMax)) 
        	showMessage(saErrors[17],true,p_fForm.firstname,"errorfirstname");

        else if (util_isEmpty(p_fForm.lastname.value))                          
        	showMessage(saErrors[6],true,p_fForm.lastname,"errorlastname");
        else if (!util_validChars(p_fForm.lastname.value,"_-' .&*") ||
		         !util_InRange(util_klastNameMin,stringTrim(p_fForm.lastname.value).length,util_klastNameMax)) 
			showMessage(saErrors[18],true,p_fForm.lastname,"errorlastname");

        else if (util_isEmpty(p_fForm.address1.value))                          
        	showMessage(saErrors[7],true,p_fForm.address1,"erroraddress1");
        else if (!util_validChars(p_fForm.address1.value,"_- .&#/'")) 
        	showMessage(saErrors[19],true,p_fForm.address1,"erroraddress1");
        else if (p_fForm.address1.value.length > util_kAddressLine1Len)
        	showMessage(saErrors[19],true,p_fForm.address1,"erroraddress1");

        else if (!util_validChars(p_fForm.address2.value,"_- .&#/'")) 
        	showMessage(saErrors[20],true,p_fForm.address2,"erroraddress2");
        else if (!util_isEmpty(p_fForm.address2.value) && p_fForm.address2.value.length > util_kAddressLine2Len)
        	showMessage(saErrors[20],true,p_fForm.address2,"erroraddress2");

        else if (util_isEmpty(p_fForm.city.value))                          
        	showMessage(saErrors[32],true,p_fForm.city,"errorcitystatezip");
        else if (!util_validChars(p_fForm.city.value,"_- .&'")) 
        	showMessage(saErrors[21],true,p_fForm.city,"errorcitystatezip");
        else if (p_fForm.city.value.length > util_kAddressCityLen)
        	showMessage(saErrors[21],true,p_fForm.city,"errorcitystatezip");
        	
		else if (p_fForm.state.selectedIndex < 1)        	
        	showMessage(saErrors[9],true,p_fForm.state,"errorcitystatezip");

        else if (util_isEmpty(p_fForm.postalcode.value))       
        	showMessage(saErrors[10],true,p_fForm.postalcode,"errorcitystatezip");
        else if (!validate_zip(p_fForm.postalcode.value))      
        	showMessage(saErrors[72],true,p_fForm.postalcode,"errorcitystatezip");

        else if (util_isEmpty(p_fForm.phone.value))       
        	showMessage(saErrors[33],true,p_fForm.phone,"errorphone");
        else if (!util_checkPhone(p_fForm.phone.value)) 
        	showMessage(saErrors[24],true,p_fForm.phone,"errorphone");
        	
        else if ((typeof(cellphone1) != "undefined") &&
                 (typeof(cellphone2) != "undefined"))
        {
	        if (!util_checkPhone(p_fForm.cellphone1.value)) 
	        	showMessage(saErrors[24],true,p_fForm.phone,"errorcellphone1");
	        	
	        else if (!util_checkPhone(p_fForm.cellphone2.value)) 
	        	showMessage(saErrors[24],true,p_fForm.phone,"errorcellphone2");
        
        	else if ((p_fForm.cellphone1.value != "") &&
                 (p_fForm.cellphone2.value != "") &&
                 (p_fForm.cellphone1.value == p_fForm.cellphone2.value))
        	showMessage(saErrors[47],true,p_fForm.phone,"errorcellphone2");
        }
       
        return (!bHaveErrors);
    }

// ----------------------------------------------------------------------------
// Validate answer to question (forgot password).
    function validate_answer(p_fForm,
                             p_strAction) 
    {  
		document.getElementById("erroranswer").style.display = "none";
    
        bHaveErrors = false;

        if (util_isEmpty(p_fForm.answer.value))                       
            showMessage(saErrors[23],true,p_fForm.answer,"erroranswer");
        else if (!util_InRange(1,stringTrim(p_fForm.answer.value).length,util_kAnswerLen))
            showMessage(saErrors[31],true,p_fForm.answer,"erroranswer");
        	
        return (!bHaveErrors);
    }

// ----------------------------------------------------------------------------
// Validate username (forgot password).
    function validate_username(p_fForm,
                               p_strAction) 
    {  
        bHaveErrors = false;

        if (util_isEmpty(p_fForm.username.value))
            showMessage(saErrors[14],true,p_fForm.username,"errorusername");
        else if (!util_userName(p_fForm.username.value)) 
            showMessage(saErrors[15],true,p_fForm.username,"errorusername");
        
        return (!bHaveErrors);
    }

    function validate_getStarted(p_fForm,
                                 p_strAction)
    {
        document.getElementById("formerror").style.display="none";
        document.getElementById("errorcaptcha").style.display="none";
    
        bHaveErrors = false;

        if (util_isEmpty(p_fForm.deviceid.value))
        	showMessage(saErrors[3],true,p_fForm.deviceid,"formerror");
       	else if(!util_validHex(p_fForm.deviceid.value))
         	showMessage(saErrors[5],true,p_fForm.deviceid,"formerror");
       	else if(p_fForm.deviceid.value.length != 12)
         	showMessage(saErrors[5],true,p_fForm.deviceid,"formerror");
        else if(util_isEmpty(p_fForm.captcha.value))
        	showMessage(saErrors[45],true,p_fForm.captcha,"errorcaptcha");         	

      	return (!bHaveErrors);
    }
    
    function validate_postalcode(p_fForm)
    {
       bHaveErrors = false;
       if (util_isEmpty(p_fForm.postalcode.value))       
        	showMessage(saErrors[10],true,p_fForm.postalcode);
       else if(!validate_zip(p_fForm.postalcode.value))      
        	showMessage(saErrors[72],true,p_fForm.postalcode);
        	
       
    }
    
    function getNewCaptcha(p_fForm,
                           p_strURL)
    {
    	// Change the form action to get a new image.
    	p_fForm.action = p_strURL;
    	
    	// Submit the form.
    	p_fForm.submit();
    }

// ----------------------------------------------------------------------------
    function validate_lineup(p_fForm,
                             p_bCheckLineup) 
 	{
 	    bHaveErrors = false;
 	    document.getElementById("errornickname").style.display="none";
        document.getElementById("errorpostalcode").style.display="none";
        
     if (changeLineupZip == "" || changeLineupZip == p_fForm.devicepostalcode.value)
     {         	    
 	    if (util_isEmpty(p_fForm.nickname.value))       
        	showMessage(saErrors[29],true,p_fForm.nickname,"errornickname");
        else if(!util_NickName(p_fForm.nickname.value))      
        	showMessage(saErrors[25],true,p_fForm.nickname,"errornickname");
 	    else if (util_isEmpty(p_fForm.devicepostalcode.value))       
        	showMessage(saErrors[10],true,p_fForm.devicepostalcode,"errorpostalcode");
        else if (!validate_zip(p_fForm.devicepostalcode.value))      
        	showMessage(saErrors[72],true,p_fForm.devicepostalcode,"errorpostalcode");
        else if (p_bCheckLineup)
        {
            var  strProvider = p_fForm.provider.options[p_fForm.provider.selectedIndex].value;
            
        	if ((strProvider != "nochannelmap") && (strProvider != "Over the Air Broadcast") && (p_fForm.lineup.selectedIndex == 0))
        	{
        		showMessage(saErrors[13],true,p_fForm.lineup,"errorlineup");
        		document.getElementById("idSubmitButtons").style.display = "none";
        	}
        }
        //save zip
        changeLineupZip = p_fForm.devicepostalcode.value;
 	 }
 	 else
 	 {
 	    //they changed the zip code lets initialize again
 	    changeLineupZip = p_fForm.devicepostalcode.value
  	    initProvider();
 	    bHaveErrors = true;
 	 }

 	    return (!bHaveErrors);
 	   
 	}

// ----------------------------------------------------------------------------
    function validate_storecheck(p_fForm) 
 	{
 	    bHaveErrors = false;
        document.getElementById("errorpostalcode").style.display="none";
        
	    if (changeLineupZip == "" || changeLineupZip == p_fForm.devicepostalcode.value)
	    {         	    
		    if (util_isEmpty(p_fForm.devicepostalcode.value))       
	       		showMessage(saErrors[10],true,p_fForm.devicepostalcode,"errorpostalcode");
	        else if (!validate_zip(p_fForm.devicepostalcode.value))      
	       		showMessage(saErrors[72],true,p_fForm.devicepostalcode,"errorpostalcode");
	        
	        // save zip
	        changeLineupZip = p_fForm.devicepostalcode.value;
		}
		else
		{
		    //they changed the zip code lets initialize again
		    changeLineupZip = p_fForm.devicepostalcode.value
	 	    initProvider();
		    bHaveErrors = true;
		}
		 
		return (!bHaveErrors);
	   
 	}
 	
// ----------------------------------------------------------------------------
    function validate_adddevice(p_fForm,
                                p_bCheckLineup) 
 	{
 	    bHaveErrors = false;
 	    
 	    document.getElementById("errornickname").style.display="none";
        document.getElementById("errorpostalcode").style.display="none";
        document.getElementById("errorhardwareid").style.display="none";
        if (p_bCheckLineup)
        	document.getElementById("errorlineup").style.display="none";
           
     if (changeLineupZip == "" || changeLineupZip == p_fForm.devicepostalcode.value)
     {   
 	    if (util_isEmpty(p_fForm.nickname.value))       
        	showMessage(saErrors[29],true,p_fForm.nickname,"errornickname");
        else if(!util_NickName(p_fForm.nickname.value))      
        	showMessage(saErrors[25],true,p_fForm.nickname,"errornickname");
        else if(strHouseholdNicknames.indexOf("|" + stringTrim(p_fForm.nickname.value) + "|") != -1)      
        	showMessage(saErrors[49],true,p_fForm.nickname,"errornickname");
 	    else if (util_isEmpty(p_fForm.hardwareid.value))
        	showMessage(saErrors[3],true,p_fForm.hardwareid,"errorhardwareid");
       	else if(!util_validHex(p_fForm.hardwareid.value))
         	showMessage(saErrors[5],true,p_fForm.hardwareid,"errorhardwareid");
       	else if(p_fForm.hardwareid.value.length != 12)
         	showMessage(saErrors[5],true,p_fForm.hardwareid,"errorhardwareid");
        else if (util_isEmpty(p_fForm.devicepostalcode.value))       
        	showMessage(saErrors[10],true,p_fForm.devicepostalcode,"errorpostalcode");
        else if (!validate_zip(p_fForm.devicepostalcode.value))      
        	showMessage(saErrors[72],true,p_fForm.devicepostalcode,"errorpostalcode");
        else if (p_bCheckLineup)
        {
            var  strProvider = p_fForm.provider.options[p_fForm.provider.selectedIndex].value;
            
        	if ((strProvider != "nochannelmap") && (strProvider != "Over the Air Broadcast") && (p_fForm.lineup.selectedIndex == 0))
        	{
        		showMessage(saErrors[13],true,p_fForm.lineup,"errorlineup");
        		document.getElementById("idSubmitButtons").style.display = "none";
        	}
        }
        //save zip
        changeLineupZip = p_fForm.devicepostalcode.value;
 	 }
 	 else
 	 {
 	    //they changed the zip code lets initialize again
 	    changeLineupZip = p_fForm.devicepostalcode.value
  	    initProvider();
 	    bHaveErrors = true;
 	 }
       
 	
 	    return (!bHaveErrors);
 	} 	
 
    function validate_updatedevices(p_fForm,
                                    p_strDeviceIDs,
                                    p_strExistingNicknames) 
    {  
    	bHaveErrors = false;
    	
 	    document.getElementById("errordeviceid").style.display="none";
 	    
 	    // Validate the nicknames.
 	    var  saIDs = p_strDeviceIDs.split("|");
 	    var  saOrigNicknames = p_strExistingNicknames.split("|");
 	    var  eNickname;
 	    
 	    // Note that the OrigNicknames have an extra empty value because the string starts with |.
 	    //   So, we ignore that one.
 	    for (var i = 0; !bHaveErrors && (i < saIDs.length); i++)
 	    {
 	    	eNickname = document.getElementById(saIDs[i]);
 	    	if ((eNickname != null) && (eNickname.value != saOrigNicknames[i+1]))
 	    	{
	            if (util_isEmpty(eNickname.value))       
	        	    showMessage(saErrors[29],true,eNickname,"errordeviceid");
	         	else if(!util_NickName(eNickname.value))      
	        	    showMessage(saErrors[25],true,eNickname,"errordeviceid");
	            else if (p_strExistingNicknames.toLowerCase().indexOf("|" + stringTrim(eNickname.value.toLowerCase()) + "|") != -1)      
	        	    showMessage(saErrors[49],true,p_fForm.nickname,"errordeviceid");
	        }
 	    }
 	    
 	    if (!bHaveErrors)
 	    {
	 	    // See if any of the devices are to be removed.
	    	var  bChecked = false;
	    	
			if (typeof(p_fForm.removedeviceid.length) != "undefined")
			{
			    for (var i = 0; !bChecked && (i < p_fForm.removedeviceid.length); i++)
			    {
			        bChecked = p_fForm.removedeviceid[i].checked;
			    }
			}
			else
				bChecked = p_fForm.removedeviceid.checked;
		    
		    if (bChecked)
		    {
		    	// We are going to remove one or more devices.  Display the warning.
				showLightBox();
			}
			else
				p_fForm.submit();
		}
			        	
        return (!bHaveErrors);
                
    }
 
 
 // ----------------------------------------------------------------------------
    function validate_changelineup(p_fForm,
                                   p_bCheckLineup) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorpostalcode").style.display="none";
        document.getElementById("errorlineup").style.display="none";
     if(changeLineupZip == "" || changeLineupZip == p_fForm.devicepostalcode.value)
     {         	    
 	    if (util_isEmpty(p_fForm.devicepostalcode.value))       
        	showMessage(saErrors[10],true,p_fForm.devicepostalcode,"errorpostalcode");
        else if (!validate_zip(p_fForm.devicepostalcode.value))      
        	showMessage(saErrors[72],true,p_fForm.devicepostalcode,"errorpostalcode");
        else if (p_bCheckLineup)
        {
            var  strProvider = p_fForm.provider.options[p_fForm.provider.selectedIndex].value;
            
        	if ((strProvider != "nochannelmap") && (strProvider != "Over the Air Broadcast") && (p_fForm.lineup.selectedIndex == 0))
        	{
        		showMessage(saErrors[13],true,p_fForm.lineup,"errorlineup");
        		document.getElementById("idSubmitButtons").style.display = "none";
        	}
        }
        //save zip
        changeLineupZip = p_fForm.devicepostalcode.value;
 	 }
 	 else
 	 {
 	    //they changed the zip code lets initialize again
 	    changeLineupZip = p_fForm.devicepostalcode.value
  	    initProvider();
 	    bHaveErrors = true;
 	 }
 	    return (!bHaveErrors);
 	}
 
 
 // ----------------------------------------------------------------------------
    function validate_zipcode(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    bHasNicknameElement = document.getElementById("nickname") != null;
 	    
        document.getElementById("errorpostalcode").style.display="none";
        if (bHasNicknameElement)
 	    	document.getElementById("errornickname").style.display="none";

        if (changeLineupZip == "" || changeLineupZip == p_fForm.devicepostalcode.value)
        {         	    
	 	    if (bHasNicknameElement && util_isEmpty(p_fForm.nickname.value))       
	        	showMessage(saErrors[29],true,p_fForm.nickname,"errornickname");
	        else if (bHasNicknameElement && !util_NickName(p_fForm.nickname.value))      
	        	showMessage(saErrors[25],true,p_fForm.nickname,"errornickname");
 	        else if (util_isEmpty(p_fForm.devicepostalcode.value))       
        	    showMessage(saErrors[10],true,p_fForm.devicepostalcode,"errorpostalcode");
            else if (!validate_zip(p_fForm.devicepostalcode.value))      
        	    showMessage(saErrors[72],true,p_fForm.devicepostalcode,"errorpostalcode");

           //save zip
           changeLineupZip = p_fForm.devicepostalcode.value;
 	    }
 	    else
 	    {
 	    	//they changed the zip code let us initialize again
 	    	changeLineupZip = p_fForm.devicepostalcode.value
 	    	bHaveErrors = true;
 	    }
 	    return (!bHaveErrors);
 	}

// ----------------------------------------------------------------------------
 // Validate device data.
     function validate_devicedata(p_fForm) 
     {  
       bHaveErrors = false;
       
       document.getElementById("errornickname").style.display="none";
               
       if(typeof(p_fForm.deviceid) != "undefined" )
 	   {
	 		if (p_fForm.deviceid.selectedIndex == 0) 
	 			showMessage(saErrors[34],true,p_fForm.deviceid,"errordeviceid");
	   }  
       
       if (p_fForm.nickname != "undefined")
         {
	 	    if (util_isEmpty(p_fForm.nickname.value))       
	        	showMessage(saErrors[29],true,p_fForm.nickname,"errornickname");
         	else if(!util_NickName(p_fForm.nickname.value))      
        	    showMessage(saErrors[25],true,p_fForm.nickname,"errornickname");
            else if(strHouseholdNicknames.indexOf("|" + stringTrim(p_fForm.nickname.value) + "|") != -1)      
        	    showMessage(saErrors[49],true,p_fForm.nickname,"errornickname");
         }
     
         return (!bHaveErrors);
     }

//-----------------------------------------------------------------------------
// validate device remove
	function validate_deviceremove(p_fForm)
	{
	      bHaveErrors = false;
	       	                  
	       if(typeof(p_fForm.deviceid) != "undefined" )
	 	   {
		 		if (p_fForm.deviceid.selectedIndex == 0) 
		 			showMessage(saErrors[35],true,p_fForm.deviceid,"errordeviceid");
		   }  
	      return (!bHaveErrors);
	}
	
// ----------------------------------------------------------------------------
// Validates username and password for login.
    function validate_login(p_fForm) 
    {  
    	var  bUserNameInvalid = false;
    	var  bPasswordInvalid = false;
    	
        bHaveErrors = 0;

        if (util_isEmpty(p_fForm.username.value))
        {
        	bUserNameInvalid = true;
        	showMessage(saErrors[14],true,null,"errorUsername");
        }
        else if (!util_userName(p_fForm.username.value)) 
        {
        	bUserNameInvalid = true;
        	showMessage(saErrors[15],true,null,"errorUsername");
        }

        else if (util_isEmpty(p_fForm.password.value))   
        {
        	bPasswordInvalid = true;
        	showMessage(saErrors[0],true,null,"errorPassword");
        }
        else if (!util_passWord(p_fForm.password.value)) 
        {
        	bPasswordInvalid = true;
        	showMessage(saErrors[1],true,null,"errorPassword");
        }
        
        if (bUserNameInvalid && bPasswordInvalid)
        {
        	// Both fields are invalid.
        	p_fForm.username.value = "";
        	p_fForm.password.value = "";
        	p_fForm.username.focus();
        }
        else if (bUserNameInvalid)
        {
        	// The username field is invalid.
        	p_fForm.username.focus();
        }
        else if (bPasswordInvalid)
        {
        	// The password field is invalid.
        	p_fForm.password.focus();
        }
        
        bHaveErrors = (bUserNameInvalid || bPasswordInvalid);

        return (!bHaveErrors);
    }
	
// ----------------------------------------------------------------------------
// Validates username for csr login.
    function validate_login_csr(p_fForm) 
    {  
        bHaveErrors = 0;

        if (util_isEmpty(p_fForm.csrpassword.value))   
        {
        	showMessage(saErrors[0],true,null,"errorCSRPassword");
        }
        else if (!util_csrpassWord(p_fForm.csrpassword.value)) 
        {
        	showMessage(saErrors[61],true,null,"errorCSRPassword");
        }

        if (bHaveErrors)
        {
        	// The password is invalid.  Clear it.
        	p_fForm.csrpassword.value = "";
        	p_fForm.csrpassword.focus();
        }

        return (!bHaveErrors);
    }

// ----------------------------------------------------------------------------
// Validates search entries
    function validate_Search(p_eSearch,
                             p_strError) 
    {  
    	bHaveErrors = false;
    	
        if (util_isEmpty(p_eSearch.value))
        	showMessage(saErrors[28],true,p_eSearch,p_strError);
        
        return (!bHaveErrors);
                
    }
 
 
 // ----------------------------------------------------------------------------
    function validate_FlickrUserName(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorflickrusername").style.display="none";
         	    
 	    if (util_isEmpty(p_fForm.flickrusername.value)) 
 	    {      
        	showMessage(saErrors[43],true,p_fForm.username,"errorflickrusername");
        }
 	
 	    return (!bHaveErrors);
 	}


    function validate_FlickrUserID(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("erroruserid").style.display="none";
          	    
 	    if (util_isEmpty(p_fForm.userid.value)) 
        	showMessage(saErrors[51],true,p_fForm.userid,"erroruserid");

 	    return (!bHaveErrors);
 	}
 
 
    function validate_FlickrPrivateUser(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorusername").style.display="none";
        document.getElementById("errorpassword").style.display="none";
         	    
 	    if (util_isEmpty(p_fForm.username.value)) 
        	showMessage(saErrors[70],true,p_fForm.username,"errorusername");
 	    else if (util_isEmpty(p_fForm.password.value)) 
        	showMessage(saErrors[71],true,p_fForm.password,"errorpassword");
 	
 	    return (!bHaveErrors);
 	}
 // ----------------------------------------------------------------------------
    function validate_Rhapsody(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorusername").style.display="none";
        document.getElementById("errorpassword").style.display="none";
         	    
 	    if (util_isEmpty(p_fForm.username.value)) 
        	showMessage(saErrors[53],true,p_fForm.username,"errorusername");
 	    else if (util_isEmpty(p_fForm.password.value)) 
        	showMessage(saErrors[54],true,p_fForm.password,"errorpassword");
        	
		if (!bHaveErrors)
		{
			// Go to the next step.
			showElement('step2');
			hideElement('step1')
		}        	
 	
 	    return (!bHaveErrors);
 	}
 
 
 // ----------------------------------------------------------------------------
    function validate_Bookmark(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errortitle").style.display="none";
        document.getElementById("errorurl").style.display="none";
         	    
        if (validate_BookmarkFields(p_fForm,true))
		{
			// Go to the next step.
			showElement('step2');
			hideElement('step1')
		}        	
 	
 	    return (!bHaveErrors);
 	}
 	
 	
 	function  testURL(p_fForm,
 	                  p_strTestPage)
 	{
        document.getElementById("errortitle").style.display="none";
        document.getElementById("errorurl").style.display="none";

        if (validate_BookmarkFields(p_fForm,false))
        {
            window.open(p_strTestPage + "?url=" + escape(p_fForm.url.value),'mywindow','left=0,top=0,screenX=0,screenY=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes');
        }
 	}
 	
 	
 	function  validate_BookmarkFields(p_fForm,
 	                                  p_bCheckTitle)
 	{
 	    bHaveErrors = false;

 	    if (p_bCheckTitle && util_isEmpty(p_fForm.title.value)) 
        	showMessage(saErrors[57],true,p_fForm.title,"errortitle");
        else if (p_bCheckTitle && stringTrim(p_fForm.title.value).length > util_kBookmarkTitleLength)
        	showMessage(saErrors[62],true,p_fForm.username,"errortitle");
 	    else if (util_isEmpty(p_fForm.url.value)) 
        	showMessage(saErrors[58],true,p_fForm.url,"errorurl");
        else if (stringTrim(p_fForm.url.value).length > util_kBookmarkURLLength)
        	showMessage(saErrors[63],true,p_fForm.username,"errorurl");
        else if (!validateURL(p_fForm.url.value))
        	showMessage(saErrors[59],true,p_fForm.url,"errorurl");
        	
        return(!bHaveErrors);
 	}
 
 
 // ----------------------------------------------------------------------------
    function validate_YouTube(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorusername").style.display="none";
        document.getElementById("errorpassword").style.display="none";
         	    
 	    if (util_isEmpty(p_fForm.username.value)) 
        	showMessage(saErrors[55],true,p_fForm.username,"errorusername");
 	    else if (util_isEmpty(p_fForm.password.value)) 
        	showMessage(saErrors[56],true,p_fForm.password,"errorpassword");
 	
 	    return (!bHaveErrors);
 	}


    function validate_CinemaNow(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorusername").style.display="none";
        document.getElementById("errorpassword").style.display="none";
         	    
 	    if (util_isEmpty(p_fForm.username.value)) 
        	showMessage(saErrors[66],true,p_fForm.username,"errorusername");
 	    else if (util_isEmpty(p_fForm.password.value)) 
        	showMessage(saErrors[67],true,p_fForm.password,"errorpassword");
 	
 	    return (!bHaveErrors);
 	}


    function validate_VuDu(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
        document.getElementById("errorusername").style.display="none";
        document.getElementById("errorpassword").style.display="none";
         	    
 	    if (util_isEmpty(p_fForm.username.value)) 
        	showMessage(saErrors[68],true,p_fForm.username,"errorusername");
 	    else if (util_isEmpty(p_fForm.password.value)) 
        	showMessage(saErrors[69],true,p_fForm.password,"errorpassword");
 	
 	    return (!bHaveErrors);
 	}


	// Use the following for the onSubmit of a form
	//   if you don't want the form automatically submitted via Enter.
	function  doNothing()
	{
		return(false);
	}


	// Use the following to submit a form without doing the onSubmit.
	function  submitForm(p_fForm)
	{
		p_fForm.submit();
	}

/* ----------------------------------------------------------------------------

                    Statusbar display functions

 ==============================================================================
*/

    function  setStatus(sMessage)
    {
       status = sMessage;
       return(true);
    }
// ----------------------------------------------------------------------------


/*
==============================================================================

                    Browser functions 

 ==============================================================================
*/  

// Determine if we are running in an acceptable browser.
//   The browser must be IE 6+  or FireFox 2+
function validate_browser(p_strWarning)
{
	var  bBrowserOK = false;
	var  strAppName = navigator.appName;
	var  strAppVersion = navigator.appVersion;
	var  fVersion = parseFloat(strAppVersion.substring(0,strAppVersion.indexOf(" ")));
	
	if (((strAppName.indexOf("Microsoft Internet Explorer") != -1) && (fVersion >= 4)) ||
	    ((strAppName == "Netscape")  && (fVersion >= 5)))
		bBrowserOK = true;
		
	if (!bBrowserOK)
		alert(p_strWarning);	
}


// Determine if cookies are enabled.
function areCookiesEnabled()
{
	var bCookieEnabled = (navigator.cookieEnabled)? true : false
	
	//if not IE4+ nor NS6+
	if (typeof navigator.cookieEnabled=="undefined" && !bCookieEnabled)
	{ 
		document.cookie="testcookie"
		bCookieEnabled=(document.cookie=="testcookie")? true : false
		document.cookie="" //erase dummy value
	}

	return(bCookieEnabled);
}

/*
==============================================================================

                    Checkbox Selection functions 

 ==============================================================================
*/  

	// Either checks or unchecks all of the check boxes.
	function setAllCheckboxes(p_cbBoxes,
	                          p_bSelect)
	{
		if (typeof(p_cbBoxes.length) != "undefined")
		{
		    for (var i = 0; i < p_cbBoxes.length; i++)
		    {
		        p_cbBoxes[i].checked = p_bSelect;
		    }
		}
		else
			p_cbBoxes.checked = p_bSelect;
	}

    function enableRateCode(p_eEnable,
                            p_strURL)
	{
		var  strEnable;
		
		if (p_eEnable.checked)
			strEnable = "enable";
		else
			strEnable = "disable";
			
		top.location.href = p_strURL + "&enableaction=" + strEnable;
	}                                    

	// Navigate to the editdevice page passing the hardware ID.
	function navigateEditDevice(p_fForm,
	                            p_strDeviceID,
	                            p_strURL)
	{
		var  strURL = p_strURL;
	 	
	 	if (p_strDeviceID != null)
	 		strURL += "&deviceid=" + p_strDeviceID;
	 	else
	 	    strURL += "&deviceid=" + p_fForm.deviceid.options[p_fForm.deviceid.selectedIndex].value;
	 	
	     top.location.href = strURL;
	}
 
	function changeeulastates(p_bAccept)
	{
	    document.getElementById('accept').checked = p_bAccept;
	    document.getElementById('decline').checked = !p_bAccept;
	    document.getElementById('submitaccept').disabled = !p_bAccept;
	}
	
	
	function setChannelLineupState()
	{
		var  bUsesOTA = document.getElementById("usesota").checked;
		var  eProvider = document.getElementById("provider");
		var  eLineup = document.getElementById("lineup");
	
		if(eProvider != undefined && eProvider != "undefined")
		{
	 		eProvider.disabled = bUsesOTA;
			eLineup.disabled = bUsesOTA;
		}
		
	}

	function showDialog(dialog, show)
	{
	   if(show)
	     document.getElementById(dialog).style.display = "block";
	   else
	     document.getElementById(dialog).style.display = "none";
	}
	
	function checkForm()
	{
		var el = document.forms[0].elements;
		for(var i = 0 ; i < el.length ; ++i)
		{
			if(el[i].type == "checkbox") 
			{
				if(el[i].checked)
				{
				  return true;
				}
			
		    }
	    }
	} 

  function getChannelMap(url,pars,mode,strProvider,strLineup)
  {
      if(pars != "")
        strURL =  url+"&"+pars;
      else
        strURL = url;     

      advAJAX.get({
    	url: strURL ,
   		onInitialization : function() {
       	 	  /* Show distractor dialog */
       	 	  if (mode == "channelmap")
       	 	  {
       	 	      document.getElementById("channelmapform").style.display = "block";
       	 	      //show distractor
       	 	      document.getElementById("providerdistractor").style.display = "block";
	    		  
	    		  //hide lineup select
  	       		  document.getElementById("idChannelProvider").style.display = "none";
  	       		  document.getElementById("idSubmitButtons").style.display = "none";
  	       		  document.getElementById("showhidelisting").style.display = "none";
  	       	
  	       		  //hide line up
	       		  document.getElementById("idChannelLineup").style.display = "none";
       	 	  }
       	 	  else if (mode == "channelmap_check")
       	 	  {
       	 	      document.getElementById("channelmapform").style.display = "block";
       	 	      document.getElementById("providerdistractor").style.display = "block";
	    		  
	    		  //hide provider select
  	       		  document.getElementById("idChannelProvider").style.display = "none";
       	 	  }
			  ajaxState = INITSTATE;
    	},
      	onSuccess : function(obj) {
      	
       	 	if ((mode != "channelmap_check") && (mode != "channelLineup_check"))
       	 	{
	            //hide the lineup
	       		document.getElementById("idSubmitButtons").style.display = "none";
	       		document.getElementById("showhidelisting").style.display = "none";
	       	}
       	
       		if (mode == "channelmap")
       		{
    		  // Hide the distractor
  	       	  document.getElementById("providerdistractor").style.display = "none";

       		  // Populate the provider drop down
    		  setChannelMap(obj.responseXML,true);
    		  document.getElementById("idChannelProvider").style.display = "block";
       		}
       		else if (mode == "channelmap_check")
       		{
    		  // Hide the distractor
  	       	  document.getElementById("providerdistractor").style.display = "none";

       		  // Populate the provider drop down
    		  setChannelMap(obj.responseXML,false);
    		  document.getElementById("idChannelProvider").style.display = "block";
       		}
            else if ((mode == "channelLineup") || (mode == "channelLineup_check"))
            {
               var selObj = document.frmDeviceData.provider.options[document.frmDeviceData.provider.selectedIndex].value

               if(selObj != "Over the Air Broadcast")
               {    
                 document.getElementById("idChannelLineup").style.display = "block";
	             setLineup(obj.responseXML);
	           }
	           else		             
	             setOTA(obj.responseXML);
		           
	           //hide distractor
  	       	   document.getElementById("providerdistractor").style.display = "none";
            }
	        else if(mode == "channelview")
	        {
	              //View lineup
	              document.getElementById("idSubmitButtons").style.display = "block";
	              document.getElementById("showhidelisting").style.display = "block";
	              document.getElementById("viewlineup").innerHTML = obj.responseText;            
	         }

       		ajaxState = SUCCESSSTATE;
  		},
    	onError : function(obj) {
           /* In case of error we show an alert */
           alert("Error: " + obj.status);
           ajaxState = ERRORSTATE;
	    },
    	onFinalization : function() {
    		 ajaxState = COMPLETESTATE;
        	 if(mode == "channelmap")
	       	 {
	    		if(strProvider != "null" && strProvider != "")
	    		{
	    		    if(typeof(document.getElementById(strProvider)) == 'object' && document.getElementById(strProvider) != null)
	    		    {
         		       document.getElementById(strProvider).selected=true;
         		       getLineup(document.frmDeviceData.provider);
         		    }
         		}
	       	 }
	         else if (mode == "channelLineup")
	         {
	            if (strLineup != "null" && strLineup != "")
	            {
	                if(typeof(document.getElementById(strLineup)) == 'object' && document.getElementById(strLineup) != null)
	    		    {
         		       document.getElementById(strLineup).selected=true;
         		       viewlineup(document.frmDeviceData.lineup)
         		    }
         		}
	         }
	 
	        

        }
       });
  }
   
  function setChannelMap(xmlobj,
                         p_bAddOTA)
  {
       //Set lineup to length to 0 and initialize select
       document.frmDeviceData.provider.options.length = 0;
       appendOptionLast(document.frmDeviceData.provider,"Select","nochannelmap")
       //if (p_bAddOTA)
       //	   appendOptionLast(document.frmDeviceData.provider,"Over the Air Broadcast","Over the Air Broadcast")
       
       //get the root element
	   var helist = xmlobj.getElementsByTagName("he_list");
	
	   //list of child nodes   
	   var childNodeList = helist[0].childNodes
	   
	   //match
	   var bMatch = false;

	   //itereate over the child nodes
	   for (var i=0; i < childNodeList.length; i++)
	   {
  
	       var zipcode = document.frmDeviceData.devicepostalcode.value;
	       
	       if (zipcode.length > 5)
	           zipcode = zipcode.substr(0,5);
	       
	       if(childNodeList[i].childNodes.length != 0 )
	       {
               var zipList = childNodeList[i].childNodes[0].nodeValue;
	           if(zipList.indexOf(zipcode) != -1)
		       {
		          //get the name attr	       
		          var chMapName = childNodeList[i].getAttribute("n");
		      
		          //add to dropdown;
		          appendOptionLast(document.frmDeviceData.provider,chMapName,chMapName);
		          
		          //found match
		          bMatch =  true
		       } 
		   }
	   }
	
	   //show error message
	   if(!bMatch)
	   {
           document.frmDeviceData.provider.options.length = 0;
           appendOptionLast(document.frmDeviceData.provider,"Cable providers not available for this zip code","nochannelmap");
           //if (p_bAddOTA)
           //    appendOptionLast(document.frmDeviceData.provider,"Over the Air Broadcast","Over the Air Broadcast");
       }
    }
       		
    function setOTA(xmlobj)
    {
  
      //Set lineup to length to 0
      document.frmDeviceData.lineup.options.length = 0;
      appendOptionLast(document.frmDeviceData.lineup,"Select","none")
  
      // get the list of lineup nodes
      var nlNodeList = xmlobj.getElementsByTagName("l");
       
      var bMatch = false;
      
      if(nlNodeList.length > 0)
      {
      
	      var headend = "";
	      
	      //get the account and node zip
	      var zipcode = document.frmDeviceData.devicepostalcode.value;
	
	      if (zipcode.length > 5)
	          zipcode = zipcode.substr(0,5);

		  for (var i=0; !bMatch && (i < nlNodeList.length); i++)
		  {
		       var attlist = nlNodeList[i];
		       var objAttribute = attlist.getAttributeNode("z");
                      	         
	          
		       if(objAttribute.value.indexOf(zipcode) != -1)
		       {       
		          //populate our variables from the node attributes
			      headend = attlist.getAttributeNode("h").value;
			      bMatch = true;
			      break;
			   }
		  }
	
	      if(headend != "")
	          viewOTAlineup(headend);
	      else
	          bMatch = false;
      }

      //show error message
      if(!bMatch)
          alert("Lineup not available for this area");
  }
  
  
  function setLineup(xmlobj)
  {
      //Set lineup to length to 0
      document.frmDeviceData.lineup.options.length = 0;
      appendOptionLast(document.frmDeviceData.lineup,"Select","nolineup")
  
      // get the list of lineup nodes
      var List = xmlobj.getElementsByTagName("l");
      
      //var childNodeList = List[0].childNodes;

      var bMatch = false;
   
      // Iterate in reverse order so that the digital lineups appear before the analogs
	  for (var i=List.length-1; i >= 0 ; i--)
	  {
	       //get the account and node zip
	       var zipcode = document.frmDeviceData.devicepostalcode.value;
	       
	       if (zipcode.length > 5)
	           zipcode = zipcode.substr(0,5);
	       
	       var attlist = List.item(i).attributes;
           var zipList = attlist.getNamedItem("z").value;
 
	       if(zipList.indexOf(zipcode) != -1)
	       {       
	    
	             //populate our variables from the node attributes
		          var communityName = attlist.getNamedItem("c").value;
		          var headend = attlist.getNamedItem("h").value;
		          var device = "";
	 	         
		          if(attlist.getNamedItem("d") != null)
		          {
		               device =  attlist.getNamedItem("d").value;
		                device="."+device;
		          }
			          
	
	              //Create the value
		          var selValue = headend+device+"|"+communityName;
            	
		          //add to dropdown;
		          appendOptionLast(document.frmDeviceData.lineup,communityName,selValue);
		          
		          bMatch = true;
		   }
	   
	  }
      
      //first option should be selected
      document.getElementById('lineup').options[0].selected=true;
      
      //show error message
      if(!bMatch)
      {
          document.frmDeviceData.lineup.options.length = 0;
          appendOptionLast(document.frmDeviceData.lineup,"Lineup not available for this area","");
      }
  }
  
  function appendOptionLast(elSel,selText,selValue)
  {
      //create a option element
	  var elOptNew = document.createElement('option');
	  
	  //assign test and value to option tag
	  elOptNew.text  = selText;
	  elOptNew.value = selValue;
	  elOptNew.id    = selValue;
	  
	  //add to select element
	  try 
	  {
	    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
	  }
	  catch(ex) 
	  {
	    elSel.add(elOptNew); // IE only
      }
  }
  
  
    // SwapNavImage 
	// Sets the src attribute of the image object passed.
  function SwapNavImage(obj, Image)
  {
	    obj.src = Image;
  }
	
  function SwapClass(obj, NewClass)
  {   
	    obj.style.className = NewClass;
  }
	
    //Cookie to preserve scroll position
    function setScrollPosition()
    {
	    var intY = document.getElementById("schedule").scrollTop;
	    document.cookie = "yPos=!~" + intY + "~!";
    }
	
    function setPositionCookie()
    {
	    var strCook = document.cookie;
	
	    if (strCook.indexOf("!~")!=0)
	    {
	        var intS = strCook.indexOf("!~");
	        var intE = strCook.indexOf("~!");
	        var strPos = strCook.substring(intS+2,intE);
	        document.getElementById("schedule").scrollTop = strPos;
	     }
    }
  
	function changeDevice(p_strURL)
	{
	    var eDate = document.getElementById("startDate");
	    var eTime = document.getElementById("startTime");
	    var strURL = p_strURL;
	    
	    if ((eDate != null) && (typeof(eDate) != "undefined"))
	    	strURL += "&startDate=" + eDate.value;
	    
	    if ((eTime != null) && (typeof(eTime) != "undefined"))
	    	strURL += "&startTime=" + eTime.value;

	    var objSelDevice = document.getElementById("device");
	    var deviceID = objSelDevice.options[objSelDevice.selectedIndex].value;
	    
	    if (typeof(deviceID) != "undefined")
	    {
	        strURL += "&device=" + deviceID;
	    }
	    
	    this.window.location.href = strURL;
	}


	function showProblemQuestion(eQuestion)
	{
	    // Hide the error string.
        document.getElementById("erroraddquestion").style.display="none";
        
		// Show the data for the selected question and hide the others.
		for (var i = 0; i < eQuestion.length; i++)
		{
			var  strQuestion = eQuestion[i].value;
			var  eElement = document.getElementById(strQuestion);
			
			if ((eElement != null) && (typeof eElement != "undefined"))
			{
				if (i == eQuestion.selectedIndex)
				{
					// Show this one.
					eElement.style.display = "block";
				}
				else
				{
					// Hide this one.
	              	eElement.style.display = "none";
				}
			}
		}
	}


 // ----------------------------------------------------------------------------
    function validate_troubleticket(p_fForm,
                                    p_bHasDevices) 
 	{
 	    bHaveErrors = false;
 	    
 	    document.getElementById("errorfullname").style.display="none";
        document.getElementById("errorproblemdate").style.display="none";
        document.getElementById("errorproblemtime").style.display="none";
        if (p_bHasDevices)
        	document.getElementById("erroraddquestion").style.display="none";
        document.getElementById("errorcomments").style.display="none";
        
        
 	    if (util_isEmpty(p_fForm.fullname.value))       
        	showMessage(saErrors[36],true,p_fForm.fullname,"errorfullname");
        else if (util_isEmpty(p_fForm.problemdate.value))       
        	showMessage(saErrors[41],true,p_fForm.problemdate,"errorproblemdate");
 	    else if (util_isEmpty(p_fForm.problemtime.value))
        	showMessage(saErrors[37],true,p_fForm.problemtime,"errorproblemtime");
        else if (p_bHasDevices && p_fForm.addquestion.selectedIndex == 0)
        	showMessage(saErrors[38],true,p_fForm.problemtime,"erroraddquestion");
        else if (!p_bHasDevices && util_isEmpty(p_fForm.comments.value))
        	showMessage(saErrors[73],true,p_fForm.problemdate,"errorcomments");
 	
 	    return (!bHaveErrors);
 	}
 	 	
	function submitProblem(p_fForm,
	                       p_bHasDevices)
	{
	   // First validate fields
	   var  bOK = validate_troubleticket(p_fForm,p_bHasDevices);
	   
       if (bOK)
       {
		    var  eLongDesc = document.getElementById("longdesc");
			var  strLongDesc = "";
			
			// See if an additional question is selected.
			var  eQuestion = document.getElementById("addquestion");
			
			if (p_bHasDevices && (eQuestion.selectedIndex > 0))
			{
				// Get the extra info.
				var  strData = eQuestion[eQuestion.selectedIndex].value;
				var  bDone = false;
				var  strName;
				var  strValue;
				var  eNext;
				
				for (var i = 1; !bDone; i++)
				{
					strValue = null;
					
					eNext = document.getElementById(strData + "_" + i);
					if ((eNext == null) || (typeof eNext == "undefined"))
						bDone = true;
					else
					{
						strName = document.getElementById(strData + "_" + i + "_label").innerHTML;
						if (eNext.type == "radio")
						{
							// Find the selected radio button for this group.
							var  aGroup = eval("document.problemdata." + eNext.name);
							
							for (var j = 0; j < aGroup.length; j++)
							{
								if (aGroup[j].checked)
									strValue = aGroup[j].value;
							}
						}
						else if ((eNext.type == "checkbox") && eNext.checked)
						{
							strValue = eNext.value;
						}
						else
						{
							strValue = eNext.value;
						}
						if ((strValue != null) && (strValue != ""))
							strLongDesc += strName + "  " + strValue + "\n\n";
					}
				}
				
				eLongDesc.value = strLongDesc;
			}
		}
		
		return(bOK);
	}
   
    function validate_registrationtroubleticket(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
 	    document.getElementById("errorfullname").style.display="none";
 	    document.getElementById("errorhardwareid").style.display="none";
        document.getElementById("erroremail").style.display="none";
        document.getElementById("errorcontacttime").style.display="none";
        document.getElementById("errorphone").style.display="none";
        document.getElementById("errorrouter").style.display="none";
        
 	    if (util_isEmpty(p_fForm.fullname.value))       
        	showMessage(saErrors[36],true,p_fForm.fullname,"errorfullname");
 	    else if (util_isEmpty(p_fForm.hardwareID.value))       
        	showMessage(saErrors[3],true,p_fForm.hardwareID,"errorhardwareid");
       	else if(!util_validHex(p_fForm.hardwareID.value))
         	showMessage(saErrors[5],true,p_fForm.hardwareID,"errorhardwareid");
       	else if(p_fForm.hardwareID.value.length != 12)
         	showMessage(saErrors[5],true,p_fForm.hardwareID,"errorhardwareid");
 	    else if (util_isEmpty(p_fForm.phone.value))
        	showMessage(saErrors[33],true,p_fForm.phone,"errorphone");
        else if (!util_checkPhone(p_fForm.phone.value))
        	showMessage(saErrors[24],true,p_fForm.phone,"errorphone");
 	    else if (util_isEmpty(p_fForm.email.value))
        	showMessage(saErrors[11],true,p_fForm.email,"erroremail");
        else if (!util_IsEmail(p_fForm.email.value))
        	showMessage(saErrors[16],true,p_fForm.email,"erroremail");
        else if (p_fForm.contacttime.selectedIndex == 0)
        	showMessage(saErrors[65],true,p_fForm.contacttime,"errorcontacttime");
 	    else if (util_isEmpty(p_fForm.router.value))
        	showMessage(saErrors[64],true,p_fForm.router,"errorrouter");
 	
 	    return (!bHaveErrors);
 	}

    function validate_chat(p_fForm) 
 	{
 	    bHaveErrors = false;
 	    
 	    document.getElementById("erroremail").style.display="none";
        document.getElementById("errorphone").style.display="none";
        
        
 	    if (util_isEmpty(p_fForm.email.value))       
        	showMessage(saErrors[11],true,p_fForm.email,"erroremail");
        else if (!util_IsEmail(p_fForm.email.value))
        	showMessage(saErrors[16],true,p_fForm.email,"erroremail");
        else if (util_isEmpty(p_fForm.phone.value))       
        	showMessage(saErrors[33],true,p_fForm.phone,"errorphone");
        else if (!util_checkPhone(p_fForm.phone.value))
        	showMessage(saErrors[24],true,p_fForm.phone,"errorphone");
 	
 	    return (!bHaveErrors);
 	}
 	 	
	//resize a page
	function resizeWin(strWidth,strHeight)
	{
      window.resizeTo(strWidth,strHeight);
    }
    
    function enterKeyDown(evnt,
                          p_strValidate) 
    {
        if (evnt.keyCode == 13)
        {
    		validateLineupSubmit(p_strValidate);
        }
    }
    
    function validateLineupSubmit(p_strValidate) 
    {
        // Note: The variable bSupportsLineups must be defined on the calling page
        
        var fForm = document.frmDeviceData;
        
    	if (bSupportsLineups)
    	{
            if ((p_strValidate == "storecheck") ||
                (document.getElementById("showhidelisting").style.display != "block"))
            {
               initProvider();
            }
            else if (document.getElementById("showhidelisting").style.display == "block")   
            {	
        		if (p_strValidate == "registration")
        		{
        			if (validate_lineup(fForm,true))
        				fForm.submit();	
        		}
        		else if (p_strValidate == "add")
        		{
        			if (validate_adddevice(fForm,true))
        				fForm.submit();
        		}
        		else if (p_strValidate == "editlineup")
        		{
        			if (validate_changelineup(fForm,true))
        				fForm.submit();
        		}
            }
        }
        else
		{
			// Lineups are not supported.
    		if (p_strValidate == "registration")
    		{
    			if (validate_zipcode(fForm))
    				fForm.submit();
    		}
    		else  if (p_strValidate == "add")
    		{
				if (validate_adddevice(fForm,false))
					fForm.submit();
			}
    		else if (p_strValidate == "editlineup")
    		{
    			if (validate_zipcode(fForm,true))
    				fForm.submit();
    		}
		}	
    }

/*
==============================================================================

                    GetRecordings functions 

 ==============================================================================
*/  

   
    /*
     * Get the recordings
     * 
     * @param  p_strURL        The URL to get the recordings from a device
     * @param  p_strMode       If "markrecordingstatus", the programs will be marked to indicate status
     *                         If "scheduled", display a table of the scheduled programs
     *                         If "scheduledrecorded", display a table of the scheduled and recorded programs
     * @param  p_strModeURL    URL to use if mode is scheduled or recorded
     * @param  p_aryShowTimes  Array of the IDs for the shows                    
     */
    function getRecordings(p_strURL,
                           p_strMode,
                           p_strModeURL,
                           p_aryShowTimes)
    {
	    var  eRecordingsDistractor = document.getElementById("recordingsdistractor");
	    
    	if (p_aryShowTimes != null)
        	aryShowTimes = p_aryShowTimes;
        
        advAJAX.get
        (
            {
                url: p_strURL,
                onInitialization : function()
                {
	       	 	    // Show distractor
	       	 	    if (eRecordingsDistractor != null)
	       	 	    	eRecordingsDistractor.style.display = "block";
	       	 	    
                    //show message on status line that we are beginning
                    window.status="retrieving recording status";
                    ajaxState = INITSTATE;
                    getRecordingURL = p_strURL;
                },
                onSuccess : function(obj)
                {
                    //Capture an array of the record nodes
                    var xmldoc = obj.responseXML;
                    arRecord = xmldoc.getElementsByTagName('record');
                    ajaxState = SUCCESSSTATE
                },
                onError : function(obj)
                {
                    //Error
                    var  xmldoc = obj.responseXML;
                    var  errorRecord = xmldoc.getElementsByTagName('pageerror');
                   
                    // todo - how to handle error?
                    //document.getElementById("default_dialog").innerHTML = errorRecord.item(0).getAttribute("message");
                    //document.getElementById("default_dialog").style.display = "block";
                   
                    alert(errorRecord.item(0).getAttribute("message"));
                  
                    ajaxState = ERRORSTATE;
                },
                onFinalization : function()
                {
	       	 	    // Hide distractor
	       	 	    if (eRecordingsDistractor != null)
	       	 	    	eRecordingsDistractor.style.display = "none";
	       	 	    
                    // Build the array of recordings data
                    if (ajaxState != ERRORSTATE)
                    {
                        buildRecordStatus(arRecord);
				        if (p_strMode == "markrecordingstatus")
				        {
			                MarkAllRecordStatus();
				        }
				        else if (p_strMode == "scheduled")
				        {
				            // Display a table of the scheduled programs
				            getScheduledGrid(p_strModeURL);
				        }
				        else if (p_strMode == "scheduledrecorded")
				        {
				            // Display a table of the scheduled/recorded programs
        					getScheduledRecorded(p_strModeURL,strCurrentTab);
				        }
                        ajaxState = COMPLETESTATE;
                    }
                    window.status="retrieving recording status complete";
                }
    
            }
        );
    }
   
   
    /*
     * Rerun getRecordings.
     */
    function seriesUpdate()
    {
        getRecordings(getRecordingURL + "&force=1","markrecordingstatus",aryShowTimes);
    }
   
   
    /*
     * Determine if the UI has a scheduled or active 
     * recording and apply the appropriate graphic
     */
    function MarkAllRecordStatus()
    {
		for (var i = 0; i < arobjRecording.length; i++)
		{
		    MarkRecordStatus(arobjRecording[i]);
		}
    }
   
   
    /*
     * Determine if the UI has a scheduled or active 
     * recording and apply the appropriate graphic
     */
    function MarkRecordStatus(obj)
    {
        // Make sure it exists
        var objElem = isInRange(obj.stationid);
       
        if (objElem != null)
        {  
            // Determine the status and show the appropriate image
            if (typeof(document.getElementById(objElem)) == "object")
            {
                if (obj.status == "future")
                    document.getElementById(objElem).className =  "state_scheduled";
                else if(obj.status == "recording")
                    document.getElementById(objElem).className = "state_recording";
            }
        }
    }
   
    /*
     * Add in a newly recorded program
     */
    function addtoRecordArray(p_station,
                              p_channel,
                              p_start,
                              p_status)
    {
        // Check for a subchannel
        var subChannel = "";
       
        var index = p_channel.indexOf(".");
      
        if (index != -1)
            subChannel = p_channel.substring(index,index+1);
          
        arobjRecording[arobjRecording.length] = new objRecording(p_station,
                                                                 p_channel,
                                                                 subChannel,
                                                                 "",
                                                                 p_start,
                                                                 "",
                                                                 "",
                                                                 p_status);
    }
    
   
    /*
     * set record to removed state
     */
    function removeRecordArray(p_recordID,p_status)
    {
        for(var i = 0; i < arobjRecording.length; i++)
        {
            if(arobjRecording[i].stationid == p_recordID)
            {
                arobjRecording[i].status = p_status;
            }
        }
    }
   
   
    /*
     * Load up our custom object with recording data
     */
    function  buildRecordStatus(p_arRecords)
    {
        var counter = 0;
      
        for (var i = 0; i < p_arRecords.length; i++)
        {
            var recordElement = p_arRecords.item(i);
          
            if (recordElement.getAttribute("status") == "future" || recordElement.getAttribute("status") == "recording")
            {
                //Build our recording object              
                arobjRecording[counter] =  new objRecording(recordElement.getAttribute('station'),
                                                            recordElement.getAttribute('channel'),
                                                            recordElement.getAttribute('subchannel'),
                                                            recordElement.getAttribute('program'),
                                                            recordElement.getAttribute('start'),
                                                            recordElement.getAttribute('end'),
                                                            recordElement.getAttribute('title'),
                                                            recordElement.getAttribute('status'));
                counter++;
            }
        }
    }
   
    
    /*
     * Record status Object
     */
    function objRecording(p_station,p_channel,p_subChannel,p_program,p_start,p_end,p_title,p_status)
    {
        
        this.station       = p_station; 
        this.channel       = p_channel;
        if(p_subChannel != null)
           this.subchannel = "."+p_subChannel;
        else
           this.subchannel = "";
        this.program       = p_program;
        this.startTime     = p_start;
        this.endTime       = p_end;
        this.title         = p_title
        this.status        = p_status;
        this.stationid     = p_station+"_"+p_channel+this.subchannel+"-"+p_start;
    }
    
    
    function isInRange(DateclientProgramID)
    {

        var clientAirDate = DateclientProgramID.split("-");
        var strID = clientAirDate[0];
        var clientAirDate = clientAirDate[1];

          for(var i = 0;i < aryShowTimes.length;i++)
          { 
              
              var strProgramIDs = aryShowTimes[i].split(":");
              if(strProgramIDs[0] != "" && strProgramIDs[1] != "")
              {
                  var strAirDate  =     strProgramIDs[0].split("-");
                  var strEndDate  =     strProgramIDs[1].split("-");

                  if(strAirDate[0] == strID)
                  {

                    if(date2Millis(clientAirDate) >= date2Millis(strAirDate[1])  &&    date2Millis(clientAirDate) < (date2Millis(strEndDate[1])))
                         return strID+"-"+strAirDate[1];
                  }
              }
          }
          return null;
    }
    
    function date2Millis(dbDateFormat)
    {
        var iYear  = dbDateFormat.substr(0,4);
        var iMonth = dbDateFormat.substr(4,2);
        var iDay   = dbDateFormat.substr(6,2);
        var iHour  = dbDateFormat.substr(9,2);
        var iMin   = dbDateFormat.substr(11,2);
        var iSec   = dbDateFormat.substr(13,2);
       
        var dDate = new Date(iYear,iMonth-1,iDay,iHour,iMin,iSec);
        
        return dDate.getTime();
      
    }
    
    function populateTimes(p_strStartTime,
                           p_iNow)
    {
    	var saTimes = new Array('12:00 AM','12:30 AM','01:00 AM','01:30 AM','02:00 AM','02:30 AM','03:00 AM','03:30 AM','04:00 AM','04:30 AM','05:00 AM','05:30 AM','06:00 AM','06:30 AM','07:00 AM','07:30 AM','08:00 AM','08:30 AM','09:00 AM','09:30 AM','10:00 AM','10:30 AM','11:00 AM','11:30 AM','12:00 PM','12:30 PM','01:00 PM','01:30 PM','02:00 PM','02:30 PM','03:00 PM','03:30 PM','04:00 PM','04:30 PM','05:00 PM','05:30 PM','06:00 PM','06:30 PM','07:00 PM','07:30 PM','08:00 PM','08:30 PM','09:00 PM','09:30 PM','10:00 PM','10:30 PM','11:00 PM','11:30 PM');
        var wDates = document.getElementById("startDate");
        var wTimes = document.getElementById("startTime");
        var iStart = 0;
        var iOption = 0;
        var iSelected = 0;
        var strSelectedTime = p_strStartTime;

        if (wTimes.options.length > 0)
            strSelectedTime = wTimes.options[wTimes.selectedIndex].value;
        
        if (wDates.selectedIndex == 0)
        {
            // Today is selected.  Restrict the times list.
            iStart = p_iNow;
        }

        // Build the start times dropdown.
        wTimes.options.length = 0;
        
        for (var i = iStart; i < saTimes.length; i++)
        {
            var newOption 
         
            if (saTimes[i] == strSelectedTime)
            {
               //set selected true non IE browser
               newOption = new Option(saTimes[i],saTimes[i],true);
               
               //set selected for IE
               newOption.selected = true; 
            }
            else
               newOption = new Option(saTimes[i],saTimes[i]);
             
            wTimes.options[iOption] = newOption   
        
            iOption += 1;
        }
     
    }
    
    /*
     * Show a grid of the scheduled programs
     */
    function getScheduledGrid(p_strURL)
    {
      	var  eDate = document.getElementById("startDate");
    	var  strURL = p_strURL;
    	
    	if (eDate != null)
    		strURL += "&startdate=" + eDate.options[eDate.selectedIndex].value;
    	
        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
       	 	    // Show distractor dialog
       	 	    document.getElementById("recordingsdistractor").style.display = "block";
	    		  
	    		// Hide recordings
  	       		document.getElementById("recordings").style.display = "none";

			    ajaxState = INITSTATE;
    	    },
      		onSuccess : function(obj) 
      		{
    		    // Hide the distractor
  	       	    document.getElementById("recordingsdistractor").style.display = "none";

				// Show the data
	            document.getElementById("recordings").style.display = "block";
	            document.getElementById("viewrecordings").innerHTML = obj.responseText;            
		       		ajaxState = SUCCESSSTATE;
  			},
    		onError : function(obj) 
    		{
    		    // Hide the distractor
       	 	    document.getElementById("recordingsdistractor").style.display = "none";
       	 	    
	            // In case of error we show an alert/
	            alert("Error: " + obj.status);
	            ajaxState = ERRORSTATE;
	    	},
    		onFinalization : function() 
    		{
    		    ajaxState = COMPLETESTATE;
        	}
       });
    }


   /*
     * Display top shows
     */
    function getTopShows(p_strURL)
    {
    	   	
    	var  strURL = p_strURL;        
        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
   			    //Distractor
   			    document.getElementById("container_topshows").innerHTML = "loading...";
       	 	    ajaxState = INITSTATE;
    	    },
      		onSuccess : function(obj) 
      		{
    		  	//Hide the tv schedule grid 
	            document.getElementById("schedule").style.display = "none";
	            
	            //hide the drop downs in account_scheduling
	            document.getElementById("tvschedule_controls").style.display = "none";
	            
	            //Show the topshow radio buttons
    	        document.getElementById("topshows_controls").style.display = "block";
    	        
    	        //show the topshow grid
    	        document.getElementById("container_topshows").style.display = "block";
    	        document.getElementById("container_topshows").innerHTML = obj.responseText;          
	
	       		ajaxState = SUCCESSSTATE;
  			},
    		onError : function(obj) 
    		{
    		    // In case of error we show an alert/
	            alert("Error: " + obj.status);
	            ajaxState = ERRORSTATE;
	    	},
    		onFinalization : function() 
    		{
    		    ajaxState = COMPLETESTATE;
        	}
       });
      
    }
    
     /*
     * Display the topshow grid on the account_scheduling grid
     */
    function displayTopShows(p_strTab, 
                             p_strView,
                             p_strURL)
    {
    	var  bAll = p_strTab == "all";
    	
		strCurrentTab = p_strTab;
	
		document.fmrfilter.tab.value = p_strTab;
		
		if (p_strView == "viewed")
			document.frmTopShows.viewedscheduled[0].checked = true;
		else if (p_strView == "scheduled")
			document.frmTopShows.viewedscheduled[1].checked = true;
				
    	// Change the class to make the tab look selected.
    	for (var iTab = 0; iTab < saTabIDs.length; iTab++)
    	{
    		var  eTab = document.getElementById(saTabIDs[iTab]);
    		
    		if (eTab.id == p_strTab)
    			eTab.className = "selected";
    		else if (eTab.id == "topshows")
    			eTab.className = "blue";
    		else
    			eTab.className = "";
    	}
    	 	
    	getTopShows(p_strURL);
     }
     
    function timeShift(p_strURL)
    {
   	    location.href=p_strURL+"&tab="+strCurrentTab;
    }
      
      
    /*
     * Display the scheduling grid for the specified tab.
     */
    function displaySchedulingGrid(p_strTab)
    {
        //If we are coming from topshows we need to show the tv schedule grid.
        document.getElementById("schedule").style.display = "block";
        document.getElementById("tvschedule_controls").style.display = "block";
    	
    	//Make sure the topshows grid and radio buttons are not showing
    	document.getElementById("topshows_controls").style.display = "none";
        document.getElementById("container_topshows").style.display = "none";
              
    	var  bAll = p_strTab == "all";
    	strCurrentTab = p_strTab;
		
		document.fmrfilter.tab.value = p_strTab;
				
    	// Change the class to make the tab look selected.
    	for (var iTab = 0; iTab < saTabIDs.length; iTab++)
    	{
    		var  eTab = document.getElementById(saTabIDs[iTab]);
    		
    		if (eTab.id == p_strTab)
    			eTab.className = "selected";
    		else if (eTab.id == "topshows")
    			eTab.className = "blue";
    		else
    			eTab.className = "";
    	}
    	
    	if (p_strTab != "topshows")
    	{
    		// Hide the cells that aren't part of this tab; show the ones that are.
    		var  eTable = document.getElementById("programs");
			var  eRows = eTable.getElementsByTagName("tr");
			var  eCells;
			var  strCategoryID;
			var  iNumVisible;
			var  iNumTimeHeaders = 0;
			var  strRowStyle;
			var  iRowCounter = 0; 
			
			for (var iRow = 0; iRow < eRows.length; iRow++)
			{
            	if (eRows[iRow].id == "timeTableHeader")
            	{
					// We have multiple time header rows.
					//   Only show the first if not "all".
					if (eRows[iRow].id == "timeTableHeader")
					{
						iNumTimeHeaders += 1;
				
	            		if (!bAll && (iNumTimeHeaders > 1))
							eRows[iRow].style.display = "none";
						else
							eRows[iRow].style.display = "";
					}
            	}
				else if (eRows[iRow].id != "logo")
                { 
					iNumVisible = 0;
					eCells = eRows[iRow].getElementsByTagName("td");
					
					for (var iCell = 0; iCell < eCells.length; iCell++)
					{
						strCategoryID = eCells[iCell].id.toLowerCase();
						
						if (!bAll && (strCategoryID != ""))
						{
							if (strCategoryID.indexOf(p_strTab) == -1)
								eCells[iCell].style.visibility = "hidden";
							else
							{
								iNumVisible += 1;
								eCells[iCell].style.visibility = "visible";
							}
						}
						else if (bAll)
						{
							eCells[iCell].style.visibility = "visible";
							iNumVisible += 1;
						}
					}
					
					if (iNumVisible == 0)
					{
						// No cells are visible.  Hide the entire row.
						eRows[iRow].style.display = "none";
					}
					else
					{
						eRows[iRow].style.display = "";
						
		                iRowCounter += 1;
		                if (iRowCounter % 2 == 0)
		                    eRows[iRow].className="tv_listing_cell_bg";
		                else
		                    eRows[iRow].className="tv_listing_cell";
					}
				} // don't mess with the logo rows in the logo subtable
			} // loop over rows
			
    		// Reset the position cookie.
        	setPositionCookie();
        	
    	} // non-topshows
    	
    }
    
    /*
     * Display the scheduled/recorded tab.
     */
    function displayScheduledRecordedTab(p_strTab)
    {
    	strCurrentTab = p_strTab;
    	
    	// Change the class to make the tab look selected.
    	if (p_strTab == "scheduled")
    	{
    		document.getElementById("scheduledTab").className = "selected";
    		document.getElementById("recordedTab").className = "";
			hideElement('recorded');
			showElement('scheduled');
		}
    	else
    	{
    		document.getElementById("recordedTab").className = "selected";
    		document.getElementById("scheduledTab").className = "";
			hideElement('scheduled');
			showElement('recorded');
    	}
    }
    
    /*
     * Show grids of the scheduled and recorded programs
     *
     * @param  p_strURL    The URL to build the grids
     * @param  p_strTab    The tab to be selected
     */
    function getScheduledRecorded(p_strURL,
                                  p_strTab)
    {
    	var  strURL = p_strURL;
    	
        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
       	 	    // Show distractor dialog
       	 	    document.getElementById("recordingsdistractor").style.display = "block";
	    		  
	    		// Hide the current grid and headers
  	       		document.getElementById("scheduleTabRow").style.display = "none";
  	       		document.getElementById("tabs").style.display = "none";

			    ajaxState = INITSTATE;
    	    },
      		onSuccess : function(obj) 
      		{
    		    // Hide the distractor
  	       	    document.getElementById("recordingsdistractor").style.display = "none";

				// Show the data
	            document.getElementById("scheduleTabRow").style.display = "block";
	            document.getElementById("tabs").style.display = "block";
	            document.getElementById("tabs").innerHTML = obj.responseText;
	            
	            // Show the appropriate tab
	            displayScheduledRecordedTab(p_strTab);            
	
	       		ajaxState = SUCCESSSTATE;
  			},
    		onError : function(obj) 
    		{
    		    // Hide the distractor
       	 	    document.getElementById("recordingsdistractor").style.display = "none";
       	 	    
	            // In case of error we show an alert/
	            alert("Error: " + obj.status);
	            ajaxState = ERRORSTATE;
	    	},
    		onFinalization : function() 
    		{
    		    ajaxState = COMPLETESTATE;
        	}
       });
    }
    
    /*
     * Expand or compress the recorded episodes folder
     *
     * @param  p_strIDBase    Base id for the elements
     */
    function showHideRecorded(p_strIDBase)
    {
    	var  eFolder = document.getElementById("folder_" + p_strIDBase);
    	
    	if (eFolder.className == "recorded_compressed")
    	{
    		// We are expanding the folder.  First change the image.
    		eFolder.className = "recorded_expanded";
    		
    		// Now show the episodes.
    		var  iEpisode = 0;
    		var  eEpisode = document.getElementById(p_strIDBase + iEpisode++);
    		
    		while ((eEpisode != null) && (typeof(eEpisode) != "undefined"))
    		{
    			eEpisode.style.display = "";
				eEpisode = document.getElementById(p_strIDBase + iEpisode++);
    		}
    	}
    	else
    	{
    		// We are compressing the folder.  First change the image.
    		eFolder.className = "recorded_compressed";
    		
    		// Now hide the episodes.
    		var  iEpisode = 0;
    		var  eEpisode = document.getElementById(p_strIDBase + iEpisode++);
    		
    		while ((eEpisode != null) && (typeof(eEpisode) != "undefined"))
    		{
    			eEpisode.style.display = "none";
				eEpisode = document.getElementById(p_strIDBase + iEpisode++);
    		}
    	}
    }
    
    /*
     * Show a grid of the scheduled programs
     */
    function displayDistractor()
    {
        // Turn on the distractor.
          //document.getElementById("dvrpopup").style.visibility = "hidden";
          adjustView(document.getElementById("tv_listings_wait"))

		return (true);    	
	}    

   
    /*
     * Disable/enable the buttons on the more info page.
     */
    function changeMoreDetailsButtons(p_bDisable)
    {
    	var  eRecordOnce = document.getElementById("recordonce");
    	var  eCancel = document.getElementById("cancel");
    	var  eRecordSeries = document.getElementById("recordseries");
    	
    	if (eRecordOnce != null)
    		eRecordOnce.disabled = p_bDisable;
    	if (eCancel != null)
    		eCancel.disabled = p_bDisable;
    	if (eRecordSeries != null)
    		eRecordSeries.disabled = p_bDisable;
    }


    /*
     *  mail a page to a friend
     */
    function mailpage()
    {
	    mail_str = "mailto:?subject=Check out the " + document.title;
	    mail_str += "&body=I thought you might be interested in the " + document.title;
	    mail_str += ". You can view it at, " + location.href;
	    location.href = mail_str;
    }


    /*
     * Show the specified homecontrols tab
     *
     * @param  p_strTab    Tab to show
     */
    function showHomeControlsTab(p_strTab)
    {
    	strCurrentTab = p_strTab;
    	
    	for (var iTab = 0; iTab < saTabIDs.length; iTab++)
    	{
    		var  eTab = document.getElementById(saTabIDs[iTab]);
    	    var  eTabDiv = document.getElementById("tab_" + saTabIDs[iTab]);
    	
    		
    		if (eTab.id == p_strTab)
    		{
    			eTab.className = "selected";
    			eTabDiv.style.display = "block";
    		}
    		else
    		{
    			eTab.className = "";
    			eTabDiv.style.display = "none";
    		}
    	}
    	
    }


    /*
     * Get the homecontrols configuration
     * 
     * @param  p_strURL        The URL to get the configuration for a device
     */
    function getHCConfiguration(p_strURL)
    {
        advAJAX.get
        (
            {
                url: p_strURL + "&tab=" + strCurrentTab,
                onInitialization : function()
                {
                },
                onSuccess : function(obj)
                {
                    var  xmlDoc = obj.responseXML;

                	if (strCurrentTab == "devices")
                		ajaxSuccess_getEquipment(xmlDoc);
                	else if (strCurrentTab == "scenes")
                		ajaxSuccess_getScenes(xmlDoc);
                	else if (strCurrentTab == "schedules")
                		ajaxSuccess_getSchedules(xmlDoc);
                	else if (strCurrentTab == "monitor")
                		ajaxSuccess_getMonitor(xmlDoc);
                	else if (strCurrentTab == "dashboard")
                		ajaxSuccess_getDashboard(xmlDoc);
                	else if (strCurrentTab == "settings")
                		ajaxSuccess_getSettings(xmlDoc);
                    
                    ajaxState = SUCCESSSTATE
                },
                onError : function(obj)
                {
                    // Error
                    var  xmlDoc = obj.responseXML;
                    var  errorRecord = xmlDoc.getElementsByTagName('pageerror');
                   
                    alert(errorRecord.item(0).getAttribute("message"));
                  
                    ajaxState = ERRORSTATE;
                },
                onFinalization : function()
                {
                }
            }
        );
    }
    
    
    /*
     * Populate the devices page
     * 
     * @param  p_xmlDoc    The XML of equipment
     */
    function ajaxSuccess_getEquipment(p_xmlDoc)
    {
    	var arEquipmentTypes = new Array();
    	var arEquipmentNames = new Array();
        var eDevicesTable = document.getElementById("tab_devices_devicestable");
		var xmlRecord = p_xmlDoc.getElementsByTagName("equipment");
        
    	if ((eDevicesTable != null) && (typeof(eDevicesTable) != "undefined"))
        {
        	// Add in the equipment.
	        for (var i = 0; i < xmlRecord.length; i++)
	        {
	            var xmlEquipment = xmlRecord.item(i);
	            var strEquipmentID = xmlEquipment.getAttribute("id");
	            var strEquipmentName = xmlEquipment.getAttribute("name");
	            var strEquipmentStatus = xmlEquipment.getAttribute("status");
	            var strEquipmentModel = xmlEquipment.getAttribute("model");
	            var strEquipmentManufacturer = xmlEquipment.getAttribute("manufacturer");
	            var strEquipmentType = getUIEquipmentType(xmlEquipment.getAttribute("type"));
	            
	            arEquipmentNames[arEquipmentNames.length] = strEquipmentName;
	            
	            // Add this type to the array if it isn't already there.
	            var  bFound = false;
	            
	            for (var j = 0; !bFound && (j < arEquipmentTypes.length); j++)
	            {
	            	bFound = (strEquipmentType == arEquipmentTypes[j]);
	            }
	            
	            if (!bFound)
	            	arEquipmentTypes[arEquipmentTypes.length] = strEquipmentType;
	            
	            var strAlert = "Equipment ID = " + strEquipmentID + 
	                           "\nName = " + strEquipmentName + 
	                           "\nStatus = " + strEquipmentStatus + 
	                           "\nModel = " + strEquipmentModel + 
	                           "\nManufacturer = " + strEquipmentManufacturer + 
	                           "\nType = " + strEquipmentType; 
	            
	            var xmlControls = xmlEquipment.getElementsByTagName("controls").item(0);
	            strAlert += "\n\nControls:";
	            for (var j = 0; j < xmlControls.childNodes.length; j++)
	            {
	            	var  nControl = xmlControls.childNodes[j];
	            	strAlert += "\n   Control ID = " + nControl.getAttribute("id") +
	            	            "\n      Command = " + nControl.getAttribute("command") +
	            	            "\n      Private = " + nControl.getAttribute("private") +
	            	            "\n      Type = " + nControl.getAttribute("type");
	            }
	            //alert(strAlert);
	       	}
	       	
	       	// Add the equipment names to the table.
	       	fillTable(eDevicesTable,arEquipmentNames);
	    }
        
        // Fill in the dropdown of equipment types
        if (arEquipmentTypes.length > 0)
        {
        	var eTypes = document.getElementById("tab_devices_devices");
        	
            if ((eTypes != "undefined") && (eTypes != undefined))
            {
	    	    eTypes.options.length = 0;
	    		eTypes.options[0] = new Option("All","");
        	
	        	arEquipmentTypes.sort();
	        	for (var i = 0; i < arEquipmentTypes.length; i++)
	        	{
		      		eTypes.options[i+1] = new Option(arEquipmentTypes[i],"");
	        	}
				eTypes.selectedIndex = 0;
	        }
        }
    }
    
    
    /*
     * Populate the scenes page
     * 
     * @param  p_xmlDoc        The XML of scenes
     */
    function ajaxSuccess_getScenes(p_xmlDoc)
    {
		var xmlRecord = p_xmlDoc.getElementsByTagName("scene");
        var eScenes = document.getElementById("tab_scenes_scenes");
    	var arSceneNames = new Array();
        
        if ((eScenes != "undefined") && (eScenes != undefined))
        {
	        for (var i = 0; i < xmlRecord.length; i++)
	        {
	            var xmlScene = xmlRecord.item(i);
	            var xmlCommands = xmlScene.getElementsByTagName("commands").item(0);
	            var strSceneID = xmlScene.getAttribute("id");
	            var strSceneName = xmlScene.getAttribute("name");
	            var strSceneStatus = xmlScene.getAttribute("status");
	            
	            arSceneNames[arSceneNames.length] = strSceneName;
	            
	            var strAlert = "Scene ID = " + strSceneID +
	                           "\nName = " + strSceneName + 
	                           "\nStatus = " + strSceneStatus;
	            
	            strAlert += "\n\nCommands:";
	            for (var j = 0; j < xmlCommands.childNodes.length; j++)
	            {
	            	var  nCommand = xmlCommands.childNodes[j];
	            	strAlert += "\n  " + nCommand.nodeName +
	            	            "\n      Control = " + nCommand.getAttribute("control") + 
	            	            "\n      Equipment = " + nCommand.getAttribute("equipment") + 
	            	            "\n      Count = " + nCommand.getAttribute("count"); 
	            }
	            //alert(strAlert);
	       	}
	       	
	       	// Fill in the scenes dropdown
    	    eScenes.options.length = 0;
    	    
        	arSceneNames.sort();
        	
        	for (var i = 0; i < arSceneNames.length; i++)
        	{
	      		eScenes.options[i] = new Option(arSceneNames[i],"");
        	}
			eScenes.selectedIndex = 0;
	    }
    }
    
    
    /*
     * Populate the schedules page
     * 
     * @param  p_xmlDoc        The XML of schedules
     */
    function ajaxSuccess_getSchedules(p_xmlDoc)
    {
		var xmlRecord = p_xmlDoc.getElementsByTagName("schedule");
	}    
    
    
    /*
     * Populate the monitor page
     * 
     * @param  p_xmlDoc        The XML of monitor data
     */
    function ajaxSuccess_getMonitor(p_xmlDoc)
    {
		var xmlRecord = p_xmlDoc.getElementsByTagName("monitor");
	}    
    
    
    /*
     * Populate the dashboard page
     * 
     * @param  p_xmlDoc        The XML of dashboard data
     */
    function ajaxSuccess_getDashboard(p_xmlDoc)
    {
    	// Get the equipment types
    	var arEquipmentTypes = new Array();
    	var arEquipmentNames = new Array();
    	var arCameraNames = new Array();
        var eDevicesTable = document.getElementById("tab_dashboard_devicestable");
        var eCameras = document.getElementById("tab_dashboard_cameras");
        
    	if ((eDevicesTable != null) && (typeof(eDevicesTable) != "undefined"))
        {
			var xmlRecord = p_xmlDoc.getElementsByTagName("equipment");
        
	        for (var i = 0; i < xmlRecord.length; i++)
	        {
	            var xmlEquipment = xmlRecord.item(i);
	            var strType = xmlEquipment.getAttribute("type");
	            var strName = xmlEquipment.getAttribute("name");
	            var strEquipmentType = getUIEquipmentType(strType);
	            
	            // Add the equipment name to the array
	            if ((strType == "camera") || (strType == "ipc_instance"))
		        	arCameraNames[arCameraNames.length] = strName;
	            else
	            {
		        	arEquipmentNames[arEquipmentNames.length] = strName;
	            
		            // Add this type to the equipment type array if it isn't already there.
		            var  bFound = false;
		            
		            for (var j = 0; !bFound && (j < arEquipmentTypes.length); j++)
		            {
		            	bFound = (strEquipmentType == arEquipmentTypes[j]);
		            }
		            
		            if (!bFound)
		            	arEquipmentTypes[arEquipmentTypes.length] = strEquipmentType;
		        }
	        }
	       	
	       	// Add the equipment names to the table.
	       	fillTable(eDevicesTable,arEquipmentNames);
	       	
	       	// Fill the cameras dropdown
	    	if ((eCameras != null) && (typeof(eCameras) != "undefined"))
	        {
	    	    eCameras.options.length = 0;
        	
	        	arCameraNames.sort();
	        	for (var i = 0; i < arCameraNames.length; i++)
	        	{
		      		eCameras.options[i] = new Option(arCameraNames[i],"");
	        	}
				eCameras.selectedIndex = 0;
	        }
        
        	// Fill in the equipment types dropdown
	        if (arEquipmentTypes.length > 0)
	        {
	        	var eTypes = document.getElementById("tab_dashboard_devices");
	        	
	        	if (typeof(eTypes) != "undefined")
	            {
		    	    eTypes.options.length = 0;
		    		eTypes.options[0] = new Option("All","");
	        	
		        	arEquipmentTypes.sort();
		        	for (var i = 0; i < arEquipmentTypes.length; i++)
		        	{
			      		eTypes.options[i+1] = new Option(arEquipmentTypes[i],"");
		        	}
					eTypes.selectedIndex = 0;
		        }
	        }
	    }
	}
	    
    function HCObject(p_xmlDoc)
    {
        var xoTree = new XML.ObjTree();
        return xoTree.parseXML(p_xmlDoc);
    }
    
    /*
     * create device components
     * 
     * @param  p_saText    The array of text to put into the table
     */
    function ajaxSuccess_getDevices(objHC)
    { 
        var eDevicesDiv = document.getElementById("componentList");

        // Add the devices to our container
        for(var i = 0; i < objHC.configuration.equipment.length; i++)
        {
            var div = document.createElement("div");
            div.className ="component";
            div.id = objHC.configuration.equipment[i]["-id"];
            div.setAttribute("onmousedown","toggleselection(this)");
             
            var celltext = document.createTextNode(objHC.configuration.equipment[i]["-name"]);
            div.appendChild(celltext);
            
            eDevicesDiv.appendChild(div);
        }
    }    
    
    
    /*
     * Populate the settings page
     * 
     * @param  p_xmlDoc        The XML of settings data
     */
    function ajaxSuccess_getSettings(p_xmlDoc)
    {
		var xmlRecord = p_xmlDoc.getElementsByTagName("setting");
	}    
    
    
    /*
     * Get the UI equipment type string
     * 
     * @param  p_strType        The equipment type
     */
    function getUIEquipmentType(p_strType)
    {
    
    	var  strUIType = p_strType;
    	
    	for (var i = 0; i < saHCEquipmentTypes.length; i++)
    	{
    		if (saHCEquipmentTypes[i].type == p_strType)
    			strUIType = saHCEquipmentTypes[i].uitype;
    	}
    	
    	return(strUIType);
	}    
    
    
    /*
     * Fill a table
     * 
     * @param  p_eTable    The table element (actually the tbody so that IE works)
     * @param  p_saText    The array of text to put into the table
     */
    function fillTable(p_eTable,
                       p_saText)
    {
    	// Remove all existing rows.
    	for (var i = p_eTable.rows.length - 1; i > -1; i--)
    	{
    		p_eTable.deleteRow(i);
    	}
    	
    	if (p_saText.length > 0)
    	{
	    	// Sort the input array.
	    	p_saText.sort();
	    	
	    	// Add the text strings as rows in the table.
	    	for (var i = 0; i < p_saText.length; i++)
	    	{
	            var row = document.createElement("tr");
	            var cell = document.createElement("td");
	            var celltext = document.createTextNode(p_saText[i]);
	            
	            cell.appendChild(celltext);
	            row.appendChild(cell);
	            p_eTable.appendChild(row);
	        }
	    }
	}    
	
	
	function  setSupportsLineups(p_strURL)
	{
		var  strURL = p_strURL + "&hardwareid=" + document.getElementById("hardwareid").value;

        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
				ajaxState = INITSTATE;
	    	},
	      	onSuccess : function(obj) 
	      	{
                var  xmldoc = obj.responseXML;
                var  eSupportsLineups = xmldoc.getElementsByTagName('supportslineups');
                var  bSupports = eSupportsLineups.item(0).getAttribute("value");

				// Note that the bSupportsLineups variable must be defined by the calling page.
				if (bSupports == "true")
				{
					bSupportsLineup = true;
	    			document.getElementById("channelmapformwrapper").style.display = "block";
	    			document.getElementById("showhidelistingwrapper").style.display = "block";
	    			document.getElementById("getlineupbutton").style.display = "inline";
	    			document.getElementById("continuebutton").style.display = "none";
				}
				else
				{
					bSupportsLineup = false;
	    			document.getElementById("channelmapformwrapper").style.display = "none";
	    			document.getElementById("showhidelistingwrapper").style.display = "none";
	    			document.getElementById("getlineupbutton").style.display = "none";
	    			document.getElementById("continuebutton").style.display = "inline";
				}
	       		ajaxState = SUCCESSSTATE;
	  		},
	    	onError : function(obj) 
	    	{
	            /* In case of error we show an alert */
                var  xmldoc = obj.responseXML;
                var  errorRecord = xmldoc.getElementsByTagName('pageerror');
               
                alert(errorRecord.item(0).getAttribute("message"));
                
	            ajaxState = ERRORSTATE;
		    },
	    	onFinalization : function() 
	    	{
	    		 ajaxState = COMPLETESTATE;
	        }
       });
	}
   
    
/* 
==============================================================================
                  Analog Dongle
==============================================================================
*/  

    function checkVCT(p_strURL)
    {
		var  oObject = document.getElementById('device');
    	var  strValue = oObject[oObject.selectedIndex].value;
    	var  strURL = p_strURL + "&device=" + escape(strValue);
    	
        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
	       		// Show distractor
	       	 	document.getElementById("analogdongle_distractor").style.display = "block";
	  	       	document.getElementById("analogdongle_device").style.display = "none";
	    		  
				ajaxState = INITSTATE;
	    	},
	      	onSuccess : function(obj) 
	      	{
	       		// Show the results
	  	       	document.getElementById("analogdongle_distractor").style.display = "none";
	    		document.getElementById("analogdongle_results").style.display = "block";

                var  xmldoc = obj.responseXML;
                var  eStatus = xmldoc.getElementsByTagName('vctstatus');

       			document.getElementById("results").innerHTML = eStatus.item(0).getAttribute("message");
	
	       		ajaxState = SUCCESSSTATE;
	  		},
	    	onError : function(obj) 
	    	{
	            /* In case of error we show an alert */
                var  xmldoc = obj.responseXML;
                var  errorRecord = xmldoc.getElementsByTagName('pageerror');
               
                // Put back the original stuff.
	       	 	document.getElementById("analogdongle_distractor").style.display = "none";
	  	       	document.getElementById("analogdongle_device").style.display = "block";
               
                alert(errorRecord.item(0).getAttribute("message"));
                
	            ajaxState = ERRORSTATE;
		    },
	    	onFinalization : function() 
	    	{
	    		 ajaxState = COMPLETESTATE;
	        }
       });
    }
   
    
/* 
==============================================================================
                  Save Email Addresses
==============================================================================
*/  

    function saveEmail(p_strURL)
    {
		var  oObject = document.getElementById('email');
    	var  strValue = oObject.value;
    	var  strURL = p_strURL + "?email=" + escape(strValue);
    	
        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
				ajaxState = INITSTATE;
	    	},
	      	onSuccess : function(obj) 
	      	{
	       		ajaxState = SUCCESSSTATE;
	  		},
	    	onError : function(obj) 
	    	{
	            ajaxState = ERRORSTATE;
		    },
	    	onFinalization : function() 
	    	{
	    		 ajaxState = COMPLETESTATE;
	        }
       });
    }
   
    
/* 
==============================================================================
                  Save Email Addresses
==============================================================================
*/  

    function sendMediaLinkEmail()
    {
    	var  strURL = "/sendMediaLinkEmail.jsp";
    	
        advAJAX.get(
        {
    		url: strURL ,
   			onInitialization : function() 
   			{
				ajaxState = INITSTATE;
	    	},
	      	onSuccess : function(obj) 
	      	{
	       		ajaxState = SUCCESSSTATE;
	  		},
	    	onError : function(obj) 
	    	{
	            ajaxState = ERRORSTATE;
		    },
	    	onFinalization : function() 
	    	{
	    		 ajaxState = COMPLETESTATE;
	        }
       });
    }

//  End -->	
