// Version 1.2 of the cms js file.
if (typeof console == 'undefined') {
	//alert('Oi - enable firebug!');
}


function cms_log(obj) {
if (typeof console === 'object') {
	console.log(obj);
}
}


function cms_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;
}

var last_bg_style = null;

function cms_highlight_span(id) {
var obj = document.getElementById("cms_" + id);
last_bg_style = obj.style.backgroundColor;
obj.style.backgroundColor = "#eef";
}

function cms_unhighlight_span(id){
var obj = document.getElementById("cms_"+id);
//obj.style.background = null;
obj.style.backgroundColor = null;
}

function dialog(url,windowname,width,height,features)
{
BrowserDetect.init();
if (BrowserDetect.browser == 'Explorer') {width=width+14; height=height;}
width=(width)?width:screen.width/2;
height=(height)?height:screen.height/2;
var screenX = (screen.width/2 - width/2);
var screenY = (screen.height/2 - height/2);
var features= "width=" + width + ",height=" + height +"toolbar=no,menubar=no,scrollbars=yes,resizable=yes,status=no,location=no,directories=no,copyhistory=no=no";
features += ",screenX=" + screenX + ",left=" + screenX;
features += ",screenY=" + screenY + ",top=" + screenY;
 
var mywin=window.open(url, windowname, features);
if (mywin)
mywin.focus();
return false;
}

function cms_edit_link(key,required_trust,id) {
	trust = cms_read_cookie('cms_trust');
	if ( parseInt(trust) >= parseInt(required_trust)) {
		if (document.getElementById('cms_missing_' + id) != null) {
			missing = document.getElementById('cms_missing_' + id)
			missing.style.visibility = 'visible';
		}
		var block = document.getElementById('cms_'+id);
		var str = " <a href='/' onmouseover='cms_highlight_span(\""+id+"\")' onmouseout='cms_unhighlight_span(\""+id+"\")' onclick='dialog(\"/_admin/admin-content-block-pop.php?"+key+"\",\"translation\",810,875); return false;' rel='nofollow' class='cms_edit'>edit<\/a> ";
		block.innerHTML += str;
	}
}


function cms_login_link() {
	document.write("<span style='float:right;'>");
	nick = cms_read_cookie("cms_nick");
	if (nick) document.write(" <a href='/_admin/logout.php' style='opacity:0.5'>logout<\/a>&nbsp;");
	else document.write(" <a href='/_admin/login.php' style='opacity:0.5'>login<\/a>&nbsp;");
	document.write("<\/span>"); 
}


function cms_load_js(src) {
// Non ajax - as allows caching of results (headers set properly)
	if( document.createElement && document.childNodes ) {
		var new_script = document.createElement('script');
		new_script.setAttribute('src',src);
		new_script.setAttribute('type','text/javascript');
		document.getElementsByTagName('head')[0].appendChild(new_script);
	} else {
		var ext_js = document.getElementById('ext_js');
		if (ext_js) ext_js.src = src;
		else document.write('<script src="', src, '" type="text/JavaScript"><\/script>');
	}	
}


function cms_dump(arr,level) {
        var dumped_text = "";
        if(!level) level = 0;

        //The padding given at the beginning of the line.
        var level_padding = "";
        for(var j=0;j<level+1;j++) level_padding += "    ";

        if(typeof(arr) == 'object') { //Array/Hashes/Objects
                for(var item in arr) {
                        var value = arr[item];

                        if(typeof(value) == 'object') { //If it is an array,
                                dumped_text += level_padding + "'" + item + "' ...\n";
                                dumped_text += cms_dump(value,level+1);
                        } else {
                                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
                        }
                }
        } else { //Stings/Chars/Numbers etc.
                dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
        }
        return dumped_text;
}


function cms_debug(obj) {

var mydiv = document.getElementById('debug');
if (mydiv == undefined) {
	document.write('<div id="debug">Debug Area<\/div>'); 
	mydiv = document.getElementById('debug');
	}

var debug = cms_dump(obj);
mydiv.innerHTML = debug;
return;

}


function cms_age(utime) {
// assumption made that the client time is correct... hmm
	var span = document.getElementById('cms_time');
	if (typeof(span) != 'object') return 0;
  if (utime < 1) return;
  var now = cms_now();
  var age = now - utime;
  if (age < 0) age = 0;
  var age_text = '';
  if (age < 600) age_text = "Age:" + age + "s";
  else if (age >= 6000) {
  	var hours = age / 60 / 60;
	age_text = "Age:" + Math.floor(hours) + "h";
  } else if (age >= 600) {
  	var mins = age / 60;
  	age_text = "Age:" + Math.floor(mins) + "m";
  }

	span.innerHTML += age_text;
}

function cms_now() {
	var today = new Date();
	var now = Math.round(today.getTime()/1000.0);
	return now;
}

function cms_timestamp_2_time(timestamp){
	var datetime = new Date(timestamp * 1000);
	return datetime;
}


function json_decode (str_json) {
    // http://kevin.vanzonneveld.net
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      improved by: T.J. Leahy
    // +      improved by: Michael White
    // *        example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *        returns 1: ['e', {pluribus: 'unum'}]

    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */

    var json = this.window.JSON;
    if (typeof json === 'object' && typeof json.parse === 'function') {
        try {
            return json.parse(str_json);
        } catch(err) {
            if (!(err instanceof SyntaxError)) {
                throw new Error('Unexpected error type in json_decode()');
            }
            this.php_js = this.php_js || {};
            this.php_js.last_error_json = 4; // usable by json_last_error()
            return null;
        } 
    }
    
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if ((/^[\],:{}\s]*$/).
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

        j = eval('(' + text + ')');

        return j;
    }

    this.php_js = this.php_js || {};
    this.php_js.last_error_json = 4; // usable by json_last_error()
    return null;
}


function json_encode (mixed_val) {
    // http://kevin.vanzonneveld.net
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      improved by: Michael White
    // +      input by: felix
    // +      bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *        example 1: json_encode(['e', {pluribus: 'unum'}]);
    // *        returns 1: '[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]'

    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */
    var retVal, json = this.window.JSON;
    try {
        if (typeof json === 'object' && typeof json.stringify === 'function') {
            retVal = json.stringify(mixed_val); // Errors will not be caught here if our own equivalent to resource
                                                                            //  (an instance of PHPJS_Resource) is used
            if (retVal === undefined) {
                throw new SyntaxError('json_encode');
            }
            return retVal;
        }

        var value = mixed_val;

        var quote = function (string) {
            var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
            var meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };

            escapable.lastIndex = 0;
            return escapable.test(string) ?
                            '"' + string.replace(escapable, function (a) {
                                var c = meta[a];
                                return typeof c === 'string' ? c :
                                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                            }) + '"' :
                            '"' + string + '"';
        };

        var str = function (key, holder) {
            var gap = '';
            var indent = '    ';
            var i = 0;          // The loop counter.
            var k = '';          // The member key.
            var v = '';          // The member value.
            var length = 0;
            var mind = gap;
            var partial = [];
            var value = holder[key];

            // If the value has a toJSON method, call it to obtain a replacement value.
            if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }

            // What happens next depends on the value's type.
            switch (typeof value) {
                case 'string':
                    return quote(value);

                case 'number':
                    // JSON numbers must be finite. Encode non-finite numbers as null.
                    return isFinite(value) ? String(value) : 'null';

                case 'boolean':
                case 'null':
                    // If the value is a boolean or null, convert it to a string. Note:
                    // typeof null does not produce 'null'. The case is included here in
                    // the remote chance that this gets fixed someday.

                    return String(value);

                case 'object':
                    // If the type is 'object', we might be dealing with an object or an array or
                    // null.
                    // Due to a specification blunder in ECMAScript, typeof null is 'object',
                    // so watch out for that case.
                    if (!value) {
                        return 'null';
                    }
                    if ((this.PHPJS_Resource && value instanceof this.PHPJS_Resource) ||
                        (window.PHPJS_Resource && value instanceof window.PHPJS_Resource)) {
                        throw new SyntaxError('json_encode');
                    }

                    // Make an array to hold the partial results of stringifying this object value.
                    gap += indent;
                    partial = [];

                    // Is the value an array?
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                        // The value is an array. Stringify every element. Use null as a placeholder
                        // for non-JSON values.

                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }

                        // Join all of the elements together, separated with commas, and wrap them in
                        // brackets.
                        v = partial.length === 0 ? '[]' :
                                gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                                '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }

                    // Iterate through all of the keys in the object.
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }

                    // Join all of the member texts together, separated with commas,
                    // and wrap them in braces.
                    v = partial.length === 0 ? '{}' :
                            gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
                case 'undefined': // Fall-through
                case 'function': // Fall-through
                default:
                    throw new SyntaxError('json_encode');
            }
        };

        // Make a fake root object containing our value under the key of ''.
        // Return the result of stringifying the value.
        return str('', {
            '': value
        });
    
    } catch(err) { // Todo: ensure error handling above throws a SyntaxError in all cases where it could
                            // (i.e., when the JSON global is not available and there is an error)
        if (!(err instanceof SyntaxError)) {
            throw new Error('Unexpected error type in json_encode()');
        }
        this.php_js = this.php_js || {};
        this.php_js.last_error_json = 4; // usable by json_last_error()
        return null;
    }
}

