/* 
 *  Copyright 2010 Albert Amengual.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

function loadScript(url,callback) {
    var head = document.getElementsByTagName("head")[0];
    var scripts = head.getElementsByTagName("script");
    for (var i = 0; i < scripts.length; i++) {
        var src = scripts[i].getAttribute("src");
        if (src == url && typeof(callback) == "function") {
            callback();
            return;
        }
    }
    
    var script = document.createElement("script");
    script.src = url;
    script.type="text/javascript";
    head.appendChild(script);
    //IE
    script.onreadystatechange = function () {
        if ((script.readyState == 'complete' || script.readyState == 'loaded') && typeof(callback) == "function") {
            callback();
        }
    }
    // Other browsers
    if (typeof(callback) == "function") {
        script.onload = function () {
            callback();
        }
    }
}

var recentHash = "";
function ajaxUpdate(container, url, saveState) {
    
    $(container).innerHTML = "<div><img src='images/ajax-loader.gif' alt='' style='position: relative; top: 156px; left: 322px;'/></div>";

    new Ajax.Updater(container,url,{
        evalScripts:true
    });

    if(typeof(saveState) == "undefined") saveState = true;
    
    if (saveState) {
        var newState = container + ":" + url.substring(0,url.indexOf('.'));

        var idx = url.indexOf('?');
        if(idx >= 0) {
            var params = url.substring(idx+1);
            var tokens = params.split('&');
            for (var i = 0; i < tokens.length; i++) {
                var pos = tokens[i].indexOf('=');
                newState += ":" + tokens[i].substring(0,pos);
                newState += ":" + tokens[i].substring(pos+1);
            }
        }
    
        window.location.hash = newState;
        recentHash = '#' + newState;
    }
}

var select = null;
function clicked(e) {
    e = $(e);
    if (select) {
        $(select.parentNode).removeClassName("select");
    }
    if (e) $(e.parentNode).addClassName("select");
    select = e;
}

function initialiseStateFromURL() {
    if (window.location.hash==recentHash) {
        return; // Nothing's changed since last polled.
    }
    recentHash = window.location.hash;
    // URL has changed, update the UI accordingly.
    var state = window.location.hash.substring(1); // remove '#'

    var tokens = state.split(":");

    var url = tokens[1] + ".do?";
    for ( var i = 2; i < tokens.length; i+=2 )
    {
        url += tokens[i] + "=" + tokens[i+1] + "&";
    }

    $(tokens[0]).innerHTML = "<div><img src='images/ajax-loader.gif' alt='' style='position: relative; top: 156px; left: 322px;'/></div>";

    new Ajax.Updater(tokens[0],url,{
        evalScripts:true
    });

    clicked(tokens[1]+"-link");
}

function submitAjaxForm(form,container,url,saveState) {
    var params = "?";
    params += processParams(form);
    if(typeof(saveState) == "undefined") saveState = true;
    ajaxUpdate(container, url+params, saveState);
}

function processParams(form) {
    var params = "";
    for (var i=0; i<form.childNodes.length; i++) {
        if (form.childNodes[i].tagName == "FIELDSET") {
            params += processParams(form.childNodes[i]);
        } else if (form.childNodes[i].tagName == "INPUT") {
            if (form.childNodes[i].type == "text") {
                params += form.childNodes[i].name + "=" + escape(form.childNodes[i].value) + "&";
            } else if (form.childNodes[i].type == "checkbox") {
                if (form.childNodes[i].checked) {
                    params += form.childNodes[i].name + "=" + form.childNodes[i].value + "&";
                } else {
                    params += form.childNodes[i].name + "=&";
                }
            } else if (form.childNodes[i].type == "radio") {
                if (form.childNodes[i].checked) {
                    params += form.childNodes[i].name + "=" + form.childNodes[i].value + "&";
                }
            }
        } else if (form.childNodes[i].tagName == "SELECT") {
            var sel = form.childNodes[i];
            params += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
        }
    }
    
    return params;
}

function getStyle(el,styleProp)
{
    var x = el;
    var y;
    if (x.currentStyle)
        y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}
