/**
 * @author Didier DURAND
 * blog: http://media-tech.blogspot.com
 * 
 * IGCheck is a gadget that checks which functions of Google Gadget environement are available in the container where it runs.
 * A comparison is then made with reference values from other containers
 */

	//gagdet parameters
	var IGCheck = {
		url:  'http://www.toojoor.com/opensocial/js/google/gadget/ig-check.php',
		okResponse: '##OK##->',
		functionSeparator: '**'
	}
	
	function main() {
		var okReport = true;
		if (typeof(_IG_FetchContent) == 'undefined') {
			writeMessage('<b>container:</b>function _IG_FetchContent not available</b>: IGCheck gagdet cannot run in this container !');
			okReport = false;
		}
		try {
			if (typeof(_IG_Analytics) != 'undefined') {
				//to report statistics on usage
				_IG_Analytics("UA-495139-4", "/IGcheck");
			}
			sayHello();
			var host = getHost();
			var container = getContainer();
			var functionList = IGFunctions();
			writeMessage('<b>host:</b> ' + host + ' <b>container:</b> ' + container);
			writeMessage('<b>IG functions:</b> ' + functionList.count);
			if (okReport == true) {
				//put string functions 1st to generate an error on server with other parameters missing in case of truncated url
				report({'functions' : functionList.string, 'count' : functionList.count, 'container' : container, 'host': host});
			}
		}
		catch (e) {
			var text = processError(e);
			writeMessage('<b>' + text + '</b>');
			if (okReport == true) {
				report({'error': text});
			}
		}
	}
	
	function report (object) {
		
		// date to store when it was run
		// date & random to keep url unique & bypass potential caching
		var date = new Date()
		var time = date.getTime();
		var rand = Math.floor(Math.random()*10000);
		var string = '?utime='+time+'&rand='+rand;
		
		//values to report put in url format -> ?key1=value1&?key2=value2
		if (typeof(object) == 'object') {
			var params = $H(object);
			var toUrl = function (pair) {
				if ((typeof(pair.value) == 'string') || (typeof(pair.value) == 'number') ) {
					string += '&' + pair.key + '=' + escape(pair.value);
				}
			}
			params.each(toUrl);
		}
		
		var url = IGCheck.url + string;
		
		var handler = function(responseText){
			if (responseText.length > 0) {
				var test = IGCheck.okResponse;
				//test below should be ==0 but bug with Ning: currently returns \n\n at beg of response
				if (responseText.indexOf(test) >= 0) {
					writeMessage(responseText.substring(test.length));
				}
				else {
					writeMessage('server PROBLEM !! ' + responseText);
				}
			} else {
					writeMessage('_IG_FetchContent PROBLEM !!');
			}	
		}
	
		_IG_FetchContent(url,handler);
	}
	
	function IGFunctions() {
		var functions = new Array();
		for (prop in window) {
			if (prop.indexOf('_IG_') == 0) {
				functions[functions.length] = prop;				
			}
		}
		//sep.length == 2 -> mandatory !
		var sep = IGCheck.functionSeparator;
		var string = '';
		var limit = 1000;
		for(var i=0 ; i < functions.length ; ++i) {
			if (i < limit) {
				string += sep + functions[i];
			}
		}
		string += sep;
		return {
			'functions': functions,
			'string': string,
			'count': functions.length
		};
	}
	
	
	function getContainer() {
		var myArgs = getArgs();
		var container = myArgs['synd'];
		//just to make a nice name
		switch (container) {
			case 'ig':
				container = 'igoogle';
				break;
			case 'hi5':
				container = 'Hi5';
				break;
			case 'orkut':
				break;
			case undefined:
				var location = myArgs['location'].toLowerCase();
				if (location) {
					if (location.indexOf('ning') >= 0) {
						container = 'ning';
					} else {
						container = 'unknown';
					}
				} else {
					container = 'undefined';
				}
		    default:
				//keep the unknown value !
				break;
		}
		return container;
	}
	
	function getHost() {
		return window.location.hostname;
	}
	
	//based on http://groups.google.com/group/opensocial/web/opensocial-gadget-parameters
	function getArgs() {
        try {
        	var q = window.location.search.substring(1);
            var a = q.split("&");
        	var args = {};
        	for (var i=0;i<a.length;i++) {
        		if (a[i] && a[i].indexOf('=')){
            		var arg = a[i].split('=');
                	args[arg[0]] = arg[1];
             	}
             }
             return args;
        } catch(err) {
        	return {};
        }
	}
	
	function sayHello(){
		var currentTime = new Date();
		var month = currentTime.getMonth() + 1;
		var day = currentTime.getDate();
		var year = currentTime.getFullYear();
		var text = 'Gadget IGCheck = check available _IG_ functions - by <a target="_blank" href="http://media-tech.blogspot.com">d.durand</a>';
		writeMessage(text);
		
		var text = month + "/" + day + "/" + year;	
		var hours = currentTime.getHours();
		var minutes = currentTime.getMinutes();
		if (minutes < 10) {
			minutes = "0" + minutes;
		}
		text += " @ " + hours + ":" + minutes + '<br/>';
		writeMessage(text);
	};
	
	function writeMessage(text) {
		$('message').innerHTML += text + '<br/>';
	}
	
	function processError (error) {
			var text = 'Error - '
			if (typeof(error.lineNumber != 'undefined')) {
				text += ' line: ' + error.lineNumber + + ' - ';
			}
	 		text +=  ' name: ' + error.name + ' - message : ' + error.message;
			return text;
		}
	

