//####### Copyright Mavice LLC 2009 – www.mavice.com ########

/* global.js
 * Only for javascript that needs to be executed on every page
 */

// Check cookie to see if the user is logged in
var is_logged_in = ($.cookie("personaId") != null ? true : false);

var personaId = null;
var accountId = null;
var personaName = null;
var lang = "en_US";

if(cookieSet("personaId")) personaId = $.cookie("personaId");
if(cookieSet("userId")) accountId = $.cookie("userId").replace(/\"/g, "");
if(cookieSet("displayName")) personaName = $.cookie("displayName");
if(cookieSet("lang")) lang = $.cookie("lang");

var successTitle;
var successMessage;
var errorTitle;
var errorMessage;
var closeButton;
var gameCodeFailure;
var friendCodeSuccess;
var friendCodeFailure;

var changeStatusText = null;

var enterCodeRetainer;
$(document).ready(function(){

    if($.browser.msie && $.browser.version.substr(0,1)<7 && !$.cookie("ie6WarningHide")){
        showAwardPopup($("#headerMessages .ie6Warning").html(), "", 300, 175);
        $("#awardPopup").addClass("ie6Warning");
    }

    successTitle = $("#sharedServicesMessages .successTitle").text();
    successMessage = $("#sharedServicesMessages .successMessage").text();
    errorTitle = $("#sharedServicesMessages .errorTitle").text();
    errorMessage = $("#sharedServicesMessages .errorMessage").text();
    closeButton = $("#sharedServicesMessages .closeButton").text();
    gameCodeFailure = $("#sharedServicesMessages .gameCodeFailure").text();
    friendCodeSuccess = $("#sharedServicesMessages .friendCodeSuccess").text();
    friendCodeFailure = $("#sharedServicesMessages .friendCodeFailure").text();

    // Calls jquery plugin to preloads images
    $.preloadCssImages();
    
    // Apply a shadow to the navigation items
    $("#navigation .item_padding").each(function(){
        $(this).FontEffect({
            shadow:             true,
            shadowColor:        "#000000",
            shadowOffsetLeft:   0,
            shadowOffsetTop:    1
        });
    });

    // Check the current page and determine which navigation item needs to be "on"
    var action = getCurrentAction();
    $("#navigation .item").each(function(){    

        // Turn a button on if its href matches the current action
        if($(this).attr("href") == action)
            $(this).addClass("on");
        
        //Hack to get shopTheMall to highlight the fashion tab
        if($(this).attr("href") == "fashion.action" && action == "shopTheMall.action")
            $(this).addClass("on");
    });

    changeStatusText = $("#changeStatusNow").text();    
    if(is_logged_in){
        initUserDetails();
        
        // profile.action calls the statusbar on its own
        if(action != "profile.action"){
            // Set up the status bar
            var rand = Math.floor(Math.random() * 100);
            var ssCall = "ss.action?service=/v2/m1/xml/casual/charmgirls/general/getUserStatus&rand="+rand+"&template=getUserStatus&noflash=1&referer=home"+getCredentials();
            $.get(ssCall, {}, function(data, textStatus){
                $("#statusbar").html($(data).find("#statusbar").html());
                
                if($("#statusbar .status .message").text().match(/^\s*$/))
                    $("#changeStatusNow").text($("#headerMessages .changeStatusInstructions").text());
                else
                    $("#changeStatusNow").text(changeStatusText);
                    
                $("#statusbar").slideDown();
            }, "html");
        }
    }
    else{
        $("#head_buttons").show();
    }

    // enter code submit
    $(function() {
        $("input#enter_code").live('keypress',function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                enterCode($('input#enter_code').val());
                return false;
            } else {
                return true;
            }
        });
    });
    $('a#enterCodeSubmit').live('click',function() {
        enterCode($('input#enter_code').val());
        return false;
    });
    
    // enter code handling
    $("input#enter_code").livequery('focus',function(event) {
        if ($("input#enter_code").val() == enterCodeRetainer)
        {
            $("input#enter_code").val('');
        }
    });
    $("input#enter_code").livequery('blur',function(event) {
        if ($("input#enter_code").val() == '')
        {
            $("input#enter_code").val(enterCodeRetainer);
        };
    });

    $('#enterCodeQuestion').live('click',function(event) {
        $("#helpPopup .inner").html("<h2>"+$('div#codeHelpData div.title').text()+"</h2>" + $('div#codeHelpData div.text').text());
        var mouse = getAdjustedMousePosition(event);
        $("#helpPopup")
            .css("left", mouse.x-110 + "px")
            .css("top", mouse.y + "px")
            .show();
        
        return false;
    });
    
    $("#helpPopup .close").click(function(){
        $("#helpPopup").hide();
    });
    
    $('#changeStatusNow').live('click',function(event){
        event.preventDefault();

        $("#statusbar .status").fadeOut("fast", function(){
            $("#statusbar .statusEdit").fadeIn("fast");
        });
    });
    
    
    // Change status handling
    $(function() {
        $("input#status_update").live('keypress',function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                changeStatus($('input#status_update').val());
                return false;
            } else {
                return true;
            }
        });
    });
    $('a#changeStatusSubmit').live('click',function(e) {
        changeStatus($('input#status_update').val());
        return false;
    });

    // Form fields
    $('span.checkbox').each(function() {
        if ($(this).children('input.checkbox').attr('checked') == true)
           $(this).css('background-position','0px -30px');
    });
    $('span.checkbox').mousedown(function() {
        if ($(this).css('background-position') == '0px 0px')
            $(this).css('background-position','0px -15px');
        else
            $(this).css('background-position','0px -45px');
    });
    $('span.checkbox').mouseup(function() {
        if ($(this).css('background-position') == '0px -15px'){
            $(this).css('background-position','0px -30px');
            $(this).addClass("checked");
        }
        else{
            $(this).css('background-position','0px 0px');
            $(this).removeClass("checked");
        }
    });
    $('span.radio').each(function() {
        if ($(this).children('input.radio').attr('checked') == true)
        $(this).css('background-position','0px -30px');
    });
    $('span.radio').mousedown(function() {
        if ($(this).css('background-position') == '0px 0px')
            $(this).css('background-position','0px -15px');
        else
            $(this).css('background-position','0px -45px');
    });
    $('span.radio').mouseup(function() {
        $('span.radio').css('background-position','0px 0px');
        if ($(this).css('background-position') == '0px -15px')
            $(this).css('background-position','0px -30px');
        else
            $(this).css('background-position','0px -30px');
    });
    
    //onscreen popup close
    $('div.onscreen_popup a.small_arrow_button').live('click',function() {
        $(this).closest('div.onscreen_popup').fadeOut('fast');
        var buttonHref = $(this).attr('href');
        if (buttonHref == '' || buttonHref == '#')
            return false;
        else
            return true;
    });

    $("#awardPopup .close").click(function(){
        hideAwardPopup();
    });
    
    setTimeout(function(){
        $("#flash_alt_content").show();
    }, 2000);
});

function initUserDetails(){
    $("#signedInInfo").hide();
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/general/getUserStatus&template=getUserDetails&noflash=1&referer=home"+getCredentials(), {}, function(data, textStatus){
        $("#signedInInfo").html($(data).find("#signedInInfo").html());
        $("#signedInInfo").show();

        // Enter Code
        enterCodeRetainer = $("input#enter_code").val();
    }, "html");
}

//TODO: This needs to be made to work with parameters
function getCurrentAction(){
    var action = window.location.pathname;
    return action.substring(action.lastIndexOf('/') + 1);
}

function enterCode(code){
    code = $.trim(code);
    if(code.length >= 10)
        submitGameCode(code);
    else
        submitFriendCodeGlobal(code);
}

/* Another user has given the logged in user a friend cod e
 * and now the logged in user adds the other person as a true friend
 * @param code A seven digit alphanumeric code
 */
function submitFriendCodeGlobal(code){
    if (code == '')
    {
        onscreenPopup('enterCodeSuccess', errorTitle, friendCodeFailure, closeButton, '#', 'enterCode');
    }
    else
    {
        $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/acceptFriend&code="+code+"&referer=profile"+getCredentials(), {}, function(data, textStatus){
            if($(data).find("response status").text() == "success"){
            
                if(getCurrentAction() == "profile.action"){
                    getUserDetails(friend_added);
                }
            
                var friendPersonaName = $(data).find("response application friendPersonaName").text();
                if(friendPersonaName != ""){
                    awardUser("friend_add_"+friendPersonaName, function(data){
                        var msg = $(data).find("root message").text();
                        var charm = $(data).find("root charms item[1] assets[size=1] BAS").text();
                        
                        showAwardPopup(msg, charm, 700, 100);
                    });
                }
                onscreenPopup('globalEnterCode', successTitle, friendCodeSuccess, closeButton, "#", 'enterCode');
                setTimeout(function() {
                    $('#globalEnterCode').fadeOut();
                },2500);
            }
            else{         
                onscreenPopup('globalEnterCode', errorTitle, friendCodeFailure, closeButton, "#", 'enterCode');
                setTimeout(function() {
                    $('#globalEnterCode').fadeOut();
                },2500);
            }            
        }, "xml");
    }    
}
/* The logged in user has a game code that they want to enter.
 */
function submitGameCode(code){
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/gamecode/activateGameCode&code="+code+getCredentials(), {}, function(data, textStatus){
        if(sharedServicesSuccess(data)){
        
            var changes = $(data).find("response application changes");
            var slots = $(changes).children("slots").text();
            var sku = $(changes).children("sku").text();
            var milestone = $(changes).children("milestone").text();
            
            var new_charms = (slots != "");
            var new_milestone = (milestone != "");

            var gameCodeMessage = "";
            if(new_charms && new_milestone)
                gameCodeMessage = $("#sharedServicesMessages .gameCodeFashionCharm").text();
            else if(new_charms)
                gameCodeMessage = $("#sharedServicesMessages .gameCodeCharm").text();
            else if(new_milestone)
                gameCodeMessage = $("#sharedServicesMessages .gameCodeFashion").text();
            else
                gameCodeMessage = $("#sharedServicesMessages .gameCodeNoChange").text();

            onscreenPopup('enterCode', successTitle, gameCodeMessage, closeButton, "#", 'enterCode');
            initUserDetails();
            flashCharmBoxUpdate();
        }
        else // error
        {
            onscreenPopup('globalEnterCode', errorTitle, gameCodeFailure, closeButton, "#", 'enterCode');
        }
    }, "xml");
}

/* The logged in user wants to change their status message
 */
function changeStatus(newStatus)
{
    $.ajax({
        url: "ss.action?service=/v2/m1/xml/casual/charmgirls/profile/updateProfile&template=setWithStatus&noflash=1&referer=home"+getCredentials(),
        type: "POST",
        dataType: "xml",
        data: {
            statusMessage: newStatus,
            debug: "true"
        },
        success: function(data, textStatus){
            if(sharedServicesSuccess(data)){
                // Updating page status (send newStatus to ss) for verification
                $('div#statusbar span.message').html(newStatus);
                logActivity("UpdateStatus");
                
                $("#statusbar .statusEdit").fadeOut("fast", function(){
                    if($("#statusbar .status .message").html() == "")
                        $("#changeStatusNow").html($("#headerMessages .changeStatusInstructions").text());
                    else
                        $("#changeStatusNow").html(changeStatusText);
                        
                    $("#statusbar .status").fadeIn("fast");
                });
            }
            else{
                $('div#changeStatusPopup div.errormessage div.error_pad').html(errorMessage);
            }
        }
    });
}

// Global onscreen info popup
function onscreenPopup(popupId, title, content, buttonTitle, buttonHref, positionAdjust)
{
    var left = '';
    var top = '';
    if (positionAdjust == 'enterCode'){
        top = "100px";
        left = "700px";
    }
    else if (positionAdjust == 'changeStatus'){
        top = "100px";
        left = "700px";
    }
    else if (positionAdjust == 'myFriends'){
        top = "900px";
        left = "300px";
    }
    else if (positionAdjust == 'myProfile' || positionAdjust == 'poll' || positionAdjust == 'decoratePage'){
        top = "900px";
        left = "100px";
    }
    
    var appendTo = 'body';
    
    if($("#helpPopup").length > 0){
        if ($("#helpPopup").css('display') == 'block')
            $("#helpPopup").hide();

        var inner = "<h2>"+title+"</h2>" + content;
        $("#helpPopup .inner").html(inner);
        
        if(left != "")
            $("#helpPopup").css("left", left);
        if(top != "")
            $("#helpPopup").css("top", top);

        $("#helpPopup").fadeIn();

        setTimeout(function(){
            $("#helpPopup").fadeOut();
        }, 3000);
    }
}

// Global Window Popup
function openPopup(url, name, width, height, status, scrollbars, moreProperties, x, y)
{
    // overrides coordinates
    var agent = navigator.userAgent.toLowerCase();
    var x, y = 0;
    if (screen) {
        x = (screen.availWidth - width) / 2;
        y = (screen.availHeight - height) / 2;
    }
    if (!status) status = '';
    // Adjust width if scrollbars are used (pc places scrollbars inside the content area; mac outside) 
    width += (scrollbars != '' && scrollbars != null && agent.indexOf("mac") == -1) ? 16 : 0;
    var properties = 'width=' + width + ',height=' + height + ',screenX=' + x + ',screenY=' + y + ',left=' + x + ',top=' + y + ((status) ? ',status' : '') + ',scrollbars' + ((scrollbars) ? '' : '=no') + ((moreProperties) ? ',' + moreProperties : '');
    window.open(url, name, properties);
    return false;
} 

function ajaxLoading(color)
{
    var colorFile;
    if (color == 'pink_on_blue' || color == 'pink_on_white' || color == 'white_on_purple')
        colorFile = color;
    else
        colorFile = 'pink_on_blue';

    return '<img src="images/loading/' + colorFile + '.gif" width="35" height="35" alt="Loading..." class="ajax_loading" />';
}

function setPageTheme(cssFile)
{
    $('#loadedCss').remove();
    if(cssFile != ''){
        var oLink = document.createElement("link");
        oLink.href = prepareThemePathFromFilename(cssFile);
        oLink.id = 'loadedCss';
        oLink.rel = 'stylesheet';
        oLink.type = 'text/css';
        document.body.appendChild(oLink);
    }
}

function prepareThemePathFromFilename(name){
    var cssFile = 'alfresco/' + lang + '/xml/themes/' + name;
    return cssFile;
}

function cleanSharedServicesError(error){
    var returner = error;
    returner = returner.replace(/\[CDATA\:\s/, '');
    returner = returner.replace(/\.\]/, '');
    return returner;
}

function sharedServicesSuccess(data){
    return ($(data).find("status").text() == "success");
}

function getCredentials(){
    var ret = "&requestorId=casual-charmgirlsclub";
    if(accountId)
        ret += "&accountId="+encode(accountId);
    if(personaId)
        ret += "&personaId="+personaId;
    
    return ret;
}

function cookieSet(cookieName){
    var cookie = $.cookie(cookieName);
    
    return (
        cookie != 0
        && cookie != "\"\""
        && cookie != ""
        && cookie
    );
}

function showAwardAnimation(){
    soundManager.play("awardSound");
    $("#signedInInfo").addClass("awardAnimation");
    setTimeout(function(){
        $("#signedInInfo").removeClass("awardAnimation");
    }, 1000);
}

function incrementPoints(add){
    var el = $("#points_stat");
    var points = parseInt(el.text());
    if(!points)
        points = 0;
        
    points += add;
    
    el.slideUp("slow", function(){
        el.text(points);
        el.slideDown("slow");
    });
    
    showAwardAnimation();
}

function incrementCharms(add){
    var el = $("#charms_stat");
    var points = parseInt(el.text());
    if(!points)
        points = 0;
        
    points += add;
    
    el.slideUp("slow", function(){
        el.text(points);
        el.slideDown("slow");
    });

    showAwardAnimation();
}

function awardUser(awardId, callback){
    $.ajax({
        url: "AwardUser.action?awardId="+awardId+getCredentials()+"&personaName="+personaName,
        type: "GET",
        dataType: "xml",
        success: function(data, textStatus){
            if($(data).find("root status").text() == "Success"){

                if(callback != null)
                    callback(data);
                
                var points = parseInt($(data).find("root points").text());
                var charms = parseInt($(data).find("root charms item").length);
                
                if(points && points > 0)
                    incrementPoints(points);
                    
                if(charms && charms > 0)
                    incrementCharms(charms);
            }
        }
    });
}

function showAwardPopup(message, charm, x, y){
    $("#awardPopupMessageContainer .title").html(successTitle);
    $("#awardPopupMessageContainer .message").html(message);
    $("#awardPopupMessageContainer .charm").html(charm);
    $("#awardPopup")
        .css("left", x+"px")
        .css("top", y+"px")
        .fadeIn();
}

function hideAwardPopup(){
    $("#awardPopup").fadeOut();
    if($("#awardPopup").hasClass("ie6Warning"))
        $.cookie("ie6WarningHide", 1);
}

function getOffsetWidth(){
    if(document.documentElement)
        return document.documentElement.offsetWidth;
    else if (window.innerWidth)
        return window.innerWidth;
    else
        return 0;
}

function getAdjustedMousePosition(e){
    return {
        x: e.pageX - ((getOffsetWidth() - 950) / 2),
        y: e.pageY
    };
}

function showAdjustedAwardPopup(message, charm, e){
    var mousePos = getAdjustedMousePosition(e);
    showAwardPopup(message, charm, mousePos.x-150, mousePos.y);
}

function logActivity(activityName){
    if(is_logged_in){
        $.get("logActivity.action?activityName="+activityName, {}, function(data, textStatus){});
    }
}

function encode(param){
    return param;
}


function omnicall(element, omniTag) {
	setOmniValues(element,'o',omniTag,'','','',0,'','');
}

function jsLink(element, omniTag, href){
    omniCall(element, omniTag);
    location.href = href;
}

function flashOmniClick(omniTag){
    var obj = swfobject.getObjectById("flash_swf");

    // The omniture call must receive a valid dom object to work
    // If flash_swf doesn't exist we are probably on the games page
    // We don't know which swf is calling, so loop until we get one that works
    if(!obj){
        for(var i=1; i<10; i++){
            obj = swfobject.getObjectById("flash_write"+i);
            if(obj)
                break;
        }
    }
    omnicall(obj, omniTag);
}

function flashCharmBoxUpdate(){
    var flashObject = swfobject.getObjectById("flash_swf");
    if(flashObject && flashObject.flashCharmBoxUpdate){
	    flashObject.flashCharmBoxUpdate();
    }
}
