var BASE = '';

function setBase(newBase) {

    BASE = newBase;

}

//vars include directories,location,resizable,menubar,toolbar,scrollbars,status
function windowopen(url, width, height, vars) {

    if(width == null) width = 300;
    if(height == null) height = 300;
    if(vars == null) vars = 'resizable,scrollbars';

    vars += ',width=' + width + ',height=' + height;

    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) {

    var toReturn = '';

    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;

}

var Cookie = {
    set: function(name, value, daysToExpire) {
        var expire = '';
        if (daysToExpire != undefined) {
            var d = new Date();
            d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
            expire = '; expires=' + d.toGMTString();
        }
        return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
    },
    get: function(name) {
        var cookie = document.cookie.match(new RegExp('(^|;)\s*' + escape(name) + '=([^;\s]*)'));
        return (cookie ? unescape(cookie[2]) : null);
    },
    erase: function(name) {
        var cookie = Cookie.get(name) || true;
        Cookie.set(name, '', -1);
        return cookie;
    }
};


function html_entity_decode(s) {
    var t=document.createElement('textarea');
    t.innerHTML = s;
    var v = t.value;
    //t.parentNode.removeChild(t);
    return v;
}


//Apply tooltips automatically
jQuery(function() {

    jQuery('.tooltip').hover(

        function(e) {

            var theTitle = jQuery(this).attr('title');
            if(!theTitle) return;

            this.t = theTitle;

            jQuery(this).removeAttr('title');

            theTitle = theTitle.replace(/(\s{1}\|{1}\s{1})/g, '<br />');

            jQuery('body').append('<p id="tooltip" style="position: absolute">' + theTitle + '</p>');

            jQuery('#tooltip')
                .css('top', (e.pageY - 10) + 'px')
                .css('left', (e.pageX + 20) + 'px');
        },

        function() {

            var theTitle = this.t;
            if(!theTitle) return;

            this.title = theTitle;

            jQuery('#tooltip').remove();

        }

    );

    jQuery('.tooltip').mousemove(function(e) {

        jQuery('#tooltip')
            .css('top', (e.pageY - 10) + 'px')
            .css('left', (e.pageX + 20) + 'px');

    });

});

//Automatically add zebra's
jQuery(function() {

    jQuery('.zebra tr:nth-child(even)').addClass('even');
    jQuery('.zebra tr:nth-child(odd)').addClass('odd');

});


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 getAdminThrobber()
{

    return '<img class="adminThrobber" src="' + BASE + 'img/admin/throbber.gif" width="16" height="16" alt="Loading" />';

}

function removeAdminThrobber()
{

    jQuery('img.adminThrobber').remove();

}
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;

}

//[BEGIN] add/edit query string
//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 + "=" + 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 + "=" + 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 + 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;
        }
    }
}

function UrlEncode(text) 
{
    text = text.replace("?", "%3F");
    text = text.replace("=", "%3D");
    text = text.replace("&", "%26");
    text = text.replace(" ", "+");
    text = text.replace(",", "%2c");    
    
    return text;
}

//[END] add/edit query string

jQuery(document).ready(function(){
    if(jQuery('#newstype.adminonly').length){
        jQuery('#text').parent('td').parent('tr').hide();
        jQuery('#link').parent('td').parent('tr').hide();
        jQuery('#asset_id').parent('td').parent('tr').hide();
        
        jQuery('#newstype.adminonly').change(function(){
            var value=jQuery(this).val();
            jQuery('#text').parent('td').parent('tr').hide();
            jQuery('#link').parent('td').parent('tr').hide();
            jQuery('#asset_id').parent('td').parent('tr').hide();            
            if(value!='') jQuery('#'+value).parent('td').parent('tr').show();
        })
    }
});
