
function checkUpdates(userID, sid) {
	xajax.config.requestURI = "mini.php?sid="
			+ sid;
	xajax.request( {
		xjxfun :'checkUserUpdates'
	}, {
		parameters :arguments
	});
	// xajax_Messenger.checkUserUpdates(userID);
	xajax.config.requestURI = "xajax.php?sid="
			+ sid;

	// window.setTimeout("checkUpdates("+userID+", "+sid+")", 10000);
}

function showAvatarProfile(avatarID) {
    toolbox.activeProfileCategory = 1;
    formValues = new Array();
    formValues['avatarID'] = avatarID;
    xajax_LayerHandler.getLayer('avatarProfile', 0, formValues);
}



var igTimestamp;

function startIngameClock(timestamp) {
	igTimestamp = timestamp;
	window.setInterval('ingameClock()', 1000);
}

function ingameClock() {
	igTimestamp = igTimestamp + 20000;
	var timestamp = igTimestamp;

	var minutes = (timestamp / 60000) % 60;
	var minutesString = String(parseInt(minutes));
	if (minutesString.length < 2) {
		minutesString = "0" + minutesString;
	}

	var hours = (timestamp / 3600000) % 24;
	var hoursString = String(parseInt(hours));
	if (hoursString.length < 2) {
		hoursString = "0" + hoursString;
	}
	$('ingameClock').innerHTML = hoursString + ":" + minutesString;
	// window.setTimeout('ingameClock(' + (timestamp + 20000) + ');', 1000);
}

var _m = "0";
var _s = "59";
var running;

function startAuctionCountdown(m, s) {
	if (running) {
		window.clearInterval(running);
	}
	_m = m;
	_s = s;
	running = window.setInterval("counterTimer()", 1000);
}

function counterTimer() {
	_s--;
	if (_s < 0) {
		_s = 59;
		_m--;
	}
	if (_m < 0) {
		_m = 59;
	}
	var __s = "" + _s;
	if (__s.length == 1)
		__s = '0' + __s;
	var __m = "" + _m;
	if (__m.length == 1)
		__m = '0' + __m;
	try {
		var counter = $('auctionCounter');
		if (counter) {
			counter.innerHTML = __m + ':' + __s;
		}
	} catch (e) {
	}
}

function getSelectionIDUser(text, li) {
	$('userID').value = li.id;
}

function getSelectionIDAvatar(text, li) {
	$('avatarID').value = li.id;
}

function getSelectionIDClan(text, li) {
	$('clanID').value = li.id;
}
/*
function loadWidgetContainer() {
   possibleDraggables = new Array();
   possibleDraggables.push("widget", "widgetPlaceholder");
   for ( var i = 0; i < 6; i++) {
		Droppables.add("container_" + i, {
			accept :possibleDraggables,
            hoverclass: 'widgetContainerHover',
			onDrop : function(dragElement, dropElement) {
                formValues = new Array();
                //dragElement is a real widget
                if(dragElement.className == "widget") {
                    if (dropElement.hasChildNodes()) {
                        if(dragElement.id == dropElement.firstChild.id) {
                            dragElement.style.left = 0;
                            dragElement.style.top = 0;
                            return;
                        }
                        oldWidget = dropElement.firstChild;
                        oldWidget.parentNode.removeChild(oldWidget);
                        dragElement.parentNode.appendChild(oldWidget);
                        formValues["oldWidget"] = new Object();
                        formValues["oldWidget"]["name"] = oldWidget.id;
                        formValues["oldWidget"]["newPosition"] = dragElement.parentNode.id.substr(10);
                    }
                    formValues["widget"] = new Object();
                    formValues["widget"]["name"] = dragElement.getAttribute("id");
                    formValues["widget"]["newPosition"] = dropElement.id.substr(10);
                    formValues["widget"]["oldPosition"] = dragElement.parentNode.id.substr(10);


                    xajax_ActionController.doAction("InternalHome", "setWidgetPosition", formValues);
                    dragElement.parentNode.removeChild(dragElement);
                    dropElement.appendChild(dragElement);
                    dragElement.style.left = 0;
                    dragElement.style.top = 0;
                //dragElement is only a widget placeholder
                } else {
                    if (dropElement.hasChildNodes()) {
                        oldWidget = dropElement.childNodes[0];
                        oldWidget.parentNode.removeChild(oldWidget);
                        formValues["oldWidget"] = new Object();
                        formValues["oldWidget"]["name"] = oldWidget.id;
                        formValues["oldWidget"]["newPosition"] = null;

                    }
                    //check if dropelement already contains a widget; remove it!
                    formValues["widget"] = new Object();
                    formValues["widget"]["name"] = dragElement.getAttribute("id");
                    formValues["widget"]["widgetContainerID"] = dropElement.getAttribute("id");

                    xajax_ActionController.doAction("InternalHome", "fetchWidget", formValues);
                    dragElement.parentNode.removeChild(dragElement);
                }
			}
		});
	}
}

function loadWidgets(widgets) {
    for(var i =0; i<6; i++) {
        if(widgets[i] != '') {
            //alert("huhu");
            new Draggable($(widgets[i] + "Widget"), {
    			revert :'failure'
    		});
        }
    }
    return;
}
*/

function updateMoney(moneyVirtual, moneyReal) {
    if(moneyVirtual != null) {
        $('moneyVirtual').innerHTML = moneyVirtual;
    }
    if(moneyReal != null) {
        $('moneyReal').innerHTML = moneyReal;
    }
}

function removeAllClasses(id) {
    var classArray = $(id).classNames().toArray();
    var len = classArray.size();
    for(var i=0; i < len; ++i) {
        $(id).removeClassName(classArray[i]);
    }
}

var clientLoader = new ClientLoader();

function ClientLoader() {
    this.userID = null;
    this.sessionID = null;
    this.invalidSession = false;


    this.majorVersion = 6;
    this.minorVersion = 20;

    this.clientVersion = "";

    this.tutorialChoiceLayer = true;
    this.isDummy = false;



    this.loadTutorial = function(sessionID, quality, language) {
        //window.setTimeout("$('qualityLayerContent').show();$('exLoading').hide();qualityLayer.hide();", 30000);
        window.setTimeout("window.location='index.es?action=externalSignup'", 30000);

        this.loadApplet(0, sessionID, true, true, quality, language);
        return;

    }

    this.javaCheck = function() {
        var javaVersion = PluginDetect.getVersion('Java', 'inc/java/getJavaInfo.jar');
        if(javaVersion != null) {

            var versionParts = javaVersion.split(',');
            if(versionParts[1] >= this.majorVersion && versionParts[3] >= this.minorVersion) {
                //check passed
                qualityLayer.show();
            } else {
                this.showInstallJavaFrame();
            }
        } else {
            this.showInstallJavaFrame();
        }
    }

    this.loadClient = function(userID, sessionID, tutorial, characterCreator) {

        new Effect.Appear($('loadingContainer'), {duration: 0.5});
        window.setTimeout("new Effect.Fade($('loadingContainer'), {duration: 0.5})", 20000);

        this.loadApplet(userID, sessionID, tutorial, characterCreator);

        return;
    }

    this.clearCache = function(userID, sessionID, type) {
        sessionID = sessionID.substr(sessionID.indexOf('=')+1);
        this.method = type;
        this.userID = userID;
        this.sessionID = sessionID;
        this.loadApplet(userID, sessionID);

        //check if applet was called after 10secs the latest; if not, kill applet and show install frame
        this.loadingInterval = window.setInterval('clientLoader.checkAppletReady()', 1000);
    }

    this.loadApplet = function(userID, sessionID, tutorial, characterCreator, quality, language) {
        if(quality == null) {
            var quality = 'default';
        }
        if(language == null) {
            var language = 'default';
        }


        start = true;
        if(sessionID.substr(sessionID.indexOf('='))) {
            sessionID = sessionID.substr(sessionID.indexOf('=')+1);
        }


        xajax.config.defaultMode = 'synchronous';
        xajax.config.requestURI = "mini.php?sid=" + sessionID;
        xajax.request( {
        xjxfun :'getClientData'
        }, {
        parameters :arguments
        });
        xajax.config.requestURI = "xajax.php?sid=" + sessionID;
        xajax.config.defaultMode = 'asynchronous';
        if(this.invalidSession) {
            var formValues = new Array();
            formValues['langIdentifier'] = 'pv.global.layers.invalidSession';
            xajax_LayerHandler.getLayer('custom', 0, formValues, null, false);
            return;
        }
        /*
        if(this.tutorialChoiceLayer && this.isDummy) {
            this.showTutorialChoiceLayer(userID, sessionID);
        } else {*/

        var javaVersion = PluginDetect.getVersion('Java', 'inc/java/getJavaInfo.jar');
        if(javaVersion != null) {

            var versionParts = javaVersion.split(',');
            if(versionParts[1] >= this.majorVersion && versionParts[3] >= this.minorVersion) {
                if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
                   var client = "<object style='width: 0px; height: 0px; margin-top: 5px;' id='gameLoader' name='Poisonville' classid='clsid:8AD9C840-044E-11D1-B3E9-00805F499D93' codetype='application/java' codebase='http://javadl-esd.sun.com/update/1.6.0/jinstall-6-windows-i586.cab#Version=6,0,0,20'><param name='code' value='net.bigpoint.loader.PoisonvilleLoader.class'><param name='archive' value='client/gameclient/" + this.clientVersion + "/loader.jar'><param name='userid' value=" + userID + "><param name='sessionid' value=" + sessionID + "><param name='tutorial' value=" + tutorial +"><param name='start' value=" + start + "><param name='charactercreator' value=" + characterCreator +"><param name='start' value=" + start + "><param name='quality' value=" + quality + "><param name='language' value=" + language + "></object>";
               } else {
                   var client = "<embed style='width: 0px; height: 0px; margin-top: 5px;' code='net.bigpoint.loader.PoisonvilleLoader.class' type='application/x-java-applet' pluginspage='http://java.sun.com/j2se/1.6.0/download.html' archive='client/gameclient/" + this.clientVersion + "/loader.jar' id='gameLoader' name='Poisonville' tutorial=" + tutorial + " charactercreator = " + characterCreator + " userid=" + userID + " sessionid=" + sessionID + " start=" + start + " quality=" + quality + " language=" + language + "><noembed>No Java Support.</noembed></embed>";
               }
               $('poisonvilleApplet').innerHTML = client;
           } else {
               this.showInstallJavaFrame();
           }

        }else {
           this.showInstallJavaFrame();
        }
        //}

    }

    this.showInstallJavaFrame = function() {
        if($('loadingContainer')) {
            $('loadingContainer').style.displax = "none";
        }
        if(deployJava.getBrowser() != "Safari" || true) {
            var os="Unknown OS";
            var formValues = new Array();
            if (navigator.appVersion.indexOf("Win")!=-1) os="Windows";
            if (navigator.appVersion.indexOf("Mac")!=-1) os="MacOS";
            if (navigator.appVersion.indexOf("X11")!=-1) os="UNIX";
            if (navigator.appVersion.indexOf("Linux")!=-1) os="Linux";

            formValues['os'] = os;
            formValues['arch'] = navigator.platform;
            formValues['browser'] = deployJava.getBrowser();

            xajax_LayerHandler.getLayer('noJava', 0, formValues);
        }
    }

    this.showTutorialChoiceLayer = function(userID, sessionID) {
        //this.tutorialChoiceLayer = false;
        var formValues = new Array();
        formValues['userID'] = userID;
        formValues['sessionID'] = sessionID;
        xajax_LayerHandler.getLayer('tutorialChoice', 0, formValues);
    }
}

var mainMenu = new MainMenu();
function MainMenu() {

    this.setActiveMenu = function(id) {
        var menuItem = $('mainMenuItem_' + id);
        //move the indicator
        var center = menuItem.offsetLeft + (menuItem.getWidth() / 2);
        center = center - ($('mainMenuIndicator').getWidth() / 2);
        new Effect.Morph($('mainMenuIndicator'), {style: 'left: ' + center + 'px', duration: 0.2});
    }
}

var toolbox = new Toolbox();

function Toolbox() {

    this.activeProfileCategory = 1;

    this.init = function() {
        this.activeProfileCategory = 1;
    }



    this.changeAvatar = function(userID, avatarID, toggleToolbar) {
        xajax_ToolbarHelper.changeAvatar(userID, avatarID);
    }

    this.changePrivacyStatus = function(userID, status) {
        xajax_ToolbarHelper.changePrivacyStatus(userID, status);
        toolbar.togglePopup('privacyStatusList');
    }

    this.switchProfileCategory = function(id) {
        //tab span
        $ ('profileCategoryCaption_' + this.activeProfileCategory).addClassName('white14px');
        $ ('profileCategoryCaption_' + this.activeProfileCategory).removeClassName('gold14px');
        $ ('profileCategoryCaption_' + id).addClassName('gold14px');
        $ ('profileCategoryCaption_' + id).removeClassName('white14px');


        //tabs background

        $('bodyHeadBackground').removeClassName('bodyHeadBackground' + this.activeProfileCategory);
        $('bodyHeadBackground').addClassName('bodyHeadBackground' + id);

        //switch content

        $('avatarProfileBody_' + this.activeProfileCategory).style.display = 'none';
        $('avatarProfileBody_' + id).style.display = 'block';

        this.activeProfileCategory = id;

    }


}

var categoryHandler = new CategoryHandler();

function CategoryHandler() {
    this.activeCategory = null;
    this.activeSubCategory = null;


    this.setActiveCategory = function(id) {
        if($('categoryFilter_' + this.activeCategory) != null) {
            $('categoryFilter_' + this.activeCategory).style.display = "none";
        }

        if($('categoryFilter_' + id) != null) {
            $('categoryFilter_' + id).style.display = "block";
        }

        this.activeCategory = id;
    }

    this.setActiveSubCategory = function(id) {

        if(this.activeSubCategory != null) {

           var category = $('category_' + this.activeSubCategory);
           if(category != null) {
               category.cleanWhitespace();

               for(i = 0; i < category.childNodes.length; i++) {
                    $(category.childNodes[i]).removeClassName('active');
               }
           }
        }
        var category = $('category_' + id);
        category.cleanWhitespace();


        for(i = 0; i < category.childNodes.length; i++) {
            $(category.childNodes[i]).addClassName('active');
        }

        this.activeSubCategory = id;
    }
}

var subMenu = new SubMenu();
function SubMenu() {
    this.activeSubMenuItem = new Array();
    this.activeSubMenuItem['InternalHome'] = null;
    this.activeSubMenuItem['InternalRankings'] = null;
    this.activeSubMenuItem['InternalStore'] = null;
    this.activeSubMenuItem['InternalClan'] = null;

    this.activeSubMenu = null;

    this.showSubMenu = function(action) {
        if(this.activeSubMenu != action) {
            if(this.activeSubMenu == null) {
                $('subMenu_' + action).style.display = 'block';



            } else {
                
                //if appear element is != null
                if($('subMenu_' + action) != null) {
                    //if fade element is != null
                    if($('subMenu_' + this.activeSubMenu) != null) {
                        new Effect.Parallel( [
                            new Effect.Fade($('subMenu_' + this.activeSubMenu), {
                            sync :true
                            }),
                            new Effect.Appear($('subMenu_' + action), {
                                sync :true
                            })
                            ], {
                            duration :0.5,
                            delay :0.0
                        });
                    } else {
                        new Effect.Appear($('subMenu_' + action), { duration: 0.2});
                    }

                } else {
                    new Effect.Fade($('subMenu_' + this.activeSubMenu), {duration: 0.2});
                }
            }

            this.activeSubMenu = action;
        } else {
            $('subMenu_' + action).style.display = 'block';
        }


    }

    this.setActiveSubMenuItem = function(action, subAction) {
       if(this.activeSubMenuItem[action] != null) {

           var item = $('subMenuItem_' + action + "_" + this.activeSubMenuItem[action]);
           if(item != null) {

               item.cleanWhitespace();
               for(i = 0; i < item.childNodes.length; i++) {
                    $(item.childNodes[i]).removeClassName('active');
               }

           }
        }
        if(subAction == '') {
            //get first element of subMenuContent
            var subMenuItem = $($('subMenu_' + action).firstDescendant().id);
            var parts = $('subMenu_' + action).firstDescendant().id.split("_");
            subAction = parts[2];

        } else {

            var subMenuItem = $('subMenuItem_' + action + "_" + subAction);
        }

        if(subMenuItem != null) {
            subMenuItem.cleanWhitespace();

            for(i = 0; i < subMenuItem.childNodes.length; i++) {
                $(subMenuItem.childNodes[i]).addClassName('active');
            }

            this.activeSubMenuItem[action] = subAction;
        }
    }
}


var actionController = new ActionController();
function ActionController() {
    this.actionInProgress = false;
    /*
    this.init = function(action, subAction) {
        //window.setTimeout("mainMenu.setActiveMenu(" + action + ")", 1000);
        mainMenu.setActiveMenu(action);

        subMenu.showSubMenu(action);
        subMenu.setActiveSubMenuItem(action, subAction);
    }
    */

    this.doAction = function(action, subAction) {
        if(this.actionInProgress) {
            return;
        }
        this.actionInProgress = true;
        xajax_ActionController.doAction(action, subAction);
    }

    this.switchAction = function(action, subAction) {
        //mainMenu.setActiveMenu(action);
        window.setTimeout("mainMenu.setActiveMenu('" + action + "')", 200);
        subMenu.showSubMenu(action);

        //switch submenu template
        this.switchSubAction(action, subAction);
    }

    this.switchSubAction = function(action, subAction, flexCrollItems) {



        $('mainContent').cleanWhitespace();

        if($('mainContent').childNodes.length == 2) {
            new Effect.Parallel( [
                new Effect.Appear($('mainContent').childNodes[0], {
                sync :true
                }),
                new Effect.DropOut($('mainContent').childNodes[1], {
                sync :true
                })
                ], {
                duration :0.5,
                delay :0.0,
                afterFinish: function() {
                    if($('mainContent').childNodes[1]) {
                        $('mainContent').removeChild($('mainContent').childNodes[1]);
                    }
                    actionController.loadFlexCrollItems(flexCrollItems);

                }
            });
        } else {
            $('mainContent').childNodes[0].style.display = "block";
        }

        $('mainContent').childNodes[0].style.zIndex = 1;
        subMenu.setActiveSubMenuItem(action, subAction);
        window.setTimeout('actionController.actionInProgress = false', 400);
    }

    this.loadFlexCrollItems = function(items) {
        if(items != null) {
            var flexCrollItems = items.split(",");
            for(i=0; i < flexCrollItems.length; i++) {
                CSBfleXcroll(flexCrollItems[i]);
            }
        }
    }
    /*

    this.createNewContainerRightSubAction = function(action, subAction) {
        var box = document.createElement("div");
        var boxID = document.createAttribute("id");
        boxID.nodeValue = "content_" + subAction;
        box.setAttributeNode(boxID);
        box.style.marginTop="-496px";
        var firstChild = $('concreteContentRight_' + action).firstChild;

        $('concreteContentRight_' + action).insertBefore(box, firstChild);
    }

    this.createNewContainerRightAction = function(action) {
        //backgroundimage div
        var backgroundBox = document.createElement("div");
        var boxID = document.createAttribute("id");
        boxID.nodeValue = "backgroundRight_" + action;
        backgroundBox.setAttributeNode(boxID);
        backgroundBox.style.display="none";
        var children = $('internalContentRight').childElements();

        $('internalContentRight').insertBefore(backgroundBox, children[0]);

        //content div
        var contentBox = document.createElement("div");
        var boxID = document.createAttribute("id");
        boxID.nodeValue = "concreteContentRight_" + action;
        contentBox.setAttributeNode(boxID);
        contentBox.style.marginTop="-496px";
        $('internalContentRight').insertBefore(contentBox, children[1]);
    }

    this.createNewContainerLeft = function(action) {

        //backgroundimage div
        var backgroundBox = document.createElement("div");
        var boxID = document.createAttribute("id");
        boxID.nodeValue = "backgroundLeft_" + action;
        backgroundBox.setAttributeNode(boxID);
        backgroundBox.style.display="none";
        var children = $('internalContentLeft').childElements();

        $('internalContentLeft').insertBefore(backgroundBox, children[0]);

        //content div
        var contentBox = document.createElement("div");
        var boxID = document.createAttribute("id");
        var boxClass = document.createAttribute("class");
        boxID.nodeValue = "subMenu_" + action;
        boxClass.nodeValue = "subMenu";
        contentBox.setAttributeNode(boxClass);
        contentBox.setAttributeNode(boxID);
        contentBox.style.marginTop="-496px";
        $('internalContentLeft').insertBefore(contentBox, children[2]);


    }

    this.switchSubAction = function(action, subAction, override) {

        subMenu.showFilter(action, subAction, override);
        subMenu.oldSubMenu = subAction;
        new Effect.Morph($('content_' + subAction), {
            style: 'margin-top: 0px;',
            duration: 0.2,
            afterFinish: function() {
                var children = $('concreteContentRight_' + action).childElements();
                if(children[1]) {
                    //window.setTimeout("$('concreteContentRight_' + action).removeChild(children[1]");
                    $('concreteContentRight_' + action).removeChild(children[1]);
                }

                subMenu.setActiveSubMenu(action, subAction);
            }
        });

    }

    this.switchAction = function(action, subAction) {
        //alert($('subMenu_' + action).style.marginTop);
        subMenu.resetActiveSubMenu();
        //subMenu.resetOldSubMenu();
        /*
        1. switch background left (fade)
        2. switch background right(fade)
        3. switch content left (dropout)
        4. switch content right(dropout)

        var childrenLeft = $('internalContentLeft').childElements();
        var childrenRight = $('internalContentRight').childElements();

        new Effect.Parallel( [
                new Effect.Morph($('subMenu_' + action), {
                    style : {
                        marginTop :'0px'
                    },
                sync :true
                }),
                new Effect.Morph($('concreteContentRight_' + action), {
                    style : {
                        marginTop :'0px'
                    },
                sync :true
                }),

                new Effect.Fade(childrenLeft[1], {
                sync :true
                }),
                new Effect.Appear(childrenLeft[0], {
                    sync :true
                }),
                new Effect.Fade(childrenRight[1], {
                sync :true
                }),
                new Effect.Appear(childrenRight[0], {
                    sync :true
                })
                ], {
                duration :0.5,
                delay :0.0,
                afterFinish: function() {
                    $('internalContentLeft').removeChild(childrenLeft[1]);
                    $('internalContentLeft').removeChild(childrenLeft[4]);

                    $('internalContentRight').removeChild(childrenRight[1]);
                    $('internalContentRight').removeChild(childrenRight[3]);
                }
            });


    }
    */
}

var internalClan = new InternalClan();

function InternalClan() {

    this.autoCompleter = null;

    this.loadAutoCompleter = function(gangID, sessionID) {
        this.autoCompleter = new Ajax.Autocompleter('clanNameSearch', 'clanChoices',
            '/mini.php?sid=' + sessionID, {
                minChars :0,
                afterUpdateElement :getSelectionIDClan,
                parameters :'xjxargs[]=S' + gangID + '&xjxargs[]=S' + sessionID
                        + '&xjxfun=getClans'
            }
        );
    }
 
    this.showClanChoices = function() {
        this.autoCompleter.activate();
        new Effect.Appear($('choicesContainer'), {duration: 0.1});
        //$('clanChoices').style.display = 'block';
    }
    //is called from within control.js!
    this.hideClanChoices = function() {
        new Effect.Fade($('choicesContainer'), {duration: 0.1});
    }

    this.applyForClan = function(formValues) {
        var formValues = new Array();
        formValues['clanID'] = $('clanID').value;
        formValues['clanName'] = $('clanNameSearch').value;
        formValues['applicationText'] = $('applicationText').value;
        xajax_ActionController.doAction('InternalClan', 'applyForClan', formValues);
    }

    this.removeClanApplication = function() {
        xajax_ActionController.doAction('InternalClan', 'removeClanApplication', xajax.getFormValues('removeClanCandidateForm'));
    }

    this.foundClan = function() {
        var formValues = new Array();
        formValues['foundClanName'] = $('clanName').value;
        formValues['foundClanTag'] = $('clanTag').value;
        formValues['foundClanDescription'] = $('clanDescriptionText').value;
        xajax_ActionController.doAction('InternalClan', 'foundClan', formValues);
    }

    this.showOverview = function(offset, limit) {
        var formValues = new Array();
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        xajax_ActionController.doAction('InternalClan', 'overview', formValues);
    }

    this.showRanks = function(offset, limit) {
        var formValues = new Array();
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        xajax_ActionController.doAction('InternalClan', 'ranks', formValues);
    }

    this.showAdministration = function(offset, limit) {
        var formValues = new Array();
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        xajax_ActionController.doAction('InternalClan', 'administration', formValues);
    }

    this.toggleMessageButton = function(id) {
        var element = $(id);
        if(element.hasClassName('buttonMessageActive')) {
            element.removeClassName('buttonMessageActive');
            element.removeClassName('black12px');
            element.addClassName('light12px');
        } else {
            element.addClassName('buttonMessageActive');
            element.removeClassName('light12px');
            element.addClassName('black12px');
        }
    }

    this.sendMessage = function() {
        var formValues = new Array();
        formValues['messageID'] = $('messageID').value;
        formValues['messageSubject'] = $('messageSubject').value;
        formValues['messageContent'] = $('messageContent').value;
        xajax_ActionController.doAction('InternalClan', 'sendClanMessage', formValues);
    }

    this.toggleWholeMessage = function(id) {
        var msgBody = $('messageContentBody_' + id);
        var msgText = $('messageText_' + id)
        if(msgBody.getHeight() == 47) {
            if(msgText.getHeight() > 47) {
                new Effect.Morph(msgBody,{
                    style: 'height: ' + (msgText.getHeight()+20) +'px;',
                    duration: 0.3
                });
                $('more_' + id).style.display = "none";
                $('less_' + id).style.display = "block";
            }
        } else {
            new Effect.Morph(msgBody,{
                style: 'height: 47px;',
                duration: 0.3
            });
            $('more_' + id).style.display = "block";
            $('less_' + id).style.display = "none";
        }
        window.setTimeout("$('boardBodyContent').scrollUpdate()", 400);
    }

    this.toggleWholeApplication = function(id) {
        var msgBody = $('applicantInfoBodyContent_' + id);
        var msgText = $('applicationText_' + id)
        if(msgBody.getHeight() == 30) {
            if(msgText.getHeight() > 30) {
                new Effect.Morph(msgBody,{
                    style: 'height: ' + (msgText.getHeight()+1) +'px;',
                    duration: 0.3
                });
                $('more_' + id).style.display = "none";
                $('less_' + id).style.display = "block";
            }
        } else {
            new Effect.Morph(msgBody,{
                style: 'height: 30px;',
                duration: 0.3
            });
            $('more_' + id).style.display = "block";
            $('less_' + id).style.display = "none";
        }
        window.setTimeout("$('applicantList').scrollUpdate()", 400);
    }

    this.deleteMessage = function(messageID) {
        xajax_ActionController.doAction('InternalClan', 'deleteClanMessage', messageID);
    }

    this.editMessage = function(messageID) {
        xajax_ActionController.doAction('InternalClan', 'editClanMessage', messageID);
    }

    this.loadMessage = function(messageID, subject, content) {
        $('messageID').value = messageID;
        $('messageSubject').value = subject;
        $('messageContent').value = content;
    }

    this.saveRank = function(id) {
        formValues = new Array();
        if(id != 0) {
            formValues['id'] = id;
        }
        formValues['rankName'] = $('rankName_' + id).value;
        formValues['rights'] = new Array();

        if($('changeTax_' + id).hasClassName('checkboxActive') || $('changeTax_' + id).hasClassName('checkboxActiveDisabled')) {
            formValues["rights"].push("changeTax");
        }
        if($('addNews_' + id).hasClassName('checkboxActive') || $('changeTax_' + id).hasClassName('checkboxActiveDisabled')) {
            formValues["rights"].push("addNews");
        }
        if($('editProfile_' + id).hasClassName('checkboxActive') || $('changeTax_' + id).hasClassName('checkboxActiveDisabled')) {
            formValues["rights"].push("editProfile");
        }
        if($('kickMembers_' + id).hasClassName('checkboxActive') || $('changeTax_' + id).hasClassName('checkboxActiveDisabled')) {
            formValues["rights"].push("kickMembers");
        }
        if($('manageCandidates_' + id).hasClassName('checkboxActive') || $('changeTax_' + id).hasClassName('checkboxActiveDisabled')) {
            formValues["rights"].push("manageCandidates");
        }
        if($('editRanks_' + id).hasClassName('checkboxActive') || $('changeTax_' + id).hasClassName('checkboxActiveDisabled')) {
            formValues["rights"].push("editRanks");
        }
        xajax_ActionController.doAction("InternalClan", "saveClanRank", formValues);
    }

    this.deleteRank = function(id) {
        xajax_ActionController.doAction("InternalClan", "deleteClanRank", id);
    }


    this.setRank = function(avatarID, rankID) {
        buttonHandler.toggleDropdown('dropdown_' + avatarID);
        var formValues = new Array();
        formValues['avatarID'] = avatarID;
        formValues['rankID'] = rankID;
        xajax_ActionController.doAction("InternalClan", "changeMemberRank", formValues);
        $('currentRankName_' + avatarID).innerHTML = $(avatarID + "_" + rankID).innerHTML;
    }

    this.setDefaultRank = function(id) {
        this.toggleDefaultMemberRanks();
        $('defaultRank').innerHTML = $('rank_' + id).innerHTML;
        xajax_ActionController.doAction('InternalClan', 'changeDefaultRank', id);
    }

    this.changeMemberRank = function(rakID) {
        var form = xajax.getFormValues('memberForm');
        var formValues = new Array();
        formValues["avatarID"] = form['selected'];
        formValues["rankID"] = $('rankID').value;
        if(form['selected']) {
            xajax_ActionController.doAction("InternalClan", "changeMemberRank", formValues);
        }
    }

    this.kickMember = function(avatarID) {
        xajax_ActionController.doAction("InternalClan", "kickMember", avatarID);
    }

    this.setClanTax = function() {
        xajax_ActionController.doAction("InternalClan", "setClanTax", $('taxValue').value);
    }

    this.deleteClan = function() {
        xajax_ActionController.doAction('InternalClan', 'deleteClan');
    }

    this.disband = function() {
        xajax_ActionController.doAction('InternalClan', 'disband');
    }

    this.acceptMember = function(id) {
        xajax_ActionController.doAction('InternalClan', 'acceptMember', id);
    }

    this.rejectCandidate = function(clanID, avatarID, isMember) {
        var formValues = new Array();
        formValues['avatarID'] = avatarID;
        formValues['clanID'] = clanID;
        formValues['isMember'] = isMember;
        xajax_ActionController.doAction('InternalClan', 'removeClanCandidate', formValues);
    }
}

var slider = new Slider();
function Slider() {
    this.expandSlider = function(id) {
        var queueReduce = Effect.Queues.get('reduce' + id);
        queueReduce.each(function(effect) { effect.cancel(); });

        new Effect.Morph($(id), {

            style: 'top: 58px;',
           duration: 0.05,
           queue: {
                position:'end',
                scope: 'expand' + id
            }
        });
    }

    this.reduceSlider = function(id) {
        var queueExpand = Effect.Queues.get('expand' + id);
        queueExpand.each(function(effect) { effect.cancel(); });
        new Effect.Morph($(id), {
            style: 'top: 120px;',
           duration: 0.1,
           queue: {
                position:'end',
                scope: 'reduce' + id
            }
        });
    }
}

var internalStore = new InternalStore();
function InternalStore() {

    this.designers = new Array();
    this.colors = new Array();

    this.activeCategory = null;

    this.buying = false;
    this.classId = null;
    this.className = null;
    this.classNameLarge = null;
    
    this.activeSubCategory = null;

    this.amount = null;

    this.initFilters = function() {
        this.designers = new Array();
        this.colors = new Array();
    }

    this.togglePreviousPageButton = function() {
        if(!$('previousPageLarge').hasClassName('previousPageLargeInactive')) {
            if($('previousPageLarge').hasClassName('previousPageLargeOver')) {
                $('previousPageLarge').removeClassName('previousPageLargeOver');
            } else {
                $('previousPageLarge').addClassName('previousPageLargeOver');
            }
        }
    }

    this.toggleNextPageButton = function() {
        if(!$('nextPageLarge').hasClassName('nextPageLargeInactive')) {
            if($('nextPageLarge').hasClassName('nextPageLargeOver')) {
                $('nextPageLarge').removeClassName('nextPageLargeOver');
            } else {
                $('nextPageLarge').addClassName('nextPageLargeOver');
            }
        }
    }

    this.toggleInfoButton = function(id) {
        var element = $(id);
        if(element.hasClassName('itemInfoButtonActive')) {
            element.removeClassName('itemInfoButtonActive');
        } else {
            element.addClassName('itemInfoButtonActive');
        }
    }

    
    
    this.toggleCloseDetailsButton = function() {
        var element = $('buttonCloseDetails');
        if(element.hasClassName('closeButtonActive')) {
            element.removeClassName('closeButtonActive');
        } else {
            element.addClassName('closeButtonActive');
        }
    }

    this.handleBuying= function(category, id, amount, classId, className){
    	if(this.buying){
    		return;
    	}
    	this.buying = true;
        if($('buy_success')) {
            layerHandler.hideLayer('buy_success');
        }
        
    	buttonHandler.EnableDisableStandardButton(classId, className);
    	window.setTimeout("internalStore.buyItem('" + category + "', " + id + ",  " + amount + ");", 200);
    	this.classId = classId;
    	this.className = className; 	
    }


    this.setAmount = function(amount, id) {
        buttonHandler.toggleDropdown(id);
        $('currentAmount').innerHTML = amount;
        $('hidden_amount').value = amount;
        this.amount = amount;

    }
    
    this.buyItemComplete =  function(){
    	if(this.className == this.classId){
    		buttonHandler.EnableDisableBuyButtonLarge(this.classId, this.className);
    	}else{
    		buttonHandler.EnableDisableStandardButton(this.classId, this.className);
    	} 	
    	this.buying = false; 
    	this.classId = null;
    	this.className = null;
        this.amount = null;
    }
    
    this.buyItem = function(category, id, amount) {	
        if(this.amount == null) {
            //this.amount is set by item details window
            if(amount == null) {
                var amount = 1;
            } 
        } else {
            var amount = this.amount
            
        }
        var formValues = new Array();
        formValues['itemID'] = id;
        formValues['shopCategory'] = category;
        formValues['amount'] = amount;
        xajax_ActionController.doAction('InternalStore', 'buyItem', formValues);
    }

    this.bid = function(category, id) {
        var formValues = new Array();
        formValues['auctionItemID'] = id;
        formValues['offer'] = $('bid_' + id).value;
        formValues['shopCategory'] = category;
        xajax_ActionController.doAction('InternalStore', 'bidItem', formValues);
    }

    this.showDetails = function(id, category) {
        var formValues = new Array();
        formValues['itemID'] = id;
        formValues['shopCategory'] = category;
        xajax_ActionController.doAction('InternalStore', 'showItemDetails', formValues);
    }

    this.hideDetails = function() {
        layerHandler.hideLayer('itemDetails');
        internalStore.amount = null;
    }

    this.showItems = function(category, subCategory) {
        if(actionController.actionInProgress) {
            return;
        }
        //will be reset in actionController
        actionController.actionInProgress = true;
        var formValues = new Array();
        formValues['mainCategory'] = category;
        formValues['subCategory'] = subCategory;
        formValues['offset'] = 0;
        formValues['limit'] = 8;
        xajax_ActionController.doAction('InternalStore', 'items', formValues);
    }

    this.showAuctionTemplate = function() {
        if(actionController.actionInProgress) {
            return;
        }
        //will be reset in actionController
        actionController.actionInProgress = true;
        var formValues = new Array();
        formValues['offset'] = 0;
        formValues['limit'] = 3;
        xajax_ActionController.doAction('InternalStore', 'auctionTemplate', formValues);
    }

    this.showAuctions = function(offset, limit) {
        var formValues = new Array();
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        xajax_ActionController.doAction('InternalStore', 'auctions', formValues);
    }

    this.showAuctionHistory = function(offset, limit) {
        var formValues = new Array();
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        xajax_ActionController.doAction('InternalStore', 'auctionHistory', formValues);
    }

    this.showCategory = function(category, subCategory, offset, limit) {
        var formValues = new Array();
        formValues['mainCategory'] = category;
        formValues['subCategory'] = subCategory;
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        formValues['designers'] = this.designers;
        formValues['colors'] = this.colors;
        xajax_ActionController.doAction('InternalStore', 'filter', formValues);
    }

    this.filterClothes = function() {
        this.showCategory(categoryHandler.activeCategory, categoryHandler.activeSubCategory, 0, 8);
    }

    this.toggleDesigner = function(designer) {
        if(this.designers.contains(designer)) {
            this.designers = this.designers.without(designer);
            $('dot_' + designer).removeClassName('dotActive');
        } else {
            this.designers.push(designer);
            $('dot_' + designer).addClassName('dotActive');
        }

        this.filterClothes();
    }

    this.toggleColor = function(color) {
        if(this.colors.contains(color)) {
            this.colors = this.colors.without(color);
            $(color).removeClassName('activeBorder');
        } else {
            this.colors.push(color);
            $(color).addClassName('activeBorder');
        }
        this.filterClothes();
    }

    this.showFilterButton = function() {
        $('storeFilter').style.display = "block";
    }

    this.hideFilterButton = function() {
        $('storeFilter').style.display = "none";
    }

    this.toggleFilterContent = function() {
        if($('storeFilterContent').style.display != "none") {
            new Effect.Fade($('storeFilterContent'), {
                duration: 0.2
            });
        } else {
            new Effect.Appear($('storeFilterContent'), {
                duration: 0.2
            });
        }
    }

    this.hideFilterContent = function() {
        if($('storeFilterContent').style.display == "block") {
            new Effect.Fade($('storeFilterContent'), {
                duration: 0.2
            });
        }
    }
}

var payment = new Payment();

function Payment() {

    this.toggleSubscriptionButton = function(id) {
        var element = $(id);
        if(element.hasClassName('activateButton')) {
            element.removeClassName('activateButton');
            element.addClassName('activateButtonOver');
        } else {
            element.removeClassName('activateButtonOver');
            element.addClassName('activateButton');
        }
    }

    this.toggleCreditsButton = function(id) {
        var element = $(id);
        if(element.hasClassName('creditsButton')) {
            element.removeClassName('creditsButton');
            element.addClassName('creditsButtonOver');
        } else {
            element.removeClassName('creditsButtonOver');
            element.addClassName('creditsButton');
        }
    }
}

var externalHome = new ExternalHome();

function ExternalHome() {

    this.toggleButton = function(id) {
        var element = $(id);
        if(element.hasClassName('button122')) {
            element.removeClassName('button122');
            element.addClassName('button122Over');
        } else {
            element.removeClassName('button122Over');
            element.addClassName('button122');
        }
    }

    this.login = function() {
        if(!actionController.actionInProgress) {
            actionController.actionInProgress = true;
            var formValues = xajax.getFormValues('loginForm_default');
            xajax_ActionController.doAction("ExternalHome", "login", formValues);
        }
    }

    this.toggleLanguageSelection = function() {
        if($('languageSelectionBox').getHeight() == 20) {
            //$('languageSelectionBox').style.height = "100px";
            new Effect.Morph("languageSelectionBox", {
                style: 'height: 90px;',
                duration: 0.3
            });
        } else {
            //$('languageSelectionBox').style.height = "20px";
            new Effect.Morph("languageSelectionBox", {
                style: 'height: 20px;',
                duration: 0.3
            });
        }
    }
}


var internalRankings = new InternalRankings();

function InternalRankings() {

    this.statisticType = 'KillPoints';
    this.rankingType = 'avatar';
    this.gangID = 0;

    this.activeTop3Avatar = 0;
    this.activeTop3Clan = 0;

    this.initTop3Box = function() {
        this.activeTop3Avatar = 0;
        this.activeTop3Clan = 0;
    }

    this.init = function() {
        this.statisticType = 'KillPoints';
        this.rankingType = 'avatar';
        this.gangID = 0;
    }

    this.toggleRowHighlight = function(id) {
        if($('rankingRow_' + id).hasClassName('rankingRowActive')) {
            $('rankingRow_' + id).removeClassName('rankingRowActive');
        } else {
            $('rankingRow_' + id).addClassName('rankingRowActive');
        }
    }

    this.showSubCategory = function(subCategory, order, orderBy, offset, reloadTop3) {
        this.initTop3Box();
        this.rankingType = subCategory;
        var formValues = new Array();
        formValues['rankingType'] = subCategory;
        formValues['order'] = order;
        formValues['orderBy'] = orderBy;
        formValues['offset'] = offset;
        formValues['statisticType'] = this.statisticType;
        formValues['gangID'] = this.gangID;
        if(reloadTop3 != null) {
            this.initTop3Box();
            formValues['reloadTop3'] = reloadTop3;
        }
        xajax_ActionController.doAction('InternalRankings', 'ranking', formValues);
    }

    this.toggleStatisticType = function(statisticType) {

        if(this.statisticType != statisticType) {

            $('dot_' + this.statisticType).removeClassName('dotActive');
            $('dot_' + statisticType).addClassName('dotActive');
            this.statisticType = statisticType;
            this.showSubCategory(this.rankingType, 'asc', 'rank', 0, true);
        }

        //this.filterClothes();
    }

    this.toggleGang = function(gangID) {
        if(this.gangID != gangID) {
            $('dot_' + this.gangID).removeClassName('dotActive');
            $('dot_' + gangID).addClassName('dotActive');
            this.gangID = gangID;
            this.showSubCategory(this.rankingType, 'asc', 'rank', 0);
        }
        //this.filterClothes();
    }

    this.toggleFilterContent = function() {
        if($('rankingFilterContent').style.display != "none") {
            new Effect.Fade($('rankingFilterContent'), {
                duration: 0.2
            });
        } else {
            new Effect.Appear($('rankingFilterContent'), {
                duration: 0.2
            });
        }
    }

    this.search = function(string) {

        var formValues = new Array();
        formValues['rankingType'] = this.rankingType;
        formValues['statisticType'] = this.statisticType;
        if(string != null) {
            formValues['name'] = string;
        } else {
            formValues['name'] = $('searchName').value
        }
        xajax_ActionController.doAction('InternalRankings', 'search', formValues);
    }

    this.nextTop3Avatar = function() {
        new Effect.Parallel( [
            new Effect.Morph($('avatar_' + this.activeTop3Avatar), {
            style : {
                marginLeft : '-20px'
            },
            sync :true
            }),
            new Effect.Fade($('avatar_' + this.activeTop3Avatar), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });

        if(++this.activeTop3Avatar > 2) {
            this.activeTop3Avatar = 0;
        }

        new Effect.Parallel( [
            new Effect.Morph($('avatar_' + this.activeTop3Avatar), {
            style : {
                marginLeft : '0px'
            },
            sync :true
            }),
            new Effect.Appear($('avatar_' + this.activeTop3Avatar), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0,
            beforeStart: function() {
                $('avatar_' + internalRankings.activeTop3Avatar).style.marginLeft = '20px';
            }
        });
        $('shownAvatarName').innerHTML = (internalRankings.activeTop3Avatar + 1) + ". " + $('avatarName_' + internalRankings.activeTop3Avatar).value;
        $('shownAvatarPoints').innerHTML = $('avatarPoints_' + internalRankings.activeTop3Avatar).value;
    }

    this.previousTop3Avatar = function() {
        new Effect.Parallel( [
            new Effect.Morph($('avatar_' + this.activeTop3Avatar), {
            style : {
                marginLeft : '20px'
            },
            sync :true
            }),
            new Effect.Fade($('avatar_' + this.activeTop3Avatar), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });

        if(--this.activeTop3Avatar < 0) {
            this.activeTop3Avatar = 2;
        }

        new Effect.Parallel( [
            new Effect.Morph($('avatar_' + this.activeTop3Avatar), {
            style : {
                marginLeft : '0px'
            },
            sync :true
            }),
            new Effect.Appear($('avatar_' + this.activeTop3Avatar), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0,
            beforeStart: function() {
                $('avatar_' + internalRankings.activeTop3Avatar).style.marginLeft = '-20px';
            }
        });
        $('shownAvatarName').innerHTML = (internalRankings.activeTop3Avatar + 1) + ". " + $('avatarName_' + internalRankings.activeTop3Avatar).value;
        $('shownAvatarPoints').innerHTML = $('avatarPoints_' + internalRankings.activeTop3Avatar).value;
    }

    this.nextTop3Clan = function() {
        new Effect.Parallel( [
            new Effect.Morph($('clan_' + this.activeTop3Clan), {
            style : {
                marginLeft : '-20px'
            },
            sync :true
            }),
            new Effect.Fade($('clan_' + this.activeTop3Clan), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });

        if(++this.activeTop3Clan > 2) {
            this.activeTop3Clan = 0;
        }

        new Effect.Parallel( [
            new Effect.Morph($('clan_' + this.activeTop3Clan), {
            style : {
                marginLeft : '0px'
            },
            sync :true
            }),
            new Effect.Appear($('clan_' + this.activeTop3Clan), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0,
            beforeStart: function() {
                $('clan_' + internalRankings.activeTop3Clan).style.marginLeft = '20px';
            }
        });
        $('shownClanName').innerHTML = (internalRankings.activeTop3Clan + 1) + ". " + $('clanName_' + internalRankings.activeTop3Clan).value;
        $('shownClanPoints').innerHTML = $('clanPoints_' + internalRankings.activeTop3Clan).value;
    }

    this.previousTop3Clan = function() {
        new Effect.Parallel( [
            new Effect.Morph($('clan_' + this.activeTop3Clan), {
            style : {
                marginLeft : '20px'
            },
            sync :true
            }),
            new Effect.Fade($('clan_' + this.activeTop3Clan), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });

        if(--this.activeTop3Clan < 0) {
            this.activeTop3Clan = 2;
        }

        new Effect.Parallel( [
            new Effect.Morph($('clan_' + this.activeTop3Clan), {
            style : {
                marginLeft : '0px'
            },
            sync :true
            }),
            new Effect.Appear($('clan_' + this.activeTop3Clan), {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0,
            beforeStart: function() {
                $('clan_' + internalRankings.activeTop3Clan).style.marginLeft = '-20px';
            }
        });
        $('shownClanName').innerHTML = (internalRankings.activeTop3Clan + 1) + ". " + $('clanName_' + internalRankings.activeTop3Clan).value;
        $('shownClanPoints').innerHTML = $('clanPoints_' + internalRankings.activeTop3Clan).value;
    }
}

var internalHome = new InternalHome();

function InternalHome() {

    this.activeCategoryBottom = "achievements";
    this.activeCategoryTop = "avatar";
    this.activeCategoryInventory = "avatar";
    this.autoCompleter = null;

    this.activeAvatar = null;
    this.avatarCount = null;

    this.newAvatar = function() {
        var formValues = new Array();
        formValues['langIdentifier'] = 'pv.internalHome.overview.comingSoon';
        xajax_LayerHandler.getLayer('custom', 0, formValues, null, false);
    }

    this.saveAvatar = function() {
        var formValues = new Array();
        formValues['avatarName'] = $('avatarName').value;
        xajax_ActionController.doAction('InternalHome', 'saveAvatar', formValues);
    }

    this.nextAvatar = function(userID) {
        if(++this.activeAvatar >= this.avatarCount) {
            this.activeAvatar = 0;
        }
        xajax_ToolbarHelper.changeAvatar(userID, this.activeAvatar);
    }

    this.previousAvatar = function(userID) {
        if(--this.activeAvatar < 0) {
            this.activeAvatar = this.avatarCount-1;
        }
        xajax_ToolbarHelper.changeAvatar(userID, this.activeAvatar);
    }

    this.switchCategoryBottom = function(category) {
        $('smallContent_' + this.activeCategoryBottom).style.display = "none";
        $('smallContent_' + category).style.display = "block";

        $('category_' + this.activeCategoryBottom).removeClassName('active');
        $('category_' + category).addClassName('active');


        CSBfleXcroll('smallContent_' + category);
        this.activeCategoryBottom = category;
    }

    this.switchCategoryTop = function(category) {
        $('smallContent_' + this.activeCategoryTop).style.display = "none";
        $('smallContent_' + category).style.display = "block";

        $('category_' + this.activeCategoryTop).removeClassName('active');
        $('category_' + category).addClassName('active');


        CSBfleXcroll('smallContent_' + category);
        this.activeCategoryTop = category;
    }

    this.showMessage = function(id) {
        $('message_' + id).remove();
        var formValues = new Array();
        formValues['messageID'] = id;
        xajax_LayerHandler.getLayer('receivedMessage', 0, formValues, null, false);
    }


    this.loadAutoCompleter = function(userID, sessionID) {
        this.autoCompleter = new Ajax.Autocompleter('avatarNameSearch', 'avatarChoices',
            '/mini.php?sid=' + sessionID, {
                minChars :3,
                afterUpdateElement :getSelectionIDAvatar,
                parameters :'xjxargs[]=S' + userID + '&xjxargs[]=S' + sessionID
                        + '&xjxfun=getAvatars'
            }
        );
    }

    this.showAvatarChoices = function() {
        new Effect.Appear($('choicesContainer'), {duration: 0.1});
        //$('clanChoices').style.display = 'block';
    }
    //is called from within control.js!
    this.hideAvatarChoices = function() {
        new Effect.Fade($('choicesContainer'), {duration: 0.1});
    }

    this.addFriend = function(name, switchSubAction) {
        formValues = new Array();
        formValues['switchSubAction'] = switchSubAction;
        if(name == null) {
            formValues['avatarName'] = $('avatarNameSearch').value;
        } else {
            formValues['avatarName'] = name;
        }


        xajax_ActionController.doAction('InternalHome', 'addFriend', formValues);
    }

    this.deleteFriend = function(id) {
        xajax_ActionController.doAction('InternalHome', 'deleteFriend', id);
    }

    this.acceptFriend = function(id) {
        xajax_ActionController.doAction('InternalHome', 'acceptFriend', id);
    }

    this.confirmFriend = function(id) {
        xajax_ActionController.doAction('InternalHome', 'confirmFriend', id);
    }

    this.declineFriend = function(id) {
        xajax_ActionController.doAction('InternalHome', 'declineFriend', id);
    }

    this.toggleAddFriendButton = function(id) {
        var element = $(id);
        if(element.hasClassName('buttonAddFriendActive')) {
            element.removeClassName('buttonAddFriendActive');
            element.removeClassName('black12px');
            element.addClassName('light12px');
        } else {
            element.addClassName('buttonAddFriendActive');
            element.removeClassName('light12px');
            element.addClassName('black12px');
        }
    }

    this.showFriends = function(offset, limit) {
        var formValues = new Array();
        formValues['offset'] = offset;
        formValues['limit'] = limit;
        xajax_ActionController.doAction('InternalHome', 'friends', formValues);
    }


    this.toggleStatisticsButton = function(id) {
        var element = $(id);
        if(element.hasClassName('statisticsButton')) {
            element.removeClassName('statisticsButton');
            element.addClassName('statisticsButtonOver');
        } else {
            element.removeClassName('statisticsButtonOver');
            element.addClassName('statisticsButton');
        }
    }

    this.fillAvatarComparisonForm = function(id, name) {
        $('avatarname').value=name;
        $('avatarID').value=id;
    }

    this.toggleAchievementDate = function(id) {
        var element = $(id);
        if(element.style.display == "none") {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
    }

    this.filterAchievements = function(filter, compare) {

        var formValues = xajax.getFormValues('compareAvatar');
        formValues['filter'] = filter;
        if($('compareAvatar')) {
            xajax_ActionController.doAction('InternalHome', 'statisticsComparison', formValues);
        } else {
            xajax_ActionController.doAction('InternalHome', 'statistics', formValues);
        }
    }

    this.setBounty = function() {
        xajax_ActionController.doAction('InternalHome', 'setBounty', xajax.getFormValues('setBountyForm'));
    }

    this.showBountyInfo = function(bountyID) {
        xajax_ActionController.doAction('InternalHome', 'showBountyInfo', bountyID);
    }

    this.acceptBounty = function(bountyID) {
        xajax_ActionController.doAction('InternalHome', 'acceptBounty', bountyID);
    }
}


var profileHandler = new ProfileHandler();

function ProfileHandler() {


    this.setResolution = function(resolution, profileID) {
        buttonHandler.toggleDropdown('dropdown_resolution_' + profileID);
        $('currentResolution_' + profileID).innerHTML = $(resolution + "_" +  profileID).innerHTML;
        $('hidden_resolution_' + profileID).value = resolution;
    }



    this.setBitDepth = function(bitDepth, profileID) {
        buttonHandler.toggleDropdown('dropdown_bitDepth_' + profileID);
        $('currentBitDepth_' + profileID).innerHTML = $(bitDepth + "_" +  profileID).innerHTML;
        $('hidden_bitDepth_' + profileID).value = bitDepth;
    }



    this.setGraphicsQuality = function(graphicsQuality, profileID) {
        buttonHandler.toggleDropdown('dropdown_graphicsQuality_' + profileID);
        $('currentGraphicsQuality_' + profileID).innerHTML = $(graphicsQuality + "_" +  profileID).innerHTML;
        $('hidden_graphicsQuality_' + profileID).value = graphicsQuality;
        buttonHandler.toggleDropdown('dropdown_graphicsQuality_' + profileID);
        $('currentGraphicsQuality_' + profileID).innerHTML = $(graphicsQuality + "_" +  profileID).innerHTML;
        $('hidden_graphicsQuality_' + profileID).value = graphicsQuality;
    }

    this.activateProfile = function(id) {
        xajax_ActionController.doAction('InternalHome', 'activateProfile', id);
    }

    this.saveProfile = function(id) {
    	var formValues = xajax.getFormValues('profileForm_' + id);
    	if($('invertMouse_'+id).hasClassName('checkboxActive')) {
    		formValues['invertMouse'] = true;
    	}
    	if($('sound_'+id).hasClassName('checkboxActive')) {
    		formValues['sound'] = true;
    	}
        xajax_ActionController.doAction('InternalHome', 'saveProfile', formValues);
    }
}

var inventory = new Inventory();

function Inventory() {

    this.origWeaponMod = null;
    this.swapWeaponMod = null;
    this.destroyElement = null;

    this.activeTab = 1;

    this.draggables = new Array();

    this.init = function() {
        this.activeTab = 1;
    }

    this.switchTab = function(tabIndex) {
        if(tabIndex != this.activeTab) {
            $("content_" + tabIndex).style.display = 'block';
            $("content_" + this.activeTab).style.display = 'none';


            //switch tab image
            $('category_' + this.activeTab).removeClassName('active');
            $('category_' + tabIndex).addClassName('active');
            this.activeTab = tabIndex;
        }
    }

    this.destroyItem = function(dragElement, dropElement) {

        var oldContainer = dragElement.parentNode.getAttribute("id").split("_");

        formValues = new Array();
        formValues["item"] = new Object();
        formValues["item"]["avatarInventoryID"] = dragElement.getAttribute("id").substr(5);
        formValues["item"]["slotID"] = oldContainer[1];
        formValues["item"]["storageLocation"] = oldContainer[0];


        xajax_ActionController.doAction("InternalHome", "destroyItem", formValues);
        this.destroyElement = dragElement;

        dragElement.parentNode.removeClassName('itemContainerFull');
        dragElement.parentNode.addClassName('itemContainerEmpty');
        dragElement.parentNode.removeChild(dragElement);

    }

    this.removeDraggable = function(id) {
        var draggable = this.draggables[id];
        
        draggable.destroy();


    }

    this.loadDraggables = function(items) {
        if(items != "") {
            var itemIDs = items.split(",");

            for ( var i = 0; i < itemIDs.length; i++) {
                var tmpItem = "item_" + itemIDs[i].toString();
                
                // alert(tmpItem);
                this.draggables[itemIDs[i].toString()] = new Draggable(tmpItem, {
                    revert :'failure',
                    superghosting: true
                });
            }
        }
    }

    this.loadDroppables = function(bagCount, homeCount) {

        var clothesTypes = new Array();
        clothesTypes[0] = "Hat";
        clothesTypes[1] = "Glasses";
        clothesTypes[2] = "Jacket";
        clothesTypes[3] = "Shirt";
        clothesTypes[4] = "Pants";
        clothesTypes[5] = "Shoes";
        clothesTypes[6] = "Ring";
        clothesTypes[7] = "Ring";


        for ( var i = 0; i < bagCount; i++) {
            Droppables.add("bag_" + i, {
                accept :'item',
                onDrop : function(dragElement, dropElement) {
                    inventory.drop(dragElement, dropElement)
                },
                onHover : function(dragElement, dropElement) {
                    dropElement.addClassName('itemContainerOver');
                },
                onUnhover : function(dropElement) {
                    dropElement.removeClassName('itemContainerOver');
                }
            });
        }

        for ( var i = 0; i < homeCount; i++) {
            Droppables.add("home_" + i, {
                accept :'item',
                onDrop : function(dragElement, dropElement) {

                    inventory.drop(dragElement, dropElement)
                },
                onHover : function(dragElement, dropElement) {
                    dropElement.addClassName('itemContainerOver');
                },
                onUnhover : function(dropElement) {
                    dropElement.removeClassName('itemContainerOver');
                }
            });
        }

        for ( var i = 0; i < 2; i++) {
            Droppables.add("WeaponBelt_" + i, {
                accept :'weaponsItem',
                onDrop : function(dragElement, dropElement) {
                    inventory.drop(dragElement, dropElement)
                },
                onHover : function(dragElement, dropElement) {
                    dropElement.addClassName('itemContainerOver');
                },
                onUnhover : function(dropElement) {
                    dropElement.removeClassName('itemContainerOver');
                }
            });
        }

        for ( var i = 0; i < 8; i++) {
            Droppables.add("Avatar_" + i, {
                accept :clothesTypes[i],
                onDrop : function(dragElement, dropElement) {
                    var child = dropElement.firstChild;
                    if(child.hasClassName("slotIcon")) {
                        dropElement.removeChild(child);
                    }
                    inventory.drop(dragElement, dropElement)
                },
                onHover : function(dragElement, dropElement) {
                    dropElement.addClassName('itemContainerOver');
                },
                onUnhover : function(dropElement) {
                    dropElement.removeClassName('itemContainerOver');
                }
            });
        }

        

        Droppables.add("trashCan", {
           accept: 'item' ,
            onDrop : function(dragElement, dropElement) {
                //var oriElement = $(dragElement.id.substr(6));
                var oriElement = dragElement;
                oriElement.parentNode.removeClassName('itemContainerFull');
                oriElement.parentNode.addClassName('itemContainerEmpty');
                inventory.destroyItem(oriElement, dropElement);
            },
            onHover : function(dragElement, dropElement) {
                dropElement.addClassName('trashCanOver');
            },
            onUnhover : function(dropElement) {
                dropElement.removeClassName('trashCanOver');
            }
        });
    }

    this.cancelWeaponModInstall = function(srcBagType, srcSlotID, modSlotID) {
        if(modSlotID != null) {
            var weaponModSlot = $("modSlot_" + modSlotID);

            if(this.swapWeaponMod != null) {
                weaponModSlot.appendChild(this.swapWeaponMod);
            } else {
                weaponModSlot.removeClassName("itemContainerFull");
                weaponModSlot.addClassName("itemContainerEmpty");
            }
        }
        var slot = $(srcBagType + "_" + srcSlotID);
        
        slot.addClassName("itemContainerFull");
        slot.removeClassName("itemContainerEmpty");

        slot.appendChild(this.origWeaponMod);
        

        this.origWeaponMod = null;
        this.swapWeaponMod = null;
    }

    this.cancelDestroy = function(srcBagType, srcSlotID) {
        var slot = $(srcBagType + "_" + srcSlotID);

        slot.addClassName("itemContainerFull");
        slot.removeClassName("itemContainerEmpty");

        slot.appendChild(this.destroyElement);

        this.destroyElement = null;

    }

    this.dropWeaponMod = function(dragElement, dropElement) {
        var oriElement = dragElement;
        if (oriElement.parentNode == dropElement) {
            oriElement.style.left = 0;
            oriElement.style.top = 0;
            return;
        }
        formValues = new Array();

        if (dropElement.hasChildNodes()) {
            swapElement = dropElement.childNodes[0];
            this.origWeaponMod = $(oriElement);
            this.swapWeaponMod = $(swapElement);

            swapElement.parentNode.removeChild(swapElement);
            oriElement.parentNode.removeClassName('itemContainerFull');
            oriElement.parentNode.addClassName('itemContainerEmpty');

            //oriElement.parentNode.appendChild(swapElement);
            formValues["swapItem"] = new Object();

            var newContainer = oriElement.parentNode.getAttribute("id").split("_");

            formValues["swapItem"]["slotID"] = newContainer[1];
            formValues["swapItem"]["avatarInventoryID"] = swapElement.getAttribute(
                    "id").substr(5);
            formValues["swapItem"]["storageLocation"] = newContainer[0];
            

        } else {
            this.origWeaponMod = $(oriElement);
            //we need the information of where the mod was to be able to revert in case of user presses "cancel""
            formValues["oldItem"] = new Object();
            var oldContainer = oriElement.parentNode.getAttribute("id").split("_");
            formValues["oldItem"]["slotID"] = oldContainer[1];
            formValues["oldItem"]["storageLocation"] = oldContainer[0];

            oriElement.parentNode.removeClassName('itemContainerFull');
            oriElement.parentNode.addClassName('itemContainerEmpty');

            dropElement.removeClassName('itemContainerEmpty');
            dropElement.addClassName('itemContainerFull');



        }
        formValues["item"] = new Object();
        var newContainer = dropElement.getAttribute("id").split("_");
        formValues["item"]["slotID"] = newContainer[1];
        formValues["item"]["avatarInventoryID"] = oriElement.getAttribute("id")
                .substr(5);
        formValues["item"]["storageLocation"] = newContainer[0];
        formValues["item"]["avatarWeaponID"] = $('avatarWeaponID').value;
        //oriElement.parentNode.removeChild(oriElement);
        dropElement.appendChild(oriElement);

        //dragElement.style.left = 0;
        //dragElement.style.top = 0;

        xajax_ActionController.doAction("InternalHome", "installMod", formValues);
    }

    this.drop = function(dragElement, dropElement) {

        //var oriElement = $(dragElement.id.substr(6));
        var oriElement = dragElement;
        if (oriElement.parentNode == dropElement) {
            oriElement.style.left = 0;
            oriElement.style.top = 0;
            return;
        }
        formValues = new Array();


        // already containing an element; switch them!
        if (dropElement.hasChildNodes()) {
            swapElement = dropElement.childNodes[0];

            swapElement.parentNode.removeChild(swapElement);
            oriElement.parentNode.appendChild(swapElement);
            formValues["swapItem"] = new Object();

            var newContainer = oriElement.parentNode.getAttribute("id").split("_");

            formValues["swapItem"]["slotID"] = newContainer[1];
            formValues["swapItem"]["avatarInventoryID"] = swapElement.getAttribute(
                    "id").substr(5);
            formValues["swapItem"]["storageLocation"] = newContainer[0];
        } else {
            var oldContainer = oriElement.parentNode.getAttribute("id").split("_");

            oriElement.parentNode.removeClassName('itemContainerFull');
            oriElement.parentNode.addClassName('itemContainerEmpty');

            if(oldContainer[0] == "Avatar") {
                var icon = document.createElement("div");
                icon.className = "slotIcon slotIcon" + oldContainer[1];
                oriElement.parentNode.appendChild(icon);
            }
            dropElement.removeClassName('itemContainerEmpty');
            dropElement.addClassName('itemContainerFull');

        }
        formValues["item"] = new Object();

        var newContainer = dropElement.getAttribute("id").split("_");

        formValues["item"]["slotID"] = newContainer[1];
        formValues["item"]["avatarInventoryID"] = oriElement.getAttribute("id")
                .substr(5);
        formValues["item"]["storageLocation"] = newContainer[0];
        //oriElement.parentNode.removeChild(oriElement);
        dropElement.appendChild(oriElement);

        //dragElement.style.left = 0;
        //dragElement.style.top = 0;

        xajax_ActionController.doAction("InternalHome", "moveItem", formValues);
    }

    this.showWeaponDetails = function(id) {
        if(id != null) {
            var formValues = id;
        } else {
            var formValues = null;
        }
        xajax_ActionController.doAction("InternalHome", "showWeaponDetails", formValues);
    }

    this.loadDroppablesWeaponMods = function(count) {
        for ( var i = 0; i < count; i++) {
            Droppables.add("modSlot_" + i, {
                accept :'weaponmodificationsItem',
                onDrop : function(dragElement, dropElement) {
                    inventory.dropWeaponMod(dragElement, dropElement)
                },
                onHover : function(dragElement, dropElement) {
                    dropElement.addClassName('itemContainerOver');
                },
                onUnhover : function(dropElement) {
                    dropElement.removeClassName('itemContainerOver');
                }
            });
        }
    }

    this.nextWeapon = function(beltIndex) {
        new Effect.Parallel( [
            new Effect.Morph($('weaponSwitcher'), {
            style : {
                left : $('weaponSwitcher').offsetLeft-53 + "px"
            },
            sync :true
            }),
            new Effect.Fade($('weaponContainer_2'), {
            sync :true
            }),
            new Effect.Appear($('weaponContainer_5'), {
            sync :true
            })
        ], {
            duration :0.2,
            delay :0.0,
            afterFinish: function() {
                $('weaponContainer_3').removeClassName('itemContainerFull');
                $('weaponContainer_3').addClassName('itemContainerEmpty');
                $('weaponContainer_4').removeClassName('itemContainerEmpty');
                $('weaponContainer_4').addClassName('itemContainerFull');
                xajax_ActionController.doAction("InternalHome", "showWeaponDetails", beltIndex);
            }
        });
    }

    this.previousWeapon = function(beltIndex) {
        new Effect.Parallel( [
            new Effect.Morph($('weaponSwitcher'), {
            style : {
                left : $('weaponSwitcher').offsetLeft+53 + "px"
            },
            sync :true
            }),
            new Effect.Fade($('weaponContainer_4'), {
            sync :true
            }),
            new Effect.Appear($('weaponContainer_1'), {
            sync :true
            })
        ], {
            duration :0.2,
            delay :0.0,
            afterFinish: function() {
                $('weaponContainer_3').removeClassName('itemContainerFull');
                $('weaponContainer_3').addClassName('itemContainerEmpty');
                $('weaponContainer_2').removeClassName('itemContainerEmpty');
                $('weaponContainer_2').addClassName('itemContainerFull');
                xajax_ActionController.doAction("InternalHome", "showWeaponDetails", beltIndex);
            }
        });
    }
    /*
    this.toggleActiveWeapon = function() {
        var element = $('activeWeaponChoiceContainer');

        if(element.style.display == 'none') {
            new Effect.Appear($('activeWeaponChoiceContainer'), {duration: 0.1});
        } else {
            new Effect.Fade($('activeWeaponChoiceContainer'), {duration: 0.1});
        }
    }

    this.setSelectedActiveWeapon = function(id) {
        $("activeWeapon_" + id).addClassName('selected');
    }

    this.unsetSelectedActiveWeapon = function(id) {
        $("activeWeapon_" + id).removeClassName('selected');
    }

    this.setActiveWeapon = function(weaponID) {
        this.toggleActiveWeapon();
        //$('activeWeaponDisplay').innerHTML = $('activeWeapon_' +  weaponID).innerHTML;
        $('activeWeapon_' + weaponID).value = weaponID;
        xajax_ActionController.doAction("InternalHome", "showWeaponDetails", weaponID);
    }
    */

}

var layerHandler = new LayerHandler();

function LayerHandler() {
    this.layerCount = 0;
    this.heightStack = 0;
    this.layers = new Array();
    this.showLayer = function(id, noDisableSite) {
        if(noDisableSite == null) {
            noDisableSite = false;
        }

        if(this.layerCount == 0 && !noDisableSite) {
            this.disableSite();
        }
        this.layerCount++;


        var height = $(id).getHeight() / 2;
        if(this.layerCount < 2 ) {
            var moveToTop = 330 - height;
            if(moveToTop < 20) {
                moveToTop = 20;
            }
        } else {
            var origTop = height - (this.heightStack);
            $(id).style.top = origTop+"px";

            var moveToTop = 330 - height - this.heightStack;

        }
        this.heightStack += $(id).getHeight();

        this.layers.push(id);

        //$(id).style.display = "block";
        /*new Effect.Morph(id, {
            style: 'top: ' + moveToTop + 'px;',
            duration: 0.3
        });*/

        new Effect.Parallel( [
            new Effect.Morph(id, {
            style : {
                top : + moveToTop + 'px'
            },
            sync :true
            }),
            new Effect.Appear(id, {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });
    }

    this.hideAllLayers = function() {
        while(this.layers.length > 0) {
            this.hideLayer(this.layers[(this.layers.length - 1)]);
        }
        this.heightStack = 0;
    }

    this.hideLayer = function(id, noEnableSite) {
        if(noEnableSite == null) {
            noEnableSite = false;
        }
        this.layerCount--;
        this.heightStack -= $(id).getHeight();
        if(this.layers.indexOf(id) != -1) {
            this.layers.splice(this.layers.indexOf(id), 1);
        }

        if(this.layerCount == 0 && !noEnableSite) {
            this.enableSite();
        }

        var top = parseInt($(id).style.top) + 40;

        new Effect.Parallel( [
            new Effect.Morph(id, {
            style : {
                top : + top + 'px'
            },
            sync :true
            }),
            new Effect.Fade(id, {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0,
            afterFinish: function() {
                $('layers').removeChild($(id));
            }
        });


    }
    this.appendLayer = function(layer) {
        /*var element = document.createElement("div");
        element.style.position = "relative";
        element.innerHTML = layer;
        */
        //$('layers').appendChild(layer);
        $('layers').innerHTML = $('layers').innerHTML + layer;
    }

    this.hideLastLayer = function() {
        var lastChild = $('layers').lastChild;
        this.hideLayer(lastChild.id);
    }


    this.disableSite = function() {
        $('disableSite').appear( {
            from :0.0,
            to :0.8,
            duration :0.3,
            beforeStart: function() {
                $('layers').style.display = "block";
            }
        });
    }

    this.enableSite = function() {
        $('disableSite').fade({
            from: 0.8,
            to: 0.0,
            duration: 0.3,
            afterFinish: function() {
                $('layers').style.display = "none";
            }
        });
    }

    this.toggleCloseLayer = function(id) {
        var element = $('layerClose_' + id);
        if(!element.hasClassName('layerCloseOver')) {
            element.addClassName('layerCloseOver');
        } else {
            element.removeClassName('layerCloseOver');
        }
    }
}
var buttonHandler = new ButtonHandler();

function ButtonHandler() {
    this.toggleStandardButton = function(id, className) {
        var element = $(id);


        element.cleanWhitespace();

        if(!element.hasClassName(className + 'Active')) {
            element.addClassName(className + 'Active');
            $(element.childNodes[0]).addClassName(className + 'BodyActive');
            if($(element.childNodes[1])) {
                $(element.childNodes[1]).addClassName(className + 'FrontActive');
            }

            /*element.removeClassName('light12px');
            element.addClassName('black12px');
            */
        } else {
            element.removeClassName(className + 'Active');
            $(element.childNodes[0]).removeClassName(className + 'BodyActive');
            if($(element.childNodes[1])) {
                $(element.childNodes[1]).removeClassName(className + 'FrontActive');
            }
            /*
            element.removeClassName('black12px');
            element.addClassName('light12px');
            */
        }
    }

    this.EnableDisableStandardButton = function(id, className) {
        var element = $(id);

        element.cleanWhitespace();

        if(!element.hasClassName(className + 'Disabled')) {
            element.addClassName(className + 'Disabled');
            $(element.childNodes[0]).addClassName(className + 'BodyDisabled');
            if($(element.childNodes[1])) {
                $(element.childNodes[1]).addClassName(className + 'FrontDisabled');
            }

            /*element.removeClassName('light12px');
            element.addClassName('black12px');*/
        } else {
            element.removeClassName(className + 'Disabled');
            $(element.childNodes[0]).removeClassName(className + 'BodyDisabled');
            if($(element.childNodes[1])) {
                $(element.childNodes[1]).removeClassName(className + 'FrontDisabled');
            }

            /*element.removeClassName('black12px');
            element.addClassName('light12px');*/
        }
    }
    
    this.toggleDropdown = function(id, baseSize) {
        var element = $(id);
        if(element.getHeight() == baseSize) {
            var ulElement = $(id + "_ul");

            new Effect.Morph(element, {
                style: 'height:'+  (baseSize + ulElement.getHeight()) + 'px;',
                duration: 0.3
             });

        } else {
            new Effect.Morph(element, {
                style: 'height: ' + baseSize + 'px;',
                duration: 0.3
             });
        }
    }

    this.toggleActiveDropdownItem = function(id) {
        var element = $(id);
        if(element.hasClassName('selected')) {
            element.removeClassName('selected');
        } else {
            element.addClassName('selected');
        }
    }

    this.toggleCheckbox = function(id) {
        var element = $(id);
        if(element.hasClassName('checkboxActive')) {
            element.removeClassName('checkboxActive');
        } else {
            element.addClassName('checkboxActive');
        }
    }
}

var avatarCreator = new AvatarCreator();

function AvatarCreator() {

    this.activeHead = null;

    this.activeHairStyle = null;

    this.activeColor = null;

    this.toggleChooseHeadForm = function(id) {
        if($('radio_head_' + id).hasClassName('radioButtonChecked')) {
            $('radio_head_' + id).removeClassName('radioButtonChecked');
            $('choice_head_' + id + '_container').removeClassName('choiceContainerSelected');
            this.activeHead = null;
        } else {
            if(this.activeHead != null) {
                $('radio_head_' + this.activeHead).removeClassName('radioButtonChecked');
                $('choice_head_' + this.activeHead + '_container').removeClassName('choiceContainerSelected');
            }
            $('radio_head_' + id).addClassName('radioButtonChecked');
            $('choice_head_' + id + '_container').addClassName('choiceContainerSelected');
            this.activeHead = id;

        }
    }

    this.showChoiceDetails = function(id, type) {
        var formValues = new Array();
        formValues['id'] = id;
        formValues['type'] = type;
        xajax_ActionController.doAction('InternalHome', 'showChoiceDetails', formValues);
    }

    this.toggleChooseHairStyle = function(id) {
        if($('radio_hairStyle_' + id).hasClassName('radioButtonChecked')) {
            $('radio_hairStyle_' + id).removeClassName('radioButtonChecked');
            $('choice_hairStyle_' + id + '_container').removeClassName('choiceContainerSelected');
            this.activeHairStyle = null;
        } else {
            if(this.activeHairStyle != null) {
                $('radio_hairStyle_' + this.activeHairStyle).removeClassName('radioButtonChecked');
                $('choice_hairStyle_' + this.activeHairStyle + '_container').removeClassName('choiceContainerSelected');
            }
            $('radio_hairStyle_' + id).addClassName('radioButtonChecked');
            $('choice_hairStyle_' + id + '_container').addClassName('choiceContainerSelected');
            this.activeHairStyle = id;

        }
    }

    this.toggleChoiceColor = function(id) {
        if($('choice_color_' + id).hasClassName('choice_color_' + id + '_selected')) {
            $('choice_color_' + id).removeClassName('choice_color_' + id + '_selected');
            this.activeColor = null;
        } else {
            if(this.activeColor != null) {
                $('choice_color_' + this.activeColor).removeClassName('choice_color_' + this.activeColor + '_selected');
            }
            $('choice_color_' + id).addClassName('choice_color_' + id + '_selected');
            this.activeColor = id;
        }
    }

    this.saveAvatar = function() {
        if(this.activeColor != null && this.activeHairStyle != null && this.activeHead != null) {
            var formValues = new Array();
            formValues['color'] = this.activeColor;
            formValues['hairStyle'] = this.activeHairStyle;
            formValues['head'] = this.activeHead;
            formValues['gangID'] = $('gangID').value;
            xajax_ActionController.doAction('InternalHome', 'saveAvatar', formValues);
        }
    }

    this.getActiveHead = function() {
        return this.activeHead;
    }

    this.getActiveHairStyle = function() {
        return this.activeHairStyle;
    }
}

function submitBetaForm() {
    xajax_ActionController.doAction('ExternalBeta', 'submitBetaForm', xajax.getFormValues('betaSignupForm'));
}

function betaResult(result) {
    if(result == "mandatoryFields") {
        $('betaResultFail').appear({from: 0.0, to: 1.0, duration: 0.5});
    } else {
        $('betaResultSuccess').appear({from: 0.0, to: 1.0, duration: 0.5});
    }
}

function hideBetaResult(box) {

    $(box).hide({from: 1.0, to: 0.0, duration: 3.5});
}


function redirect() {
    window.setTimeout("window.location = 'index.es?action=ExternalHome'", 2000);
}

function checker() {
    window.setInterval("scrollCheck.check()",500);
}

var scrollCheck = new ScrollCheck();
function ScrollCheck() {

    this.check = function() {
        if($('ndaContent')) {
            if($('ndaContent').scrollTop == ($('ndaText').getHeight() - $('ndaContent').getHeight())) {
                $('closeButtonDisabled').style.display = "none";
                $('closeButton').style.display = "block";
            }
        }
    }
}

var infoLayer = new InfoLayer();

function InfoLayer() {
    this.show = function() {


        $('disableSiteInfo').appear( {
            from :0.0,
            to :0.8,
            duration :0.3,
            beforeStart: function() {
                $('infoLayer').style.display = "block";
            }
        });

        var height = $('info').getHeight() / 2;
        var top = 330 - height;

        if(top < 20) {
            top = 20;
        }


        $('info').style.display = "block";
        new Effect.Morph('info', {
            style: 'top: ' + top + 'px;',
            duration: 0.3
        });

    }

    this.hide = function() {
        $('disableSiteInfo').fade({
            from: 0.8,
            to: 0.0,
            duration: 0.3,
            afterFinish: function() {
                $('infoLayer').style.display = "none";
            }
        });

        var top = parseInt($('info').style.top) + 40;

        new Effect.Parallel( [
            new Effect.Morph('info', {
            style : {
                top : + top + 'px'
            },
            sync :true
            }),
            new Effect.Fade('info', {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });


    }
}

var qualityLayer = new QualityLayer();

function QualityLayer() {
    this.show = function() {
        $('disableSiteQuality').appear( {
            from :0.0,
            to :0.8,
            duration :0.3,
            beforeStart: function() {
                $('qualityLayer').style.display = "block";
            }
        });

        var height = $('quality').getHeight() / 2;
        var top = 330 - height;

        if(top < 20) {
            top = 20;
        }


        $('quality').style.display = "block";
        new Effect.Morph('quality', {
            style: 'top: ' + top + 'px;',
            duration: 0.3
        });
    }

    this.hide = function() {
        $('disableSiteQuality').fade({
            from: 0.8,
            to: 0.0,
            duration: 0.3,
            afterFinish: function() {
                $('qualityLayer').style.display = "none";
            }
        });

        var top = parseInt($('quality').style.top) + 40;

        new Effect.Parallel( [
            new Effect.Morph('quality', {
            style : {
                top : + top + 'px'
            },
            sync :true
            }),
            new Effect.Fade('quality', {
            sync :true
            })
        ], {
            duration :0.3,
            delay :0.0
        });


    }
}

var messageSystem = new MessageSystem();
function MessageSystem() {
    this.newMessageCount = 0;

    /* show the "write new message" layer */
    this.writeNewMessage = function(avatarID) {
        var formValues = new Array();
        formValues['avatarID'] = avatarID;
        xajax_LayerHandler.getLayer('message', 0, formValues, null, false);
    }
    /* same as above, but user pressed "reply" */
    this.replyToMessage = function(avatarID) {
        var formValues = new Array();
        formValues['avatarID'] = avatarID;
        xajax_LayerHandler.getLayer('message', 0, formValues, null, true);
    }

    /* sends the message to the buddy */
    this.sendMessage = function() {
        layerHandler.hideLayer('message', true);

        var formValues = new Array();
        formValues['recipientID'] = $('recipientID').value;
        formValues['message'] = $('sendMessageContent').value;

        xajax_ToolbarHelper.sendMessage(formValues);
    }

    /* show the "new message from ..." layer */
    this.showNewMessage = function(avatarID) {
        this.unHighlightBuddy(avatarID);

        var formValues = new Array();
        formValues['avatarID'] = avatarID;
        xajax_LayerHandler.getLayer('newMessage', 0, formValues);
    }

    /* toggles message history in "write new message" layer */
    this.toggleMessageHistory = function() {
        var blindItem = $('messageHistory');
        var scrollItem = $('messageHistoryContent');
        if (blindItem.style.display == 'none') {
            new Effect.BlindDown(blindItem,{
                duration :0.2,
                delay :0.0,
                afterFinish: function() {
                    CSBfleXcroll(scrollItem.id);
                }
            });
        } else {
            new Effect.BlindUp(blindItem,{
                duration :0.2,
                delay :0.0
                
            });
        }
    }

    this.updateNewMessageCount = function(count) {
        this.newMessageCount +=count;

        if(this.newMessageCount >0) {
            if(!$('messageCaption').hasClassName('gold12px')) {
                $('messageCaption').addClassName('gold12px');
            }
        } else {
            if($('messageCaption').hasClassName('gold12px')) {
                $('messageCaption').removeClassName('gold12px');
            }
        }
    }

    this.highlightBuddy = function(avatarID) {
        if($('friendListItem_' + avatarID) != null) {
            if(!$('friendListItem_' + avatarID).hasClassName('gold12px')) {
                $('friendListItem_' + avatarID).addClassName('gold12px');
                this.updateNewMessageCount(1);
            }
            $('friendListItem_' + avatarID).onclick = function(){messageSystem.showNewMessage(avatarID);};
        }
    }

    this.unHighlightBuddy = function(avatarID) {
        this.updateNewMessageCount(-1);
        if($('friendListItem_' + avatarID).hasClassName('gold12px')) {
            $('friendListItem_' + avatarID).removeClassName('gold12px');
        }
        $('friendListItem_' + avatarID).onclick = function(){messageSystem.writeNewMessage(avatarID);};
    }

}


function showCbsLayer() {
    window.setTimeout("xajax_LayerHandler.getLayer('cbs_postponed')", 1000);
}

Array.prototype.contains = function(searchValue) {
    for (var i = 0, len = this.length; i < len && this[i] !== searchValue; i++);
    return i < len;
}

