/////////////////////////////////////////////////////////////
////////////////////////// COMMON ///////////////////////////
/////////////////////////////////////////////////////////////

var DHTML = (document.getElementById || document.all || document.layers);

function getObj(name)
{
    if (document.getElementById)
    {
        return document.getElementById(name);
    }
    else if (document.all)
    {
        return document.all[name];
    }
    else if (document.layers)
    {
        return document.layers[name];
    }
}

function getParentWin()
{
    return window.parent;
}

function hideObj(name)
{
    var d = getObj(name);
    if (d)
    {
        d.style.display="none";
    }
}

function showObj(name)
{
    var d = getObj(name);
    if (d)
    {
        d.style.display="block";
    }
}

function hideForm(name)
{
    var f = document.forms[name];
    if (f)
    {
        f.style.display="none";
    }
}

function showForm(name)
{
    var f = document.forms[name];
    if (f)
    {
        f.style.display="block";
    }
}

/////////////////////////////////////////////////////////////
///////////////////// PAGE - SPECIFIC ///////////////////////
/////////////////////////////////////////////////////////////

function toggleChooseSideDiv()
{
    var chooseSideDiv = getObj("chooseSideDiv");
    if (chooseSideDiv)
    {
        var tid = getObj("tid");
        if (tid)
        {
            if (tid.checked)
            {
                chooseSideDiv.style.display="block";
            }
            else
            {
                chooseSideDiv.style.display="none";
            }
        }
    }
}

/////////////////////////////////////////////////////////////
/////////////////////////// MAIN ////////////////////////////
/////////////////////////////////////////////////////////////

var toolbarDivName = "toolbarContent";
var loggedInDivName = "toolbarLoggedIn";
var notLoggedInDivName = "toolbarNotLoggedIn";
var loginNameDivName = "loginNameDiv";
var newAccountDivName = "toolbarNewAccount";
var popupBoxName = "popupBox";
var popupBox;
var toolbarLoginDivName = "toolbarLogin";
var toolbarPasswordDivName = "toolbarForgotPassword";



function init()
{
    initXYRecorder();
    initPopup();
}



var clickX = 0;
var clickY = 0;

function initXYRecorder() 
{
   var recordXY = function(e) {
      var bgId = YAHOO.util.Event.getTarget(e, true).id;
      if (bgId && bgId.indexOf('popup') > -1)
      {
          return;
      }
      clickX = YAHOO.util.Event.getPageX(e);
      clickY = YAHOO.util.Event.getPageY(e);
   };
   
   YAHOO.util.Event.addListener(document, 'click', recordXY);
};

function initPopup()
{
    popupBox = new YAHOO.widget.Dialog(popupBoxName, 
                                       { width:"500px",
                                         height:"400px",
                                         visible:false, 
                                         constraintoviewport:true,
                                         draggable:true,
                                         modal:false,
                                         underlay:"none",
                                         zIndex:"1000000",
                                         postmethod:"form"
                                       } );   
    popupBox.render();
    getObj(popupBoxName).style.display="block";
}


function updateVoteBoxes(opinion2voteCSL)
{
    var ids = opinion2voteCSL.split(",");
    for (var i = 0; i < ids.length; i++)
    {
        var kv = ids[i].split("=");
        var opinionId = kv[0];
        var vote = kv[1];
        if (getObj("votebox"+opinionId))
        {
            getObj("voteButtons"+opinionId).style.display="none";
            getObj("voted"+opinionId).style.display="block";
            getObj("votedImg"+opinionId).src="/images/content/vote"+vote+".gif";
        }
    }
}

function clearVoteBoxes()
{
    var divs = YAHOO.util.Dom.getElementsByClassName('voteButtons','div');    
    for(i = 0; i < divs.length;i++)    
    {    
        divs[i].style.display="block";    
    }

    var divs = YAHOO.util.Dom.getElementsByClassName('voted','div');    
    for(i = 0; i < divs.length;i++)    
    {    
        divs[i].style.display="none";    
    }
}



function getToolbarDiv()
{
    return getObj(toolbarDivName);
}

function getLoggedInDiv()
{
    return getObj(loggedInDivName);
}

function getNotLoggedInDiv()
{
    return getObj(notLoggedInDivName);
}

function getLoginNameDiv()
{
    return getObj(loginNameDivName);
}

function getToolbarNewAccountDiv()
{
    return getObj(newAccountDivName);
}

function showToolbarNewAccountDiv()
{
    var newAccountDiv = getToolbarNewAccountDiv();
    if (newAccountDiv)
    {
        newAccountDiv.style.display="block";
    }

    brightenToolbarNewAccountDiv();
}

function hideToolbarNewAccountDiv()
{
    var newAccountDiv = getToolbarNewAccountDiv();
    if (newAccountDiv)
    {
        newAccountDiv.style.display="none";
    }
}

var firstNA = true;

function na(loginMessage, acctMessage, inNavbar)
{
    if (inNavbar)
    {
        var message = loginMessage+acctMessage;
        if (message && message != "")
        {
            alert(message);
        }

        if (firstNA)
        {
            firstNA = false;
    
            var anim = new YAHOO.util.Anim(newAccountDivName, 
                                           { opacity: { to: 0 } }, 
                                           0.01, 
                                           YAHOO.util.Easing.easeOut);
    
            anim.onComplete.subscribe(expandToolbar);
    
            anim.animate();
        }
        else
        {
            expandToolbar();
        }
    }
    else
    {
        showLoginPopup(loginMessage, acctMessage);
    }
}

function expandToolbar()
{
    var toolbarAnim = new YAHOO.util.Anim(toolbarDivName, 
                                          {height: { to: 200 }}, 
                                          1, 
                                          YAHOO.util.Easing.easeOut);

    toolbarAnim.onComplete.subscribe(showToolbarNewAccountDiv);

    toolbarAnim.animate();
}

function brightenToolbarNewAccountDiv()
{
    var anim = new YAHOO.util.Anim(newAccountDivName, 
                                   { opacity: { to: 1 } }, 
                                   1, 
                                   YAHOO.util.Easing.easeOut);
    anim.animate();
}

function contractToolbar()
{
    fadeToolbarNewAccountDiv();
}

function fadeToolbarNewAccountDiv()
{
    var anim = new YAHOO.util.Anim(newAccountDivName, 
                                   { opacity: { to: 0 } }, 
                                   1, 
                                   YAHOO.util.Easing.easeOut);

    anim.onComplete.subscribe(contractToolbarStep2);

    anim.animate();
}

function contractToolbarStep2()
{
    hideToolbarNewAccountDiv();

    var toolbarAnim = new YAHOO.util.Anim(toolbarDivName, 
                                          {height: { to: 45 }}, 
                                          1, 
                                          YAHOO.util.Easing.easeOut);

    toolbarAnim.animate();
}




function showLoginPopup(loginMessage, acctMessage)
{
    var message = loginMessage+acctMessage;
    if (message && message != "")
    {
        alert(message);
    }

    popupBox.moveTo(clickX,clickY);
    popupBox.show();
}

function hideLoginPopup()
{
    popupBox.hide();
}

function isValidEmail(email) 
{
	var regexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

	if (email.length < 5 || !email.match(regexp)) 
    { 
        return false; 
    }
	
	return true;
}

function isValidUsername(name) 
{
	var regexp = /^[\w\-]{5,20}$/

	if (name.length < 5 || !name.match(regexp)) 
    { 
        return false; 
    }
	
    return true;
}

function acctCreateVerify()
{
    if (getObj('inputRegisterVerify').checked==false)
    {
        alert('Please verify that you agree to our terms of service.');
        return false;
    }
    else if (isValidUsername(getObj('inputRegisterBarUsername').value)==false)
    {
        alert('Your username should be 5 to 20 characters long and use only letters, numbers, dashes and underscores.');
        return false;
    }
    else if (isValidEmail(getObj('inputRegisterBarEmail').value)==false)
    {
        alert('Please enter a valid email address.');
        return false;
    }
    else if (getObj('inputRegisterBarPass').value=="" || getObj('inputRegisterBarPass').value!=getObj('inputRegisterBarPass2').value)
    {
        alert('Please enter the same password twice.');
        return false;
    }
    else if (getObj('inputRegisterBarCaptcha').value.length!=4)
    {
        alert('Please enter the 4-digit number you see in the image.');
        return false;
    }

    return true;
}

function acctPopupCreateVerify()
{
    if (getObj('popupRegisterVerify').checked==false)
    {
        alert('Please verify that you agree to our terms of service.');
        return false;
    }
    else if (isValidUsername(getObj('popupRegisterBoxUsername').value)==false)
    {
        alert('Your username should be 5 to 20 characters long and use only letters, numbers, dashes and underscores.');
        return false;
    }
    else if (isValidEmail(getObj('popupRegisterBoxEmail').value)==false)
    {
        alert('Please enter a valid email address.');
        return false;
    }
    else if (getObj('popupRegisterBoxPass').value=="" || getObj('popupRegisterBoxPass').value!=getObj('popupRegisterBoxPass2').value)
    {
        alert('Please enter the same password twice.');
        return false;
    }
    else if (getObj('popupRegisterBoxCaptcha').value.length!=4)
    {
        alert('Please enter the 4-digit number you see in the image.');
        return false;
    }

    return true;
}

function checkLogin()
{
    if (isLoggedIn)
    {
        return true;
    }
    else
    {
        return confirm("Post anonymously?\n\nClick 'OK' if you want to post your opinion anonymously.\nIf not, click 'Cancel' and then log in.  You will not have to retype your opinion.");
    }
}

function checkLogin2()
{
    if (isLoggedIn)
    {
        return true;
    }
    else
    {
        return confirm("Post anonymously?\n\nClick 'OK' if you want to create your smargument anonymously.\nIf not, click 'Cancel' and then log in.  You will not have to retype anything on this page.");
    }
}



function addOpinion(statusCode, opinionId, topicId)
{
    if (statusCode == 0)
    {   
        if (topicId && topicId != "")
        {
            document.location="/smargument.jsp?o=new&id="+topicId;
        }
        else
        {
            document.location="/opinion.jsp?id="+opinionId;
        }
    }
    else if (statusCode & 2)
    {
        logout("You need to log in");
        showLoginPopup("","");
    }
    else if (statusCode & 1)
    {
        alert("Error");
    }
    else if (statusCode & 4)
    {
        alert("Error: Missing Smargument ID");
    }
    else if (statusCode & 8)
    {
        alert("Error: Missing Smargument Side");
    }
    else if (statusCode & 16)
    {
        alert("Error: Blank Opinion");
    }
    else
    {
        alert("Error "+statusCode);
    }
}

function addTopic(statusCode, topicId)
{
    if (statusCode == 0)
    {
        document.location="/smargument.jsp?id="+topicId;
    }
    else if (statusCode & 2)
    {
        logout("You need to log in");
        showLoginPopup("","");
    }
    else if (statusCode & 1)
    {
        alert("Error");
    }
    else if (statusCode & 4)
    {
        alert("Error: Missing Smargument Title");
    }
    else
    {
        alert("Error "+statusCode);
    }
}

function vote(opinionId, opinionSide, voteSide, statusCode)
{
    if (statusCode == 0)
    {
        var votetotal = getObj("votetotal"+opinionId);
        if (votetotal)
        {
            var newTotal = votetotal.innerHTML;
            if (voteSide == 0)
            {
                newTotal++;
            }
            else
            {
                newTotal--;
            }
            votetotal.innerHTML = newTotal;
            if (newTotal > 0)
            {
                votetotal.className="voteTotal pos";
            }
            else if (newTotal < 0)
            {
                votetotal.className="voteTotal neg";
            }
            else
            {
                votetotal.className="voteTotal zero";
            }
        }

        var imageSuffix = "Down";

        if (voteSide == 0)
        {
            var votes = getObj("voteup"+opinionId);
            if (votes)
            {
                var newVotes = votes.innerHTML;
                newVotes++;
                votes.innerHTML = newVotes;
            }

            if (opinionSide == 0)
            {
                imageSuffix = "UpPro";
            }
            else
            {
                imageSuffix = "UpCon";
            }
        }
        else
        {
            var votes = getObj("votedown"+opinionId);
            if (votes)
            {
                var newVotes = votes.innerHTML;
                newVotes++;
                votes.innerHTML = newVotes;
            }

            imageSuffix = "Down";
        }

        updateVoteBoxes(opinionId+"="+imageSuffix);
    }
    else if (statusCode & 2)
    {
        logout("You need to log in");
        showLoginPopup("","");
    }
    else if (statusCode & 1)
    {
        alert("Error");
    }
    else if (statusCode & 4)
    {
        alert("Error: You Already Voted");
    }
    else if (statusCode & 8)
    {
        alert("Error: Missing Smargument Side");
    }
    else if (statusCode & 16)
    {
        alert("Error: Missing Smargument ID");
    }
    else
    {
        alert("Error "+statusCode);
    }
}

function makeAccount(statusCode, name, inNavbar)
{
    var toolbarDiv = getToolbarDiv();
    if (toolbarDiv)
    {
        if (statusCode == 0)
        {
            updateToolbarOnLogin(name);
        }
        else
        {
            var message = "";
            if (statusCode & 1)
            {
                message = "Error creating account.  Please try again later.";
            }
            else if (statusCode & 2)
            {
                message = "Please enter your email.";
            }
            else if (statusCode & 4)
            {
                message = "Please enter a password.";
            }
            else if (statusCode & 8)
            {
                message = "Please verify the password.";
            }
            else if (statusCode & 16)
            {
                message = "You already have an account.";
            }
            else if (statusCode & 32)
            {
                message = "Please enter the number you see in the image.";
            }
            else if (statusCode & 128)
            {
                message = "Please choose a user name.";
            }
            else if (statusCode & 256)
            {
                message = "Sorry, the name '"+name+"' is already taken.";
            }
            
            na("", message, inNavbar);
        }
    }
}

function login(statusCode, name, inNavbar)
{
    var toolbarDiv = getToolbarDiv();
    if (toolbarDiv)
    {
        if (statusCode == 0)
        {
            updateToolbarOnLogin(name);

            if (typeof(topicId) != "undefined")
            {
                var f = getObj("ajaxFrame");
                if (f)
                {
                    f.src="/ajax/voteboxdata.jsp?t="+topicId;
                }
            }
        }
        else
        {
            var message = "";
            if (statusCode & 1)
            {
                message = "Error logging in.  Please try again later.";
            }
            else if (statusCode & 2)
            {
                message = "Please enter your email.";
            }
            else if (statusCode & 4)
            {
                message = "Please enter your password.";
            }
            else if (statusCode & 64)
            {
                message = "Invalid login.";
            }
            
            na(message, "", inNavbar);
        }
    }
}

function updateToolbarOnLogin(name)
{
    var loggedInDiv = getLoggedInDiv();
    var notLoggedInDiv = getNotLoggedInDiv();
    if (loggedInDiv && notLoggedInDiv)
    {
        loggedInDiv.style.display="block";
        notLoggedInDiv.style.display="none";
    }

    var loginNameDiv = getLoginNameDiv();
    if (loginNameDiv)
    {
        loginNameDiv.innerHTML=name;
    }

    contractToolbar();

    isLoggedIn = true;
}

function logout(message)
{
    var loggedInDiv = getLoggedInDiv();
    var notLoggedInDiv = getNotLoggedInDiv();
    if (loggedInDiv && notLoggedInDiv)
    {
        loggedInDiv.style.display="none";
        notLoggedInDiv.style.display="block";
    }

    var email = getObj("inputToolbarEmail");
    if (email)
    {
        email.value="";
    }
    var password = getObj("inputToolbarPass");
    if (password)
    {
        password.value="";
    }

    var loginNameDiv = getLoginNameDiv();
    if (loginNameDiv)
    {
        loginNameDiv.innerHTML="";
    }

    isLoggedIn = false;

    clearVoteBoxes();
}

function forgotPassword()
{
    var toolbarLoginDiv = getObj(toolbarLoginDivName);
    var toolbarPasswordDiv = getObj(toolbarPasswordDivName);
    if (toolbarLoginDiv && toolbarPasswordDiv)
    {
        toolbarLoginDiv.style.display="none";
        toolbarPasswordDiv.style.display="block";
    }
}

function rememberedPassword()
{
    var toolbarLoginDiv = getObj(toolbarLoginDivName);
    var toolbarPasswordDiv = getObj(toolbarPasswordDivName);
    if (toolbarLoginDiv && toolbarPasswordDiv)
    {
        toolbarPasswordDiv.style.display="none";
        toolbarLoginDiv.style.display="block";
    }
}



/////////////////////////////////////////////////////////////
/////////////////////////// AJAX ////////////////////////////
/////////////////////////////////////////////////////////////

function ajaxLogin(statusCode, name, inNavbar)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.login(statusCode, name, inNavbar);
    }
}

function ajaxLogout(message)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.logout(message);
    }
}

function ajaxMakeAccount(statusCode, name, inNavbar)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.makeAccount(statusCode, name, inNavbar);
    }
}

function ajaxVote(opinionId, opinionSide, voteSide, statusCode)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.vote(opinionId, opinionSide, voteSide, statusCode);
    }
}

function ajaxAddOpinion(statusCode, opinionId, topicId)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.addOpinion(statusCode, opinionId, topicId);
    }
}

function ajaxAddTopic(statusCode, topicId)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.addTopic(statusCode, topicId);
    }
}

function ajaxUpdateVoteBoxes(opinion2voteCSL)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.updateVoteBoxes(opinion2voteCSL);
    }
}

function ajaxEmailedPassword(statusCode)
{
    if (statusCode == 0)
    {
        alert("Your password was emailed to you.  Please check your email and try logging in.");
    }
    else
    {
        alert("We were unable to send you your password.");
    }
}

function ajaxBuyProduct(url)
{
    var parent = getParentWin();
    if (parent)
    {
        parent.document.location=url;
    }
}



