/**
 * The favor exchange service
 *
 * @author Amir Razmara
 * @version $Id: favorpals_scripts.js,v 1.94 2009-06-04 20:34:45 tiago Exp $
 */

//--------------------------------------------------------------------
// global variables
//--------------------------------------------------------------------
var login_email;
var redirectionURL;

var twentyNineDaysString="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29";
var thirtyDaysString="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
var thirtyOneDaysString="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31";

var loginMessageMap = new Object();
loginMessageMap['user_not_exist'] = "You are not a user of the system; please sign-up!";
loginMessageMap['user_not_activated'] = "You have not been activated yet please activate your account via the account activation email link!";
loginMessageMap['failure'] = "We are currently experiencing technical difficulties; please try again later!";
loginMessageMap['success'] = "You have sucessfully logged in!";

var monthToDaysMap = new Object();


function populateMonthToDaysMap() {
    document.userRegistrationForm.month.options.length = 0; 

    document.userRegistrationForm.month.options[0]=new Option('Jan','Jan');
    document.userRegistrationForm.month.options[1]=new Option('Feb','Feb');
    document.userRegistrationForm.month.options[2]=new Option('Mar','Mar');
    document.userRegistrationForm.month.options[3]=new Option('Apr','Apr');
    document.userRegistrationForm.month.options[4]=new Option('May','May');
    document.userRegistrationForm.month.options[5]=new Option('Jun','Jun');
    document.userRegistrationForm.month.options[6]=new Option('Jul','Jul');
    document.userRegistrationForm.month.options[7]=new Option('Aug','Aug');
    document.userRegistrationForm.month.options[8]=new Option('Sep','Sep');
    document.userRegistrationForm.month.options[9]=new Option('Oct','Oct');
    document.userRegistrationForm.month.options[10]=new Option('Nov','Nov');
    document.userRegistrationForm.month.options[11]=new Option('Dec','Dec');
    document.userRegistrationForm.month.options.selectedIndex=0;
    
    
    monthToDaysMap['Jan']=thirtyOneDaysString;
    monthToDaysMap['Feb']=twentyNineDaysString;
    monthToDaysMap['Mar']=thirtyOneDaysString;
    monthToDaysMap['Apr']=thirtyDaysString;
    monthToDaysMap['May']=thirtyOneDaysString;
    monthToDaysMap['Jun']=thirtyDaysString;
    monthToDaysMap['Jul']=thirtyOneDaysString;
    monthToDaysMap['Aug']=thirtyOneDaysString;
    monthToDaysMap['Sep']=thirtyDaysString;
    monthToDaysMap['Oct']=thirtyOneDaysString;
    monthToDaysMap['Nov']=thirtyDaysString;
    monthToDaysMap['Dec']=thirtyOneDaysString;
    
    getDays();
    
    
}


//---------------------------------------------------------------------
// Validates the form nick name
//---------------------------------------------------------------------
function validateNickName(nickNameId)
{
  var nickName = $(nickNameId);
  nickName.value = trim(nickName.value);
  
  if (nickName.value.length < 2 || nickName.value.length > 12)
  {
    nickName.focus();
    nickName.select();
    return "bad-nickname-size";
  }
  
  return "good-nickname";
}
//-------------------------------------------------------------------
// Create an absolute URL
//-------------------------------------------------------------------

function getAbsoluteUrl(relativeLink)
{
    var myUrl=top.location.host + relativeLink;
    return myUrl;
}
//---------------------------------------------------------------------
// Validates the form email
//---------------------------------------------------------------------
function validateEmail(emailId)
{
    var email = $(emailId);
    // Note: The next expression must be all on one line...
    //       allow no spaces, linefeeds, or carriage returns!
    var goodEmail = email.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);

    if (goodEmail)
    {
        return "good-email";
    } 

    email.focus();
    email.select();
    return "bad-email-format";
}

function validatePassword(passwordId)
{
    var password = $(passwordId);
    if (password.value.length < 6 || password.value.length > 15)
    {
        return "bad-password-size";
    }
    
    return "good-password";
}

//---------------------------------------------------------------------
// Validates the form passwords (password & confirm password)
//---------------------------------------------------------------------
function validatePasswords(passwordId, confirmPasswordId)
{
  var password, confPassword, result;
  password = $(passwordId);
  confPassword = $(confirmPasswordId);
  password.value = trim(password.value);
  confPassword.value = trim(confPassword.value);
  
  if (password.value.length < 6 || password.value.length > 15 ||
      confPassword.value.length < 6 || confPassword.value.length > 15)
  {
    return "bad-password-size";
  }
  if (password.value != confPassword.value) 
  {
    return "passwords-mismatch";
  }
  else 
  {
    return "passwords-match";
  }     
}

//---------------------------------------------------------------------
// Validates the form passwords (password & confirm password)
//---------------------------------------------------------------------
function validateChangePassword(oldPasswordId, newPasswordId, confirmPasswordId)
{
  var oldPassword, newPassword, confPassword, result;
  
  oldPassword = $(oldPasswordId);
  newPassword = $(newPasswordId);
  confPassword = $(confirmPasswordId);
  
  oldPassword.value = trim(oldPassword.value);
  confPassword.value = trim(confPassword.value);
  newPassword.value = trim(newPassword.value);
  //alert("oldPassword.value =" + oldPassword.value);
  //alert("confPassword.value =" + confPassword.value);
  //alert("newPassword.value =" + newPassword.value);
  
  if (oldPassword.value.length < 6 || oldPassword.value.length > 15 ||
      confPassword.value.length < 6 || confPassword.value.length > 15 ||
      newPassword.value.length < 6 || newPassword.value.length > 15)
  {
    return "bad-password-size";
  }
  if (oldPassword.value == newPassword.value)
  {
    return 'old_and_new_password_cannot_be_same';
  }
  if (newPassword.value != confPassword.value)
  {
    return 'new_and_conf_password_must_be_same';
  }

  return "change_password_success_validation";    
}

//--------------------------------------------------------------------
//Generically show menu div 
//--------------------------------------------------------------------
var menuAction = null;
var mouseMenuEventTimer;

function showMenuDiv(otherDiv,divName) 
{
 var aDiv;

 aDiv = $(divName);
 //aDiv.style.display =  "block";
 var position = $(otherDiv).cumulativeOffset();
 var divMargin = position[0] + "px";
 var other = document.getElementById(otherDiv);

//alert("otherDiv:" + divMargin);    
 aDiv.setStyle({
 //	 'marginLeft':divMargin,
     left:position[0] + "px",
     top:(position[1] + $(otherDiv).offsetHeight) + "px"
 });
 

 //if (!Element.visible(divName)) {
 clearTimeout(mouseMenuEventTimer);
 mouseMenuEventTimer = setTimeout(function(){
 	Effect.Appear(aDiv, {
 		duration: 0.25
 	});
 } , 150);


//if(null == menuAction){
// 	Effect.Appear(aDiv, {
// 		duration: 0.25
// 	});
//	menuAction="active";
// }//endif  
}
//--------------------------------------------------------------------
// hide Menu Div
//---------------------------------------------------------------------
function hideMenuDiv(divName)
{
	
 clearTimeout(mouseMenuEventTimer);
 mouseMenuEventTimer = setTimeout(function(){
 	Effect.Fade($(divName), {
 		duration: 0.25
 	});
 } , 150);
	
	
 //if (Element.visible(divName)) {
 //if(null != menuAction){
 //	Effect.Fade($(divName), {
 //		duration: 0.25
 //	});
 // menuAction=null;//reset
 //}//endif
 
}
// --------------------------------------------------------------------
// Generically show any div 
// --------------------------------------------------------------------
function showDiv(divName) 
{
    var aDiv;

    aDiv = $(divName);
    aDiv.style.display =  "block";
}

// --------------------------------------------------------------------
// Hide the login div and show the login link element
// --------------------------------------------------------------------
function hideLoginDivAndShowLoginLink()
{
    Effect.Fade($('loginDivId'),{duration:0.25});
    
    $('loginLinkDivId').show();
}

// --------------------------------------------------------------------
// Hide the login link element
// --------------------------------------------------------------------
function hideLoginLink()
{
    var loginLink = $('loginLinkDivId');
    loginLink.style.display = "none";
}



// --------------------------------------------------------------------
// Generically hide any div 
// --------------------------------------------------------------------
function hideDiv(element) {
    $(element).hide();
}

//-------------------------------------------------------------------
// Show the login popup and hide the login link
// ------------------------------------------------------------------
function showLoginPopupAndHideLoginLink() 
{
    var topDiv = $('loginDivId');
    var linkDiv = $('loginLinkDivId'); 
    var position = $('headerId').cumulativeOffset();    
    var dimensions = topDiv.getDimensions();
    
    messageDiv = $("favorLoginMessageDiv");
    messageDiv.style.display =  "none";
    topDiv.setStyle({
        left:(position[0] + $('headerId').getWidth() - $(topDiv).getWidth()) + "px",
        top:position[1] + "px"
    });

    Effect.Appear(topDiv,{
        duration:0.25,
        afterFinish:function() {
            $('loginEmailId').focus();
        }
    });
    
    if (null != linkDiv)
    {
        linkDiv.hide();
    }
}
//-------------------------------------------------------------------
// Show the popup div on top of another div
// ------------------------------------------------------------------
function showPopupDivTopOfDiv(popUpdiv, otherDiv, focusId) 
{
    var topDiv = $(popUpdiv);
    var position = $(otherDiv).cumulativeOffset();    
    
    topDiv.setStyle({
        left:position[0] + "px",
        top:position[1] + "px"
    });

    Effect.Appear(topDiv,{
        duration:0.25,
        afterFinish:function() {
            $(focusId).focus();
        }
    });
}
//-------------------------------------------------------------------
// Show the popup div on top left of another div
// No focus rewquired.
// ------------------------------------------------------------------
function showPopupDivTopLeftOfDiv(popUpdiv, otherDiv) 
{
    var topDiv = $(popUpdiv);
    var position = $(otherDiv).cumulativeOffset();    
	var width = (position[0] - $(popUpdiv).getWidth());
	
    topDiv.setStyle({
        left:width + "px",
        top:position[1] + "px"});

    Effect.Appear(topDiv,{duration:0.1});
}
//-------------------------------------------------------------------
// Show the popup div on top left of another div
// No focus required.
// ------------------------------------------------------------------
function showDiv(popUpdiv) 
{
    var topDiv = $(popUpdiv);
    Effect.Appear(topDiv,{duration:0.2});
}

//-------------------------------------------------------------------
// Show the Change Password popup and overlay on top of the controlPanel
// ------------------------------------------------------------------
function showChangePasswordPopupOnTopOfControlPanel() 
{
    var topDiv = $('changePasswordDivId');
    var position = $('myControlPanelId').cumulativeOffset();    
    
    topDiv.setStyle({
        left:position[0] + "px",
        top:position[1] + "px"
    });

    Effect.Appear(topDiv,{
        duration:0.25,
        afterFinish:function() {
            $('oldChangePasswordId').focus();
        }
    });
}

//-------------------------------------------------------------------
// Show the login popup and hide the login link
// ------------------------------------------------------------------
function hideLogoutLinkAndShowLoginLink() 
{
    var loginLink = $('loginLinkDivId');
    loginLink.style.display = "none";
    
    var logoutLink = $('logoutLinkDivId');
    logoutLink.style.display = "none";

}

function changeColor(baseDiv,colorCode){
    var divId = $(baseDiv);
    divId.style.backgroundColor=colorCode;
}


//-------------------------------------------------------------------
function highestTopOffset(elementId, currentTopOffset){
    baseId = $(elementId);
    offset = $(elementId).cumulativeOffset();
    
    if(offset[1] > currentTopOffset) {
        return offset[1];
    }
    else {
        return currentTopOffset;
    }
}
//-------------------------------------------------------------------
// Show the hidden div
// ------------------------------------------------------------------
function showHiddenDiv(divName, baseDiv) 
{
    var topDiv, bottomDiv, linkDiv, offset;
    
    topDiv = $(divName);
    topDiv.style.display =  "block";

    bottomDiv = $(baseDiv);
    offset = (bottomDiv.offsetLeft - topDiv.offsetWidth) + 40;
    
    topDiv.style.left = offset;
    topDiv.style.top = bottomDiv.offsetTop;
}

//-------------------------------------------------------------------
function showHiddenDivRightOf(divName, baseDiv) {
    var topDiv, bottomDiv, offset;

    topDiv = $(divName);
    topDiv.style.display =  "block";
    baseDivElement = $(baseDiv);
    offset = $(baseDivElement).cumulativeOffset();

    //bottomDiv = $(baseDiv);
    
    topDiv.style.left = offset[0];
    topDiv.style.top = offset[1];
}
//-------------------------------------------------------------------
function showHiddenDivEndOfMenu(element, targetPosition) {
    var topDiv = $(element);
    var targetPositionElement = $(targetPosition);
    var position = $(targetPositionElement).cumulativeOffset();

    topDiv.setStyle({
        left: (position[0] + $(targetPositionElement).getWidth() - $(topDiv).getWidth()) + "px",
        top: position[1] + "px"
    });

    Effect.Appear(topDiv,{
        duration:0.25,
        afterFinish:function() {
            $('nickNameId').focus();
        }
    });
}
//-------------------------------------------------------------------
function showHiddenDivEndSignupButton(element, targetPosition) {
    var topDiv = $(element);
    var targetPositionElement = $(targetPosition);
    var position = $(targetPositionElement).cumulativeOffset();

    topDiv.setStyle({
        left: (position[0] + $(targetPositionElement).getWidth() - $(topDiv).getWidth()) + "px",
        top: (position[1] - ($(element).getHeight() - 12)) + "px"
    });

    Effect.Appear(topDiv,{
        duration:0.25,
        afterFinish:function() {
            $('nickNameId').focus();
        }
    });
}

function showInControlPanelDiv(element, targetPosition, focusElement) {
    var topDiv = $(element);
    var inputFocus = $(focusElement);
    var targetPositionElement = $(targetPosition);
    var position = $(targetPositionElement).cumulativeOffset();

    topDiv.setStyle({
        left: (position[0]) + "px",
        top: (position[1]) + "px"
    });

    Effect.Appear(topDiv,{
        duration:0.25
    });
    
}

//---------------------------------------------------------------------
function showCountryDetail(currentCountry,
                           currentCountrySeparator,   
                           lastCountry,
                           lastCountrySeparator,
                           lastState,
                           lastStateSeparator){
                        
var currentCountryId, currentCountrySeparatorId, lastCountryId, lastCountrySeparatorId, lastStateId, lastStateSeparatorId;
                        
    if("-1"!=lastCountry) {
        lastCountryId = $(lastCountry);
        lastCountryId.style.display =  "none";
    }
    if("-1" != lastCountrySeparator){
        lastCountrySeparatorId= $(lastCountrySeparator);
        lastCountrySeparatorId.style.display =  "none";
    }
    if("-1" != lastState){
        lastStateId = $(lastState);
        lastStateId.style.display =  "none";
    }
    if("-1" != lastStateSeparator){
        lastStateSeparatorId = $(lastStateSeparator);
        lastStateSeparatorId.style.display =  "none";
    }   
    
    currentCountryId = $(currentCountry);
    currentCountrySeparatorId = $(currentCountrySeparator);
    currentCountryId.style.display =  "block";
    currentCountrySeparatorId.style.display =  "block";
    
    $('cityListDivId').hide();
    // clear and hide final query incase user reselects country
    if ($('cityResults')) $('cityResults').update();
}

//--------------------------------------------------------------------
function showStateDetail(currentState,
                         currentStateSeparator,   
                         lastState,
                         lastStateSeparator,
                         topValue){
                        
var currentStateId, currentStateSeparatorId, lastStateId, lastStateSeparatorId;
                        
    if("-1" != lastState){
        lastStateId = $(lastState);
        lastStateId.style.display =  "none";
    }
    if("-1" != lastStateSeparator){
        lastStateSeparatorId = $(lastStateSeparator);
        lastStateSeparatorId.style.display =  "none";
    }   
    
    currentStateId = $(currentState);
    currentStateSeparatorId = $(currentStateSeparator);
    //currentStateSeparatorId.style.top = topValue;
    
    currentStateId.style.display =  "block";
    currentStateSeparatorId.style.display =  "block";
    
    $('cityListDivId').show();

    // clear and hide final query incase user reselects state
    if ($('cityResults')) $('cityResults').update();
}

//--------------------------------------------------------------------
function showCityDetail(country,state,city) {
    var url = "/favorpals/jsp/browse/BrowseCity.jsp?countryId=" + country + "&stateId=" + state + "&cityId=" + city;
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: parseCityResponse
    });
    return false;
}

//--------------------------------------------------------------------
function parseCityResponse(transport) {
    if (transport) {
        var response = transport.responseText;
        if (response) {
            response = response.replace(/\r|\n/g,"");
            $("cityResults").update(response);
        }
    }
    return false;
}

//--------------------------------------------------------------------
function showCategoryDetail(primaryId,secondaryId,primaryName,secondaryName) {
    var url = "/favorpals/jsp/browse/BrowseSecondaryCategory.jsp?primaryCategoryId=" + primaryId + "&secondaryCategoryId=" + secondaryId;
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: parseCategoryResponse
    });
    return false;
}

//--------------------------------------------------------------------
function parseCategoryResponse(transport) {
    if (transport) {
        var response = transport.responseText;
        if (response) {
            response = response.replace(/\r|\n/g,"");
            $("categoryResult").update(response);
        }
    }
    return false;
}

//--------------------------------------------------------------------
function moveDiv(divName, baseDiv) {
    baseDivElement = $(baseDiv);
    offset = $(baseDivElement).cumulativeOffset();
    newX = $(baseDivElement).positionedOffset();
    topDiv = $(divName);
    
    //alert("Y:" + topDiv.style.top + "new x[0]:" + newX[0] + ":" + newX[1]);

    topDiv.style.left = $(baseDivElement).getWidth();
    topDiv.style.top =  newX[1];
}

//---------------------------------------------------------------------
function countryBlindDown(countryDivId) {
    Effect.BlindUp('<%=country%>_DivId', {duration: 0.9});  
}
//---------------------------------------------------------------------
function secondaryCategoryBlindDown(currentPrimaryId, currentSecondaryId, lastPrimary,lastSecondaryId) {
    
    if(("-1"!=lastSecondaryId) && (lastSecondaryId != currentSecondaryId)){
        $(lastSecondaryId).hide();;
    }
    $(currentSecondaryId).show();
    
    $('categoryResult').update();
    
    return currentSecondaryId;
}

function getXwithWidth(baseDiv) {
    baseDivElement = $(baseDiv);
    offset = $(baseDivElement).cumulativeOffset();
    return (offset[1] + baseDivElement.getWidth());
}

function getY(baseDiv) {
    baseDivElement = $(baseDiv);
    offset = $(baseDivElement).cumulativeOffset();
    return offset[1];
}

//---------------------------------------------------------------------
function registerUser(pForm) {
    var form;
    var response;
    
    form = $(pForm);
    
    new Ajax.Request('http://' + top.location.host + '/favorpals/jsp/register_new_user.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
   return response;
}

//---------------------------------------------------------------------
function replyFavor(pForm) {
    var form;
    
    //Note: include the check for login and if not, prompt for login.
    
    form = $(pForm);
    
    new Ajax.Request('http://' + top.location.host + '/favorpals/jsp/store_reply.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                           
                                        var response = transport.responseText;

                        },
                        onFailure: function(){
                          alert('Login attempt failed, please try again.') 
                        }   
                     }); 
   return false;
}
//----------------------------------------------------------------------------------
function validateLogin()
{
     var emailValidationVal = validateEmail('loginEmailId');
     if ("bad-email-format" == emailValidationVal)
     {
        alert("The email provided has a bad format");
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.update("The email provided has a bad format");
        return false;
     }
     
     var passwordValidationVal = validatePassword('loginPasswordId');
     if ("bad-password-size" == passwordValidationVal)
     {
        alert("The password must be between 6 and 15 characters long");
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.update("The password must be between 6 and 15 characters long");
        return false;
     }

     return true;
}

// Login the user and update the display artifacts
  function loginUserAndUpdateDisplayArtifacts()
  {
    var validationVal = validateLogin();
    
     if(true == validationVal) {
         hideDiv("loginDivId");     
     }
    
    if (validationVal == false)
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        return false;
    }
    var response = loginUser();

    if (response == "user_not_exist") 
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        hideDiv('loginDivId');
        showDiv('loginLinkDivId');
        alert("You are not a user of the system; please sign-up!");
        return false;

    }
    else if (response == "user_not_activated")
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        hideDiv('loginDivId');
        showDiv('loginLinkDivId');
        alert("You have not been activated yet please activate your account via the account activation email link!");
        return false;

    }
    else if (response == "failure")
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        hideDiv('loginDivId');
        showDiv('loginLinkDivId');
        alert("We are currently experiencing technical difficulties; please try again later!");
        return false;

    }
    else if (response == "success")
    {
        //hideDiv('loginDivId');
        //showDiv('logoutLinkDivId');
        //showDiv('createFavorExchangeLinkDivId');
        //var response = getMyFavorExchanges();
        //var favorExchangeList = $('favorExchangeListId');
        //favorExchangeList.innerHTML = response;
        
        if (null != redirectionURL)
        {
            window.location = redirectionURL;
        }
        else
        {
            window.location = 'http://' + top.location.host + '/favorpals/jsp/my.jsp';
        }
    
        return true;

    }
    
    return false;
}

//---------------------------------------------------------------------
// Login the user and update the display artifacts from home page
  function loginFromHomePageAndUpdateDisplayArtifacts()
  {
    var validationVal = validateLogin();
    if (validationVal == false)
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        return false;
    }
    var response = loginUser();

    if (response == "user_not_exist") 
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        messageDiv.update("You are not a user of the system; <br/><br/>Please sign-up to enjoy the benefits of Favorpals.");
        return false;

    }
    else if (response == "user_not_activated")
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        messageDiv.update("Your account is not yet activated. <br/><br/>Please activate your account using the link send via email.<br/>");
        return false;

    }
    else if (response == "failure")
    {
        messageDiv = $("favorLoginMessageDiv");
        messageDiv.style.display =  "block";
        messageDiv.update("We are currently experiencing technical difficulties; please try again in few minutes.");
        return false;

    }
    else if (response == "success")
    {

        if (null != redirectionURL)
        {
            window.location = redirectionURL;
        }
        else
        {
            window.location = 'http://' + top.location.host + '/favorpals/jsp/my.jsp';
        }
        
    
        return true;

    }
    
    return false;
}




//---------------------------------------------------------
function createFavor() { //Check if logged in go to Create Favor page, else pop up the login dialog
    
    if('true' == isLoggedIn()) {
        location.href='https://' + top.location.host + '/favorpals/jsp/CreateFavorExchange.jsp';
    }
    else {
        showLoginPopupAndHideLoginLink();
    }
}
//---------------------------------------------------------
// this is only from home page (index.jsp) to not do a login dialog popup
//---------------------------------------------------------
function createFavorFromHomePage() { //Check if logged in go to Create Favor page, else pop up the login dialog
    
    if('true' == isLoggedIn()) {
        location.href='http://' + top.location.host + '/favorpals/jsp/CreateFavorExchange.jsp';
    }
    else {
        alert("Please login prior to creating a new favor exchange");
    }
}

//---------------------------------------------------------
function showFavor(favorExchangeId, respondingToUserId) { //Check if logged in go to the favorexchange page, else pop up the login dialog
    
    if('true' == isLoggedIn()) {
        location.href='http://' + top.location.host + '/favorpals/jsp/FavorExchangeDialogue.jsp?favorExchangeId=' + favorExchangeId + '&respondingToUserId=' + respondingToUserId;
    }
    else {
        showLoginPopupAndHideLoginLink();
    }
}


function logoutUserAndUpdateDisplayArtifacts()
{

    var retVal = logoutUser();
    
    if (retVal == false)
    {
        alert("Something went wrong while attempting to logout. We are experiencing technical difficulties"); 
        return;
    }

    location.href='http://'+ top.location.host + '/favorpals/jsp/index.jsp'; 
}

//---------------------------------------------------------------------
function logoutUser() 
{
    var retVal = true;
    new Ajax.Request('http://'+ top.location.host + '/favorpals/jsp/logout_user.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           onSuccess: function(transport)
                           {
                                var response = transport.responseText;
                                response = trim(response,null);

                                if (response == "success") 
                                {
                                    cookie = transport.getResponseHeader('set-cookie');
                                    cookie = trim(cookie, null);
                                    if ("" != cookie)
                                    {
                                        document.cookie=cookie;
                                    }
                                }
                            },
                            onFailure: function()
                            {
                              retVal=false;
                            }   
                     }); 
   return retVal;
}

//---------------------------------------------------------------------
function postFavorExchange() 
{
    var response;
    var cookie;
    var form = $('postFavorExchangeFormId');

    new Ajax.Request('http://' + top.location.host + '/favorpals/jsp/store_favor_exchange.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                                        response = transport.responseText;
                                        response = trim(response, null);
                        },
                        onFailure: function()
                        {
                          response = "failure"; 
                        }   
                     }); 
    return response;
}


function validateUserFields(pFormId)
{
    var myForm = $(pFormId);

     var nickNameValidationVal = validateNickName('nickNameId');
     if ("bad-nickname-size" == nickNameValidationVal)
     {
        alert("The nickname must be between 2 and 12 characters long");
        return false;
     }

     var emailValidationVal = validateEmail('emailId');
     if ("bad-email-format" == emailValidationVal)
     {
        alert("The email provided has a bad format");
        return false;
     }
     
     var passwordValidationVal = validatePasswords('passwordId', 'confirmPasswordId');
     if ("bad-password-size" == passwordValidationVal)
     {
        alert("The password must be between 6 and 15 characters long");
        return false;
     }
     
     if ("passwords-mismatch" == passwordValidationVal)
     {
        alert("The password and confirm password do not match");
        return false;
     }
     
     
     return true;
}

function validateAndRegisterUser(pForm)
{
    myForm = $(pForm);
    alert(myForm.valueOf());
    
     var nickNameValidationVal = validateNickName('nickNameId');
     if ("bad-nickname-size" == nickNameValidationVal)
     {
        alert("The nickname must be between 2 and 12 characters long");
        return false;
     }

     var emailValidationVal = validateEmail('emailId');
     if ("bad-email-format" == emailValidationVal)
     {
        alert("The email provided has a bad format");
        return false;
     }
     
     var passwordValidationVal = validatePasswords('passwordId', 'confirmPasswordId');
     if ("bad-password-size" == passwordValidationVal)
     {
        alert("The password must be between 6 and 15 characters long");
        return false;
     }
     if ("passwords-mismatch" == passwordValidationVal)
     {
        alert("The password and confirm password do not match");
        return false;
     }
     
     var registerUserVal = registerUser(pForm);
     if ("duplicate" == registerUserVal)
     {
        alert("This entry is already in our system; please try a different email address and/or nickname");
        return false;
     }
     else if ("general_failure" == registerUserVal)
     {
        alert("We are currently experiencing technical difficulties; please retry again later");
        return false;
     }
     
     hideDiv("favorRegisterDiv");
     alert("Thank you for registering; you will soon receive an email with an account activation link");
     return true;
  }
  
 





//---------------------------------------------------------------------
// Validates the summary
//---------------------------------------------------------------------
function validateSummary()
{
  var summary = $("summaryId");
  summary.value = trim(summary.value);

  
  if (0 == summary.value.length)
  {
    summary.focus();
    summary.select();
    return "empty-summary";
  }
  
  return "good-summary";
}


//---------------------------------------------------------------------
// Validates the favor to receive
//---------------------------------------------------------------------
function validateFavorToReceive()
{
  var favorToReceiveDescription = $("favorToReceiveDescriptionId");
  favorToReceiveDescription.value = trim(favorToReceiveDescription.value);
  
  if (0 == favorToReceiveDescription.value.length)
  {
    favorToReceiveDescription.focus();
    favorToReceiveDescription.select();
    return "empty-favorToReceive";
  }
  
  return "good-favorToReceive";
}

//---------------------------------------------------------------------
// Validates the favor to give
//---------------------------------------------------------------------
function validateFavorToGive()
{
  var favorToGiveDescription = $("favorToGiveDescriptionId");
  favorToGiveDescription.value = trim(favorToGiveDescription.value);
  
  if (0 == favorToGiveDescription.value.length)
  {
    favorToGiveDescription.focus();
    favorToGiveDescription.select();
    return "empty-favorToGive";
  }
  
  return "good-favorToGive";
}

//---------------------------------------------------------------------
function getMyFavorExchanges() 
{
    var response;
    new Ajax.Request('http://'+ top.location.host + '/favorpals/jsp/MyFavorExchanges.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('We are currently experiencing technical difficulties, please try again.' + response) 
                           }   
                     }); 
   return response;
}

//---------------------------------------------------------------------
function getRecentFavorExchanges() 
{
    var response;
    new Ajax.Request('http://'+ top.location.host + '/favorpals/jsp/RecentFavorExchanges.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('We are currently experiencing technical difficulties, please try again.' + response) 
                           }   
                     }); 
   return response;
}



function validateAndPostFavorExchange()
{
     var summaryIdValidationVal = validateSummary();
     if ("empty-summary" == summaryIdValidationVal)
     {
        alert("The summary cannot be empty");
        return false;
     }
     
     var favorToReceiveValidationVal = validateFavorToReceive();
     if ("empty-favorToReceive" == favorToReceiveValidationVal)
     {
        alert("The favor to receive cannot be empty");
        return false;
     }
     
     var favorToGiveValidationVal = validateFavorToGive();
     if ("empty-favorToGive" == favorToGiveValidationVal)
     {
        alert("The favor to give cannot be empty");
        return false;
     }

     var postFavorExchangeRetval = postFavorExchange();
     
     if ("true" == postFavorExchangeRetval)
     {
        return true;
     }
     
     window.location = 'http://' + top.location.host + '/favorpals/jsp/UploadFavorExchangeImage.jsp';
 }


function getDays() 
{
    var selectedMonthIndex = document.userRegistrationForm.month.selectedIndex;
    var selectedMonth = document.userRegistrationForm.month.options[selectedMonthIndex].value;
    
    var daysArrayAsStr = monthToDaysMap[selectedMonth];
    var daysArray = daysArrayAsStr.split(",");
    document.userRegistrationForm.day.options.length = 0; 
    for (var i=0; i < daysArray.length; i++) 
    {
        var day = daysArray[i];
        document.userRegistrationForm.day.options[i] = new Option(day, day);
    }
}

 
 // Populate states and cities
 function populateStatesAndCities()
 {
    populateStates();
    populateCities();
 }
 
 // Populate the states
 function populateStates()
 {
    //var selectedCountry = document.postFavorExchangeForm.country.options[document.postFavorExchangeForm.country.selectedIndex].value;
    var states = getStates();
    var stateArray = states.split(",");
    document.postFavorExchangeForm.state.options.length = 0; 
      document.postFavorExchangeForm.state.options[0] = new Option("-------Select-------", -1);
    for (var i=0; i < stateArray.length; i++) 
    {
        var state = stateArray[i];
        document.postFavorExchangeForm.state.options[i + 1] = new Option(state, state);
    }
 }
 
 // Make an AJAX call to get the states
 function getStates()
 {
    var response;
    var protocol = getProtocol();
    new Ajax.Request(protocol + '//'+ top.location.host + '/favorpals/jsp/GetStates.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(document.postFavorExchangeForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('We are currently experiencing technical difficulties, please try again.' + response) 
                           }   
                     }); 
   return response;
 }
 
 // Populate the cities
 function populateCities()
 {
    //var selectedCountry = document.postFavorExchangeForm.country.options[document.postFavorExchangeForm.country.selectedIndex].value;
    //var selectedState = document.postFavorExchangeForm.state.options[document.postFavorExchangeForm.state.selectedIndex].value;
    var cities = getCities();
    var cityArray = cities.split(",");
    document.postFavorExchangeForm.city.options.length = 0; 

	document.postFavorExchangeForm.city.options[0] = new Option("-------Select-------", -1);
    
    for (var i=0; i < cityArray.length; i++) 
    {
        var city = unescape(cityArray[i]);
    	document.postFavorExchangeForm.city.options[i + 1] = new Option(city, city);
    }
 }
 
 // Make an AJAX call to get the cities
 function getCities()
 {
    var response;
    var protocol = getProtocol();
    new Ajax.Request(protocol + '//'+ top.location.host + '/favorpals/jsp/GetCities.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(document.postFavorExchangeForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('Failed to retrieve cities, please try again.' + response) 
                           }   
                     }); 
   return response;
 } 

  // Populate the secondary categories for the favor to give
  function populateSecondaryCategoriesForFavorToGive()
  {
    //var primaryCategory = document.postFavorExchangeForm.primaryCategoryId.options[document.postFavorExchangeForm.primaryCategoryId.selectedIndex].value;
    document.postFavorExchangeForm.favorToGiveSecondaryCategoryId.options.length = 0; 
	document.postFavorExchangeForm.favorToGiveSecondaryCategoryId.options[0] = new Option("--------------Select--------------", -1);

    var favorToGiveSecondaryCategories = getSecondaryCategoriesForFavorToGive();
    if (favorToGiveSecondaryCategories=="failure" || favorToGiveSecondaryCategories=="empty")
    {
    	return;
    }    

    var favorToGiveSecondaryCategoriesArray = favorToGiveSecondaryCategories.split(",");
    for (var i=0; i < favorToGiveSecondaryCategoriesArray.length; i++) 
    {
        var favorToGiveSecondaryCategory = favorToGiveSecondaryCategoriesArray[i];
        var nameValueArray = favorToGiveSecondaryCategory.split("=");
        var favorToGiveSecondaryCategoryName = nameValueArray[0];
        var favorToGiveSecondaryCategoryId = nameValueArray[1];
        document.postFavorExchangeForm.favorToGiveSecondaryCategoryId.options[i+1] = new Option(favorToGiveSecondaryCategoryName, favorToGiveSecondaryCategoryId);
    }
  }

 
  // Populate the secondary categories for the favor to receive
  function populateSecondaryCategoriesForFavorToReceive()
  {
    //var primaryCategory = document.postFavorExchangeForm.primaryCategoryId.options[document.postFavorExchangeForm.primaryCategoryId.selectedIndex].value;
    document.postFavorExchangeForm.favorToReceiveSecondaryCategoryId.options.length = 0; 
	document.postFavorExchangeForm.favorToReceiveSecondaryCategoryId.options[0] = new Option("--------------Select--------------", -1);

    var favorToReceiveSecondaryCategories = getSecondaryCategoriesForFavorToReceive();
    if (favorToReceiveSecondaryCategories=="failure" || favorToReceiveSecondaryCategories=="empty")
    {
    	return;
    }
    
    var favorToReceiveSecondaryCategoriesArray = favorToReceiveSecondaryCategories.split(",");
    for (var i=0; i < favorToReceiveSecondaryCategoriesArray.length; i++) 
    {
        var favorToReceiveSecondaryCategory = favorToReceiveSecondaryCategoriesArray[i];
        var nameValueArray = favorToReceiveSecondaryCategory.split("=");
        var favorToReceiveSecondaryCategoryName = nameValueArray[0];
        var favorToReceiveSecondaryCategoryId = nameValueArray[1];
        document.postFavorExchangeForm.favorToReceiveSecondaryCategoryId.options[i+1] = new Option(favorToReceiveSecondaryCategoryName, favorToReceiveSecondaryCategoryId);
    }
  }
  
  // Populate the secondary categories for the favor to receive
  function populateSecondaryCategoriesForProfile()
  {
    var secondaryCategories = getSecondaryCategoriesForProfile();
    var secondaryCategoriesArray = secondaryCategories.split(",");
    document.profileAddCategoryForm.interestedSecondaryCategory.options.length = 0; 
	document.profileAddCategoryForm.interestedSecondaryCategory.options[0] = new Option("--------------Select--------------", -1);
 
    for (var i=1; i < secondaryCategoriesArray.length; i++) 
    {
        var secondaryCategory = secondaryCategoriesArray[i];
        var nameValueArray = secondaryCategory.split("=");
        var secondaryCategoryName = nameValueArray[0];
        var secondaryCategoryId = nameValueArray[1];
 
        document.profileAddCategoryForm.interestedSecondaryCategory.options[i] = new Option(secondaryCategoryName, secondaryCategoryId);
    }
  }

  // Make an AJAX call to get the secondary categories for the favor to give
  // This method is used by the addCategory witin profile
  function getSecondaryCategoriesForProfile()
  {
    var response;
    var protocol = getProtocol();
    new Ajax.Request(protocol + '//'+ top.location.host + '/favorpals/jsp/controller/getSecondaryCategories.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(document.profileAddCategoryForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('We are currently experiencing technical difficulties, please try again.' + response) 
                           }   
                     }); 
    return response;
 }

  
  // Make an AJAX call to get the secondary categories for the favor to give
  function getSecondaryCategoriesForFavorToGive()
  {
    var response;
    var protocol = getProtocol();
    new Ajax.Request(protocol + '//'+ top.location.host + '/favorpals/jsp/GetSecondaryCategoriesForFavorToGive.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(document.postFavorExchangeForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('We are currently experiencing technical difficulties, please try again.' + response) 
                           }   
                     }); 
    return response;
 }
 
//--------------------------------------
//return the protocolwith : i.e. http:
 function getProtocol()
 {
    return window.location.protocol;
 }

  // Make an AJAX call to get the secondary categories for the favor to receive
  function getSecondaryCategoriesForFavorToReceive()
  {
    var response;
    var protocol = getProtocol();
    new Ajax.Request(protocol + '//'+ top.location.host + '/favorpals/jsp/GetSecondaryCategoriesForFavorToReceive.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(document.postFavorExchangeForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('We are currently experiencing technical difficulties, please try again.' + response) 
                           }   
                     }); 
    return response;
 }
 
 
 // Processes the forgot password by generating a new password, updating the user account and emailing the password to the user
 // It also takes care of any errors that this process may generate
 function processForgotPassword(forgotPasswordDivId,forgotPasswordFormId,forgotPasswordInvalidEmailMessageDivId)
 {
    var tmpDiv;
    
    var emailValidationVal = validateEmail('forgotPasswordEmailTextboxId');
    if ("bad-email-format" == emailValidationVal)
    {
        alert("The email provided has a bad format");
        return false;
    }
    
    var response = generateUpdateEmailPassword(forgotPasswordFormId);

    if (response == "user_not_exist")
    {
        tmpDiv = $(forgotPasswordInvalidEmailMessageDivId);
        tmpDiv.style.display = "block";
    }
    else if (response == "success")
    {
        tmpDiv = $(forgotPasswordDivId);
        tmpDiv.style.display = "none";
        alert("Please check your email to retrieve your password. If you still are unable to login please contact us at info@favorpals.com");
    }
    // Technical problems show site error page
    else
    {
        window.location = 'http://' + top.location.host + '/favorpals/jsp/siteError.jsp';
    }
 }
 
  //---------------------------------------------------------------------------------------------------------------------
  // Make an AJAX call  for generating a new password, updating the user account and emailing the password to the user
  function generateUpdateEmailPassword(forgotPasswordFormId)
  {
    var response;
    var forgotPasswordForm = $(forgotPasswordFormId);
    new Ajax.Request('https://'+ top.location.host + '/favorpals/jsp/GenerateUpdateEmailPassword.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(forgotPasswordForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('Something went wrong while updating and emailing password, please try again or contact us at info@favorpals.com' + response) 
                           }   
                     }); 
    return response;
 }
 
// --------------------------------------------------------------------
// Hide the forgot password div and show the login link element
// --------------------------------------------------------------------
function hideforgotPasswordDivAndShowLoginLink() {
    Effect.Fade($('forgotPasswordDivId'),{duration:0.25});
    
    $('loginLinkDivId').show();
}
// --------------------------------------------------------------------
// Hide the forgot password div and show the login link element
// --------------------------------------------------------------------
function hideforgotPasswordDivAndShowHomePageLoginLink() {
    Effect.Fade($('homePageForgotPasswordDivId'),{duration:0.25});

}

 
//----------------------------------------------------- 
 function hideLoginDivAndShowForgotPasswordDiv() {
    $('loginDivId').hide();
    
    
    var forgotPasswordDiv = $('forgotPasswordDivId');
    var position = $('headerId').cumulativeOffset();

    forgotPasswordDiv.setStyle({
        left:(position[0] + $('headerId').getWidth() - $('forgotPasswordDivId').getWidth()) + "px",
        top:position[1] + "px"
    });

    Effect.Appear(forgotPasswordDiv,{
        duration:0.25,
        afterFinish:function() {
            $('forgotPasswordEmailTextboxId').focus();
        }
    })
}
 
//----------------------------------------------------- 
 function showHomePageForgotPasswordDiv() {

    var forgotPasswordDiv = $('homePageForgotPasswordDivId');
    var position = $('homeLoginPanelId').cumulativeOffset();

    forgotPasswordDiv.setStyle({
        left:(position[0]- 5) + "px",
        top:(position[1] ) + "px"
    });

    Effect.Appear(forgotPasswordDiv,{
        duration:0.25,
        afterFinish:function() {
            $('forgotPasswordEmailTextboxId').focus();
        }
    })
} 
 
 //------------------------------------------------------
 function validateAndChangePassword(changePasswordDiv, changePasswordFormId, oldPasswordId, newPasswordId, confirmPasswordId)
 {
    var changePasswordDiv = $('changePasswordDivId');
    var changePasswordForm = $('changePasswordFormId');
    
    var validationVal = validateChangePassword(oldPasswordId,newPasswordId,confirmPasswordId);
            
    if (validationVal == 'bad-password-size')
    {
        alert("The passwords must be between 6 and 15 characters long");
        return;
    }
    else if (validationVal == 'old_and_new_password_cannot_be_same')
    {
        alert("The old password and new password cannot be the same");
        return;
    }
    else if (validationVal == 'new_and_conf_password_must_be_same')
    {
        alert("The new password and confirm password must be the same");
        return;
    }
    
    var response = changePassword(changePasswordFormId);
    if (response == 'failure')
    {
        alert("We are currently experiencing technical difficulties, please try this operation again");
        return;
    }
    alert("You have successfully modified your password, please logout and login again");
 }
 
   //-----------------------------------------------    
   // Make an AJAX call  to change the password
   // Uses https protocol.
  function changePassword(changePasswordFormId)
  {
    var response;
    var changePasswordForm = $(changePasswordFormId);
    new Ajax.Request('https://'+ top.location.host + '/favorpals/jsp/ChangePassword.jsp',
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(changePasswordForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                           }   
                     }); 
    return response;
 }


function validateSearch()
{
  var searchInput = $("searchInputId");
  searchInput.value = trim(searchInput.value);
  
  if (0 == searchInput.value.length)
  {
    searchInput.focus();
    searchInput.select();
    return false;
  }
  
  return true;
} 

function setVisible(elementId, visibility)
{
    var element = $(elementId);
    element.style.display = visibility;
}

function gotoElementPosition(elementId)
{   
    var element = $(elementId);
    var posX = findPosX(element);
    var posY = findPosY(element);
    window.scrollTo(posX, posY);
    alert("element with id " + elementId + "; has posX=" + posX + " and posY=" + posY);
} 

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

//---------------------------------------------------------------------
function postUser()
{
     var postUserRetval = updateUser();
     
     if ("success" != postUserRetval)
     {
        return true;
     }
     
     alert("User has been updated with sucess.");
     location.href = 'http://' + top.location.host + '/favorpals/jsp/admin/index.jsp?action=manageUsers'
}

function updateUser() 
{
    var response;
    var cookie;
    var form = $('postUserFormId');

    new Ajax.Request('http://' + top.location.host + '/favorpals/jsp/admin/update_user.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                                        response = transport.responseText;
                                        response = trim(response, null);
                        },
                        onFailure: function()
                        {
                          response = "failure"; 
                        }   
                     }); 
    return response;
}

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

function displayExpirationConfirmation(redirectionURL)
{
    var answer = confirm("Are you sure you want to expire the favor exchange?");
    if (answer != false)
    {
        location.href=redirectionURL;
    }
}

//---------------------------------------------------------------------
function updateProfileCategory(pForm) {
    var form;
    var response;
    
    form = $(pForm);
    
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/updateProfileCategory.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
	                        },
	                        onFailure: function(){
	                          response = "general_failure"; 
	                        }   
                     }); 
	if( response != undefined && response.length>0){
		document.getElementById("addCategoryErrorMessagesId").innerHTML=response;    
		return false; 
	}else{
		hideDiv(document.getElementById("addProfileCategoryId"));
	}
   return true;
}

//---------------------------------------------------------------------
function new_updateProfileCategory(pForm) {
    var form;
    var response;
    
    form = $(pForm);
    
    new Ajax.Request('https://' + top.location.host + '/favorpals/profile/category/update.fp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
	                        },
	                        onFailure: function(){
	                          response = "general_failure"; 
	                        }   
                     }); 
	if( response != undefined && response.length>0){
		document.getElementById("addCategoryErrorMessagesId").innerHTML=response;    
		return false; 
	}else{
		hideDiv(document.getElementById("addProfileCategoryId"));
	}
   return true;
}

//---------------------------------------------------------------------
function updateProfileExperience(pForm) {
    var form;
    var response;
    form = $(pForm);
    
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/updateProfileExperience.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
	if( response != undefined && response.length>0){
		document.getElementById("editExperienceErrorMessagesId").innerHTML=response;    
		return false; 
	}else{
		hideDiv(document.getElementById("addExperienceId"));
	}
   return true;
}


//---------------------------------------------------------------------
function updateProfileEducation(pForm) {
    var form;
    var response;
    
    form = $(pForm);
    
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/updateProfileEducation.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);         
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
	if( response != undefined && response.length>0){
		document.getElementById("editEducationErrorMessagesId").innerHTML=response;    
		return false; 
	}else{
		hideDiv(document.getElementById("addEducationId"));
	}
   return true;
}

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

function validateAndUpdateCategory(pForm)
{
    myForm = $(pForm);
     var userVal = updateProfileCategory(pForm);
     return userVal;
 }
  
//---------------------------------------------------------------------  

function new_validateAndUpdateCategory(pForm)
{
    myForm = $(pForm);
     var userVal = new_updateProfileCategory(pForm);
     return userVal;
 }
  
//---------------------------------------------------------------------  

function validateAndUpdateEducation(pForm)
{
    myForm = $(pForm);
     var userVal = updateProfileEducation(pForm);
     return userVal;
 }

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

function validateAndUpdateExperience(pForm)
{
    myForm = $(pForm);
     var userVal = updateProfileExperience(pForm);
     return userVal;
 }

  
//---------------------------------------------------------------------  
  
function removeEducation(educationId){
    var response;
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/remove_education.jsp?educationId='+educationId,
                         { method:'form.action',
                           asynchronous:false,
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
	document.getElementById("errorMessages").innerHTML=response;                     
   return response;
}
//---------------------------------------------------------------------  

function removeExperience(experienceId){
    var response;
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/remove_experience.jsp?experienceId='+experienceId,
                         { method:'form.action',
                           asynchronous:false,
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
	document.getElementById("errorMessages").innerHTML=response;                     
   return response;
}

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

function removeCategory(categoryId){
    var response;
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/remove_user_category.jsp?categoryId='+categoryId,
                         { method:'form.action',
                           asynchronous:false,
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
	document.getElementById("errorMessages").innerHTML=response;                     
   return response;
}

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

function new_removeCategory(categoryId){
    var response = "";
    new Ajax.Request('https://' + top.location.host + '/favorpals/profile/category/remove.fp?categoryId='+categoryId,
                         { method:'form.action',
                           asynchronous:false,
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "Oops! We got a technical difficulty. Please try again."; 
                        }   
                     });
	if (response != "")
	{
		alert(response);
	}                      
}

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

function validateAndUpdateProfile(pForm) {
    var form;
    var response;
    form = $(pForm);
    
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/update_profile.jsp',
                         { method:'form.action',
                           asynchronous:false,
                           parameters: Form.serialize(form),
                           onSuccess: function(transport){
                           
                            response = transport.responseText;
                            response = trim(response);              
                        },
                        onFailure: function(){
                          response = "general_failure"; 
                        }   
                     }); 
        if(response != undefined && response != ""){
			document.getElementById("editProfileErrorMessagesId").innerHTML=response;  
			return false; 
		}
	alert("Your profile data was successfully changed.");
   return true;
}

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

  function sendInvitation(pForm)
  {
    var response;
    var invitationForm = $(pForm);
	var pageReferalInput = invitationForm['inviterPageReferalId'];
	alert('https://' + top.location.host + '/favorpals/jsp/controller/sendInvitation.jsp' + $(pageReferalInput).getValue());
    new Ajax.Request('https://' + top.location.host + '/favorpals/jsp/controller/sendInvitation.jsp?pageReferalId=' + $(pageReferalInput).getValue(),
                        { method:'form.action',
                          asynchronous:false,
                          parameters: Form.serialize(invitationForm),
                          onSuccess: function(transport)
                           {
                                response = transport.responseText;
                                response = trim(response,null); 
                           },
                           onFailure: function()
                           {
                              alert('Something went wrong while attempting to invite friends'); 
                           }   
                     }); 
    return response;
 }

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

function markCheckbox(pCheckBox)
{
	if (pCheckBox.checked)
	{
		pCheckBox.value = "true";
	} else {
		pCheckBox.value = "false";
	}	
}

function showTabFromTab(pTabIndex, pColorTab, pNumTabs, pTabPrefix, pTitlePrefix)
{
	for (i=0; i<pNumTabs; i++) 
	{
		if (i == pTabIndex)
		{
			setVisible(pTabPrefix+'_'+i, 'block');
			pColorTab[i] = '#78AC1A';
			
		} else {
			setVisible(pTabPrefix+'_'+i, 'none');
			pColorTab[i] = '#FFFFFF';
		}
		changeColor(pTitlePrefix+'_'+i, pColorTab[i]);
	}
	
	return pColorTab;
}

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

// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gPopupIsShown = false;
var gHideSelects = false;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = keyDownHandler;
}	

/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/
 *
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 *
 * Gets the full width/height because it's different for most browsers.
 */
function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 

	return window.undefined; 
}
function getViewportWidth() {
	var width = null;
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
}

/**
 * Sets the size of the popup mask.
 *
 */
function setMaskSize() {
	var theBody = document.getElementsByTagName("BODY")[0];
			
	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();
	
	// Determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) {
		popHeight = fullHeight;
	} else {
		popHeight = theBody.scrollHeight;
	}
	
	if (fullWidth > theBody.scrollWidth) {
		popWidth = fullWidth;
	} else {
		popWidth = theBody.scrollWidth;
	}
	
	gPopupMask.style.height = popHeight + "px";
	gPopupMask.style.width = popWidth + "px";
}

/**
 * X-browser event handler attachment and detachment
 * TH: Switched first true to false per http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html
 *
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}
function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

/**
 * Gets the real scroll top
 */
function getScrollTop() {
	if (self.pageYOffset) // all except Explorer
	{
		return self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollTop;
	}
}
function getScrollLeft() {
	if (self.pageXOffset) // all except Explorer
	{
		return self.pageXOffset;
	}
	else if (document.documentElement && document.documentElement.scrollLeft)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollLeft;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollLeft;
	}
}

/**
 * Hide the popup window
 */
function hidePopWin() {
	gPopupMask = document.getElementById("popupMask");
	gPopupContainer = document.getElementById("popupContainer");
	gPopFrame = document.getElementById("popupFrame");

	gPopupIsShown = false;
	var theBody = document.getElementsByTagName("BODY")[0];
	theBody.style.overflow = "";
	restoreTabIndexes();
	if (gPopupMask == null) {
		return;
	}
	gPopupMask.style.display = "none";
	gPopupContainer.style.display = "none";
	gPopFrame.src = "about:blank";
	// display all select boxes
	if (gHideSelects == true) {
		displaySelectBoxes();
	}
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}

/**
 * Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
 * IE has a problem with wanted select form tags to always be the topmost z-index or layer
 *
 * Thanks for the code Scott!
 */
function hideSelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++) {
    x[i].style.visibility = "hidden";
  }
}

/**
 * Makes all drop down form select boxes on the screen visible so they do not 
 * reappear after the dialog is closed.
 * 
 * IE has a problem with wanting select form tags to always be the 
 * topmost z-index or layer.
 */
function displaySelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++){
    x[i].style.visibility = "visible";
  }
}

//
function centerPopWin(width, height) {
	if (gPopupIsShown == true) {
		if (width == null || isNaN(width)) {
			width = gPopupContainer.offsetWidth;
		}
		if (height == null) {
			height = gPopupContainer.offsetHeight;
		}
		
		var theBody = document.getElementsByTagName("BODY")[0];
		var scTop = parseInt(getScrollTop(),10);
		var scLeft = parseInt(theBody.scrollLeft,10);
	
		setMaskSize();
		
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		
		gPopupContainer.style.top = (scTop + ((fullHeight - height) / 2)) + "px";
		gPopupContainer.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
	}
}

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

function checkLogin(pIsLoggedIn)
{
	if (null == pIsLoggedIn || "true" != pIsLoggedIn)
	{
		var requestURL = window.location.href;
		window.location = 'https://' + top.location.host + '/favorpals/jsp/favorpals_login.jsp?redirectionURL=' + requestURL;
	}
}

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

var advancedSearch = false;

function toggleAdvancedSearch()
{
	if (advancedSearch == false)
	{
		advancedSearch = true;
		document.getElementById('advancedSearchDivId').style.display = 'block';
		document.getElementById('searchLinkId').innerHTML = 'Back to Basic Search';
	}
	else
	{
		advancedSearch = false;
		document.getElementById('advancedSearchDivId').style.display = 'none';
		document.getElementById('searchLinkId').innerHTML = 'Go to Advanced Search';
	}
}

function checkBoxEnableTextField(pCheckBoxId, pTextFieldId)
{
	var checkBox = document.getElementById(pCheckBoxId);
	var textField = document.getElementById(pTextFieldId);
	
	if (checkBox.checked == false)
	{
		textField.value = '';
		textField.disabled = 'disabled';
		textField.style.backgroundColor = '#EEEEEE';
		textField.style.border = '1px solid rgb(204, 204, 204)';
	}
	else
	{
		textField.disabled = '';
		textField.style.backgroundColor = '#FFFFFF';
		textField.style.border = '1px solid rgb(204, 204, 204)';
	}
}

function showTabFromSelect(pSelectId, pTabPrefix, pNumTabs)
{
	var select = document.getElementById(pSelectId);
	var selectedIndex = select.selectedIndex;

	for (i=0; i < pNumTabs; i++)
	{
		var tab = document.getElementById(pTabPrefix+'_'+i);
		if (i == selectedIndex)
		{
			tab.style.display = 'block';
		}
		else
		{
			tab.style.display = 'none';
			clearAdvancedSearchTabFields(tab);
		}
	}
}

function validateAdvancedSearchForm(pFormId)
{
	var form = document.getElementById(pFormId);
	var selectedTerms = 0;
	
	for (i=0; i<form.length; i++)
	{
		var element = form.elements[i];
		
		if (element.type == 'checkbox' && element.checked == true)
		{
			selectedTerms++;
			element = form.elements[++i];
			if (element.value == '')
			{
				alert('You need to fill in all the provided terms for the advanced search.');
				return false;
			}
		}
	}
	
	if (selectedTerms == 0)
	{
		alert('You need to provide at least one term for the advanced search.');
		return false;
	}
	
	return true;
}

function clearAdvancedSearchTabFields(pTab)
{
	var form = pTab.getElementsByTagName('form')[0];
	var i;
	
	for (i=0; i<form.length; i++)
	{
		var element = form.elements[i];
		
		if (element.type == 'checkbox' && element.checked == true)
		{
			var textBox = form.elements[++i];
			element.checked = false;
			checkBoxEnableTextField(element.id, textBox.id);
		} 
	}
}

function removeEntryText(entryText)
{
	document.getElementById(entryText).value="";
}
function displayHiddenElement(hidden, real)
{
	if (document.getElementById(real).value == null ||
	    document.getElementById(real).value == "") 
	{
		document.getElementById(real).style.display = "none";
		document.getElementById(hidden).style.display = "block";
	}
}

function resetHiddenValue(vlaue, hiddenElement, realElement)
{
	if(document.getElementById(realElement).value == null ||
	  document.getElementById(realElement).value =="")
	{
		document.getElementById(hiddenElement).value = value;
	}
}

function selectEntryText(entryText)
{
	document.getElementById(entryText).select();
}
function switchEntry(hidden, real) {
   document.getElementById(hidden).style.display="none";
   document.getElementById(real).style.display="block";
   document.getElementById(real).focus();
   //document.getElementById(real).click();
}

//-------------------------------------------------------------------
// Twitter and Facebook
//-------------------------------------------------------------------

function postFavorExchangeOnTwitter(pFavorExchangeId) 
{
	location.href = '/favorpals/twitter/start-post-favor-exchange.fp?favorExchangeId=' + pFavorExchangeId;
}

function postUrlOnTwitter(pText, pUrl) 
{
	location.href = '/favorpals/twitter/start-post-url.fp?text=' + pText + '&url=' + pUrl;
}

function postFavorExchangeOnFacebook(pFavorExchangeId) 
{
	location.href = '/favorpals/facebook/start-post-favor-exchange.fp?favorExchangeId=' + pFavorExchangeId;
}

function postUrlOnFacebook(pText, pUrl) 
{
	location.href = '/favorpals/facebook/start-post-url.fp?text=' + pText + '&url=' + pUrl;
}

function whyToProvideBirthDate()
{
	var message = "We need you to provide your authentic birthdate as our culture is based on the truth and we enforce that every user should be able to trust and be trusted.";
	alert(message);
}

function populateBirthDate(pMonth, pDay, pYear)
{
	populateMonth(pMonth);
    populateYear(pYear);
    populateDays(pDay);
}
 
function populateMonth(pMonth)
{
    var monthArray = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    document.userRegistrationForm.month.options.length = 0; 
	document.userRegistrationForm.month.options[0] = new Option("Month:", -1);
    
    for (var i=0; i < monthArray.length; i++) 
    {
        var month = unescape(monthArray[i]);
    	document.userRegistrationForm.month.options[i + 1] = new Option(month, month);
    	
    	if (pMonth != '' && pMonth == month)
    	{
    		document.userRegistrationForm.month.options[i + 1].selected = true;
    	}
    }
}

function populateYear(pYear)
{
    var yearArray = new Array();
    document.userRegistrationForm.year.options.length = 0; 
	document.userRegistrationForm.year.options[0] = new Option("Year:", -1);
    
    var year = new Date().getFullYear();
    for (var i=0; year >= 1900; i++, year--)
    {
    	document.userRegistrationForm.year.options[i + 1] = new Option(year, year);
    	
    	if (pYear != '' && parseInt(pYear) == year)
    	{
    		document.userRegistrationForm.year.options[i + 1].selected = true;
    	}
    }
}

function populateDays()
{
	populateDays(null);
}

function populateDays(pDay)
{
	var oldSelection = document.userRegistrationForm.day.selectedIndex;

    var daysPerMonthArray = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    
    // Year analisys
    var yearSelectedIndex = document.userRegistrationForm.year.selectedIndex;
    var selectedYear = parseInt(document.userRegistrationForm.year.options[yearSelectedIndex].value);
    
    if (selectedYear == -1)
    {
    	selectedYear = new Date().getFullYear();
    }
    
    // Bissext year
    if (selectedYear % 4 == 0)
    {
    	daysPerMonthArray[1]++;
    }
    
    document.userRegistrationForm.day.options.length = 0; 
	document.userRegistrationForm.day.options[0] = new Option("Day:", -1);
	
	// Month analisys
	var monthSelectedIndex = document.userRegistrationForm.month.selectedIndex;
	
	if (monthSelectedIndex == 0)
	{
		monthSelectedIndex = 1;
	}
	
	var totalDays = daysPerMonthArray[monthSelectedIndex-1];
	
    for (var i=0; i < totalDays; i++) 
    {
    	document.userRegistrationForm.day.options[i+1] = new Option(i+1, i+1);
    	
    	if (pDay != '' && parseInt(pDay) == i+1)
    	{
    		document.userRegistrationForm.day.options[i + 1].selected = true;
    	}
    }
    
    if (oldSelection != 0 && oldSelection < totalDays)
    {
    	document.userRegistrationForm.day.selectedIndex = oldSelection;
    }
}