var g_aRfgCommandQueue = new Array();
var g_bRfgOnLoadComplete = false;

//Window event handlers
var g_pOldOnLoad = window.onload;
window.onload = RfgOnPageLoad;

/*----------------------------------------------------------------------\
| FUNCTION:    RfgQueueCommand                                          |
| RETURNS:     N/A                                                      |
| PARAMETERS:  Command text to later execute.                           |
| PURPOSE:     Requests a command be executed after the page has fully  |        
|              loaded, or if the page is already loaded, now.           |
\----------------------------------------------------------------------*/
function RfgQueueCommand( strEncodedCommand )
{
   var strCommand = unescape(strEncodedCommand.replace(/\+/g," "));
   if( !g_bRfgOnLoadComplete ) {
      g_aRfgCommandQueue.push( strCommand );
   } else {
      eval( strCommand );
   }
}

/*----------------------------------------------------------------------\
| FUNCTION:    RfgOnPageLoad                                            |
| RETURNS:     N/A                                                      |
| PARAMETERS:  N/A                                                      |
| PURPOSE:     Internal document.onload handler -- saves previous       |
|              onload events and fires them after our onload events are |
|              complete.                                                |
\----------------------------------------------------------------------*/
function RfgOnPageLoad()
{
   g_bRfgOnLoadComplete = true;
   while( g_aRfgCommandQueue.length > 0 ) {
      var strCmd = g_aRfgCommandQueue.shift();
      try{
         eval(strCmd);
      } catch( xE ) {            
         //Do not error on user defined code.
      }
   }
   
   if( g_pOldOnLoad ) g_pOldOnLoad();
}


//---------------------------------------------------------------------||
// FUNCTION:    FallBackPopup                                          ||
// PARAMETERS:  Url, width of popup, height of popup                   ||
// RETURNS:     False on popup successfull                             ||
// PURPOSE:     Create popup, or go to URL ere appropriate             ||
//---------------------------------------------------------------------||
function FallBackPopup( strUrl, iWidth, iHeight )
{
   wind=window.open(strUrl,'','width='+iWidth+',height='+iHeight+',resizable=yes,scrollbars=yes,status=yes');
   if ( wind ) return false;

   return true;
}

//---------------------------------------------------------------------||
// FUNCTION:    PopupFromHref                                          ||
// PARAMETERS:  Url, width of popup, height of popup                   ||
// RETURNS:     False on popup successfull                             ||
// PURPOSE:     Create popup, or go to URL ere appropriate             ||
//---------------------------------------------------------------------||
function PopupFromHref( pThisHref, iWidth, iHeight )
{
   if( pThisHref && pThisHref.href ) {
      strUrl = pThisHref.href; 
      wind=window.open(strUrl,'','width='+iWidth+',height='+iHeight+',resizable=yes,scrollbars=yes,status=yes');
      if ( wind ) return false;

      return true;
   }

   return true;
}

//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}

//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;

   while ( i < clen ) {
      var j = i + alen;
      if ( document.cookie.substring(i, j) == arg ) return(getCookieVal (j));
      i = document.cookie.indexOf(" ", i) + 1;
      if ( i == 0 ) break;
   }

   return(null);
}

//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
   document.cookie = name + "=" + escape (value) +
                     ((expires) ? "; expires=" + expires.toGMTString() : "") +
                     ((path) ? "; path=" + path : "") +
                     ((domain) ? "; domain=" + domain : "") +
                     ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    change_parent_url                                      ||
// PARAMETERS:  Url                                                    ||
// RETURNS:                                                            ||
// PURPOSE:     Redirect parent to past url                            ||
//---------------------------------------------------------------------||
function change_parent_url(url)
{
   document.location=url;
}		

/**
 * Returns the value of the specified query string parameter.
 * This method is not used internally by the Browser History Manager.
 * However, it is provided here as a helper since many applications
 * using the Browser History Manager will want to read the value of
 * url parameters to initialize themselves.
 *
 * @method getQueryStringParameter
 * @param {string} paramName Name of the parameter we want to look up.
 * @param {string} queryString Optional URL to look at. If not specified,
 *     this method uses the URL in the address bar.
 * @return {string} The value of the specified parameter, or null.
 * @public
 */
function getQueryStringParameter(paramName, url) {

    var i, len, idx, queryString, params, tokens;

    url = url || top.location.href;

    idx = url.indexOf("?");
    queryString = idx >= 0 ? url.substr(idx + 1) : url;

    // Remove the hash if any
    idx = queryString.lastIndexOf("#");
    queryString = idx >= 0 ? queryString.substr(0, idx) : queryString;

    params = queryString.split("&");

    for (i = 0, len = params.length; i < len; i++) {
        tokens = params[i].split("=");
        if (tokens.length >= 2) {
            if (tokens[0] === paramName) {
                return unescape(tokens[1]);
            }
        }
    }

    return null;
}


//Signs a user up to the PV newsletter
function DoNewsletterSignup( strSignupFieldId, strThankyouDivId )
{
   var pField = document.getElementById( strSignupFieldId );
   var pThanks = document.getElementById( strThankyouDivId );
   if( pField && pThanks ) {
      var strEmail = pField.value;
      if( strEmail == '' ) alert('You must enter your email address.');
      newsltrAjaxObj = null;
      try {
         if (window.XMLHttpRequest) {
            newsltrAjaxObj = new XMLHttpRequest();
         } else {
            newsltrAjaxObj = new ActiveXObject("Microsoft.XMLHTTP");
         }
         if (newsltrAjaxObj == undefined || newsltrAjaxObj == null) {
            alert("This website requires that your browser support AJAX.  Please update your browser, or use the accesible site links at the bottom of the page to continue.");
         }
      } catch (e) {
         alert("This website requires that your browser support AJAX.  Please update your browser, or use the accesible site links at the bottom of the page to continue.");
      }
      var strThankYouHtml = pThanks.innerHTML;
      newsltrAjaxObj.onreadystatechange = function() { 
         if( newsltrAjaxObj.readyState == 4 ) {
             var strResponse =  newsltrAjaxObj.responseText.split(' ').join('');
             if (strResponse == "SUCCESS" ) {
                pThanks.innerHTML = strThankYouHtml;
             } else {
                pThanks.innerHTML = newsltrAjaxObj.responseText;
             }
         }
         setTimeout( function(){pField.value = ''; pThanks.style.display = 'none';}, 3000 );
      }
      pThanks.style.display = 'block';
      pThanks.innerHTML = 'Loading...';
      newsltrAjaxObj.open("GET", "/newslettersignup.siml?email="+escape(strEmail), true);
      newsltrAjaxObj.send(null); 
   } else {
      alert("Could not read form data.");
   }
}

/*
Added to persist the relocate querystring parameter through to the end of a login process.
*/
function getAndSetRelocateCookie() {
   var strRelocate = GetCookie('relocate');
   if(strRelocate == null || strRelocate == '' ) {
      //When the cookie does not exist, try to get the data
      strRelocate = getQueryStringParameter('relocate',document.location.href);
      if(strRelocate != "" && strRelocate != null) {
         //When the data does exist, set the cookie
         SetCookie("relocate",strRelocate,null,"/");
      }
   }
   return strRelocate;
}

function setRelocate(frm) {
   strRelocate = getAndSetRelocateCookie();
   if(fld = frm.elements['relocate']) {
      fld.value = strRelocate
   } else {
      frm.innerHTML += "<input type=\"hidden\" name=\"relocate\" value=\""+strRelocate+"\">";
   }
   var savedRelocate = GetCookie('savedrelocate');
   if(savedRelocate!=null && savedRelocate!='') {
      var callback = {
         success: function(o) {
            status = eval('('+o.responseText+')');
            if(status.success == true && status.loggedin == true)
               document.location.href=o.argument[0];
         }
        ,failure: function(o) {}
        ,argument: [savedRelocate]
      }
      var t = YAHOO.util.Connect.asyncRequest('GET','/ajax.php?cmd=isloggedin', callback, null);
   }
}

