
/* Global functions */

function addEvent(name, type, func) {
	var obj = document.getElementById(name);
	eval("obj." + type + " = function() { " + func + "}");
}

function consoleLogger(message) {
	if (!message) {
		sendData("post_consolelogger.php", "consoleLoggerReturn");
		return;
	}
	sendData("post_consolelogger.php", "consoleLoggerReturn", "message", message);
}

function consoleLoggerReturn(message) {
	var console = document.getElementById("console");
	console.innerHTML = message;
	console.scrollTop = console.scrollHeight;
}



/* Menu controller */

var MenuTab = {
	disable:function(id) {
		var menu = document.getElementById(id);
		if (menu) {
			menu.className = "disabled";
			menu.onclick = function() { return false; };			
		}
	},
	enable:function(id) {
		var menu = document.getElementById(id);
		if (menu) {
			menu.onclick = function() {};
			menu.className = "enabled";
		}
	}
}


function isDateValid(date) {

	// Check if we got the diffrent parts
	if (date.indexOf("-") < 0) return false;	

	// Split string
	var dateArray = date.split("-");
	if (dateArray.length != 3) return false;
	
	// Set local variables
	var year = dateArray[0];
	var month = dateArray[1];
	var day = dateArray[2];

	// Length of string
	if (year.length != 4) return false;
	if (!(month.length == 1 || month.length == 2)) return false;
	if (!(day.length == 1 || day.length == 2)) return false;

	// Date checking
	if (month > 12 || month < 1) return false;
	if (day > 31 || day < 1) return false;	
	if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) return false;
	if (month == 2 && day > 29) return false;

	// seems ok
	return true;
}

function isTimeValid(time) {

	// Check if we got the diffrent parts
	if (time.indexOf(":") < 0) return false;	

	// Split string
	var timeArray = time.split(":");
	if (!(timeArray.length == 2 || timeArray.length == 3)) return false;
	
	// Set local variables
	var hour = timeArray[0];
	var minute = timeArray[1];
	var second = timeArray[2];

	// Date checking
	if (hour > 23 || hour < 0) return false;
	if (minute > 59 || minute < 0) return false;
	if (second && (second > 59 || second < 0)) return false;	

	// seems ok
	return true;
}

function getSelectValue(name) {
	var obj = document.getElementById(name);
	return obj.options[obj.selectedIndex].value;
}


function getSelectedValues(name) {
	var values = Array();
	var obj = document.getElementById(name);
	
	for (var i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			values.push(obj.options[i].value);
		}
	}
	return values;
}

function encode(str) {
	return str;
	if (str == "" || !str) return "";
	var result = "";
	for (j=0; j<str.length; j++) {
		if (str.charAt(j) == " ") result += "+";
		else result += str.charAt(j);
	}
	return escape(result);
}

function gebi(name) {
	return document.getElementById(name);
}



function markrow(checkbox) {
	var row = checkbox.parentNode.parentNode
	row.className = row.className.replace(' marked', '');
	var checkAllBox = $j("input[type='checkbox']")[0];
	var noCheck = 0;
	var boxes = 0;
	$j("input[type='checkbox']").slice(1).each(function() {
		boxes++;
		if (!this.checked)
				noCheck++;
	});
	if (checkAllBox.indeterminate == true)
		    checkAllBox.checked = true;
	if (checkbox.checked == true ) {
		row.className += ' marked';
		if (checkAllBox.checked) {
			if (noCheck > 0 && checkAllBox.indeterminate == true) {
				checkAllBox.checked = false;
				$j(checkAllBox).prop("indeterminate", true);
			} else {
				$j(checkAllBox).prop("indeterminate", false);
			}
		}
	} else {
		row.className = row.className.replace(' marked', '');
		if (checkAllBox.checked) {
			if (noCheck == boxes) {
				$j(checkAllBox).prop("indeterminate", false);
				checkAllBox.checked = false;
			} else {
				//chkbox.indeterminate = true;
				$j(checkAllBox).prop("indeterminate", true);
				checkAllBox.checked = false;
			}
		}
	}
}


function CheckAll(container, control) {
	var inputs = $j("input[type='checkbox']").slice(1);
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i] && inputs[i].type == "checkbox") {
			inputs[i].checked = control.checked;
			markrow(inputs[i]);
		}
	}
}


/* "Sleep" Function */
function pause(millis) {
        var date = new Date();
        var curDate = null;

        do { curDate = new Date(); } 
        while(curDate-date < millis)
} 

/* Ajax */
var sendDataItem = "sendData";
var sendingSelection = false;
function sendData(filename, returner) {
	
	// Check that setSelection is not running...
	if (sendingSelection) {
		// ok, its running let us wait until its done...
		var int = 0;
		while (sendingSelection) {
			int++;
			// pause(100); startLoading()
			// if (int > 10) break;
			if (int > 10000) break;
		}
	}
	
	if (returner && returner != "consoleLoggerReturn") startLoading();
	
	var args = "filename=" + filename;
	args += "&returner=" + returner;

	for (i=2; i<arguments.length; i=i+2) {
		args += "&" + encode(arguments[i]) + "=" + encode(arguments[i+1]);
	}

	// Send request
	if (sendDataItem == "sendData") {
		sendDataItem = "sendData2";
		ajax.call("sendData2", args);
	} else {
		sendDataItem = "sendData";
		ajax.call("sendData", args);
	}
	return true;
}

function returnData(a, data) {
	
	var returner = data.substring(0, data.indexOf("|"));
	if (!returner || returner == "") return;
	
	if (returner != "consoleLoggerReturn") stopLoading();
	
	var data = data.substring(data.indexOf("|")+1);
	if (returner == "debug") {
		alert(data);
		return;
	}
	var func = eval(returner);
	func(data);
//	eval(returner + "('" + data + "');");
}

function selectAll(name, unselect) {
	var obj = document.getElementById(name);
	if (!obj) return;
	
	if (unselect) {
		obj.selectedIndex = -1;
		return;
	}
	
	for(var i = 0; i< obj.length;i++){
		obj.options[i].selected = true;
	}
}

function unSelectAll(name) {
	selectAll(name, true);
}

function formParams(form) {
	var obj = document.getElementById(form);
	if (!obj) alert("ERROR: 1943 - Can’t find form...");

	var params = Array();
	for (var i=0; i<obj.elements.length; i++) {
		if (!obj.elements[i].type) continue;
		var type = obj.elements[i].type.toUpperCase();		

		if (type != "BUTTON" && type != "SUBMIT") {
			if (type == "RADIO" || type == "CHECKBOX") {
				if (obj.elements[i].checked) {
					//params[obj.elements[i].name] = encode(obj.elements[i].value);
					params.push( new keyValue(obj.elements[i].name, encode(obj.elements[i].value)));	
				}
			} else if (type == "SELECT" || type == "SELECT-ONE") {
				if (obj.elements[i].options[obj.elements[i].selectedIndex].value != "") {
					//params += obj.elements[i].name + "=" + obj.elements[i].options[obj.elements[i].selectedIndex].value + "&";
					params.push( new keyValue(obj.elements[i].name, obj.elements[i].options[obj.elements[i].selectedIndex].value));	
				} else {
					//params += obj.elements[i].name + "=" + encode(obj.elements[i].options[obj.elements[i].selectedIndex].text) + "&";
					params.push( new keyValue(obj.elements[i].name, encode(obj.elements[i].options[obj.elements[i].selectedIndex].text)));	
				}
			} else {
				//params += obj.elements[i].name + "=" + encode(obj.elements[i].value) + "&";
				params.push( new keyValue(obj.elements[i].name, encode(obj.elements[i].value)));	
			}				
		}
	}
	
	return params;
}

function keyValue(key, value) {
	this.key = key;
	this.value = value;
	
	this.toString = function () {
		return this.key + "|" + this.value;
	}
}

var ajax = new AjaxManager();
ajax.addCallout("sendData", returnData, "/ajaxhandler.php", ajax.POST, ajax.HTML);
ajax.addCallout("sendData2", returnData, "/ajaxhandler.php", ajax.POST, ajax.HTML);
ajax.addCallout("getPage", getPageReturn, "/ajaxpage.php", ajax.POST, ajax.HTML);
ajax.addCallout("setContent", setContentReturn, "/ajaxhandler.php", ajax.POST, ajax.HTML);

function returnSelection() {
	sendingSelection = false;
}

function setSelection(obj) {
	if (obj.type == "select-one") {				
		if (obj.options[obj.selectedIndex].value != "") {
			value = obj.options[obj.selectedIndex].value;
		} else {
			value = obj.options[obj.selectedIndex].text;
		}
		sendingSelection = true;
		sendData('complete_selection/post_presentation_selection.php', 'returnSelection', 'key', obj.name, 'value', value);
	} else if (obj.type == "text") {
        if((obj.value).search(/[^0-9a-zA-Z\-\_\040\<\>\(\)\%\.]/g) >= 0 && !(obj.id == 'generation_date_to' || obj.id == 'generation_date_from' || 'generation_periodic_value')){
            alert("Only alphanumeric characters(A to z, 0 to 9), space, and the following characters (<>()%_.-) are allowed.");
            obj.value = obj.value.replace(/[\f\n\r\t\v]/gi,' ');
            obj.value = obj.value.replace(/[^0-9a-zA-Z\-\_\040\<\>\(\)\%\.]/gi,'');
            obj.focus();
        }
		sendingSelection = true;
		sendData('complete_selection/post_presentation_selection.php', 'returnSelection', 'key', obj.name, 'value', obj.value);
	} else if (obj.type == "radio") {
		sendingSelection = true;
		sendData('complete_selection/post_presentation_selection.php', 'returnSelection', 'key', obj.name, 'value', obj.value);
	} else if (obj.type == "checkbox") {
		if (obj.checked) {
			sendingSelection = true;
			sendData('complete_selection/post_presentation_selection.php', 'returnSelection', 'key', obj.name, 'value', obj.value);
		} else {
			sendingSelection = true;
			sendData('complete_selection/post_presentation_selection.php', 'returnSelection', 'key', obj.name, 'value', '');
		}
	} else {
		alert(obj.type);
	}
}

// Set content
var activeContentDiv;
function setContent(url, div) {

	activeContentDiv = div;
	
	var args = "filename=" + url;
	
	for (i=2; i<arguments.length; i=i+2) {
		args += "&" + encode(arguments[i]) + "=" + encode(arguments[i+1]);
	}
		
	// get content
	startLoading();	
	ajax.call("setContent", args);	
}

function setContentReturn(nn, data) {
	if (gebi(activeContentDiv)) {
		gebi(activeContentDiv).innerHTML = data;
	}
	stopLoading();
}


// Handling pages
var pageCache = Array();
var pageActive = null;

function getPage(pageName, fresh) {
	
	if (pageActive == pageName) return;
	
	// set old pag to cache
	if (pageActive != null) {
		pageCache[pageActive] = document.getElementById("content").innerHTML;
	}
	
	// use cached page
	if (pageCache[pageName] != null && !fresh) {
		document.getElementById("content").innerHTML = pageCache[pageName];
		pageActive = pageName;
		return;
	}
	
	// get new page
	ajax.call("getPage", "page=" + pageName);	
}

function removePageFromCache(pageName) {
	pageCache[pageName] = null;
}

function getPageReturn(nn, data) {
	var pageName = data.substring(0, data.indexOf("|"));
	if (!pageName || pageName == "") return;
	var data = data.substring(data.indexOf("|")+1);
	
	document.getElementById("content").innerHTML = data;
	pageCache[pageName] = data;
	pageActive = pageName;	
}





// LOADING PAGE
function startLoading() {
	var loading = document.getElementById("loading");
	if (loading) {	
		loading.style.display = "block";
	}
}

function stopLoading() {
	var loading = document.getElementById("loading");
	if (loading) {
		loading.style.display = "none";
	}
}


function showSelects(state) {
	if (document.all){
		var content_frame = document.getElementById("content");
		var myEls = content_frame.getElementsByTagName("select");
		for ( i=0; i<myEls.length; i++ ) {
			if (state) {
				myEls(i).style.visibility = "visible";
				//myEls(i).style.display = "block";
			}else{
				myEls(i).style.visibility = "hidden";
				//myEls(i).style.display = "none";
			}
		}
	}
}

// Error box
function showError(message, title) {
	var title = (title != "") ? title : "Error";
	var error_background = document.getElementById("error_background");
	var error_box = document.getElementById("error_box");

	error_box.innerHTML = "<h1>" + title + "</h1><p>" + message + '</p><input type="button" id="error_message_ok_button" value="OK" onclick="hideError()" />';

	if (error_background && error_box) {	
		error_background.style.top = "0px";

		if (document.body.offsetHeight > document.documentElement.clientHeight) {
			error_background.style.height = document.body.offsetHeight + "px";
		} else {
			error_background.style.height = document.documentElement.clientHeight + "px";
		}

		showSelects(false);
		error_background.style.display = "block";
		error_box.style.display = "block";
		
		// Set the focus to the error button, so a simple "Enter" would remove the error message
		gebi("error_message_ok_button").focus();
	}
}

function hideError() {
	var error_background = document.getElementById("error_background");
	var error_box = document.getElementById("error_box");
	if (error_background && error_box) {
		error_background.style.display = "none";
		error_box.style.display = "none";
		showSelects(true);
	}
}

// Change Password box
function showChPass() {
	var old_password = $( "#old_password" );
	var new_password = $( "#new_password" );
	var confirm_password = $( "#confirm_password" );
	dialogFields = $j( [] ).add( old_password ).add( new_password ).add( confirm_password );
	var dial = $j( "#change_password" ).dialog({
      autoOpen: false,
      height: 370,
      height: 370,
      width: 400,
      modal: true,
      buttons: {
		  "chpassbutton" : {
			  text: "Change Password",
			  id: 'chpassb',
			  click: confirmPassword
		  },
		  "cancelbutton" : {
			  text: "Cancel",
			  id: 'cancelb',
			  click: CancelDialog
		  }
      },
      close: function() {
        dialogFields.removeClass( "ui-state-error" );
      }
    });
	$j("#chpassb .ui-button-text").html("Change Password");
	$j("#chpassb .ui-button-text").focus();
	$j("#cancelb .ui-button-text").html("Cancel");
	
	if($j("#isreset").val() == 1 || $j("#reset").val() == 2){
		$j("#cancelb").hide();
		$j( "#change_password" ).dialog({ dialogClass: 'no-close' });
		$j( "#change_password" ).dialog({  closeOnEscape: false });
	}
	
	dial.dialog( "open" );
}

function CancelDialog(){
	var dial = $j( "#change_password" )
	dial.dialog( "close" );
}
	
	

function confirmPassword(){
	var old_password = $j( "#old_password" ).val();
	var confirm_pass = $j( "#confirm_password" ).val();
	var new_pass = $j( "#new_password" ).val();
	var csrf_token = $j("input[name=change_csrf_token]").val();
	var reset = $j( "#reset" ).val();
	var id = $j( "#user_id" ).val();
	var pass_error = $j( "#pass_error" );
	
	if(!old_password || !new_pass || !confirm_pass){
		pass_error.text("Fields Cannot be empty");
		pass_error.show();
		return false;
	}else if(new_pass.length < 5){
		pass_error.text("Password must be at least five(5) characters");
		pass_error.show();
		return false;
	}
	else if(new_pass != confirm_pass){
		pass_error.text("Password do not match");
		pass_error.show();
		return false;
	}
	else if(old_password){
		$j.ajax({
			type:"post",
			dataType:"json",
			url: "/access_control/post_edit_password.php",
            data: {id:id,old_password:old_password,new_password:new_pass,confirm_password:confirm_pass,reset:reset,change_csrf_token:csrf_token},
            success: function(response){
				if(response != 1){
					pass_error.text("Old Password Incorrect");
					pass_error.show();
				}else if(response == 1 && old_password == new_pass){
					pass_error.text("New Password should not be the same as Old Password");
		pass_error.show();
				}
				else{
					window.location = '/access_control/edit_user.php?id='+id+'&success=update';
				}
		}});
		return false;
	}
}

// Reset Password box
function showResetPass() {
	var pop_background = document.getElementById("pop_background");
	var reset_pass = document.getElementById("reset_password");

	if (pop_background && reset_pass) {	
		pop_background.style.top = "0px";

		if (document.body.offsetHeight > document.documentElement.clientHeight) {
			pop_background.style.height = document.body.offsetHeight + "px";
		} else {
			pop_background.style.height = document.documentElement.clientHeight + "px";
		}

		pop_background.style.display = "block";
		reset_pass.style.display = "block";
	}
}

function resetPassword(){
	var temp_pass = $j( "#temp_password" ).val();
	var reset = $j( "#reset" ).val()
	var id = $j( "#user_id" ).val();
	var csrf_token = $j("input[name=reset_csrf_token]").val();
	$j.ajax({type:"post",dataType:"json",url: "/access_control/post_edit_password.php",
            data: {id:id,temp_pass:temp_pass,reset:reset,reset_csrf_token:csrf_token},
            success: function(response){
			if(response == 1){
			   	window.location = '/access_control/edit_user.php?id='+id+'&success=reset';
			}
		}});

	return false;
}

var FrameManager = {

	    currentFrameId : '',
	    currentFrameHeight : 0,
	    lastFrameId : '',
	    lastFrameHeight : 0,
	    resizeTimerId : null,

	    init: function() {

	        if (FrameManager.resizeTimerId == null) {

	            FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 500);

	        }

	    },

	    resizeFrames: function() {

	        FrameManager.retrieveFrameIdAndHeight();

	        if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) {

	            var iframe = document.getElementById(FrameManager.currentFrameId.toString());

	            if (iframe == null) return;

	            iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";

	            FrameManager.lastFrameId = FrameManager.currentFrameId;
	            FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
	            window.location.hash = '';

	        }

	    },

	    retrieveFrameIdAndHeight: function() {

	        if (window.location.hash.length == 0) return;

	        var hashValue = window.location.hash.substring(1);

	        if ((hashValue == null) || (hashValue.length == 0)) return;

	        var pairs = hashValue.split('&');

	        if ((pairs != null) && (pairs.length > 0)) {

	            for(var i = 0; i < pairs.length; i++) {

	                var pair = pairs[i].split('=');

	                if ((pair != null) && (pair.length > 0)) {

	                    if (pair[0] == 'frameId') {

	                        if ((pair[1] != null) && (pair[1].length > 0)) {

	                            FrameManager.currentFrameId = pair[1];
	                        }
	                    } else if (pair[0] == 'height') {

	                        var height = parseInt(pair[1]);

	                        if (!isNaN(height)) {

	                            FrameManager.currentFrameHeight = height;
	                            FrameManager.currentFrameHeight += 15;

	                        }
	                    }
	                }
	            }
	        }

	    },

	    registerFrame: function(frame) {

	        var currentLocation = location.href;
	        var hashIndex = currentLocation.indexOf('#');

	        if (hashIndex > -1) {

	            currentLocation = currentLocation.substring(0, hashIndex);
	        }

	        frame.contentWindow.location = frame.src + '?frameId=' + frame.id + '#' + currentLocation;

	    }
	};

function validateFormText(form){
        var idList = ["name","edit_username"];
        var idOptList = ["server","client", "logfile","description","title","topbanner","bottombanner"];
        for (i=0; i<form.elements.length; i++) {
            
            if(form.elements[i].type != null && form.elements[i].type.indexOf("text")>=0 && idList.indexOf(form.elements[i].id)>=0){
                var sname = form.elements[i].value;
                sname = sname.replace(/^\s*|\s*$/,"");		//trim whitespaces
                
                if(sname == ""){
                    alert(form.elements[i].alt +" cannot be empty.")
                    form.elements[i].focus();
                    return false;
                    
                }else if(sname.search(/[^0-9a-zA-Z\-\_\040\<\>\(\)\%\.]/g) >= 0){
                    alert("Only alphanumeric characters(A to z, 0 to 9), space, and the following characters (<>()%_.-) are allowed.")
                    form.elements[i].focus();
                    return false;
                }
            }
            
            if(form.elements[i].type != null && form.elements[i].type.indexOf("text")>=0 && idOptList.indexOf(form.elements[i].id)>=0){
                var sname = form.elements[i].value;
                sname = sname.replace(/^\s*|\s*$/,"");
                var RegexUrl = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
                if(form.elements[i].id == "client" && sname!="" && !RegexUrl.test(sname)){
                    alert("Not a valid client URL.");
                    form.elements[i].focus();
                    return false;
                }else if(form.elements[i].id == "server" && sname!="" && sname.search(/[^0-9a-zA-Z\-\_\.\/:.?+=&%@]/g) >= 0){
                    alert("Not a valid server name or URL.");
                    form.elements[i].focus();
                    return false;
                }else if(form.elements[i].id == "logfile" && sname!=""){ // this filter is only temporary, path must be verified if it exists
                    if( document.getElementById("serverOS").value == "LIN" && sname.search(/[^0-9a-zA-Z\-\_\040\<\>\%\.=\\\/]/g) >= 0) {
                        alert("Only alphanumeric characters(A to z, 0 to 9), space, and the following characters (<>%_./-=\\) are allowed as file path.");
                        form.elements[i].focus();
                        return false;
                    }else if( sname.search(/[^0-9a-zA-Z\-\_\040\<\>\(\)\%\:\.=\\\/]/g) >= 0){
                        alert("Only alphanumeric characters(A to z, 0 to 9), space, and the following characters (<>()%_:./-=\\) are allowed as file path.");
                        form.elements[i].focus();
                        return false;
                    }
                }else if(form.elements[i].id == "description" && sname!="" && sname.search(/[^0-9a-zA-Z\-\_\=\040\<\>\(\)\%\.\,\n\r\/]/g) >= 0){
                    alert("Only alphanumeric characters(A to z, 0 to 9), space, and the following characters (<>()%_.,/-=) are allowed.");
                    form.elements[i].focus();
                    return false;
                }else if(["title","topbanner","bottombanner"].indexOf(form.elements[i].id)>=0 && sname!="" && sname.search(/[^0-9a-zA-Z\-\_\=\040\<\>\%\.\(\)\,\n\/]/g) >= 0){
                    alert("Only alphanumeric characters(A to z, 0 to 9), space, and the following characters (<>()%_.,/-=) are allowed.");
                    form.elements[i].focus();
                    return false;
                }
            }
            
            if(form.elements[i].type == "password"){
                if((form.elements[i].value).replace(/^\s*|\s*$/,"") == ""){
                    alert("Password cannot be empty.");
                    form.elements[i].focus();
                    return false;
                }else if((form.elements[i].value).length < 5){
                    alert("Password must be at least five(5) characters");
                    form.elements[i].focus();
                    return false;
                }
            }
        }
        //form.submit();
        //return false;
}


// JSON
/*
(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};

*/
