var loadedtabs = new Object();

function loadTabAjax(tabID, contentID, sourceAction, trackingObject, defaultModuleId, defaultModuleName, params) {

    if ((typeof params == undefined || params == null) && typeof defaultModuleId != undefined) {
        params = { box : defaultModuleId};
    } else {
        params.box = defaultModuleId;
    }

    if (loadedtabs[contentID] != true) {
        switchToLoadingDiv(contentID);
        selectTab(tabID, contentID, trackingObject);
        new Ajax.Updater(contentID, sourceAction,
        { method : 'post',
            parameters : params,
            evalScripts: true,
            onSuccess: function() {
                loadedtabs[contentID] = true;
            },
            onComplete: function(transport) {
                if (transport.status == 200 && typeof defaultModuleId != undefined
                        && typeof defaultModuleName != undefined) {
                    toggleBox(defaultModuleId, defaultModuleName);
                }
            }
        });
    } else {
        selectTab(tabID, contentID, trackingObject);
    }
}

var loadedBoxes = new Object();
function loadBoxAjax(boxID,boxName, sourceAction, params) {

    if (typeof params == undefined || params == null) {
        params = {};
    }

    if (loadedBoxes[boxID] != true) {
       // toggleBox(boxID, boxName);
        switchToLoadingDiv(boxID);

        new Ajax.Updater(boxID, sourceAction,
        { method : 'post',
          parameters : params,
          evalScripts: true,
          onSuccess: function() {
              loadedBoxes[boxID] = true;
          }
        });
    } else {
        //toggleBox(boxID, boxName);
    }

}

function switchToLoadingDiv(id) {
    $(id).innerHTML = '<div class="ajax_loader">&nbsp;</div>';
}


/*
    Challenges Tab
 */

var inviteeCounts;

/** function used to add an invitee
 *  to a challenge
 */
function addInvitee(checkGame, messageid, startCount) {

    if (typeof messageid == undefined || messageid == null) {
        messageid = "";
    }

    var email = $('email'+messageid).value;

    if (checkGame && !checkGameSelection($('challenge_game_dropdown_input'))) {
        return;
    }
    if (email == null || email.length < 1) {
        return;
    }

    // we use this code to handle count validation when we're adding
    // to a previously configured challenge.
    if (typeof startCount == undefined || startCount == null) {
        startCount = 0;
    }

    if (($('friends_list'+messageid).childElements().size() + startCount) > 9) {
        $('challenge_email_failure_message'+messageid).innerHTML = "You\'ve already invited the maximum of 9 players to this challenge.";
        showBox("challenge_email_failure"+messageid);
        return;
    }
    var children = $('friends_list'+messageid).childElements();
    if (!checkDuplicateEmail(children, email, messageid)) {
        return;
    }

		new Ajax.Request("/ajax/check-email?email=" + email + "&checkSelf=true", {
			method: "get",
			onComplete: function(transport) {
				var jo = transport.responseJSON;
                if (transport.status == 200) {
                    if (jo.status == "ok") {
                        var childrenCount = $('friends_list'+messageid).childElements().size();
                        var itemName = 'added_email'+childrenCount;
                        var li = new Element('li', { 'id': itemName, 'class': 'added_email' }).update(email);
                        var a = new Element('a', { 'href': 'javascript:removeInvitee(\''+itemName+'\')', 'class': 'delete_button'})
                        var img = new Element('img', { 'src': '/assets/images/modules/my_cs/delete_button.gif'} );
                        li.insert(a, {position: 'after'});
                        a.insert(img, {position: 'after'});
                        $('friends_list'+messageid).insert(li, {position: 'after'});
                        $('email'+messageid).setValue("");
                        hideBox("challenge_email_failure"+messageid);
                    } else {

                        var msg = "";
                        if (jo.self == "true") {
                            msg = 'You can\'t invite yourself to a challenge.';
                        } else {
                            msg = 'The email address you\'ve entered is not valid.';
                        }

                        $('challenge_email_failure_message'+messageid).innerHTML = msg;
                        showBox("challenge_email_failure"+messageid);
                    }
                }
			}
		});
}
/**
 * function used to remove an invitee from a challenge
 * @param invitee
 */
function removeInvitee(invitee) {
    $(invitee).remove();
}

function checkGameSelection(select) {
    var gameName = $('challenge_game_dropdown_input').selectedIndex;

    if (gameName == 0) {
        $('challenge_game_failure_message').innerHTML = "You must select a game before adding friends or issuing the challenge.";
        showBox("challenge_game_failure");
        return false;
    } else {
        hideBox("challenge_game_failure");
        return true;
    }
}

function checkInvitesExist(children) {

    if (children.size() == 1) {
        $('challenge_email_failure_message').innerHTML = "You must invite at least on person to your challenge.";
        showBox("challenge_email_failure");
        return false;
    } else {
        hideBox("challenge_email_failure");
        return true;
    }

}

function checkDuplicateEmail(children, email, messageid) {
    for(var i=1; i<children.size();i++){
        var child = children[i];
        if (getNodeValue(child) == email) {
            var msg = 'You\'ve already added this email address to your invite list.';
            if (typeof messageid == undefined || messageid == null) {
                $('challenge_email_failure_message').innerHTML = msg;
                showBox("challenge_email_failure");
            } else {
                $('challenge_email_failure_message'+messageid).innerHTML = msg;
                showBox("challenge_email_failure"+messageid);
            }

            return false;
        } else {
            if (typeof messageid == undefined || messageid == null) {
                hideBox("challenge_email_failure");
            } else {
                hideBox("challenge_email_failure"+messageid);
            }
        }
    }
    return true;
}

function createChallenge(){

    if (!checkGameSelection($('challenge_game_dropdown_input'))) {
        return;
    }
    var selectedGame = $('challenge_game_dropdown_input').selectedIndex;
    var gameId = $('challenge_game_dropdown_input').options[selectedGame].value;
    var children = $('friends_list').childElements();
    if (!checkInvitesExist(children)) {
        return;
    }

    var emailAddrs = "";
    for(var i=1; i<children.size();i++){
        var child = children[i];
        emailAddrs = emailAddrs + getNodeValue(child) + ",";
    }

    new Ajax.Request("/my/create-challenge", {
        method: "post",
        parameters: {'gameId': gameId,
                     'friends': emailAddrs
        },
        onComplete: function(transport) {

            if (transport.status == 200) {
                var jo = transport.responseJSON;
                if (jo.status == 'ok') {
                    hideBox('create_challenge_module');
                    showBox('challenge_end_module');
                    new PeriodicalExecuter(function(pe) {
                        confirmChallengeSent();
                        pe.stop();
                    }, 5);
                } else {
                    $('challenge_email_failure_message').innerHTML = jo.msg;
                    showBox("challenge_game_failure");
                }
            }
        }
    });
}

function confirmChallengeSent() {
    // reset the content status flag & reload
    loadedtabs['challenges_content'] = false;
    loadTabAjax('challenges_tab','challenges_content', '/my/challenges', {type:'page', label:'/MY Pages/MY CS/Challenges'}, 'challenge_1','challenge_group_module');
}

function openAddPlayers(divId) {
    hideBox('challenge_list'+divId);
    showBox('challenge_add'+divId);
}

function addNewFriends(challengeUuid, divId) {

    var children = $('friends_list'+divId).childElements();

    var emailAddrs = "";
    for(var i=1; i<children.size();i++){
        var child = children[i];
        emailAddrs = emailAddrs + getNodeValue(child) + ",";
    }

    new Ajax.Request("/my/add-friends-to-challenge", {
			method: "post",
            parameters: {
                'friends' : emailAddrs,
                'challengeUuid': challengeUuid
            },
			onComplete: function(transport) {
                if (transport.status == 200) {
                    var jo = transport.responseJSON;
                    if (jo.status == "ok") {
                        confirmChallengeSent();
                    } else {
                        $('challenge_email_failure_message'+divId).innerHTML = jo.msg;
                        showBox("challenge_email_failure"+divId);
                    }
                }
			}
		});
}

function confirmChallengeEnded() {
    // reset the content status flag & reload
    loadedtabs['challenges_content'] = false;
    loadTabAjax('challenges_tab','challenges_content', '/my/challenges', {type:'page', label:'/MY Pages/MY CS/Challenges'}, 'challenge_2','challenge_group_module');
}


function endChallenge(uuid) {

    new Ajax.Request("/my/end-challenge", {
        method: "post",
        parameters: {
            challengeUuid: uuid
        },
        onComplete: function(transport) {
            if (transport)
               if (transport.status == 200) {
                    var jo = transport.responseJSON;
                    if (jo.status == "ok") {
                        confirmChallengeEnded();
                    } else {
                        $('challenge_email_failure_message'+divId).innerHTML = jo.msg;
                        showBox("challenge_email_failure"+divId);
                    }
                }
			}
    });

}

/*
    Icon Tab
 */

var oldAvatarUrl;

    
    
function chooseIcon(icon) {

    oldAvatarUrl = $("avatar_preview").src;
    $('reset_link').show(); 
    var newimg = new Element("img", {"id" : "avatar_preview", "alt": "Candystand Avatar", "src" : icon});
    newimg.width = '44';
    newimg.height = '44'
    $("avatar_preview").replace(newimg);

}

function resetToPreviousIcon(){

    if (oldAvatarUrl != null) {
        var tmpAvatarUrl = $("avatar_preview").src;
        var newimg = new Element("img", {"id" : "avatar_preview", "alt": "Candystand Avatar", "src" : oldAvatarUrl});
	newimg.width = '44';
	newimg.height = '44';
        $("avatar_preview").replace(newimg);
        oldAvatarUrl = tmpAvatarUrl;
    }
}

function saveIcon() {
    
	var avatarIconUrl = $("avatar_preview").src;

	new Ajax.Request("/my/save-icon", {
			method: "post",
            parameters: {'avatarIconUrl':avatarIconUrl},
			onComplete: function(transport) {
                if (transport.status == 200) {
                    var jo = transport.responseJSON;
                    if (jo.status == "ok") {
                        
                    	hideBox("icon_button_module");
                        showBox("icon_success_module");
                        if ($("avatar_nav")) $("avatar_nav").src = $("avatar_preview").src;
                        if ($("avatar_my_profile")) $("avatar_my_profile").src = $("avatar_preview").src;
                        loadedtabs['home_content'] = false;
                        loadedtabs['profile_content'] = false;
                        loadTabAjax('profile_tab', 'profile_content', '/my/profile', {type:'page', label:'/MY Pages/MY CS/Edit Profile'});
/*
                        new PeriodicalExecuter(function(pe) {
                            hideBox("icon_success_module");
                            showBox("icon_button_module");
                            pe.stop();
                        }, 5);
*/

                    } else {
                        resetToPreviousIcon();
                    }
                }
            }
		});
}

function dismissIconSuccessBox() {
    hideBox("icon_success_module");
    showBox("icon_button_module");
}

/*
    Favorites Tab
 */

function addFavorite(selected) {

    var option = selected.options[selected.selectedIndex];
    var gameId = option.value;

    if (gameId.length != 5 ) {
        return;
    }

    new Ajax.Updater("favorites_content", "/my/add-favorites", {
        method: "post",
        parameters: {'gameId': gameId}

    });
}

function removeFavorite(gameId) {

    if (gameId.length != 5 ) {
        return;
    }

    new Ajax.Updater("favorites_content", "/my/remove-favorites", {
        method: "post",
        parameters: {'gameId': gameId}

    });
}

/*
    Tournaments Tab
 */

function reloadCompleted(select) {

    var mode =  { mode: select.options[select.selectedIndex].value};
    var searchUser = $F('searchUserName');
    var actionUrl = '/my/completed';

    if (typeof searchUser != undefined && searchUser != null && searchUser != "") {
        mode.userName = searchUser;
        actionUrl = '/my/other-completed'
    }

    loadedBoxes['tournament_5_content'] = false;
    loadBoxAjax('tournament_5_content','challenge_group_module', actionUrl, mode);
    //toggleBox('tournament_5', 'challenge_group_module');

}

function reloadInProgress(select) {

    var mode =  { mode: select.options[select.selectedIndex].value};
    var searchUser = $F('searchUserName');
    var actionUrl = '/my/in-progress';

    if (typeof searchUser != undefined && searchUser != null && searchUser != "") {
        mode.userName = searchUser;
        actionUrl = '/my/other-in-progress'
    }
    
    loadedBoxes['tournament_3_content'] = false;
    loadBoxAjax('tournament_3_content','challenge_group_module', actionUrl, mode);
    //toggleBox('tournament_3', 'challenge_group_module');
}

function reloadScoresAndTrophies(select, mode, user) {
    var sort  =  { sort: select.options[select.selectedIndex].value};

    var searchUser = $F('searchUserName');

    if (typeof searchUser != undefined && searchUser != null) {
        sort.userName = searchUser;
    }

    loadedtabs['scores_content'] = false;

    if (mode == 'trophy') {
        loadTabAjax('scores_tab', 'scores_content', '/my/trophies', {type:'page', label:'/MY Pages/MY CS/Trophies and Scores'}, null, null, sort);
    } else {
        loadTabAjax('scores_tab', 'scores_content', '/my/scores', {type:'page', label:'/MY Pages/MY CS/Trophies and Scores'}, null, null, sort);
    }
}

function ChangeFavoriteScoresCallback(targetId) {
	this.targetId= targetId;
}

ChangeFavoriteScoresCallback.prototype.callback = function(jo) {

    var duplicate = jo.duplicate && jo.duplicate == "yes";

    if (!duplicate) {
        $(this.targetId).style.display = "none";
    }

};

function tournamentSignup(modId, containerId, tournamentId) {

    var on = $(modId+'_on');
    var statusUpdates;
    if (on.checked == true) {
        statusUpdates = 'on';
    } else {
        statusUpdates = 'off';
    }

    new Ajax.Updater(containerId, "/my/signup", {
        method: 'post',
        evalScripts: true,
        parameters: { tournamentId: tournamentId,
                      statusUpdates: statusUpdates}
    });
}

function tournamentToggleBox(boxID,boxName,id,tid) {
    if (loadedBoxes[boxID] != true) {
        swfobject.embedSWF("/assets/swf/tournaments/tournament.swf?confPath=/pages/body/my/me_content/tournaments/conf.xml&tournamentid="+tid+"&conferenceid=&swlist=", id, "616", "448", "9.0", "/games/flash_express_install.swf");
    }
    toggleBox(boxID, boxName);
}


/*
    Profile Tab
 */

function updateProfile(form) {

    var elements = Form.getElements(form);
    elements.push(document.getElementById('internalOptIn'));

    new Ajax.Updater('edit_profile_module', "/my/profile-save", {
        method: 'post',
        parameters: Form.serializeElements(elements),
        evalScripts: true
    });
}

function confirmUpdateProfile() {
    // reset the content status flag & reload
    loadedtabs['profile_content'] = false;
    loadTabAjax('profile_tab','profile_content', '/my/profile', {type:'page', label:'/MY Pages/MY CS/Edit Profile'});
}

/*
    Other User Search
*/

function playerSearch() {
    var userName = $('player_search').value;

    if (typeof userName == undefined || userName == null || userName == "") {
        return;
    }

    new Ajax.Request("/my/player-search",{
            method: 'post',
            parameters: { userName: userName },
            onComplete: function(transport) {
                if (transport.status == 200) {

                    resp = transport.responseJSON;

                    if (resp.status == 'ok') {
                        window.location.href = "/users/" + userName;
                    } else {
                        $('player_search').value = 'Username not found';
                    }
                }
            }
    });
}

function getNodeValue(node) {

    if (Prototype.Browser.IE) {
      return node.innerText;
    }
    
    return node.textContent;
}

function TabLoginCallback(contentId) {
    this.contentId = contentId;
}

/*
  Callback used to reload a my cs tab that's been opened
  in the logged out state.  
 */
TabLoginCallback.prototype.callback = function() {


    var contentId = this.contentId;

    if (window.location.search != null && window.location.search != "") {
        window.location.reload();
    } else {
        var url = "/my/me.do?tab="+contentId;
        window.location.replace(url);
    }
};

var myCsUserName = '';

function refreshFriends(page, pageSize, search) {

    new Ajax.Updater('friends_list', '/facebook/ajax/friends-wide',
    {
      method: "post",
      parameters: {start : page,
                   pageSize: pageSize,
                   search: search,
                   userName: myCsUserName},
      evalScripts: true
    });

};

function scrollNews(page, size, queryString) {


    var ajaxCall = '/facebook/ajax/newsfeed';
    if(typeof queryString != undefined && queryString != null) {
        ajaxCall = '/facebook/ajax/newsfeed?'+queryString;
    }

    new Ajax.Updater('personal_news_feed', ajaxCall, {
      method: "post",
      parameters: {page: page,
                   size: size}
    });

};

function showWorldRankTab(templateID) {
	$('friend_ranking').hide();
	$('world_ranking').show();
	$('world_rank_tab').src='/assets/images/modules/my_cs/themes/' + templateID + '/world_rank_tab_on.gif';
	$('friend_rank_tab').src='/assets/images/modules/my_cs/themes/' + templateID + '/friend_rank_tab_off.gif';
}

function showFriendRankTab(templateID) {
	
	$('world_ranking').hide();
	$('friend_ranking').show();
	$('world_rank_tab').src='/assets/images/modules/my_cs/themes/' + templateID + '/world_rank_tab_off.gif';
	$('friend_rank_tab').src='/assets/images/modules/my_cs/themes/' + templateID + '/friend_rank_tab_on.gif';
}