/** 
 *
 * ajax toolkit for globalgiving
 * @author srogers
 * @since 05/01/2006
 *
 * encapsulate all code for Ajax calls in req object
 */
 
/**
 * Create Array to hold events to fire upon window.onload
 * @see globalgiving.js pageOnLoad() method
 */ 
window.onloadListeners=new Array();
window.addOnloadListener = function(listener) {
  window.onloadListeners[window.onloadListeners.length]=listener;
}

/**
 * This is the main Object for making an Ajax Call as a GET, and receiving 
 * the response as XML
 */
var req = new Object();
//
// constructor method, initialized things, and calls action
//
req.Request = function(url, callback, data)
{
   this.url = url;
   this.xmlReq = null;
   this.onload = callback;
   this.onerror = this.defaultError;
   this.loadXMLDoc(url);
}
//
// Prototype  of the req.Request object
//
req.Request.prototype = 
{
   loadXMLDoc:function(url) 
   {
      if (window.XMLHttpRequest)    // mozilla browser?
      {
           this.xmlReq = new XMLHttpRequest();
      }
      else if (window.ActiveXObject)
      {
        this.xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
      }
      else
      {
        alert("cannot use this browser for this application");
      }
      // set the onreadstatechange to a function, and call it upon completion
      var loader = this;
      this.xmlReq.onreadystatechange= function() {
             loader.onReadyState.call(loader);
          }
      url = url + "&ts=" + new Date().getTime();    // append timestamp to query string
      this.xmlReq.open('GET', url, true);         // open the URL  in GET mode, and send request
          this.xmlReq.send(null);
   },
   onReadyState:function() 
   {
      var xmlReq = this.xmlReq;
      var ready = xmlReq.readyState;
      if (ready == 4)               // only do this when readyState is complete
      {
         var httpStatus = xmlReq.status;
         if (httpStatus == 200 || httpStatus == 0)
         {
            this.onload.call(this);  // if http status is OK call the specifed callback
         }
         else
         {
            this.onerror.call(this); // otherwise call the specifed onerror function
         }
      }
   },
   defaultError:function()
   {
     if (this.xmlReq.status == 502) // bad gateway
     {
       alert("The server is currently undergoing maintenance\nand is unable to process your request at this time.\n\n"+
             "We apologize for the inconvienence. Please try again later.");
     }
     else
     {
       alert("error fetching data!"
         + "\nreadyState:"+this.xmlReq.readyState
         + "\nstatus:"+this.xmlReq.status
         + "\nheaders:"+this.xmlReq.getAllResponseHeaders());
     }
   }
}
/*****************************************************************
 *  CALLBACK FUNCTIONS
 *****************************************************************/

/**
 * callback function to load login info
 */
function showLogin()
{
//  alert('In showLogin()');
  var loginmsg = this.xmlReq.responseXML;
  var status = loginmsg.getElementsByTagName("status")[0].firstChild.nodeValue;
  if (status=='SUCCESS')
  {
    // process login "name" from cookie
    var name = getCookieValue(getCobrandFromURL()+'LoginName');
    setLoggedIn(name);
    if(document.getElementById('dual_box')!=null)
    {
       document.getElementById('overlay_login').style.cssText="display:none;";
       document.getElementById('dual_box').style.cssText="display:none;";
     }
  }
  else
  {
    // process the failure message
    var msg = loginmsg.getElementsByTagName("message")[0].firstChild.nodeValue;
    document.getElementById('login_err').innerHTML = msg;
    document.getElementById('loggedindiv').style.cssText = "display:none;";
    document.getElementById('nologindiv').style.cssText = "display:inline;";
    if(document.getElementById('overlay_login')!=null)
    {
      document.getElementById('overlay_login').innerHTML=msg;
    }
  }
  // disable the "loading" image.   
  document.getElementById('loadinglogin').style.cssText = "display:none;";
} 
/**
 * Call Back Function to logout user, after server call
 */
function logMeOut()
{
   setNotLoggedIn();
   location.href=location.protocol+"//"+location.host+"/cb/vfpserv/index.html";    // redirect user to the home page.
}
/**
 * Call Back function to show that password was sent
 */
function showPasswd()
{
  var passwdmsg = this.xmlReq.responseXML;
  var msg = passwdmsg.getElementsByTagName("message")[0].firstChild.nodeValue;
  document.getElementById('login_err').innerHTML = msg;
  // disable the "loading" image.   
  //document.getElementById('loadinglogin').style.cssText = "display:none;";
}
/**
 * callback function to show a vote
 */
function showVote()
{
    var votemsg = this.xmlReq.responseXML;
    var msgid = votemsg.getElementsByTagName("msgid")[0].firstChild.nodeValue;
    var result = votemsg.getElementsByTagName("result")[0].firstChild.nodeValue;
    var vote = votemsg.getElementsByTagName("vote");
    var elem = document.getElementById('message'+msgid);
    elem.innerHTML = result;
    document.getElementById('voteno'+msgid).checked=false;
    document.getElementById('voteyes'+msgid).checked=false;
    // see if the user has already voted
    if (vote && vote.length > 0)
    {
       // make the voting readonly, and redisplay the users vote
       document.getElementById('voteno'+msgid).setAttribute("disabled",true);
       document.getElementById('voteyes'+msgid).setAttribute("disabled",true);
       document.getElementById('commenttext'+msgid).setAttribute("readOnly","true");
       document.getElementById('commenttext'+msgid).style.cssText = "background-color:#D4D0C8;height:45px; width:280px;";
       document.getElementById('voteonit'+msgid).style.cssText = "display:none;";
       var answer = vote[0].getElementsByTagName("radio")[0].firstChild.nodeValue;
       var comment = vote[0].getElementsByTagName("comment")[0].firstChild.nodeValue;
       document.getElementById('vote'+answer+msgid).checked=true;
       document.getElementById('commenttext'+msgid).innerHTML = comment;
       document.getElementById('label'+msgid).innerHTML = "Thank you for your vote. Your comments are helpful to us.";
       //document.getElementById('commentBox'+msgid).style.cssText = "display:none;";
    }
    else  // enable the submit button
    {
       document.getElementById('voteonit'+msgid).style.cssText = "display:inline;float:left;";
    }
     document.getElementById('voteonit'+msgid).removeAttribute("disabled");
    // Now build the list of comments....
    var commentList = votemsg.getElementsByTagName("comments");
    showComments(msgid, commentList);
}
/**
 * function to show comments
 */
function showComments(msgid, comments)
{
   var cbid = document.getElementById('cbid'+msgid).value;
   removeComments(msgid);
   for (var i=0;i<comments.length;i++)
   {
      var commenttext = comments[i].getElementsByTagName("comment")[0].firstChild.nodeValue;
      var username = comments[i].getElementsByTagName("username")[0].firstChild.nodeValue;
      var userid = comments[i].getElementsByTagName("userid")[0].firstChild.nodeValue;
      var commdt = comments[i].getElementsByTagName("date")[0].firstChild.nodeValue;
      var commid = comments[i].getElementsByTagName("id")[0].firstChild.nodeValue;

      var table=document.getElementById("rptCommentsArea"+msgid);

      var table_body = null;
      var new_row = null;
      if (i < 3)    // only first 3 go in this table
      {
         table_body = document.getElementById("onebody"+msgid);
      }
      else
      {
         table_body = document.getElementById("morebody"+msgid);
      }      
      if (i !=0 ) // if it is NOT the first row, add a comment separator
      {
         new_row = table_body.insertRow(table_body.rows.length);
         createImageRow(new_row);
      }         
      //Displays the user name with links to their profile
      new_row = table_body.insertRow(table_body.rows.length);
      createLinkRow(new_row, username,commdt,userid);
      new_row = table_body.insertRow(table_body.rows.length);
      createCommentRow(new_row, commenttext);
      new_row = table_body.insertRow(table_body.rows.length);
      createReportRow(new_row, commid, cbid);
   } // end for loop
   if (comments.length > 3) // need to activate the show all
   {
       document.getElementById("moreLink"+msgid).style.cssText = "display:inline;position:relative;top:-4pt;";
   }  
}

function showMore(msgid)
{
   var isIE = navigator.appVersion.indexOf("MSIE")>0;
   var isNav = navigator.appVersion.indexOf("Nav")>0;
   if (isIE==true)
   {
     document.getElementById("moreLink"+msgid).style.cssText = "display:none;";
     document.getElementById("moreCommentsArea"+msgid).style.cssText = "display:inline;position:relative;top:-4.5pt;";
   }
   else
   {
     document.getElementById("moreLink"+msgid).style.cssText = "display:none;";
     document.getElementById("moreCommentsArea"+msgid).style.cssText = "display:inline;position:relative;top:-7.5pt;";
   }
}

/**
 * This function is placed in an array to be called upon window.onload, to initialize
 * Progress Report votes, when a projd template is loaded.
 */
function loadVote(node, query)
{
   var onloadFunc = function() {
       new req.Request("/dy/prvote/loadx?"+query, showVote, node);
   }
   window.addOnloadListener(onloadFunc); 
}

/**
 * This function Sends the VOTE to the server, and has a callback using showvote
 *
 */
function castVote(msgid)
{
   var projid = document.getElementById('projid'+msgid).value;
   var cbid = document.getElementById('cbid'+msgid).value;
   var voteNo = document.getElementById('voteno'+msgid);
   var voteYes = document.getElementById('voteyes'+msgid);
   var comment = document.getElementById('commenttext'+msgid).value;
   if (!voteNo.checked && !voteYes.checked)
   {
     alert('Please take a moment to tell us if this Progress Report was valuable '
       +'by choosing "yes" or "no".\nComments are optional but welcome!  Thanks!');
     //debugButton(document.getElementById('voteonit'+msgid));
     document.getElementById('voteonit'+msgid).removeAttribute("disabled");
     return false;
   }
   else
   {
      var url = "/dy/prvote/votex?msgid="+msgid+"&cbid="+cbid+"&projid="+projid+
        "&vote="+(voteNo.checked?"no":"yes");
      if (comment.length > 0)
      {
        url = url + "&commenttext="+escape(comment);
      }
      
      
      var new_url="/dy/prvote/commentx?msgid="+msgid+"&cbid="+cbid+"&projid="+projid+
      new req.Request(url,showVote,msgid);
   }
   return true;     // dont submit the form... for now anyway.
}

/** 
 * this function checks the key pressed on an input filed, and returns
 * true if the the enter key (13), or false otherwise
 */
function isEnterKey(event)
{
  var e = event || window.event;
  var thisKey = e.charCode || e.keyCode;
  if (thisKey == 13)
  {
    return true;
  }
  else
  {
    return false;
  }
}
/**
 * this function checks the key pressed on an input field, and if
 * it is hte enter key (13), it tries to Login.
 *
 */
function loginOnEnter(event)
{
   var e = event || window.event;
   var thisKey = e.charCode || e.keyCode;
   //alert('thiskey='+thisKey);
   if (thisKey == 13)
   {
      tryLogin();
   }
}

/**
 * This function checksLogin.  done on pageLoad
 * First - if Session Cookie for User Name, assume Logged in.
 * Second - Check for ggLogin cookie, and if exists, send for verification using Ajax
 * Third - use is not logged in
 *
 */
function tryLogin()
{   
   var emailaddr = document.getElementById('login_email').value;
   var passwd = document.getElementById('login_passwd').value;
   var rememb = document.getElementById('login_rememb').checked;
   if (emailaddr.length == 0 || passwd.length == 0)
   {
      alert('Please enter both your email address and password to login.');
      return false;
   }
   else
   {
      // enable the "loading" image.    
      document.getElementById('loadinglogin').style.cssText = "display:inline;";
      //var url = "/dy/login/vfpserv.html?cmd=xlogin&email="+escape(emailaddr)+"&passwd="+escape(passwd)+"&rempass="+rememb;
      var url = "/dy/j_spring_security_check?cobrand=vfpserv&xlogin=true&email="+escape(emailaddr)+"&passwd="+escape(passwd)+"&rempass="+rememb;
      new req.Request(url, showLogin);          // send the login attempt to the server
   }
   return false;        // dont submit the form... for now anyway.
}

function checkLogin()
{
   // look for Session Cookie with LoginName - indicates if user has logged in.
   var cbid = getCobrandFromURL();
   var loginName = getCookieValue(cbid+'LoginName');
   if (loginName != null && userHasCookie(cbid+'_globalgive') )
   {
      // update the login box without a serverside ajax call
      setLoggedIn(loginName);
      // disable the "loading" image.   
      if (document.getElementById('loadinglogin')) {
         document.getElementById('loadinglogin').style.cssText = "display:none;";
      }
      // check if this is new registered user, and if so, send event to omniture
      if (userHasCookie('ggnewuser'))
      {
         // talk to ominture
         clearOmnVars();
         s=s_gi(s_account);  // set our omniture RSID
         s.linkTrackVars='events';
         s.linkTrackEvents='event4';
         s.events='event4';
         s.tl(this,'o','Register New User');
         deleteCookie('ggnewuser','/');
      }  
   }
   else
   {
      if (userHasCookie(cbid+'_rememberMe'))
      {
         // make serverside Ajax call and validate from this cookie
        // var url = "/dy/login/vfpserv.html?cmd=xautologin";
    	 var url = "/dy/j_spring_security_check?cobrand=" + cbid + "&xautologin=true";
         new req.Request(url, showLogin);           // send the login attempt to the server
      }
      else      // User is just plain not logged in/
      {
         setNotLoggedIn();
         // disable the "loading" image.    
         if (document.getElementById('loadinglogin')) {
            document.getElementById('loadinglogin').style.cssText = "display:none;";
         }
      }
   }
}

function setLoggedIn(name)
{
   //alert('encoded="'+name+'",unencoded="'+decodeURIComponent(name)+'"');
   if (document.getElementById('login_name')) {
      document.getElementById('login_name').innerHTML = 'Welcome ' + decodeURIComponent(name) + "!";
   }
   if (document.getElementById('nologindiv')) {
      document.getElementById('nologindiv').style.cssText = "display:none;";
   }
   if (document.getElementById('loggedindiv')) {
      document.getElementById('loggedindiv').style.cssText = "display:inline;";
   }
}
function setNotLoggedIn()
{
   // future, we may name diff cookies for diff cobrands...
   var cbid = getCobrandFromURL();
   deleteCookie(cbid+'_globalgive','/');
   deleteCookie(cbid+'LoginName', '/');
   if (document.getElementById('loggedindiv') != null) {
      document.getElementById('loggedindiv').style.cssText = "display:none;";
   }
   //document.getElementById('login_err').innerHTML = "";  // clear any message
   if (document.getElementById('nologindiv') != null) {
      document.getElementById('nologindiv').style.cssText = "display:inline;";
   }
}
function Logout()
{
   // enable the "loading" image.   
   document.getElementById('loadinglogin').style.cssText = "display:inline;";
   //var url = "/dy/login/vfpserv.html?cmd=xlogout";
   var url ="/dy/j_spring_security_logout?cobrand=vfpserv&xlogout=true";
   new req.Request(url, logMeOut);          // send the logout attempt to the server
   return false;
}
function sendMyPassword(fieldName)
{
   if (fieldName == null) {
      fieldName = 'login_email';
   }
   if (document.getElementById(fieldName)) {
       var emailaddr = document.getElementById(fieldName).value;
       if (emailaddr.length == 0)
       {
          alert('Please enter your email address to have your password sent to you.');
          return false;
       }
       else
       {
          // enable the "loading" image.    
    //      document.getElementById('loadinglogin').style.cssText = "display:inline;";
          var url = "/dy/login/vfpserv.html?cmd=xpassword&email="+encodeURIComponent(emailaddr);
          new req.Request(url, showPasswd);         // send the login attempt to the server
       }
   }
   return false;        // dont submit the form... for now anyway.
}
/**
 * This function creates the rows and cells in the table and sets their attributes
 */
function createCommentRow(row, rptComments)
{
   row.setAttribute("valign","top");
   row.setAttribute("align","left");
   var tdcell=row.insertCell(row.cells.length);
   tdcell.colSpan=2;
   tdcell.setAttribute("width","510");
  
   var lines = rptComments.split("\n");
   for (var i = 0; i < lines.length; i++)
   {
     if (i > 0)
     {
       var linebr = document.createElement("br");
       tdcell.appendChild(linebr);
     }
     var cell_data=document.createTextNode(lines[i]);
     tdcell.appendChild(cell_data);
   }
}

function createImageRow(row)
{
   var tdcell=row.insertCell(row.cells.length);
   tdcell.colSpan=2;
   var voteimage=document.createElement("img");
   voteimage.setAttribute("src","/img/vote_divide.gif");
   voteimage.setAttribute("align","middle");
   voteimage.setAttribute("height","13");
   voteimage.setAttribute("width","212");
   
   tdcell.appendChild(voteimage);
}

function createReportRow(row, commid, cbid)
{
   var tdcell=row.insertCell(row.cells.length);
   tdcell.colSpan=2;
   tdcell.setAttribute("align","right");
   var reportimg=document.createElement("img");
   reportimg.setAttribute("src","/img/report_comment.gif");
   reportimg.style.cssText='margin-right:3pt;';
   reportimg.setAttribute("height","10");
   reportimg.setAttribute("width","10");
   var reportit=document.createElement("a");
   reportit.setAttribute("href","javascript:popup2('/dy/prvote/report?comment="+commid+"&cbid="+cbid+"', 'Win1', 600, 600)");
   reportit.appendChild(document.createTextNode("report this comment as inappropriate"));

   tdcell.appendChild(reportimg); 
   tdcell.appendChild(reportit);
}

/**
 * This function creates links dynamically for the user profiles 
 */
function createLinkRow(row, userName, voteDate, node)
{
   row.setAttribute("valign","top");
   row.setAttribute("align","left");
  
   //creates profile link for usernames
   var cell=row.insertCell(row.cells.length);
   cell.setAttribute("width","50%");   
   var cell_data=document.createElement("a");
   cell_data.setAttribute("id" ,node);
   var userid=cell_data.getAttribute("id");
   if (node!=-1)
   {
      cell_data.setAttribute("href","/dy/profile/vfpserv.html?cmd=preview&ruserid="+userid);
   }
  
   cell_data.appendChild(document.createTextNode(userName));
   cell_data.setAttribute("target","_blank");
   cell.appendChild(cell_data);
   
   //sets the date
   var dtcell = row.insertCell(row.cells.length);
   dtcell.className = "";
   dtcell.setAttribute("width","50%");
   dtcell.setAttribute("align","right");
   var dtcell_data = document.createTextNode(voteDate);
   dtcell.appendChild(dtcell_data);
}


/**
 *  Login for progress report vote function 
 */
function voteLogin()
{
   var emailaddr=document.getElementById('loginEmail').value;
   var passwd=document.getElementById('loginPasswd').value;
   var rememb=false;
   
   if (emailaddr.length == 0 || passwd.length == 0)
   {
      alert('Please enter both your email address and password to login.');
      return false;
   }
   else
   {
      //var url = "/dy/login/vfpserv.html?cmd=xlogin&email="+emailaddr+"&passwd="+escape(passwd)+"&rempass="+rememb;
	   var url = "/dy/j_spring_security_check?cobrand=vfpserv&xlogin=true&email="+emailaddr+"&passwd="+escape(passwd)+"&rempass="+rememb;
      // send the login attempt to the server
      new req.Request(url, showLogin);  
   }
   return false;    
}

/**
 *  Cancel login for progress report vote function 
 */
function cancelLogin()
{
   var cancelTarget=document.getElementById('dual_box');    
   cancelTarget.style.cssText='display:none';
}


 /**
  * Signup for the progress report vote comments
  */
 function voteSignUp()
 {
    var emailaddr=document.getElementById('accountEmail').value;
    var aliasname=document.getElementById('accountAlias').value;
    var passwd=document.getElementById('accountPasswd').value;
    var passwd2=document.getElementById('accountPasswd2').value;
    var fname=document.getElementById('accountFname').value;
    var lname=document.getElementById('accountLname').value;
    var rememb=false;
    
    if(emailaddr.length==0||passwd.length==0||aliasname==0)
    {
       alert('Please make sure you have entered all the required fields correctly');
       return false;
    }
    else
    {
       //var url="/dy/login/vfpserv.html?cmd=xsignup&email="+emailaddr+"&passwd="+escape(passwd)+"&passwd2="+escape(passwd2)+"&alias="+aliasname+"&fname="+fname+"&lname="+lname;
    	var url="/dy/j_spring_security_check?cobrand=vfpserv&xlogin=true&show=createAccount&email="+emailaddr+"&passwd="+escape(passwd)+"&passwd2="+escape(passwd2)+"&alias="+aliasname+"&fname="+fname+"&lname="+lname;
       new req.Request(url,showSignUp);
    }       
    return false;
 }
 
 function showSignUp()
 {
    var loginmsg = this.xmlReq.responseXML;
    var status = loginmsg.getElementsByTagName("status")[0].firstChild.nodeValue;
    var rememb=false;
    
    if (status=='SUCCESS')
    {
       var emailaddr=loginmsg.getElementsByTagName("email")[0].firstChild.nodeValue;
       var passwd=loginmsg.getElementsByTagName("passwd")[0].firstChild.nodeValue;
       //var new_url = "/dy/login/vfpserv.html?cmd=xlogin&email="+emailaddr+"&passwd="+escape(passwd)+"&rempass="+rememb;
       var new_url = "/dy/j_spring_security_check?cobrand=vfpserv&xlogin=true&email="+emailaddr+"&passwd="+escape(passwd)+"&rempass="+rememb;
       new req.Request(new_url,showLogin);
    }
    else 
    {
       var errors= loginmsg.getElementsByTagName("err_email");
       if (loginmsg.getElementsByTagName("err_email"))
       {
         if (loginmsg.getElementsByTagName("err_email").length>=1)
         {
            var erremail = loginmsg.getElementsByTagName("err_email")[0].firstChild.nodeValue;
            document.getElementById('err_email').innerHTML=erremail;
         }
         else
            document.getElementById('err_email').style.cssText="display:none";
       }
       if (loginmsg.getElementsByTagName("err_passwd"))
       {
         if (loginmsg.getElementsByTagName("err_passwd").length>=1)
         {
           var errpasswd = loginmsg.getElementsByTagName("err_passwd")[0].firstChild.nodeValue;
           document.getElementById('err_passwd').innerHTML=errpasswd;
         }
         else
             document.getElementById('err_passwd').style.cssText="display:none";
       }
       if (loginmsg.getElementsByTagName("err_lname"))
       {
          if (loginmsg.getElementsByTagName("err_lname").length>=1)
          {
            var errlname = loginmsg.getElementsByTagName("err_lname")[0].firstChild.nodeValue;
            document.getElementById("err_lname").innerHTML=errlname;
          }
          else
             document.getElementById('err_lname').style.cssText="display:none";
       }
       if (loginmsg.getElementsByTagName("err_fname"))
       {
          if (loginmsg.getElementsByTagName("err_fname").length>=1)
          {
            var errfname = loginmsg.getElementsByTagName("err_fname")[0].firstChild.nodeValue;
            document.getElementById("err_fname").innerHTML=errfname;
          }
          else
            document.getElementById('err_fname').style.cssText="display:none";
       }
       if (loginmsg.getElementsByTagName("err_alias"))
       {
         if (loginmsg.getElementsByTagName("err_alias").length>=1)
         {
            var erralias = loginmsg.getElementsByTagName("err_alias")[0].firstChild.nodeValue;
            document.getElementById("err_alias").innerHTML=erralias;
         }
         else
            document.getElementById('err_alias').style.cssText="display:none";
       }
       if (loginmsg.getElementsByTagName("err_passwd2"))
       {
         if (loginmsg.getElementsByTagName("err_passwd2").length>=1)
         {
            var errpasswd2=loginmsg.getElementsByTagName("err_passwd2")[0].firstChild.nodeValue; 
            document.getElementById("err_passwd2").innerHTML=errpasswd2;
         }
         else
            document.getElementById('err_passwd2').style.cssText="display:none";
       }
    }
 }
/**
 * Checks to see if the user is logged in 
 */ 
function checkLog(msgid,e)
{
   var cbid = getCobrandFromURL();
   var loginName = getCookieValue(cbid+'LoginName');
   var targetID=document.getElementById('dual_box');
   if (loginName != null && userHasCookie(cbid+'_globalgive') )
   {
     return castVote(msgid);
   }
   else 
   {
     alertCoord(e);
     document.getElementById('voteonit'+msgid).removeAttribute("disabled");
   }
   return false;
 }

/**
 * returns the x and y coordinates of the cursor
 */
function alertCoord(e) 
{
     var targetID=document.getElementById('dual_box');
     var ieflag;
     if ( !e ) 
     {
       if ( window.event ) 
       {
          //Internet Explorer
          e = window.event;
        } 
        else 
        {
          //total failure, we have no way of referencing the event
          return;
        }
      }
      if ( typeof( e.pageX ) == 'number' ) 
      {
        //most browsers
        ieflag=false;
        var xcoord = e.pageX;
        var ycoord = e.pageY;
      }
      else if ( typeof( e.clientX ) == 'number' ) 
      {
        ieflag=true;
        var xcoord = e.clientX;
        var ycoord = e.clientY;
        var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
         ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
         ( navigator.vendor == 'KDE' )
      }
      if ( !badOldBrowser ) 
      {
        if ( document.body && 
           ( document.body.scrollLeft || document.body.scrollTop ) ) 
        {
            //IE 4, 5 & 6 (in non-standards compliant mode)
            xcoord += document.body.scrollLeft;
            ycoord += document.body.scrollTop;
        }
        else if ( document.documentElement && 
                ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) 
        {
            //IE 6 (in standards compliant mode)
            xcoord += document.documentElement.scrollLeft;
            ycoord += document.documentElement.scrollTop;
         }
         moveLogin(targetID,xcoord,ycoord,ieflag);
       }
       else 
       {
         //total failure, we have no way of obtaining the mouse coordinates
         return;
       }
   //window.alert('Mouse coordinates are ('+xcoord+','+ycoord+')');
}

function moveLogin(targetId,xcoord,ycoord,flag)
{
  var id=targetId;
  with(targetId.style)
  {
    display = "block";
    position = "absolute";
    if (!flag)
    {
      left = (xcoord)/2+200+"px";
      top = (ycoord)/2-60+"px";
      zIndex=90;
      opacity='0.9';
    }
    else
    {
      left=(xcoord)-100+"px";
      top=(ycoord)-300+"px";
    }
  }  // end with
}


function accountCreate()
{
    var swapAccountlink=document.getElementById("dual_box_create_account_link");
    var swapbox=document.getElementById("dual_box_create_account");
    
    if (swapAccountlink.style.cssText.value=="display:none")
    {
      swapAccountlink.style.cssText="display:inline";
      swapbox.style.cssText="display:none";
    }
    else 
    {
      swapAccountlink.style.cssText="display:none";
      swapbox.style.cssText="display:inline";
    }
 }

/**
 * remove table rows from the comments display section of progress reports.
 * @param the msgid of the progress report
 */ 
function removeComments(msgid)
{
   var tbodyone=document.getElementById('onebody'+msgid);
   var tbodymore=document.getElementById('morebody'+msgid);
   while(tbodyone.rows.length > 0)
   {
      tbodyone.deleteRow(0);
   }
   while(tbodymore.rows.length > 0)
   {
      tbodymore.deleteRow(0);
   }
   return;  
}

 
// debug function
function debugButton(butt_elem)
{
   var nodes=butt_elem.childNodes;
   alert('has '+nodes.length+' children Nodes!');
   var attr = butt_elem.attributes;
   alert('has '+attr.length+' attributes!');
   alert('butt_elem isdisabled='+butt_elem.isDisabled);
}


//*****************************************************************
//**  giving cart ajax calls, using dojo framework and json      **
//*****************************************************************
function updateItemAmount(itemid)
{
   var itemElem = document.getElementById('amount'+itemid);
   var newAmount = itemElem.value;
   if (validateNumber(itemElem, false, 'Donation amount', true, 0, 10, Number.MAX_VALUE))
   {
      // make ajax call using dojo
      dojo.io.bind({
            url: "/dy/gcart/vfpserv.html",
            method: "POST",
            content: {
                cmd: "xUpdateAmt",
                itemid: itemid,
                newAmount: newAmount
            },          
            load: function(type, data, evt){ updateCartAmount(data, itemid); },
            error: function(type, error){ displayError(error); },
            mimetype: "text/plain"
        });
   }
   else
   {
      if (newAmount == 0)
      {
        if (confirm("Are you sure you want to remove this item from your cart?"))
        {
          location = "/dy/gcart/vfpserv.html?cmd=del&itemid="+itemid;
        }
        else
        {
          itemElem.value = document.getElementById('preamount'+itemid).value;
          itemElem.select();
          setTimeout(function(){itemElem.focus()},10);
          return false;
        }
      }
      else
      {
        alert("Donation amount must be a whole number greater than US $10.");
        itemElem.select();
        setTimeout(function(){itemElem.focus()},10);
      }
      return false;
   }
}

function updateItemType(itemid, isGift)
{
   dojo.io.bind({
         url: "/dy/gcart/vfpserv.html",
         method: "POST",
         content: {
           cmd: "xUpdateIType",
           itemid: itemid,
           isGift: isGift
         },         
      load: function(type, data, evt){ giftInfoUpdated(data); },
      error: function(type, error){ displayError(error); },
      mimetype: "text/plain"
   });
}

function updateAnonymous(itemid, isAnonymous)
{
   dojo.io.bind({
         url: "/dy/gcart/vfpserv.html",
         method: "POST",
         content: {
           cmd: "xUpdateAnon",
           itemid: itemid,
           isAnon: isAnonymous
         },         
      error: function(type, error){ displayError(error); },
      mimetype: "text/plain"
   });
}  

function updateSubscribe(gcartid, newsletter, isSubscribe)
{
  dojo.io.bind({
        url: "/dy/gcart/vfpserv.html",
        method: "POST",
        content: {
          cmd: "xUpdateSub",
          gcartid: gcartid,
          newsletter: newsletter,
          subscribe: isSubscribe
        },
        error: function(type, error) { displayError(error); },
        mimetype: "text/plain"
  });
}

function updateCartAmount(data, itemid)
{
   var result = eval("(" + data + ")");
   var total = document.getElementById('gross_total');
   var net = document.getElementById('net_total');
   var item = document.getElementById('amount'+itemid);
   var pitem = document.getElementById('preamount'+itemid);
   item.value = result.item_amount;
   pitem.value = result.item_amount;
   total.innerHTML = result.gross_total;
   net.innerHTML = result.net_total; 
   var comAmt = result.amount;
   updatePaymentInfo(result.payinfo);
}

function updatePaymentInfo(payinfo)
{
/*
alert('displaying payinfo returned via json:\n'+
    'payinfo.allowcc='+payinfo.allowcc+'\n'+
    'payinfo.allowpp='+payinfo.allowpp+'\n'+
    'payinfo.allowck='+payinfo.allowck+'\n'+
    'payinfo.payment_method='+payinfo.payment_method+'\n'+
    'payinfo.pay_msg='+payinfo.pay_msg); 
*/
   document.getElementById('check').checked=false;
   document.getElementById('paypal').checked=false;
   document.getElementById('creditcard').checked=false;
   document.getElementById('check').removeAttribute("disabled");
   document.getElementById('paypal').removeAttribute("disabled");
   document.getElementById('creditcard').removeAttribute("disabled");
     document.getElementById('colorcc').setAttribute("class","");
     document.getElementById('colorcc').setAttribute("className","");
     document.getElementById('colorpp').setAttribute("class","");
     document.getElementById('colorpp').setAttribute("className","");
     document.getElementById('colorck').setAttribute("class","");
     document.getElementById('colorck').setAttribute("className","");
   document.getElementById('chkout_butt').removeAttribute("disabled");
   document.getElementById('payment_method').value=payinfo.payment_method;
   document.getElementById('exceedmsg').style.cssText="display:none;";
   document.getElementById('showCheck').style.cssText = "display:inline;";
   if (!payinfo.allowcc)
   {
     //alert('dont allow cc');
     document.getElementById('creditcard').setAttribute("disabled", true);
     document.getElementById('colorcc').setAttribute("class","grayout");
     document.getElementById('colorcc').setAttribute("className","grayout");
   } 
   if (!payinfo.allowpp)
   {
     //alert('dont allow pp');
     document.getElementById('paypal').setAttribute("disabled", true);
     document.getElementById('colorpp').setAttribute("class","grayout");
     document.getElementById('colorpp').setAttribute("className","grayout");
   }
   if (!payinfo.allowck)
   {
     //alert('dont allow ck');
     document.getElementById('check').setAttribute("disabled", true);
     document.getElementById('colorck').setAttribute("class","grayout");
     document.getElementById('colorck').setAttribute("className","grayout");
     document.getElementById('showCheck').style.cssText = "display:none;";
   }
   if (payinfo.payment_method=="cc") 
   {
     //alert('setting credit card checked');
     document.getElementById('creditcard').checked=true;
   }     
   else if (payinfo.payment_method=="pp") 
   {
     //alert('setting paypal checked');
     document.getElementById('paypal').checked=true;
   }     
   else if (payinfo.payment_method=="ck") 
   {
     //alert('setting check checked');
     document.getElementById('check').checked=true;
   }   
   if (!payinfo.allowClick)
   {
     document.getElementById('chkout_butt').setAttribute("disabled", true);
   }
   if (payinfo.pay_msg.length > 0)
   {
     //alert('setting exceedmsg to visible');
     document.getElementById('exceedmsg').style.cssText="display:inline;";
     document.getElementById('exceedmsg').innerHTML=payinfo.pay_msg;
   }  
   if (payinfo.gcBalance)
   {
     document.getElementById('gcBalanceMsg').style.cssText="display:inline;";
   }
   else
   {
     document.getElementById('gcBalanceMsg').style.cssText="display:none;";
   }
}
function updateGiftInfo(itemid,cardtype,carddesign,recva_fname,recva_lname,recva_email,
                    recva_addr1,recva_addr2,recva_city,recva_state,recva_postal,
                    recva_ctryid,senda_name,message)
{
  dojo.io.bind({
         url: "/dy/gcart/vfpserv.html",
         method: "POST",
         content: {
           cmd: "xUpdateGift",
           itemid: itemid,
           cardtype: cardtype,
           carddesign: carddesign,
           recva_fname: recva_fname,
           recva_lname: recva_lname,
           recva_email: recva_email,
           recva_addr1: recva_addr1,
           recva_addr2: recva_addr2,
           recva_city: recva_city,
           recva_state: recva_state,
           recva_postal: recva_postal,
           recva_ctryid: recva_ctryid,
           senda_name: senda_name,
           message : message
         },         
      error: function(type, error){ displayError(type,error); },
      load: function(type, data, evt){ giftInfoUpdated(data); },
      mimetype: "text/plain"
   });
}
function giftInfoUpdated(data)
{
   var result = eval("(" + data + ")");
   if (result.status = "SUCCESS")
   {
     updatePaymentInfo(result.payinfo);  // if its an e-card, now check is not an option!!!
   }
   else
   {
     // not ok
   }  
}
function addGiftCert()
{
  document.getElementById("gcmsg").style.cssText = "display:none;";
  var gcnumber = document.getElementById("gcnum").value;
  if (gcnumber.length > 0)
  {
    dojo.io.bind({
         url: "/dy/gcart/vfpserv.html",
         method: "POST",
         content: {
           cmd: "xaddGiftCert",
           gcnum: gcnumber
         },         
      error: function(type, error){ displayError(type,error); },
      load: function(type, data, evt){ updateGiftCert(data); },
      mimetype: "text/plain"
    });
  }
}  
function updateGiftCert(data)
{
  //alert('In updateGiftCert...');
  var result = eval("(" + data + ")");
  var status = result.status;
  var msg = result.msg;
  //alert('status='+status);
  //alert('msg='+msg);
  if (status == "FAIL")
  {
    document.getElementById("gcmsg").innerHTML = msg;
    document.getElementById("gcmsg").style.cssText = "display:inline;";
    var gcnumber = document.getElementById("gcnum");
    gcnumber.select();
    setTimeout(function(){gcnumber.focus()},10);
  }
  else if (status == "LOGIN") // send user to login page
  {
     location.href=location.protocol+"//"+location.host+"/dy/login/vfpserv.html?cmd=login&andthen="+encodeURIComponent('/dy/gcart/vfpserv.html?cmd=xaddGiftCert');    // redirect user to the home page.
  }
  else if (status == "SUCCESS")
  {
    // add a row to the table of gift certs
    table_body = document.getElementById("giftcert_tbody");
    new_row = table_body.insertRow(table_body.rows.length);
    createGCRow(new_row, result.gcnum,result.expdate,result.gcamt);
    // update the net_total
    document.getElementById("net_total").innerHTML = result.net_total;
    // clear the gcnum entered.
    document.getElementById("gcnum").value = "";
    // make sure the table is "visible"
    document.getElementById('giftcert_table').style.cssText = "display:block;";
    // update the payment options and gift cert balance message
    updatePaymentInfo(result.payinfo);
  }    
}
function createGCRow(row, gcnum, expdate, amt)
{
   var emptycell = row.insertCell(row.cells.length);
   var emptycell_data = document.createTextNode("");
   emptycell.appendChild(emptycell_data);
   
   var numcell = row.insertCell(row.cells.length);
   var numcell_data = document.createTextNode(gcnum);
   numcell.appendChild(numcell_data);
   
   var datecell = row.insertCell(row.cells.length);
   var datecell_data = document.createTextNode(expdate);
   datecell.appendChild(datecell_data);
   
   var amtcell = row.insertCell(row.cells.length);
   var amtspan1 = document.createElement("SPAN");
   amtspan1.style.cssText="float:right;";
   var amtspan2 = document.createElement("SPAN");
   amtspan2.style.cssText="padding-left: 10px;";
   //var amtdata = document.createTextNode(amt);
   //amtspan2.appendChild(amtdata);
   amtspan2.innerHTML = amt;
   amtspan1.appendChild(amtspan2);
   amtcell.appendChild(amtspan1);
}
function displayError(type,error)
{
   if (error.type && error.num)
   {
     alert('Error occured processing request: \n'+
         'message='+error.message+'\ntype='+error.type+'\nnum='+error.num);
   }
}
