/******************************************************************************
@owner: SVSi
@author: Arthur Johnson (ajohnson@svsiav.com)
@functions: Storage Utility functions for localstorage, indexedDB, database, and json
@varied
*******************************************************************************/

if (undef(pb)) var pb = {};

var idbSupported = false;
pb.idb = false;

Function.prototype.toJSON = Function.toString;

if ("indexedDB" in window) idbSupported = true;

if (idbSupported){

	var openRequest = indexedDB.open("panelbuilder",1);

	openRequest.onupgradeneeded = function(e) {
		
		pb.idb = e.target.result;
		
		if(pb.idb.objectStoreNames.contains("dbStorage")) {
			pb.idb.deleteObjectStore("dbStorage");
		}

		pb.idb.preview = pb.idb.createObjectStore("dbStorage", {keyPath: "name"});

	}

	openRequest.onsuccess = function(e) {
		pb.idb = e.target.result;
	}

	openRequest.onerror = function(e) {
		console.log("error", e, e.target.result);
	}
}
 


function setLocalDBObject(name, object){

	var transaction = pb.idb.transaction(["dbStorage"],"readwrite");
	var store = transaction.objectStore("dbStorage");
	var request = store.put({
		"data": json_encode(object),
		"name" : name
	});
	
	request.onsuccess = function(e) {
		console.log('success', e, e.target.result);
	}
	request.onerror = function(e) {
		console.log('error', e, e.target.result);
	}
}

function getLocalDBObject(name, callback){

	if (undef(callback)) callback = noop;

	var db = pb.idb;
	var transaction = db.transaction(["dbStorage"], "readwrite");
	var store = transaction.objectStore("dbStorage");
	
	pb.idbresult = false;
	
	var cursorRequest = store.openCursor(name);

	cursorRequest.onsuccess = function(e) {
		var result = e.target.result;
		if(!!result == false)
			return;
		pb.idbresult = json_decode(result.value.data);
		this(pb.idbresult);
	}.bind(callback);
}

if ('localStorage' in window && window['localStorage'] !== null){
	var localstorage = window.localStorage;
}

function setLocalObject(name, object){
	localstorage[name] = json_encode(object);
}

function getLocalObject(name){
	return json_decode(localstorage[name]);
}

function emptyLocalStorage(){
	window.localStorage.clear();
}

function json_encode(obj){
	return JSON.stringify(obj, null, "\t");
}

function json_decode(str, failsafe){

	if (undef(str)) return {};
	if (str == '') return {};

	if (failsafe){
		try {
			var obj = JSON.parse(str.trim() || "null", function(a,b){
				if (!undef(b)){
					if (b === null || b === false) return b;
					if (b.match && b.match(/^function[\w\W]+\}$/)){ 
						b = eval("b=0||"+b);
					}
					return b;
				}
			});
			return obj;
		}
		catch (err){
			window.location = '../initial.php';
			/*console.log(err);
			return {
				"id": -99999999,
				"name": "[!corrupted]",
				"buttonindex": 0,
				"widgetindex": 0,
				"widgetpartindex": 0,
				"templateindex": 0,
				"panelindex": 0,
				"panels": [{
					"core": {
						"name": "Panel-1",
						"id": "Panel-0",
						"scale": 1,
						"width": 1024,
						"height": 768,
						"style": "float: left; width: 1024px; height: 768px; position: absolute; left: 0px; border: 1px solid black;",
						"className": " panel selectables"
					},
					"buttons":[],
					"widgets":[]
				}]};*/
		}
	}
	else {
		//if (dev) console.log('decode', str);
		try {
			var obj = JSON.parse(str.trim() || "null", function(a,b){
				if (!undef(b)){
					if (b === null || b === false) return b;
					if (b.match && b.match(/^function[\w\W]+\}$/)){
						try {
							b = eval("b=0||"+b);
						}
						catch (e){
							console.log('error decoding:', b, e);
						}
					}
					return b;
				}
			});
			return obj;
		}
		catch (e){
			//console.log('error decoding:', str, e);
			return false;
		}
	}
	
} 

function setRemoteObject(object, filename, phpfilename){

	if (undef(phpfilename)) var phpfilename = 'server.php';
	jQuery.post(phpfilename, {name: filename, json: json_encode(object)});

}

function getRemoteObject(filename){

	var request = new XMLHttpRequest();
	request.open("GET", filename, false);
	request.send(null);
	return json_decode(request.responseText);

}

function queryDB(obj, phppage){

	if (undef(phppage)) var phppage = "query.php";

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", phppage, true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

	if (!undef(obj.data)) var data = obj.data;
		else var data = {};
	xmlhttp.send("opts="+encodeURIComponent(JSON.stringify(obj.opts))+
							"&data="+encodeURIComponent(JSON.stringify(data)));

    xmlhttp.onreadystatechange = function(){
		
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
		
			//console.log('xmlresponse: ', xmlhttp.responseText);
		
			if (!undef(obj.callback)){
				if (!undef(obj.script)) obj.callback(xmlhttp.responseText, obj.script, obj.self, obj.scriptorconditional);
				else obj.callback(xmlhttp.responseText);
			}
			
		}
	}; 

}

function jQueryDB(obj, phppage){

	if (undef(phppage)) var phppage = "query.php";
	
	$.post(
		phppage,
		{
			opts:obj.opts,
			data:obj.data
		},
		function (data, status){
			if (!undef(obj.callback)) obj.callback(data, status);
		}
	);

}

function checkDBSave(idnum){
	queryDB({opts: {query: 'select', id: idnum}, callback: function(data){
		json_decode(data, 'There was an error saving your project, please try saving again.');
	}});
}

function server(obj, phppage){

	if (standalone||wallcon||ncommand||modero){
		//console.log('ok...wallcon...');
		var callback = obj.callback;
		delete obj.callback;
		//console.log('back', callback);
		if (typeof callback !== 'function') callback = function(data){console.log('acallback',data);};
		if (!obj.opts) obj.opts = {command: 'none'};
		obj.opts.data = json_encode(obj.data);
		//console.log('SENDSENDSEND', obj.opts, callback);
		websocket.emit('message', obj.opts, callback);
		
		return;
	}
	
	//console.log('nonWEBSOCKETSEND');

	if (undef(phppage)) var phppage = "server.php";

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", phppage, true);
    if (!obj.formdata) xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

	if (!undef(obj.data)) var data = obj.data;
		else var data = {};
		
	var tosend = "opts="+encodeURIComponent(JSON.stringify(obj.opts))+
							"&data="+encodeURIComponent(JSON.stringify(data));
	
	if (obj.formdata){
		tosend = obj.formdata;
	}
		
	xmlhttp.send(tosend);

    xmlhttp.onreadystatechange = function(){
		
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
		
			console.log('xmlresponse: ', xmlhttp.responseText);
		
			if (!undef(obj.callback)){
				if (!undef(obj.script)) obj.callback(xmlhttp.responseText);
				else obj.callback(xmlhttp.responseText);
			}
			
		}
	}; 

}


function server2(obj, phppage){
	
	//console.log('nonWEBSOCKETSEND');

	if (undef(phppage)) var phppage = "server.php";

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", phppage, true);
    if (!obj.formdata) xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

	if (!undef(obj.data)) var data = obj.data;
		else var data = {};
		
	var tosend = "opts="+encodeURIComponent(JSON.stringify(obj.opts))+
							"&data="+encodeURIComponent(JSON.stringify(data));
	
	if (obj.formdata){
		tosend = obj.formdata;
	}
		
	xmlhttp.send(tosend);

    xmlhttp.onreadystatechange = function(){
		
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
		
			console.log('xmlresponse: ', xmlhttp.responseText);
		
			if (!undef(obj.callback)){
				if (!undef(obj.script)) obj.callback(xmlhttp.responseText);
				else obj.callback(xmlhttp.responseText);
			}
			
		}
	}; 

}

function $server(obj, phppage){

	if (undef(phppage)) var phppage = "server.php";
	
	$.post(
		phppage,
		{
			opts:obj.opts,
			data:obj.data
		},
		function (data, status){
			if (!undef(obj.callback)) obj.callback(data, status);
		}
	);

}

function getWeather(bindobj){

	if (undef(pb.location.zip)) return;
	
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "server.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

	xmlhttp.send("zip=" + parseInt(pb.location.zip));

    xmlhttp.onreadystatechange = function(){
	
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
			bindobj.weatherHTML = xmlhttp.responseText;
		}
		
	}.bind(bindobj); 

}