/***************************************************************/
/* SabreTooth 5 JavaScript library loader                      */
/*                                                             */
/* loaded libraries:                                           */
/* core                                                        */
/* util                                                        */
/* api                                                         */
/* cookies                                                     */
/* flash                                                       */
/* geolocation                                                 */
/*                                                             */
/***************************************************************/


if (typeof fm == 'undefined') {

	fm = function() { }

} 


fm.util = function() {}

fm.util.toJSON = function(obj) {

    var type = typeof obj;

    switch(type) {

		case 'object' :
			if (!obj) return null; 
			var list = [];
			if (obj instanceof Array) {
				for(var i=0; i < obj.length; i++) {
					list.push(fm.util.toJSON(obj[i]));
				}
				return '[' + list.join(',') + ']';
			}

			for(var prop in obj) {
				list.push(fm.util.toJSON(prop) + ':' + fm.util.toJSON(obj[prop]));
			}
			return '{' + list.join(',') + '}';

		case 'string' :
            // Easiest way to handle this is to escape everything in a single operation,
            // otherwise you're likely to run into issues where the backslash from one
            // escape sequence gets escaped again.
            return '"' + obj.replace (
                /([\\"\n\t\r\b\f])/g,
                function ( specialChar ) {
                    switch ( specialChar ) {
                        case '\n': return '\\n';
                        case '\t': return '\\t';
                        case '\r': return '\\r';
                        case '\b': return '\\b';
                        case '\f': return '\\f';

                        case '"':
                        case '\\':
                            return '\\' + specialChar;

                        default: return specialChar;
                    }
                }
            ) + '"';

		case 'number' :
		case 'boolean' :
			return new String(obj);

    }

}

fm.util.getXMLHTTPObject = function() {

	try {
		var x = new XMLHttpRequest();
    } catch(e) {
		try {
			var x = new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
 			try { 
				var x = new ActiveXObject('Microsoft.XMLHTTP'); 
			} catch(e) {
				fm.util.log('Fatal error, could not locate XMLHTTPObject');
				return null;
			}
        } 
	}
	return x;

}

fm.util.log = function(message) {
	if (console.log) {
		console.log(message);
	}
}

fm.util.escapeHTML = function(str) {

	if (typeof(str)!='string') str = str.toString();
	return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');

}

fm.util.toQueryString = function(hashmap) {

	var parts = [];
	for(prop in hashmap)
		 parts.push(escape(prop) + '=' + escape(hashmap[prop]));

	return parts.join('&');

}
fm.api = function() { }

fm.api.Request = function(method,args) {

  this.method = method;
  this.args   = args;
  this.onResult = null;
  this.onError  = null;
  this.endPoint = '/services/json';
  this.currentRequest = null;

  this.invoke = function () {

	var request = fm.util.getXMLHTTPObject();
    this.currentRequest = request; 
  	request.open("POST",this.endPoint,true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	var self = this;
    request.onreadystatechange = function() { self.onreadystatechange() };
    request.send('method=' + this.method + '&jsonArgs=' + encodeURIComponent(fm.util.toJSON(args)));

  }

  this.onreadystatechange = function() {
    switch(this.currentRequest.readyState) {

		case 4 :
			var resultData = eval("(" + this.currentRequest.responseText + ")");
 			if (resultData.status == true) {
				if (this.onResult) this.onResult(resultData.result);
			} else if (this.onError) {
				this.onError(resultData);
			} else {
				fm.util.log('Unhandled error from json api: ' + resultData.result);
			}
			break; 

    }

  }

} 
fm.cookies = function() { }

fm.cookies.addCookie = function(name,value, expire) {
    
    if (expire){
        var date = new Date();
        date.setTime(date.getTime() + (expire * 1000)); // getTime returns milliseconds since 1970. We pass it the number of seconds (* 1000 for milliseconds)  we want the cookie to live from "now".

        var expires = "; expires="+date.toGMTString();
    } else {
        var expires = "";
    }
	
    var newCookie = name + '=' + escape(value) + expires +"; path=/";
	
    document.cookie = newCookie;

}

fm.cookies.getCookie = function(name) {
	var results = document.cookie.match ( '(^|; )' + name + '=(.*?)(;|$)' );

	if ( results )
		return unescape ( results [ 2 ] );
	else
		return null;
}
fm.flash = function() { }

fm.flash.getVersion = function() {

	var version = [0, 0, 0];

	if (navigator.plugins && navigator.plugins.length && navigator.plugins['Shockwave Flash']) {

		var plugin = navigator.plugins['Shockwave Flash'];

		var versionparts = plugin.description.match(/Shockwave Flash ([\d]*).([\d]*) r([\d]*)/);
		version = [ parseInt(versionparts[1]), parseInt(versionparts[2]), parseInt(versionparts[3]) ];

	}

	if (window.ActiveXObject) {

		try {

			var x = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
			if (x) {
				var versionparts = x.GetVariable("$version").split(' ')[1].split(',');
				version = [ parseInt(versionparts[0]), parseInt(versionparts[1]), parseInt(versionparts[2]) ]	
			}

		} catch (e) {  };

	}

	return version;

}

fm.flash.Object = function(options) {

	this.src = null;
	this.width = 0;
	this.height = 0;
	this.flashVars = {}
	this.allowScriptAccess = 'always';
    this.backgroundColor = null;
	this.allowFullScreen = true;
	this.wmode = null;
	this.id = null;

	// Loop through options, only overwrite property if they already exist
	for(i in options)
		if (typeof(this[i])!='undefined')
			this[i] = options[i];


	this.embed = function(element) {

		if (typeof(element)=='string') 
			element = document.getElementById(element);
		
		element.innerHTML = this.generateHTML();

	}

	this.write=function() {

		document.write(this.generateHTML());

	}

	this.generateHTML = function() {

		if (!this.src) throw 'Url to swf was not set';

		var html = '<object type="application/x-shockwave-flash" data="' +
			fm.util.escapeHTML(this.src) + '" ' 
			+ 'width="' + fm.util.escapeHTML(this.width) + '" ' 
			+ 'height="' + fm.util.escapeHTML(this.height) + '" ';

		if (this.id) html+='id="' + fm.util.escapeHTML(this.id) + '"'; 

		html+='>\n';

		html+='  <param name="movie" value="' + fm.util.escapeHTML(this.src) + '" />\n';

		if (this.allowScriptAccess) 
			html+='  <param name="allowScriptAccess" value="' + fm.util.escapeHTML(this.allowScriptAccess) + '" />\n';

		if (this.backgroundColor) 
			html+='  <param name="bgcolor" value="' + fm.util.escapeHTML(this.backgroundColor) + '" />\n';

		if (this.allowFullScreen)
			html+='  <param name="allowFullScreen" value="true" />\n';

		if (this.flashVars)
			html+='  <param name="flashvars" value="' + fm.util.toQueryString(this.flashVars) + '" />\n';
 
		// Wmode controls the transparancy. Use 'transparent' or 'opaque'
		if (this.wmode)
			html+='  <param name="wmode" value="' + fm.util.escapeHTML(this.wmode) + '" />\n'; 
		
		html+='</object>';

		return html;

	}

}


fm.geolocation = function() { }

fm.geolocation.getCurrentPosition = function(successCallback, errorCallback, options) {

	// Built-in
	if (false && typeof navigator.geolocation != 'undefined') {

		var geo = navigator.geolocation;

	} else {

	// Google gears
		try {	

			var geo = google.gears.factory.create('beta.geolocation');

		} catch (ex) { 
			errorCallback({ code: 0, message: 'Could not find support for the geolocation api'});
			return;
		}

	}

	geo.getCurrentPosition(successCallback, errorCallback, options);

}

