/* ###############################

	TrackStats.js version 1.0
	
	imambo player stats tracker. data is submitted onunload
	with a synconous ajax call.
	
############################### */
var debug = false;
	
$(document).ready(function() {

	// if debug add and load debug form
	if(debug) {
		$('body').append('<div id="form-data"></div>');
		$("#form-data").load("debug.html");
	}

	$(window).unload(function() {
		
		$.ajax({
			url: "http://www.imambo.com/clnt/_scripts/proxy.php" /*baseURL + '/cgi-bin/client/reports/player/video_stats.pl'*/,
			global: false,
			async: false,
			type: "POST",
			data: getData(),
			success: function(data) {
    			if(debug) alert("sucess: " + data);
  			},
  			error: function(XMLHttpRequest, textStatus, errorThrown) {
    			if(debug) alert("error: " + errorThrown);
  			}

		});
	});
	
	//get ip address
	$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
		//alert( "Your ip: " + data.ip);
		dataObj['ip_address'] = data.ip;
	});
	
	
});


function getData() {
	if(size(dataObj) == 0) {
		var obj = {test: "value1", test2: "value2" };
		return obj;
	}
	else {
		return dataObj;
	}
};

function ElapsedTime(ts) {
	dataObj['timestamp'] = ts;
	
	if(debug) {
		$("#timestamp").val(ts);
		displayKeys();
	}
};

function Session(s) {
	dataObj['session_id'] = s;
};

function addKey() {
	var key = $("#key").val();
	var val = $("#key_value").val();
	
	if(key != "") {
		dataObj[key] = val;
	
		$("#key").val("");
		$("#key_value").val("");
	
		displayKeys();
	}
	else {
		alert("enter a key name");
	}
};

function displayKeys() {
	var str = "<strong>Key/Value:</strong><br />";
	
	for(var key in dataObj) {
		str += (key + "=" + dataObj[key] +"<br />");
	}
	
	$("#key_results").html(str);
};


/* ###################### START - helpers */

// calculate the lenght of object
function size(d) {
  var len = d.length ? --d.length : -1;
    for (var k in d)
      len++;
  return len;
};


