// for checking if we've been srced
var caspian_util = {};

/*
Array.prototype.clone = function () {
    var a = new Array(); 
    for (var property in this) {
        a[property] = typeof (this[property]) == 'object' ?
        this[property].clone() : this[property]
     } 
    return a;
}
*/

var __UTIL__saveRows = null;

function resizeFrameHeight(frameObj, newHeight) {
    var p = frameObj.parent;
    // e.g. '50,*,30', possibly contains spaces
    var r = p.document.body.rows;
    var frameIndex;

    for (var i=0; i<p.frames.length; i++) {
        if (p.frames[i] == frameObj) { 
            frameIndex = i;
            break;
        } else {
            //return;
            continue;
        }
    }

    //is this right?
    var re = / +/g;
    r.replace(re,"");
    var a = r.split(",");

    var oldHeight = a[frameIndex];
    //a[frameIndex] *= coef;
    a[frameIndex] = newHeight;
    var newRows = a.join(",");
    //alert(newRows);

    p.document.body.rows = newRows;
}


function show_e(e, d) {
    if (!d) d='block';
    e.style.display = d;
}

function showOnlyFrame(frameObj) {
    /*
    var f = frameObj.parent.frames;
    var d;
    var b;
    for (i in f) {
        if (f[i] != frameObj) {
            d = f[i].document;
            if (d) { 
                b = d.body;
                if (b) {
                    __UTIL__saveContent[f[i]] = b.innerHTML;
                    b.innerHTML = '';
                }
            }
        }
    }
    */

    var p = frameObj.parent;
    // e.g. '50,*,30', possibly contains spaces
    var r = p.document.body.rows;

    __UTIL__saveRows = r;

    //is this right?
    var re = / +/g;
    r.replace(re,"");
    var a = r.split(",");

    var frameIndex;

    for (var i=0; i<p.frames.length; i++) {
        if (p.frames[i] == frameObj) { 
        } else {
            a[i] = 1;
        }
    }

    var newRows = a.join(",");

    p.document.body.rows = newRows;
}

// takes arg cuz we gotta know parent
function restoreFrames(frameObj) {
    frameObj.parent.document.body.rows = __UTIL__saveRows;
}
                
function _appear(id) {
    document.getElementById(id).style.visibility = 'visible';
    document.getElementById(id).style.opacity = 1;
}

// document is in context of caller
function toggle(id) {
    var i = document.getElementById(id);
    var d = i.style.display;
    alert(d);
    if (d == "none") appear(i);
    else if (d == "block") fade(i);
}

// document is in context of caller
function toggle_fast(id) {
    var i = document.getElementById(id);
    var d = i.style.display;
    if (d == "none") i.style.display = 'block';
    else if (d == "block") i.style.display = 'none';
}

// document is in context of caller
function hide(id) {
    var i = document.getElementById(id);
    var d = i.style.display;
    i.style.display = 'none';
}

function hide_e (e) {
    var d = e.style.display;
    e.style.display = 'none';
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}


function ajaxFillElement(element, url, userCallback) {
    
    var content;

    var callback = function(_content) {
        content = _content;
    };

    ajaxSimple(callback, url);

    // 20 secs timeout
    var WAIT = 100;
    var NUM_CYCLES = 200;
    var cycle = 0;
    var timerID;
    var checkResponse = function() {

        if (content == undefined) {
            if (++cycle >= NUM_CYCLES) {
                alert("Get page timed out. Slow network maybe? Please click reload. (Url was " + url + ")");
                clearInterval(timerID);
            }
        }
        else {

            clearInterval(timerID);
            element.innerHTML = content;
            parseScripts(element);
            if (userCallback) userCallback();

        }
    };

    timerID = setInterval(checkResponse, WAIT);

}

function ajaxSimple(callback, url) {
    //if (! top.globals) alert ("util.js: top.globals is null");
    //log("waitingForAjax->1");
    //top.globals.waitingForAjax = 1;
    var xhr;
    if (window.XMLHttpRequest) { 
        xhr = new XMLHttpRequest();     // Firefox, Safari, ...
    } 
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer 
    } 
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {

            if (xhr.status != 200) {
                alert("Error retrieving page '" + url + "': status was " +
                xhr.status);
            }

/*
            var f = function() {
                if (top.test_hang) {
                    if (! getTestHangMsgPrinted() ) {
                        log("simulating hang, blocking ajax");
                        testHangMsgPrinted = 1;
                    }
                    setTimeout(f, 50);
                }
                else {
                    //clearTimeout(jobTestHang);
                    testHangMsgPrinted = 0;
                    log("waitingForAjax->0");
                    top.globals.waitingForAjax = 0;
                    callback(xhr.responseText);
                }
            };
*/
            var f = function() {
                callback(xhr.responseText);
            }

            setTimeout(f, 50);

        } else {
        }
    };

    xhr.open('GET', url, true);                  
    // false unable to retrieve some pages (in firefox, ok in opera)
    //xhr.open('GET', url, false);                  
    xhr.send(null); 

}

function parseScripts(_parent) {
    var d = _parent.getElementsByTagName("script");
    for (var i = 0, l = d.length; i < l; i++) {

        var newScript = document.createElement('script');
        newScript.type = "text/javascript";
        var t;
        var foundSomething = 0;
        if (t = d[i].text) {
            foundSomething = 1;
            newScript.text = t;
        }
        if (t = d[i].src) {
            foundSomething = 1;
            newScript.src = t;
        }

        // have to remove it too??? or else the source is doubled.
        // which actually isn't terrible -- the first part won't do
        // anything. 

        _parent.appendChild(newScript);
    }
}

/*
Credits: 
        Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url] 
        Function by Jens Anders Bakke, webfreak.no 
*/  
function $get(key,url){  
    if(arguments.length < 2) url =location.href;  
    if(arguments.length > 0 && key != ""){  
        if(key == "#"){  
            var regex = new RegExp("[#]([^$]*)");  
        } else if(key == "?"){  
            var regex = new RegExp("[?]([^#$]*)");  
        } else {  
            var regex = new RegExp("[?&]"+key+"=([^&#]*)");  
        }  
        var results = regex.exec(url);  
        return (results == null )? "" : results[1];  
    } else {  
        url = url.split("?");  
        var results = {};  
            if(url.length > 1){  
                url = url[1].split("#");  
                if(url.length > 1) results["hash"] = url[1];  
                url[0].split("&").each(function(item,index){  
                    item = item.split("=");  
                    results[item[0]] = item[1];  
                });  
            }  
        return results;  
    }  
}  

function log(s) {
    if (typeof(console) == 'object') {
        console.log(s);
    }
    else if (typeof(opera) == 'object') {
        opera.postError(s);
    }
}

/*
function getMainWindow() {
    //return Cookie.read('mainWindow');
}
*/


function popup(url, param) {
    var width;
    var height;
    if (param) {
        width = param.width;
        height = param.height;
    }
    if (! width) width = 300;
    if (! height) height = 300;
    window.open(
        url,
        "popup", 
        'status=false, resize=true, toolbar=false, scrollbars=false,' + 
        'width=' + width + ',' +
        'height=' + height 
        );
    }


function myScrollTo(win, id) {
    win.scroll(0,$(id).getCoordinates()['top'])
}

// return rand int x := i <= x <= j
function rand(i, j) {
    return Math.floor(Math.random() * (j - i + 1)) + i;
}

