// 
// AJAX & FUNCTIONS
// LPMETHOD GAME v1.0
// Copyright 2009 Creativat Multimedia - http://www.creativat.com
//


// FUNCION CAMBIAR FONDO COLOR
function gmCanviaFons(imgFons) {
	$("#game1, #game2").fadeTo('normal', 0, function(){
		$("#juego").removeClass().addClass(imgFons);
		$("#footerFons").attr("src", "game/img/bottom-"+imgFons+".png");
		$("li.colorLateral").fadeIn('def');
		$("#lateral-"+imgFons).hide();
		$("#game2").fadeTo('normal', 1);
	});
	
	$.post('./game/ajax/ajax.proc.php', 'accion=sessioncolor&color='+imgFons,
		function (resp) {
		}, "json");	
}

function tancaJoc() {
	$("#fondo_opaco").addClass("desaparece");
	$('#juego').hide('slow', function(){
		if (demoUsuario!="")
		top.location.href = "../logout.proc.php";
		else
		top.location.href = returnJuego;
	});
}
function gmCanviaFonsLogin(imgFons) {
	$("#game1").fadeTo('normal', 0, function(){
		$("#juego").removeClass().addClass(imgFons);
		$("#footerFons").attr("src", "game/img/bottom-"+imgFons+".png");
		$("#colorsIntro li").fadeIn('def');
		$("#login-"+imgFons).hide();
		$("li.colorLateral").show();
		$("#lateral-"+imgFons).hide();
		$("#game1").fadeTo('normal', 1);
	});
	
	$.post('./game/ajax/ajax.proc.php', 'accion=sessioncolor&color='+imgFons,
		function (resp) {
		}, "json");	
}


function gmLogin(errorText) {
	//var mrwUser = $("#user").val();
	//var mrwPass = $("#pass").val();
	var datos = $("#logLP").serialize();
	$.post('./game/ajax/ajax.proc.php', 'accion=login&'+datos,
		function (resp) {
			if (resp==1) {
				//$("#game1").hide('slow', function() {
				//	$("#game2").show('slow');
				//});
				$('#mrwLoginKO').html('<font style="color:green; font-weight:bold;">OK. Enjoy!');
				//top.location.href = '?m=11';
				top.location.href = $("#params").val();
			}
			else {
				$('#mrwLoginKO').text(errorText);
			}
		}, "json");
}

// FUNCION CATEGORIAS
function categoria(categoriaID, leyendaCat) {
	$.post('./game/ajax/ajax.proc.php', 'accion=consultaEstado',
					function (resp) {
						if (resp[0]==1 || resp[1]==1) {
							$("#mTest").hide();
						}
					}, "json");
	
	if (categoriaID==0) {
		$.post('./game/ajax/ajax.proc.php', 'accion=categorias&categoriaID='+categoriaID,
		function (resp) {
			$("#divCategorias").hide()
			.html(resp)
			.fadeIn('slow');
			$("li.subCategoria").hide();	
		}, "json");
	}
	else {
		//$("#leyendaPunto1").hide();
		//$("#leyendaCat").hide();
		
		$("#leyendaPunto1").show();
		$("#leyendaCat").attr("href", "?m=11&llegendaId="+categoriaID+"&llegendaCat="+leyendaCat)
		.text(leyendaCat.replace("@", "&"))
		.show();
		$("li.subCategoria").hide();
		$("li.subCategoria.cat"+categoriaID).fadeIn('def');
		$("#categoria a.marcado").removeClass();
		$("#catBloc"+categoriaID).addClass("marcado");
	}	
}
nivelDemo="";
function categoria_demo(categoriaID, leyendaCat, nivel) {
nivelDemo=nivel;
	$.post('./game/ajax/ajax.proc.php', 'accion=consultaEstado',
					function (resp) {
						if (resp[0]==1 || resp[1]==1) {
							$("#mTest").hide();
						}
					}, "json");
	
	if (categoriaID==0) {
		$.post('./game/ajax/ajax.proc.php', 'accion=categorias_demo&categoriaID='+categoriaID+'&nivel='+nivel,
		function (resp) {
			$("#divCategorias").hide()
			.html(resp)
			.fadeIn('slow');
			$("li.subCategoria").hide();
			$("#entradillaDemo").hide();
			$("#entradillaDemo3").show();
		}, "json");
	}
	else {
		//$("#leyendaPunto1").hide();
		//$("#leyendaCat").hide();
		
		$("#leyendaPunto1").show();
		$("#leyendaCat").attr("href", "?m=11&llegendaId="+categoriaID+"&llegendaCat="+leyendaCat)
		.text(leyendaCat.replace("@", "&"))
		.show();
		$("li.subCategoria").hide();
		$("li.subCategoria.cat"+categoriaID).fadeIn('def');
		$("#categoria a.marcado").removeClass();
		$("#catBloc"+categoriaID).addClass("marcado");
	}	
}

function categoriaLeyenda(categoriaID, leyendaCat) {
	$("#leyendaPunto1").show();
	$("#leyendaCat").attr("href", "?m=11&llegendaId="+categoriaID+"&llegendaCat="+leyendaCat.replace("&amp;", "@"))
	.html(leyendaCat)
	.show();

	$.post('./game/ajax/ajax.proc.php', 'accion=categorias&categoriaID='+categoriaID,
		function (resp) {
			$("#divCategorias").hide()
			.html(resp)
			.fadeIn('slow');
			$("li.subCategoria").hide();	
			$("li.subCategoria").hide();
			$("li.subCategoria.cat"+categoriaID).fadeIn('def');
			$("#categoria a.marcado").removeClass();
			$("#catBloc"+categoriaID).addClass("marcado");
}, "json");
		//$("#leyendaPunto1").hide();
		//$("#leyendaCat").hide();
}


// FUNCION ABRIR JUEGO
var juegoID = "";
var tipoID = "";
var abierto = "no";
function obreJoc(oJjuegoID, oJtipoID, leyendaJuego, esDemo, nivelDemo) {
	$("#mStart, #textCat").hide();
	$("#mMenu, #eleccio").show();
	$.post('./game/ajax/ajax.proc.php', 'accion=estaLogueado',	
	function (resp) {
		if (resp=='OK') {
			juegoID = oJjuegoID;
			tipoID = oJtipoID;
			if (abierto=="no") {
				switch(juegoID) {
					case 4:
					case 15:
						cuant_temps = 2;
						break;
					case 1:
					case 6:
					case 3:
					case 8:
						cuant_temps = 3;
						break;
					case 9:
					case 11:
					case 13:
					case 16:
					case 18:
					case 19:
					case 4:
						cuant_temps = 4;
						break;
					case 7:
					case 14:
					case 2:
					case 12:
					case 25:
						cuant_temps = 5;
						break;
					case 10:
					case 5:
						cuant_temps = 10;
						break;
					default:
						cuant_temps = 5;
				}				
				$.getScript("./game/ajax/jquery.countr.js");
				abierto = "si";
				$.getScript("./game/ajax/juegos/juego-"+tipoID+".js", function(){
					cargaEstructura('no');
					/*if (esDemo=="demo") {
						$("#entradillaDemo").hide();
						$("#entradillaDemo2").show();
						$("#footDemo").hide();
						botoStart("demo", 30 * 1000, nivelDemo, 1);
					}*/				
				});
				$("#leyendaPunto2").show();
				$("#leyendaSubCat").html('&nbsp;').html('<u>'+leyendaJuego+'</u>').show();
				$("#mrwZonaFinal").text(leyendaJuego);
			
				$.post('./game/ajax/ajax.proc.php', 'accion=abrirJuego&juegoID='+juegoID+'&tipoID='+tipoID,
				function (resp) {			
					$("#time, #time-instructions, #time-gramatica").val(cuant_temps);
					
					$("#tiuloSec").text(resp[0]);
					$("#textoObjective").html(resp[1]);
					$("#textoReminder").html(resp[2]);
					$("#textoInstructions").html(resp[3]);
					$("#tipoID").attr("value", resp[4]);
					$("#imatgeFons"+tipoID).attr("src", "game/img/fondos/"+resp[5]);
					if (tipoID==6) {
						$("#imatgeFons6_2").attr("src", "game/img/fondos/"+resp[8]+".gif");
						$("#qOir").removeClass();
						$("#qOir").addClass(resp[8]);
					}
					$("#level").html(resp[6]);
					$("#set").html(resp[7]);
					
					$("#level-instructions").html(resp[6]);
					$("#set-instructions").html(resp[7]);
					
					$("#level-gramatica").html(resp[6]);
					$("#set-gramatica").html(resp[7]);
					$('#time').val(resp[9]);
				}, "json");
			}
		}
		else {
			top.location.href = '?m=11';
		}
	}, "json");
} //ABRIR JOC

// FUNCION ABRIR LECCION
var juegoID = "";
var tipoID = "";
var abierto = "no";
function abrirLeccion(oJjuegoID,nivel) {
	document.getElementById('divCategorias').innerHTML = "";
	$("#mStart, #textCat").hide();
	
	$.post('./game/ajax/ajax.proc.php', 'accion=estaLogueado',	
	function (resp) {
		if (resp=='OK') {
			juegoID = oJjuegoID;
			if (abierto=="no") {
				abierto = "si";
				
				
				$.post('./game/ajax/ajax.proc.php', 'accion=abrirLeccion&juegoID='+juegoID+'&tipoID='+tipoID+'&nivelID='+nivel,
				

				function (resp) {	
					$("#tiuloSec").text(resp[0]);	
					$("#lessonContent").html(resp[1]).fadeIn('def');
											$('.tip').imgPreview({
	srcAttr: 'rel',
	containerID: 'imgPreviewWithStyles'
});
					$("#leyendaPunto2").show();
					$("#leyendaSubCat").html('&nbsp;').html('<u>'+resp[0]+'</u>').show();
					//$("#startPractising").attr("onClick", "obreJoc(" + resp[2] + "," + oJtipoID + ",'name','demo',1)")
					$("#startPractising").attr("href", "game-lpmethod?m=11&juegoID=" + resp[2])
					//$("#startPractising").attr("href", "javascript:;")
					
					//$("#startPractising").attr("onClick", "javascript:obreJoc("+oJjuegoID+","+oJtipoID+",'"+oJname+"');")
					
				}, "json");
				
				$("#mMenu").show();
				
				$("#divLeccion").show("fast");
				
				//$("#divLeccion").fadeIn("slow"); 
				

			}
			
			soundManager.play('sigSound','http://esp.lp-method.com/game/audios/sigTune2.mp3');
		}
		else {
			top.location.href = '?m=11';
		}
	}, "json");
	
}



// FUNCION ABRIR ZONE POPUP
function abrirZonePopUp(name,juegoID,tipoID,lang,nivel) {
	$("#zoneName").html(name);

	if( lang == "ES"){
		var javascripts = "<a onclick=\"abrirLeccion("+juegoID+","+nivel+");$('#dialog').jqmHide();\" href=\"#\" id=\"lessonButton\">Lección</a><a href=\"#\" onclick=\"obreJoc("+juegoID+", "+tipoID+" ,'"+name+"');$('#dialog').jqmHide();\" id=\"exerciseButton\" >Ejercicio</a>";
	}else if( lang == "CA"){
		var javascripts = "<a onclick=\"abrirLeccion("+juegoID+","+nivel+");$('#dialog').jqmHide();\" href=\"#\" id=\"lessonButton\">Lliçó</a><a href=\"#\" onclick=\"obreJoc("+juegoID+", "+tipoID+" ,'"+name+"');$('#dialog').jqmHide();\" id=\"exerciseButton\" >Exercici</a>";
	}else{
		var javascripts = "<a onclick=\"abrirLeccion("+juegoID+","+nivel+");$('#dialog').jqmHide();\" href=\"#\" id=\"lessonButton\">Lesson</a><a href=\"#\" onclick=\"obreJoc("+juegoID+", "+tipoID+" ,'"+name+"');$('#dialog').jqmHide();\" id=\"exerciseButton\" >Exercise</a>";
	}


	$("#buttons").html(javascripts);
	$('#dialog').jqmShow();
}







// FUNCION PARA OBTENER SETS DISPONIBLES SEGUN NIVEL
function obtenerSets() {
nivelSeleccionado = $("#level").val();
$.post('./game/ajax/ajax.proc.php', 'accion=obtenerSets&juegoID='+juegoID+'&tipoID='+tipoID+'&nivel='+nivelSeleccionado,
		function (resp) {
			$("#set").html(resp[0]);
		}, "json");
}

function obtenerSets_instructions() {
nivelSeleccionado = $("#level-instructions").val();
$.post('./game/ajax/ajax.proc.php', 'accion=obtenerSets&juegoID='+juegoID+'&tipoID='+tipoID+'&nivel='+nivelSeleccionado,
		function (resp) {
			$("#set-instructions").html(resp[0]);
		}, "json");
}

function obtenerSets_gramatica() {
nivelSeleccionado = $("#level-gramatica").val();
$.post('./game/ajax/ajax.proc.php', 'accion=obtenerSets&juegoID='+juegoID+'&tipoID='+tipoID+'&nivel='+nivelSeleccionado,
		function (resp) {
			$("#set-gramatica").html(resp[0]);
		}, "json");
}

// FUNCION ABRIR CERRAR ROI's

function canviaRoi(roi) {
	$("#objective, #reminder, #instructions").hide();
	$("#"+roi).fadeIn('def');
	
	$("#mObjective, #mReminder, #mInstructions").removeClass();
	$("#m"+ucfirst(roi)).addClass("marcado");
}

// FUNCION PARA SUMAR EL TIEMPO REQUERIDO DE TIMEOUT
function tiempoReq(que) {
	var valorTime = parseInt($("#time").val());
	if (que=="suma") {
		if (valorTime<30) $("#time, #time-instructions, #time-gramatica").attr("value", valorTime + 1);
	}
	if (que=="resta") {
		if (valorTime>1) $("#time, #time-instructions, #time-gramatica").attr("value", valorTime - 1);
	}
}

// FUNCIONALIDADES ABRIR SECCIONES
tiempo_restante = "";
tiempo_restante_next = "";
tiempo_restante_1 = "";
tiempo_restante_2 = "";
var testCargado = false;
function abrirSeccion(sec, leyendaSec) {
if (tiempo_restante!="") tiempo_restante.stop();
if (tiempo_restante_next!="") tiempo_restante_next.stop();
if (tiempo_restante_1!="") tiempo_restante_1.stop();
if (tiempo_restante_2!="") tiempo_restante_2.stop();


$("#menuROI, #divPuntuacio, #reminder, #objective, #instructions, #tipo1, #tipo2, #tipo3, #tipo4, #tipo5, #tipo6, #tipo7, #tipo8, #tipo9, #categoria, #divMystats, #divMyaccount, #divLptest, #divMistakes, #final, #divLptestInicio, #lpTestAprobado, #lpTestSuspendido, #divLptestMistakes, #lpTestQuests, #eleccio").hide('def');
$("#mStart, #mMenu, #mMyStats, #mMyAccount, #mMistakes, #mTest, #mManual, #mLanguage").removeClass("marcado");

$("#leyendaPunto1, #leyendaCat, #textCat").hide();
$("#leyendaPunto2, #leyendaSubCat").hide();

$("#leyendaPunto1, #leyendaCat").show();
$("#leyendaCat").text(leyendaSec)

	switch (sec) {
		case "startlp":
			$("#mStart").addClass("marcado");		
			$("#cateogira").show(); // PRINCIPI
			categoria(0);
			$("#tiuloSec").text("LP CATEGORIES");
			break;
		case "mystats":
			$("#mMyStats").addClass("marcado");	
			$("#divMystats").show('def');
			$("#tiuloSec").text("MY STATS");
			$("#entradillaDemo").text("Para visualizar tu evolución en las distincas zonas y niveles en el juego");
			if (demoUsuario=="demo") {
				$("#footDemo").hide();
			}
			//mystatsBars();
			break;
		case "myaccount":
			$("#mAccount").addClass("marcado");	
			$("#divMyaccount").show('def');
			$("#tiuloSec").text("MY ACCOUNT");
			$("#entradillaDemo").text("Para editar tu cuenta");
			if (demoUsuario=="demo") {
				$("#footDemo").hide();
			}
			//mystatsBars();
			$("#mAccount").addClass("marcado");
			break;

		case "lptest":
			$("#mTest").attr("onclick", "");
			$("#mTest").addClass("marcado");	
			$('#divLptest, #inicioTest').show('def');
			$("#tiuloSec").text("LP TEST");
			$("#entradillaDemo").text("Para hacer únicamente los ejercicios que correspondan a tu nivel");
			//if (testCargado==false) {
			$.getScript("./game/ajax/lptest.js");
			//}
			if (demoUsuario=="demo") {
				$("#footDemo").hide();
			}			
			break;
		case "lpmanual":
			break;
		case "language":
			break;
	}
}

// ABRIR/CERRAR DIV IDIOMAS
function obrirIdioma() {
	//alert('hello');
	$("#idiomes").toggle('fast');
}
function obrirDiccionario() {
	$("#diccionario").toggle('fast');
	
}

// APLICA EFECTO RELLENO BARRAS DE PROGRESO NIVEL
function mystatsBars() {
	cuantasProgress = $('img.progressBar').size();
	tiempo_mystats = $.timer(2000, function (timer) {
		tiempo_mystats.stop();
		for (i=1;i<=cuantasProgress;i++) {
			numeroRand = rand(1, 100);
			//console.log("#progressBar"+i);
			//$("#percentatge"+i).text(numeroRand+"%").fadeIn(1500);
			/*$("#progressBar"+i).animate({
				width: numeroRand+"%"
			}, 1400);*/
		}
	});
}

// VER DETALLES Y BOTON ATRAS
function myStats(que) {
	switch (que) {
		case "atras":
			$("#mystatsdetalles").hide('def');
			$("#mystatsbars").show('def');
			abajo = "";
			break;
	}
}

function verDetallesStats(usuarioID, categoriaID, juegoID, nivel) {
	//alert(usuarioID+", "+categoriaID+", "+juegoID+", "+nivel);
	$.post('./game/ajax/ajax.proc.php', 'accion=detalleStats&usuarioID='+usuarioID+'&categoriaID='+categoriaID+'&juegoID='+juegoID+'&nivel='+nivel,
				function (resp) {
					$("#mystatsdetalles").html(resp);
					$("#lvlMystatsDetalle").html(nivel);

	$.post('./game/ajax/score.proc.php', 'accion=puntosxjuegoynivel&juegoID='+juegoID+'&nivel='+nivel,
					function (resp) {
						$("#globalScoreDetalles").html(resp[0]+" / 1000");
					}, "json");	
				}, "json");

	$("#mystatsdetalles").show('def');
	$("#mystatsbars").hide('def');
}

function lptest() {
	lpTestStart();	
}

//////////////////////////////////////////////////
//               FUNCIONES REGISTROS BDD
//////////////////////////////////////////////////

var dbSesionID="";
function dbInicioSesion() {
	if (demoUsuario!="demo") {
		$.post('./game/ajax/ajax.proc.php', 'accion=inicioSesion&juegoID='+juegoID+'&nsets='+sets+'&nivel='+nivel+'&time_request='+timeout,
					function (resp) {
						dbSesionID = resp[0];
					}, "json");
	}
}

function dbFinalSesion() {
	if (demoUsuario!="demo") {
		$.post('./game/ajax/ajax.proc.php', 'accion=finalSesion&sesionID='+dbSesionID,
		   function() {
				$.post('./game/ajax/score.proc.php', 'accion=puntosxjuegoynivel&juegoID='+juegoID+'&nivel='+nivel,
									function (resp) {
										if (resp[0]==1000) $("#entradillaFinalSesion").hide();
										$("#puntsTotalT").text(resp[0]);
										$("#puntsTotal").text(resp[0]);
										$("#mrwLevelFinal").text(nivel);
									}, "json");
		   });
	
/*$.post('./game/ajax/score.proc.php', 'accion=puntosxjuegoynivel&juegoID='+juegoID+'&nivel='+nivel,
					function (resp) {
						$("#puntsTotalT").text(resp[0]);
						$("#puntsTotal").text(resp[0]);
					}, "json");*/
	}
}

function dbFinalSet() {
	StopStartTimer();
	if (demoUsuario!="demo") {
	errores = $.toJSON(a);
	//$.post('./game/ajax/ajax.proc.php', 'accion=finalSet&sesionID='+dbSesionID+'&score='+score);
	$.post('./game/ajax/score.proc.php', 'accion=controlscore&juegoID='+juegoID+'&nivel='+nivel+'&score='+score+'&sesionID='+dbSesionID+'&sesion_finalizada='+controlSets,
		   function (resp) {
						$("#textoFinalSesion").html(resp[3]);
						$("#puntsFinalT").text(resp[5]);
						if (resp[4]==0) {
							$("#entradillaFinalSesion").hide();
						}
						if (resp[1]==1 || resp[2]==1) {
							$("#divMistakes, #divPuntuacio, #tipo"+tipoID).hide();
							$("#final").show('slow');						
							// PONER AQUI COMPROBACION DE SI PUNTUA O NO (PUNTUCION MINIMA) PARA ASI RESTAR AL TOTALSCORE LA PUNTUACION REALIZADA EN ESE SET QUE NO DEBERIA SUMARSE
							// totalscore = totalscore - score;
						}
					}, "json");
	$.post('./game/ajax/ajax.proc.php', 'accion=almacenaErrores&sesionID='+dbSesionID+'&errores='+errores);
	}
	if (demoUsuario=="demo") {
		$("#footDemo").show();
	}	
}

var abajo = "";
function scrollUpDetalles() {
	if (abajo=="") {
		var mydiv = document.getElementById("listadoStats");
		abajo = "si";
		mydiv.scrollTop = mydiv.scrollHeight - mydiv.clientHeight;
	}
}

var running = false;
function showProgressDots(numberOfDots) {
    if (running) {
		switch(numberOfDots) {
			case 1:
				$("#textQ").html('<p class="loader">loading .</p>');
				timerHandle = setTimeout('showProgressDots(2)',200);
				break;
			case 2:
				$("#textQ").html('<p class="loader">loading ..</p>');
				timerHandle = setTimeout('showProgressDots(3)',200);
				break;
			case 3:
				$("#textQ").html('<p class="loader">loading ...</p>');
				timerHandle = setTimeout('showProgressDots(1)',200);
				break;
		}
	}
}

function StopStartTimer() {
   if (running) {
      running=false;
   }
   else {
      running=true;
      window.setTimeout('showProgressDots(1)',100);
   }
}

//////////////////////////////////////////////////

//
// FUNCIONES EXTRA
//

function ucfirst( str ) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

function strtoupper( str ) {
    return (str+'').toUpperCase();
}

function rand( min, max ) {
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

(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 + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};
	
	$.parseJSON = function(v, safe) {
		if (safe === undefined) safe = $.parseJSON.safe;
		if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
			return undefined;
		return eval('('+v+')');
	};
	
	$.parseJSON.safe = false;

})(jQuery);
