var BASE = '';

function setBase(newBase) {

    BASE = newBase;

}

//vars include directories,location,resizable,menubar,toolbar,scrollbars,status
function windowopen(url, width, height, vars) {

    var windowLeft = typeof window.screenX != 'undefined'? window.screenX : window.screenLeft;
    var windowTop = typeof window.screenY != 'undefined' ? window.screenY :window.screenTop;
    var windowWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.documentElement.clientWidth;
    var windowHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.documentElement.clientHeight-22);

    if(width == null) width = windowWidth - 200;
    if(height == null) height = windowHeight - 200;
    if(vars == null) vars = 'resizable,scrollbars';

    vars += ',width=' + width + ',height=' + height;

    if(vars.indexOf('left') == -1) {

        var left = parseInt(windowLeft + ((windowWidth - width) / 2), 10);

        vars += ',left=' + left;

    }

    if(vars.indexOf('top') == -1) {

        var top = parseInt(windowTop + ((windowHeight-height) / 2.5), 10);

        vars += ',top=' + top;

    }

    var currentTime = new Date();

    window.open(url, currentTime.getTime(), vars);

    return false;

}

function getParam(varName, urlToParse) {

    if(urlToParse == null) urlToParse = document.location;

    var toReturn = '';

    var urlHalves = String(urlToParse).split('?');

    if(urlHalves[1]) {
        var urlVars = urlHalves[1].split('&');
        for(i=0; i<=(urlVars.length); i++) {
            if(urlVars[i]){
                var urlVarPair = urlVars[i].split('=');
                if (urlVarPair[0] && urlVarPair[0] == varName) {
                    toReturn = urlVarPair[1];
                }
            }
        }
    }

    return toReturn;

}

function getPart(number, location) {

    if (!location) {
        location = String(document.location);
    }
    location = location.replace(BASE, '');

    var Rs = location.split('/');

    //get rid of the last GET variable if its there
    var last = Rs[Rs.length - 1];
    var split_last = last.split();
    if(split_last[0] == '?') {
        Rs.splice(-1);
    }

    number--;

    if(Rs[number]) {
        return Rs[number];
    } else {
        return '';
    }

}

function redirect(page) {

    document.location.href = page;

    return false;

}

function goBack() {

    history.go(-1);

    return false;

}

function html_entity_decode(s) {
    var t=document.createElement('textarea');
    t.innerHTML = s;
    var v = t.value;
    //t.parentNode.removeChild(t);
    return v;
}

function decodeJSON(src)
{
    var filtered = src;
    filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
    filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

    if (/^[\],:{}\s]*$/.test(filtered))
        return eval("(" + src + ")");
    else
        throw new SyntaxError("Error parsing JSON, source is not valid.");
};


function toJSON(o, compact)
{

    var type = typeof(o);

    if (type == "undefined")
        return "undefined";
    else if (type == "number" || type == "boolean")
        return o + "";
    else if (o === null)
        return "null";

    // Is it a string?
    if (type == "string")
    {
        return quoteString(o);
    }

    // Does it have a .toJSON function?
    if (type == "object" && typeof o.toJSON == "function")
        return o.toJSON(compact);

    // Is it an array?
    if (type != "function" && typeof(o.length) == "number")
    {
        var ret = [];
        for (var i = 0; i < o.length; i++) {
            ret.push( toJSON(o[i], compact) );
        }
        if (compact)
            return "[" + ret.join(",") + "]";
        else
            return "[" + ret.join(", ") + "]";
    }

    // If it's a function, we have to warn somebody!
    if (type == "function") {
        throw new TypeError("Unable to convert object of type 'function' to json.");
    }

    // It's probably an object, then.
    var ret = [];
    for (var k in o) {
        var name;
        type = typeof(k);

        if (type == "number")
            name = '"' + k + '"';
        else if (type == "string")
            name = quoteString(k);
        else
            continue;  //skip non-string or number keys

        var val = toJSON(o[k], compact);
        if (typeof(val) != "string") {
            // skip non-serializable values
            continue;
        }

        if (compact)
            ret.push(name + ":" + val);
        else
            ret.push(name + ": " + val);
    }
    return "{" + ret.join(", ") + "}";

};

function quoteString(string)
{

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;

    var meta = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };

    if (escapeable.test(string))
    {
        return '"' + string.replace(escapeable, function (a)
        {
            var c = meta[a];
            if (typeof c === 'string') {
                return c;
            }
            c = a.charCodeAt();
            return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
        }) + '"';
    }
    return '"' + string + '"';

};

function getContentDimensions(content)
{

    var contentFull = '<span id="fetch_content_dimensions" style="overflow: hidden">' + content + '</span>';

    jQuery('body').append(contentFull);

    var results = {
        width: jQuery('#fetch_content_dimensions').width(),
        height: jQuery('#fetch_content_dimensions').height()
    };

    jQuery('#fetch_content_dimensions').remove();

    return results;

}

//http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3614&lngWId=2
function changeQueryStringValue(url, qsname, qsvalue)
{

    //if no querystring present
    if (url.indexOf('?') == -1) {

        if (qsvalue.length == 0) {
            return url;
        }
        return (url + "?" + qsname + "=" + jQuery.URLEncode(qsvalue)); //x.php?name=Peter+Paul

    } else {
        //passed querystring not already present
        if ((url.indexOf("?" + qsname + "=") == -1) && (url.indexOf("&" + qsname + "=") == -1)) {

            if (qsvalue.length == 0) {
                return url;
            }
            return (url + "&" + qsname + "=" + jQuery.URLEncode(qsvalue)); //x.php?age=25&name=Peter+Paul;

        } else { //passed querystring already present, replace it no matter if it is ?name= or &name=

            var replaceQSPrefix = (url.indexOf("?" + qsname + "=") == -1) ? "&" + qsname + "=" : "?" + qsname + "=";
            var replaceQSSuffix = ""; //This will be John in case of ?name=John or &name=John
            var startpos = url.indexOf(replaceQSPrefix);

            for (a=(startpos + replaceQSPrefix.length); a<url.length; a++) {
                if (url.charAt(a) == '&') //next querystring beginning
                    break;
                else
                    replaceQSSuffix += url.charAt(a);
            }
            var newurl = url.replace(replaceQSPrefix + replaceQSSuffix, replaceQSPrefix + jQuery.URLEncode(qsvalue));

            if (qsvalue.length == 0) {
                if (url.indexOf("?" + qsname + "=") == -1) { //if querystring is not the first
                    newurl = newurl.replace("&" + qsname + "=&", "");
                    return newurl.replace("&" + qsname + "=", "");
                } else { //if querystring is first
                    if (url.indexOf("&") == -1) { //if no '&' is found
                        newurl = newurl.replace("?" + qsname + "=&", "");
                        return newurl.replace("?" + qsname + "=", "");
                    } else {
                        newurl = newurl.replace(qsname + "=&", "");
                        return newurl.replace(qsname + "=", "");
                    }
                }
            }
            return newurl;
        }
    }
}

//URLEncode and URLDecode
//eg: jQuery.URLEncode('string');
//eg: jQuery.URLDecode('string');
jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

