/*
 * Generalized JavaScript functions.  Feel free to utilize the code in this
 * file as you wish, but attribution is always welcome (in other words, please
 * toss us a link if this code has helped you, or you are using it.)
*/
function $(id) {
    return document.getElementById(id) ? document.getElementById(id) : false;
}
var setScript = new Image(); setScript.src = "/Services/User/Script/Enable";
function XmlRequest() {}
XmlRequest.create = function() {
    if ( typeof ActiveXObject != "undefined" ) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP")
        } catch(a) { }
    }
    if ( typeof XMLHttpRequest != "undefined" ) {
        return new XMLHttpRequest()
    }
    return null;
}

function fadeTimeout( obj, start, timeout ) {
    obj.style.opacity    = "1.0";
    obj.style.MozOpacity = "1.0";
    obj.style.filter     = "alpha(opacity=100)";

    obj.timeout = setTimeout(
        function() { fadeStep(obj, timeout, 0.07); }, start);
}

function fadeStep( obj, timeout, inc ) {
    if ( parseFloat(obj.style.opacity) >= 0.0 ) {
        var newOpacity = parseFloat( obj.style.opacity || 1 );
        newOpacity -= inc;
        obj.style.opacity    = newOpacity;
        obj.style.MozOpacity = newOpacity;
        obj.style.filter = "alpha(opacity=" + parseInt(newOpacity*100) + ")";
        obj.timeout = setTimeout(
            function() { fadeStep(obj, timeout, inc); }, timeout );
    } else {
        obj.style.display = "none";
        obj.timeout = null;
    }
}


var lastUsedzIndex = 5000;
function createFloatingWindow(container, width, height) {
    var w = document.createElement("div");
    w.style.zIndex     = lastUsedzIndex++;
    w.style.position   = "absolute";
    if ( width )
        w.style.width = width;
    if ( height ) 
        w.style.height = height;
    return w;
}


function addClass( element, name ) {
    if ( !element ) return;
    var list = element.className.split(" ");
    for ( var i = 0; i < list[i]; ) {
        if ( list[i] == name )
            return;
    }
    list.push(name);
    element.className = list.join(" ");
}

function delClass( element, name ) {
    if ( !element ) return;
    var list = element.className.split(" ");
    var list2 = new Array();
    for ( var i = 0; i < list[i]; ) {
        if ( list[i] != name )
            list2.push(list[i]);
    }
    element.className = list2.join(" ");
}

function linkTracker(pk1) {
    return true;
}

var loginPop; var loginContent;
function loginPopup( pObject ) {
   if ( !loginPop ) {
        var ctn  = document.createElement("div");
        var form = document.createElement("form");
        form.method   = "post"; form.action = "#";
        form.id       = "loginPopupForm";
        ctn.style.whiteSpace = "nowrap";
        ctn.appendChild(form);
        if ( !pObject ) { pObject = $("userControl"); }
        loginPop      = createFloatingWindow(pObject);
        loginPop.id   = "loginPopupWindow";
        var username  = document.createElement("input");
        username.type = "text"; username.size = "15";
        username.id   = "loginPopUsername"; username.name = "login";
        var label     = document.createElement("label");
        label.setAttribute("for", "loginPopUsername");
        label.appendChild(document.createTextNode("Username: "));
        form.appendChild(label);
        form.appendChild(username);
        form.appendChild(document.createElement("br"));
        var password  = document.createElement("input");
        password.type = "password"; password.size = "15";
        password.id   = "loginPopPassword"; password.name = "password";
        label     = document.createElement("label");
        label.setAttribute("for", "loginPopPassword");
        label.appendChild(document.createTextNode("Password: "));
        form.appendChild(label);
        form.appendChild(password);
        var p = document.createElement("p");
        p.style.textAlign = "center";
        var b = document.createElement("input");
        b.type = "submit"; b.value = "Login";
        p.appendChild(b);
        var b = document.createElement("input");
        b.type = "button"; b.value = "Cancel";
        addEvent(b, "click", hideLoginPopup, false);
        p.appendChild(b);
        form.appendChild(p);
       
        loginPop.style.position   = "absolute";
        loginPop.style.right      = "30px";
        loginPop.style.background = "#fff";
        loginPop.style.padding    = "1ex";
        loginPop.style.width      = "20em";
        loginPop.style.border     = "2px solid black";

        loginPop.appendChild(ctn);
        loginPop.style.top = pObject.offsetTop + "px"; 
        document.body.appendChild(loginPop);
        loginContent = loginPop.innerHTML;
    } else {
        loginPop.innerHTML = loginContent;
    }
    addEvent($("loginPopupForm"), 'submit', processLogin, false);
    loginPop.style.opacity    = "1.0";
    loginPop.style.MozOpacity = "1.0";
    loginPop.style.filter     = "alpha(opacity=100)";

    loginPop.style.display = "";
    return false;
}

function hideLoginPopup() {
    loginPop.style.display = "none";
}

function processLogin(e) {
    knackerEvent(e);
    var login    = $("loginPopUsername").value;
    var password = $("loginPopPassword").value;
    var request  = XmlRequest.create();
    request.open('POST', '/Services/User/Login', true);
    request.setRequestHeader('Content-Type',
        'application/x-www-form-urlencoded');
    var okImage = new Image();
    okImage.src   = "/images/bgbox/frame_logo.png";
    okImage.align = "left";
    okImage.alt   = "";
    loginPop.innerHTML = "";
    loginPop.appendChild(okImage);
    var text = document.createElement("h3");
    text.style.textAlign = "center";
    text.appendChild(document.createTextNode("Please wait while we authenticate you."));
    var loadingImage = new Image();
    loadingImage.src = "/images/loading.gif";
    loadingImage.alt = "";
    loadingImage.align = "center";
    loginPop.appendChild(text);
    var ctn = document.createElement("p"); ctn.style.textAlign = "center";
    ctn.appendChild(loadingImage);
    loginPop.appendChild(ctn);
    request.send('login=' + login + '&' + 'password=' + password);
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            loginResponse(request.responseXML);
        }
    }
    return false;
}

function loginResponse( response ) {
    var rsp = response.getElementsByTagName("response");
    var okImage = new Image();
    okImage.src   = "/images/bgbox/frame_logo.png";
    okImage.align = "left";
    okImage.alt   = "";
    loginPop.innerHTML = "";
    loginPop.appendChild(okImage);
    var text = document.createElement("h3");
    text.style.textAlign = "center";
    if ( rsp && rsp[0] && rsp[0].getAttribute("status") == "ok" ) {
        var username = response.getElementsByTagName("login");
        $("userControl").innerHTML = "<b><a href=\"/My/Profile\">My Profile :: Logged in as " + username[0].firstChild.nodeValue + "</a></b> | <a href=\"/Login?expr=1\">Logout</a>";
        text.appendChild(document.createTextNode("Welcome back, " + username[0].firstChild.nodeValue));
    } else {
        text.appendChild(document.createTextNode("Sorry, you could not be logged in.  Please try again."));
    }
    loginPop.appendChild(text);
    fadeTimeout(loginPop, 1000, 200);
}

/* 
 * Cross-browser event handling, by Scott Andrew
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}

/* 
 * Kills an event's propagation and default action.
 * Taken from http://www.yourhtmlsource.com (and I love the name)
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

var tagEditor;
function editTags(profile, key) {
    var tagWin  = document.getElementById("tags");
    var tagList = document.getElementById("tagList");

    if ( tagEditor ) {
        tagEditor.getTags();
        tagEditor.openWindow();
    } else {
        tagEditor = new TagEditor(tagWin, profile, key);
    }

    if ( tagList ) {
        tagEditor.updateCallback = function( response ) {
            var list = new Array();
            var tags = response.responseXML.getElementsByTagName("tag");
            for ( var i = 0; i < tags.length; i++ ) {
                if ( tags[i].getAttribute("set") ) {
                    list.push(tags[i].firstChild.nodeValue);
                }
            }
            tagList.innerHTML = list.join(", ");
        }
    }
}

function TagEditor(container, profile, key) {
    if ( !container )
        return false;
    this.container = container;
    this.profile   = profile;
    this.updateKey = key;
    this.initialize();
}

TagEditor.prototype.initialize = function() {
    this.setKeys = new Array();

    this.win = createFloatingWindow(this.container);
    this.win.style.border     = "2px solid #000";
    this.win.style.background = "#fff";
    this.win.style.padding    = "1ex";
    this.win.style.top   = "4em";
    this.win.style.width = "30em";
    this.win.appendChild(document.createTextNode("Please wait..."));
    this.loadingImg = document.createElement("img");
    this.loadingImg.src = "/images/loading.gif";
    this.win.appendChild(this.loadingImg);
    this.container.parentNode.appendChild(this.win);
    this.getTags();

}

TagEditor.prototype.openWindow = function() {
    this.win.style.display = "";
}

TagEditor.prototype.closeWindow = function() {
    this.win.style.display = "none";
}

TagEditor.prototype.getTags = function() {
    var request = XmlRequest.create();
    var t = this;
    request.open('GET', '/Services/Tags/' + this.profile, true);
    request.onreadystatechange = function() {
        if ( request.readyState == 4 ) {
            clearTimeout(t.timeoutTimer);
            t.drawWindow( request.responseXML );
        }
    }
    this.timeoutTimer = setTimeout( function() { t.commError() }, 2000 );
    request.send(null);
}

TagEditor.prototype.commError = function() {
    this.win.innerHTML = "";

    var errorMessage = document.createElement("p");
    errorMessage.className = "error";
    errorMessage.appendChild(document.createTextNode("Sorry, there was a communications error with the server, please try again later."));
    this.win.appendChild(errorMessage);

    var controls = document.createElement("p");
    controls.className   = "center";
    controls.style.clear = "both";
   
    var btn  = document.createElement("input");
    btn.style.margin = "0 1em";
    btn.type = "button";
    btn.value = "Cancel";
    var t = this;
    addEvent(btn, "click", function() { t.closeWindow(); }, false);
    controls.appendChild(btn);
    this.win.appendChild(controls);

    if ( !this.closeButton ) {
        this.closeButton = document.createElement("img");
        setCursor(this.closeButton,"pointer");
        this.closeButton.src = "/images/close.gif";
        this.closeButton.style.position = "absolute";
        this.closeButton.style.width  = "14px";
        this.closeButton.style.height = "13px";
        this.closeButton.style.top    = "14px";
        this.closeButton.style.left = (this.win.offsetWidth - 28) + "px";
        addEvent(this.closeButton, "mousedown", function() { t.closeWindow() }, false);
    }
    this.win.appendChild(this.closeButton);

}

TagEditor.prototype.updateValue = function( obj ) {
    if ( obj && this.setKeys ) {
        if ( this.setKeys[obj.name] && !obj.checked ) {
            this.setKeys[obj.name] = false;
            obj.parentNode.style.fontWeight = "normal";
        } else {
            this.setKeys[obj.name] = true;
            obj.parentNode.style.fontWeight = "bold";
        }
    }
}

function getCheckboxClosure(p, func, obj) {
    return function() { func.call(p, obj) };
}

TagEditor.prototype.drawWindow = function( response ) {
    var t = this;
    this.win.innerHTML = "";
    //var form = document.createElement("form");
    var list = document.createElement("ul");
    list.style.width  = "100%";
    list.style.padding = "0";
    list.style.margin  = "0";
    var status = response.getElementsByTagName("response");
    if ( !status[0] || status[0].getAttribute("status") != "ok" ) {
        return this.commError();
    }
    var tags = response.getElementsByTagName("tag");
    if ( tags && tags.length > 0 ) {
        for ( var i = 0; i < tags.length; i++ ) {
            var item = document.createElement("li");
            item.style.cssFloat      = "left";
            item.style.display       = "inline";
            item.style.listStyleType = "none";
            item.style.width         = "30%";
            var check   = document.createElement("input");
            check.type  = "checkbox";
            check.id    = "check_" + tags[i].getAttribute("pk1");
            check.name  = tags[i].getAttribute("pk1");
            check.value = "1";
            if ( tags[i].getAttribute("set") ) {
                this.setKeys[check.name] = true;
                check.checked            = true;
                item.style.fontWeight    = "bold";
            }

            check.onchange = getCheckboxClosure(this, this.updateValue, check);

            item.appendChild(check);
            try {
                var label = document.createElement("label");
                label.setAttribute("for", check.id);
                label.appendChild(document.createTextNode(tags[i].firstChild.nodeValue));
                item.appendChild(label);
                list.appendChild(item);
            } catch(e) { alert("Can't load item: " + i + "\n" + e); }
        }
        this.win.appendChild(list);
        var controls = document.createElement("p");
        controls.className   = "center";
        controls.style.clear = "both";
        
        var btn  = document.createElement("input");
        btn.style.margin = "0 1em";
        btn.type = "button";
        btn.value = "Cancel";
        addEvent(btn, "click", function() { t.closeWindow(); }, false);
        controls.appendChild(btn);

        btn  = document.createElement("input");
        btn.style.margin = "0 1em";
        btn.type = "button";
        btn.value = "Save";
        controls.appendChild(btn);
        addEvent(btn, "click", function() { t.setTags(); }, false);
        this.win.appendChild(controls);
    }
    if ( !this.closeButton ) {
        this.closeButton = document.createElement("img");
        setCursor(this.closeButton,"pointer");
        this.closeButton.src = "/images/close.gif";
        this.closeButton.style.position = "absolute";
        this.closeButton.style.width  = "14px";
        this.closeButton.style.height = "13px";
        this.closeButton.style.top    = "14px";
        this.closeButton.style.left = (this.win.offsetWidth - 28) + "px";
        addEvent(this.closeButton, "mousedown", function() {t.closeWindow()}, false);
    }
    this.win.appendChild(this.closeButton);
}


TagEditor.prototype.setTags = function() {
    var newKeys = new Array();
    for ( var i in this.setKeys ) {
        if ( this.setKeys[i] == true )
            newKeys.push(i);
    }
    var updateString = newKeys.join(",");
    if ( updateString.length > 0 ) {
        var request = XmlRequest.create();
        var t = this;
        request.open('GET', '/Services/Tags/' + this.profile + '/Update/' + updateString, true);
        request.onreadystatechange = function() {
            if ( request.readyState == 4 ) {
                if ( t.updateCallback ) {
                    t.updateCallback(request);
                }
                t.closeWindow();
            }
        }
        request.send(null);
    } else {
        alert("You must specify at least one tag");
    }
}

