var undefined;

function go(url) {
    window.location = url;
}

function refresh() {
    window.location = window.location;
}

function go_back() {
    history.back();
}

function post(url, data) {
    var f = $('post-form');
    f.action = url;
    f.submit();
}

function fsubmit(id) {
    $(id).submit();
}

function insert_after(newElement, targetElement) {
    var parent = targetElement.parentNode;
    if (parent.lastChild == targetElement) {
        parent.appendChild(newElement);
    }
    else {
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

//FIXME: it's not quite effective
function uniq(arr) {
    var unique = [];
    arr.each(function(l) { if(!unique.include(l)) { unique[unique.length] = l; }});
    return $A(unique);
}

var _linit = 0;
var _layingout = 0;

/*-----------------------------------------------------------------------------------------------*/

var DEBUG = 1;

function TRACE(msg) {
    if(DEBUG) alert(msg);
}

function add_load_handler( f ) {
    Event.observe( window, 'load', f );
}

var utf8 = {
    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

var SPINNER;
Try.these( function() {
    SPINNER = '<img src="' + STATIC_URL + 'images/spinner.gif" title="loading..." />';
});

var AJAX_OPTIONS = {
    onException: function(r,ex) {
        alert("Erorr: " + ex);
    }
};

function invoke_later( f ) {
    setTimeout( f, 1 );
}

function dmerge( d1, d2 ) {
    return ($H(d1).merge($H(d2))).toObject();
}

function dict(d) {
    return $H(d).toObject();
}

// Explorer needs this wrapper
function make_spinner(e, label) {
    Element.makeSpinner($(e), label);
}

Element.addMethods({
    // Creates a spinner, inserts it after the element and hides the element
    makeSpinner: function(element, label) {
        if( label === undefined ) label = "Loading...";
        var span = '<span class="spinner">' + SPINNER + "&nbsp;" + label + '</span>';
        var spinner = element.insert({after:span}).next();
        element.hide();
        return {
            stop: function() {
                element.show();
                spinner.remove();
            }
        }
    },
    // Inserts a spinner into the element replacing the cold content
    insertSpinner: function(element, label) {
        if( label === undefined ) label = "Loading...";
        element.update('<span class="spinner">' + SPINNER + "&nbsp;" + label + '</span>');
        var spinner = element.down('.spinner');
        return {
            stop: function() {
                spinner.remove();
            }
        }
    },
    remoteUpdate: function(element, url, options) {
        element = $(element);
        if(options.spinner) {
            element.insertSpinner(options.spinnerMessage||'');
        }
        new Ajax.Updater(element, url, options);
        return element;
    },
    setDisabled: function(element, disable) {
        if(disable === undefined || disable) {
            element.addClassName('disabled');
            if(element.nodeName.toLowerCase() == 'input') {
                element.setAttribute('disabled', 'disabled');
            }
        }
        else {
            element.removeClassName('disabled');
            if(element.nodeName.toLowerCase() == 'input') {
                element.removeAttribute('disabled');
            }
        }
    }
});

function call_home( url, parameters, success, options ) {
    if( options == null ) options = {};
    var call = dmerge(AJAX_OPTIONS, {
        parameters : dict(parameters),
        asynchronous : Boolean(options['async']),
        onSuccess : function(r) {
            var result = r.responseText;
            if( ! options['noeval'] ) {
                result = eval("(" + r.responseText + ")");
            }
            success( result );
        }
    });
    new Ajax.Request( url, call );
}

function ajax_update( element, url, parameters, success ) {
    element = $(element);
    element.update(SPINNER);
    new Ajax.Updater( element, url, dmerge(AJAX_OPTIONS, {
        parameters : dict(parameters),
        onSuccess : function( t ) {
            if( success ) { success( t.responseText, t.responseJSON ); }
        }
    }));
    return element;
}

function ajax_call( url, parameters, success, spinner ) {
    new Ajax.Request( url, dmerge( AJAX_OPTIONS, {
        parameters : dict(parameters),
        onSuccess : function( t ) {
            success( t.responseText, t.responseJSON );
        },
        onLoading : function() {
            if( spinner ) {
                $(spinner).show();
            }
        },
        onComplete : function() {
            if( spinner ) {
                $(spinner).hide();
            }
        }
    }));
}

//FIXME: replace this with call_home_text
function call_home_for_text( url, parameters, success ) {
    return call_home( url, parameters, success, {'noeval':1} );
}

var _ldefs = [];
var _linit = 0;
var _layingout = 0;

function layout( id, side, to_id, to_side, distance ) {
    _ldefs[ _ldefs.length ] = {
        'id':id, 'side':side, 'to_id':to_id, 'to_side':to_side, 'dist':distance
    };
}

function do_layout(af) {
    setTimeout( function() {
        var body = document.getElementsByTagName("body")[0];
        _layingout = 1;
        try {
            _ldefs.each( function(l) {
                if( l == null ) return;
                var to = $(l['to_id']);
                var tos = l['to_side'];
                var pos = 0;
                if( tos == 'top' ) {
                    pos = to.offsetTop;
                }
                else if( tos == 'bottom' ) {
                    pos = to.offsetTop + to.offsetHeight;
                }
                else if( tos == 'left' ) {
                    pos = to.offsetLeft;
                }
                else if( tos == 'right' ) {
                    pos = to.offsetLeft + to.offsetWidth;
                }
                var o = $(l['id']);
                var off = 0;
                var s = l['side'];
                if( s == 'bottom' ) {
                    off = o.offsetTop;
                    s = 'height';
                }
                else if( s == 'right' ) {
                    off = o.offsetLeft;
                    s = 'width';
                }
                var n = '' + ((pos + l['dist']) - off) + 'px';
                o.style[s] = n;
            } );
            if(af != null) {
                af();
            }
        }
        catch( e ) {
            alert("Error: " + e);
        }
        _layingout = 0;
    }, 100 );
}

function do_init_layout() {
    if( !_linit ) {
        Event.observe( document, 'onresize', function() { do_layout(); } );
        _linit = 1;
    }
}


// tables -------------------------

function atr(id) {
    var tr = $(id);
    if( tr ) {
        var table = tr.up();
        var ts = table.select(".tr-selected");
        $A(ts).each( function(t) {
            t.removeClassName('tr-selected');
        });
        tr.addClassName('tr-selected');
    }
    return 1;
}

function scr(id) {
    var e = $(id);
    if( e ) e.scrollIntoView(false);
}

function traverse( node, f ) {
    if( ! f(node) ) return;
    var cn = node.childNodes;
    for( var i=cn.length-1; i >= 0; i-- ) {
        var n = cn[i];
        traverse( n, f );
    }
}

// cookies (taken from http://www.quirksmode.org/js/cookies.html)

function create_cookie(name,value,days) {
    if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function read_cookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function erase_cookie(name) {
    create_cookie(name,"",-1);
}

//Eolas fix
function docwrite(what) {
  document.write(what);
}

function quote(s) {
    return s.replace("'", "\\'");
}

function get_select_value( select ) {
    return select.options[ select.selectedIndex ].value;
}

function activate_postbacks( form, prefix, fx ) {
    if( form != undefined ) {
        $A( form.getElementsByTagName('select') ).each( function(s) {
            if( s.id != undefined && s.id.indexOf(prefix) == 0 ) {
                Event.observe(s, 'change', function() {
                    if( fx )
                        fx(form, s);
                    else
                        form.submit();
                });
            }
        });
        $A( form.getElementsByTagName('input') ).each( function(s) {
            if( s.id != undefined && s.type == 'radio' && s.id.indexOf(prefix) == 0 ) {
                Event.observe(s, 'click', function() {
                    if( s.checked ) {
                        if( fx )
                            fx(form, s);
                        else
                            form.submit();
                    }
                });
            }
        });
    }
}

Postback = {
    activate: function(elements) {
        $A(elements).each(function(element){
            var event = 'click';
            var name = element.tagName.toLowerCase();
            var type = element.type.toLowerCase();
            if(name == 'select' || (name == 'input' && (type == 'text' || type == 'checkbox'))) {
                event = 'change';
            }
            element.observe(event, function(){ element.form.submit(); });
        });
    },
    activateForm: function(id){
        Postback.activate($(id).select('select', 'input[type="radio"]', 'input[type="checkbox"]'));
    },
    init: function(){
        Postback.activate($$('.postback select',
                             '.postback input[type="radio"]',
                             '.postback input[type="checkbox"]'));
    }
}

// Mozilla innerText patch

Try.these( function() {
    if((typeof HTMLElement != undefined) && (HTMLElement.prototype.__defineGetter__ != undefined)) {
        HTMLElement.prototype.__defineGetter__("innerText", function () {
            var r = this.ownerDocument.createRange();
            r.selectNodeContents(this);
            return r.toString();
        });
    }
});
