var styler;
var link;
var toReplace=null;
var targetIframe=document.createElement('IFRAME');
targetIframe.id='upload_target';
targetIframe.name='upload_target';
targetIframe.src='';
targetIframe.style.display='none';
targetIframe.addEventListener('load',complexFormHandler,false);
var showHide = {add : addShowHideObj, objs : [], toggle : toggleShowHide, init : showHideInit};

/* getElementsByTagNames is ppk's script. */
function getElementsByTagNames(list,obj) {
    if (!obj) var obj = document;
    var tagNames = list.split(',');
    var resultArray = [];
    for (var i=0;i<tagNames.length;i++) {
        var tags = obj.getElementsByTagName(tagNames[i]);
        for (var j=0;j<tags.length;j++) {
            resultArray.push(tags[j]);
        }
    }
    var testNode = resultArray[0];
    if (!testNode) return [];
    if (testNode.sourceIndex) {
        resultArray.sort(function (a,b) {
                return a.sourceIndex - b.sourceIndex;
        });
    }
    else if (testNode.compareDocumentPosition) {
        resultArray.sort(function (a,b) {
                return 3 - (a.compareDocumentPosition(b) & 6);
        });
    }
    return resultArray;
}

//Some funtions to manage element classes.
function toggleClass(ele,class1,class2)
{
    if(hasClass(ele,class1))
    {
        removeClass(ele,class1);
        addClass(ele,class2);
    } else {
        removeClass(ele,class2);
        addClass(ele,class1);
    }
}
function hasClass(ele,val)
{
    var classes=ele.className.split(' ');
    for(ci=0;ci<classes.length;ci++)
    {
        if(classes[ci]==val) return true;
    }
    return false;
}
function removeClass(ele,val)
{
    var classes=ele.className.split(' ');
    for(ci=0;ci<classes.length;ci++)
    {
        if(classes[ci]==val) classes[ci]=null;
    }
    ele.className=classes.join(' ').replace(/\s+/,' ');
}
function addClass(ele,val)
{
    var classes=ele.className.split(' ');
    for(ci=0;ci<classes.length;ci++)
    {
        if(classes[ci]==val) return;
    }
    classes.push(val);
    ele.className=classes.join(' ');
}

function changeStyles()
{
    for(i in toReplace)
    {
        addClass(toReplace[i].ele,'hidden');
    }
    document.getElementById('mainStyle').href='/styles/'+this.value+'.css';
    document.getElementById('icon').href='/images/look/'+this.value+'/icon.ico';
    
    imgReplace();
    
    var req=new XMLHttpRequest();
    req.open('GET','/globals/setter.html?style='+this.value,true);
    req.send(null);
}

//Simple submission handler.
function simpleFormHandler(req,obj)
{
    document.getElementById(obj.name+'-response').innerHTML=req.responseText;
}

function simpleFormSubmit(e)
{
    e.preventDefault();
    url=this.action;
    postData=postFormData(this);
    request(url,simpleFormHandler,postData,this);
}

//Slightly more complicated form submission
function complexFormHandler(req,obj)
{
    x=targetIframe.parentNode;
    document.getElementById(x.name+'-response').innerHTML=targetIframe.contentDocument.body.innerHTML;

    iframeUnload();
}

function iframeUnload()
{
    //Give Firefox (and other browsers?) time to realize that yes, the iframe
    //is loaded.
    setTimeout(
            function()
            {
                targetIframe.parentNode.removeAttribute('target');
                targetIframe.parentNode.removeChild(targetIframe);
            },
            100
        );
}

function complexFormSubmit()
{
    this.target='upload_target';
    this.appendChild(targetIframe);
}

//Format a form's fields as postData
function postFormData(obj)
{
    var arr=[];
    for(i=0;i<obj.elements.length;i++)
    {
        if(obj.elements[i].name)
	{
            if(obj.elements[i].type=='checkbox')
	    {
	        if(obj.elements[i].checked)
		{
	            arr.push(obj.elements[i].name+'=on');
		} else {
		    arr.push(obj.elements[i].name+'=');
		}
	    } else {
	        arr.push(obj.elements[i].name+'='+escape(obj.elements[i].value));
	    }
	}
    }
    return arr.join('&');
}

//Make a simple HTTPRequest.
function request(url,callback,postData,arg)
{
    var req = new XMLHttpRequest();
    method=(postData) ? 'POST' : 'GET';
    req.open(method,url,true);
    req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
            if (req.readyState !=4) return;
            if (req.status != 200 && req.status!=304) {return;}
            if(arg)
            {
                callback(req,arg);
            } else {
                callback(req);
            }
        }
    if(req.readyState==4) return;
    req.send(postData);
}

function emdec(anchor)
{
    var address;
    var href=anchor.getAttribute('href');
    address = href.replace(/.*con\/tact:([a-z0-9._%-]+)\+([a-z0-9._%-]+)\+([a-z.]+)/i, 'mailto:$1@$2.$3');
    if (href != address) {
        anchor.setAttribute('href',address);
    }
    address=href.replace(/.*con\/join:email.html/, '/email.html?p=join&j=y');
    if (href != address) {
        anchor.setAttribute('href',address);
    }
    address=href.replace(/.*con\/joinout:email.html/, '/email.html?p=joinout&j=y');
    if (href != address) {
        anchor.setAttribute('href',address);
    }
    address=href.replace(/.*con\/leave:email.html/, '/email.html?p=leave&j=y');
    if (href != address) {
        anchor.setAttribute('href',address);
    }
    address=href.replace(/.*con\/leaveout:email.html/, '/email.html?p=leaveout&j=y');
    if (href != address) {
        anchor.setAttribute('href',address);
    }
}

function imgReplace()
{
    if(toReplace===null)
    {
        toReplace=[];
        x=document.getElementsByClassName('replace');
        var span=new RegExp('</?span>','gi');
        for(i=0;i<x.length;i++)
        {
            id='img'+i;
            x[i].setAttribute('imgid',id);
            toReplace[id]={ele : x[i], children : [], alt : x[i].innerHTML.replace(span,'')};
            y=x[i].childNodes;
            for(j=0;j<y.length;j++)
            {
                if(y[j].nodeType==1 || y[j].nodeType==3) toReplace[id].children.push(y[j]);
            }
        }
    }
    
    var replace = document.createElement('img');
    var chars=new RegExp("[ .,!':]*",'gi');
    for (i in toReplace)
    {
        if(toReplace[i].ele.nodeType==1)
        {
            var ptitle=toReplace[i].alt;
            var path=ptitle.toLowerCase().replace(chars,'');
            path='/images/text/'+link+'/'+path+'.png';            
            var y = replace.cloneNode('true');
            y.src = path;
            y.alt = ptitle;
            y.id = i;
            y.onload=function(){
                x=toReplace[this.id].ele.childNodes;
                while(x.length>0)
                {
                    toReplace[this.id].ele.removeChild(x[0]);
                }
                toReplace[this.id].ele.appendChild(this);
                removeClass(toReplace[this.id].ele,'hidden');
            }
            y.onerror = function() {
                x=toReplace[this.id].ele.childNodes;
                while(x.length>0)
                {
                    toReplace[this.id].ele.removeChild(x[0]);
                }
                for(j=0;j<toReplace[this.id].children.length;j++)
                {
                    toReplace[this.id].ele.appendChild(toReplace[this.id].children[j]);
                }
                removeClass(toReplace[this.id].ele,'hidden');
            }
        }
    }
}

function toggleShowHide(id)
{
    obj=showHide.objs[id];
    if(hasClass(obj.toHide,'hidden'))
    {
        removeClass(obj.toHide,'hidden');
        obj.ele.innerHTML=obj.hideText;
    } else {
        addClass(obj.toHide,'hidden');
        obj.ele.innerHTML=obj.showText;
    }
}

function addShowHideObj(id,ele,toHide,hideText,showText)
{
    ele.setAttribute('rel',id);
    showHide.objs[id] = new showHideObj(ele,toHide,hideText,showText);
}
function showHideObj(ele,toHide,hideText,showText)
{
    this.ele=ele;
    this.ele.addEventListener('click',function(e){e.preventDefault();showHide.toggle(this.getAttribute('rel'));},false);
    this.toHide=toHide;
    this.hideText=hideText;
    this.showText=showText;
}
function showHideInit()
{
    for(i in showHide.objs)
    {
        showHide.toggle(i);
    }
}

function oswingInit()
{
    styler.addEventListener('change',changeStyles,false);
    var test = new Image();
    var tmp = new Date();
    var suffix = tmp.getTime();
    test.src = '/images/look/test.gif?'+suffix;
    test.onload = imgReplace;
    var links = document.getElementsByTagName('a');
    for (var i = 0 ; i < links.length ; i++) {
        var h=links[i].getAttribute('href');
        if (h!==null) links[i].onclick = function() {emdec(this);}
    }
}

function init()
{
    if(!document.head) document.head=document.getElementsByTagName('HEAD')[0];
    styler=document.getElementById('styleSelect');
    link = styler.value;
    if(CSSFontFaceRule && document.styleSheets[0].cssRules[0] instanceof CSSFontFaceRule)
    {
        var y = document.head.getElementsByTagName('LINK')[0];
        var x = document.createElement('LINK');
	x.rel='stylesheet';
	x.type='text/css';
	x.href='/styles/'+link+'_font-face.css';
	x.insert(y,'after');
    }
    oswingInit();
    if (typeof preInit=='function') preInit();
    if (typeof manageSlotsInit=='function') manageSlotsInit();
    if (typeof prepareForm=='function') prepareForm();
    if (typeof smailInit=='function') smailInit();
}
addEventListener("DOMContentLoaded",init,false);

//Helper Functions
HTMLElement.prototype.insert = function(node,rel)
{
    if(rel===null) place='before';
    if(!node instanceof HTMLElement)
    {
        console.error(node+' is not a valid HTML element.');
	return false;
    }
    
    if(rel=='before')
    {
        node.parentNode.insertBefore(this,node);
    } else if(rel=='after') {
        node.parentNode.insertBefore(this,node);
        node.parentNode.insertBefore(node,this);
    } else {
        console.error(rel+' is not a valid option.');
	return false;
    }
    return true;
}