//Will move all page generated boxes into the right side list of boxes. Usefull for custom boxes
function addStatsBox(txt, elem, before) {
    var li = new Element("li",{'class':'normal'});
    var ul = new Element("ul");
    var span = new Element("span",{'class':'heading'});
    var box = new Element("li",{'class':'normal'});

    box.adopt(span);
    box.adopt(ul);
    ul.adopt(li);
    li.adopt($(elem));
    span.appendChild(document.createTextNode(txt));
    if (before) {
        $(before).injectBefore(box);
    } else {
        $E("#right ul").appendChild(box);
    }
}
$ES("#boxes .box").each(function(item) {
    addStatsBox(item.title, item);
});

//Funxtion for converting a string in the form {key1:val1,key2:val2} into a java
//object
var cookieToArray = function(item) {
    var result = {};
    item.substr(1,item.length-2).split(",").each(function(line) {
        var key = line.substr(0, line.indexOf(":"));
        var val = line.substr(line.indexOf(":")+1);
        result[key] = val;
    });
    return result;
}
//Function for converting a javascript object into a string in the form
//{key1:val1,key2:val2}
var arrayToCookie = function(item) {
    var items = Array();
    for (var a in item) items.push(a+":"+item[a]);
    return "{"+items.join(",")+"}";
}

//Code for making navigation boxes foldable
$ES("#site_item #left span.heading,#site_item #right span.heading").each(function(item) {
    var li = $(item.parentNode);
    var list = $E("ul",li);
    //Add the actual slider
    if (list) {
    	list.slide = new Fx.Slide(list, {'onComplete':function() {
        	li.removeClass("closed");
	        setFooter(true);
        	var opens = Cookie.get("openBoxes");
	        if (opens==false) opens = {};
        	else opens = cookieToArray(opens);
	        opens[item.innerHTML] = (list.parentNode.offsetHeight==0)?0:1;
        	Cookie.set("openBoxes",arrayToCookie(opens),{'path':'/','duration':'60'});
	    }});
	    item.onclick = function() {list.slide.toggle();}
	    if (li.hasClass("closed")) item.onclick();
    }
});


//Ajax form handler submitting data and showing errors correctly
$ES("form.ajax").each(function (item) {
    item.addEvent('submit', function(ev) {
        new Event(ev).stop();
        var self=this;
        ajaxLoader(self);
        var xhr = new XHR({'method':'post'});
        xhr.onSuccess = function() {
            $ES(".error",self).each(function (item,index){item.addClass("hide");});
            var result = Json.evaluate(this.transport.responseText);
            var i=0;
            if (result['proceed']) window.location = result['proceed'];
            else for (var a in result) {
                if ($(a+"_error", self)) $(a+"_error", self).removeClass("hide").innerHTML = result[a];
                i++;
            }
            if (i==0) ajaxLoaderDone(self);
            $ES(".ajaxLoad",$(item)).each(function(item){item.addClass("hide")});
            setFooter();
        };
        xhr.send(this.action, this.toQueryString());
    });
});

$ES("a.ajax").each(function (item) {
    item.addEvent('click', function(ev) {
        new Event(ev).stop();
        var self=this;
        var xhr = new XHR({'method':'post'});
        xhr.onSuccess = function() {
            eval(this.transport.responseText);
        };
        xhr.send(this.href, null);
    });
});

//Updated aterNate function, which shows a text in a textbox until the user enters it
function alterCate(elm, onoff) {
    if (typeof(onoff) == "undefined" ) onoff = "blur";
    if (!elm.base) elm.base = elm.value;
    if (elm.value == elm.base && onoff != "blur") elm.value = "";
    else if (elm.value == "" && onoff == "blur") elm.value = elm.base;
}

//Footer position script. Makes sure footer is low enough for small pages.
//footer will always be in bottom of screen. even tall screens
var setFooter = function(growOnly) {
    var c = $E("#content"); var r = $E("#right"); var l = $E("#left");
    c = c.offsetHeight+c.offsetTop; r = r.offsetHeight+r.offsetTop; l = l.offsetHeight+l.offsetTop;
    var h=c; if (r>h) h=r; if (l>h) h=l;

    var f = $E("#footer");

    var newTop=0;

    if (h<window.getHeight()-f.offsetHeight) newTop = (window.getHeight()-f.offsetHeight);
    else newTop = (h+50);

    while (newTop%176!=0) newTop++; //make sure the background fits the footer.

    if (!growOnly || f.style.top<newTop) f.style.top = newTop+"px";
}
window.addEvent('domready', setFooter).addEvent('resize', setFooter).addEvent('load', setFooter);

//Method for switching between player views
if ($E("#playerInfoSelect")) {
    $E("#playerInfoSelect").addEvent("change",function(ev) {
        $ES("#login_top p").each(function(item){item.addClass("hide");});
        $E("#player_"+this.value).removeClass("hide");
    });
    $E("#player_"+$E("#playerInfoSelect").value).removeClass("hide");
}

//Functions for ajax loading
function ajaxLoader(item) {
    $ES(".content", $(item)).each(function(item){item.addClass("hide")});
    $ES(".ajaxLoad",$(item)).each(function(item){item.removeClass("hide")});
    setFooter();
}
function ajaxLoaderDone(item) {
    $ES(".content", $(item)).each(function(item){item.removeClass("hide")});
    $ES(".ajaxLoad",$(item)).each(function(item){item.addClass("hide")});
    setFooter();
}

//Script for adding borders to the thBorder elements. Done by js to keep markup clean
var doThBorder = function(item) {
    var center = new Element("div",{'class':'thBorderCenter'});
    var container = new Element("div").adopt(
        new Element("div",{'class':'thBorderTop'}).adopt(new Element("div",{'class':'thBorderTopRight'}),new Element("div",{'class':'thBorderTopLeft'})), new Element("div",{'class':'thBorderLeft'}).adopt(new Element("div",{'class':'thBorderRight'}).adopt(center)), new Element("div",{'class':'thBorderBottom'}).adopt(new Element("div",{'class':'thBorderBottomLeft'}),new Element("div",{'class':'thBorderBottomRight'}))
    );

    //Make container hide rather than inner item
    if (item.hasClass("hide")) container.addClass("hide");
    item.removeClass("hide")

    //Replace with border
    item.replaceWith(container);
    center.adopt(item);

    //Fix ids
    var id=item.id;
    item.id = id+"_old";
    container.id = id;
}
$ES(".thBorder, fieldset").each(doThBorder);

//Script for enabling tooltips
$ES(".popup").each(function(item) {
    new Tips(item,{'className':'popup'});
});

//Remove all empty textnodes - They shouldnt be present anyways
var removeEmptyTextNodes = function(item) {
    for (var i = 0; i < item.childNodes.length; i++) {
        var node = item.childNodes[i];
        if (node.nodeType == 3) {
            if (!/\S/.test(node.nodeValue)) {
                node.parentNode.removeChild(node);
                i--;
            }
        } else removeEmptyTextNodes(node);
    }
}
removeEmptyTextNodes(document.getElementById("site_item"));

//Place the footer when all this is done (make sure no last change made it be placed wrong..
setTimeout('setFooter();',2000);
