
/*
 * Copied from: http://www.quirksmode.org/js/detect.html
 * Does not support Safari and OmniWeb (must be checked for manually).
 *
 */  
function BrowserMetadata () {
	this.browser = this.searchString(this.dataBrowser);
	this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion);
	this.operatingSystem = this.searchString(this.dataOS);
	this.width = this.screenWidth();
	this.height = this.screenHeight();
}

BrowserMetadata.prototype.saveUrl = "/profile/save/settings";

BrowserMetadata.prototype.dataBrowser = [
	{string: navigator.userAgent,subString: "Chrome",identity: "Chrome"},
	{string: navigator.userAgent,subString: "OmniWeb",versionSearch: "OmniWeb/",identity: "OmniWeb"},
	{string: navigator.vendor,subString: "Apple",identity: "Safari",versionSearch: "Version"},
	{prop: window.opera,identity: "Opera"},
	{string: navigator.vendor,subString: "iCab",identity: "iCab"},
	{string: navigator.vendor,subString: "KDE",identity: "Konqueror"},
	{string: navigator.userAgent,subString: "Firefox",identity: "Firefox"},
	{string: navigator.vendor,subString: "Camino",identity: "Camino"},
	{/* for newer Netscapes (6+) */	string: navigator.userAgent,subString: "Netscape",identity: "Netscape"},
	{string: navigator.userAgent,subString: "MSIE",identity: "Explorer",versionSearch: "MSIE"},
	{string: navigator.userAgent,subString: "Gecko",identity: "Mozilla",versionSearch: "rv"},
	{/* for older Netscapes (4-) */	string: navigator.userAgent,subString: "Mozilla",identity: "Netscape",versionSearch: "Mozilla"}
];

BrowserMetadata.prototype.dataOS = [
	{string: navigator.platform,subString: "Win",identity: "Windows"},
	{string: navigator.platform,subString: "Mac",identity: "Mac"},
	{string: navigator.platform,subString: "Linux",identity: "Linux"},
	{string: navigator.platform,subString: "iPod",identity: "iPhone"},
	{string: navigator.platform,subString: "iPhone",identity: "iPhone"}
];

BrowserMetadata.prototype.searchString = function (data) {
	for (var i=0;i<data.length;i++)	{
		var dataString = data[i].string;
		var dataProp = data[i].prop;
		this.versionSearchString = data[i].versionSearch || data[i].identity;
		if (dataString) {
			if (dataString.indexOf(data[i].subString) != -1)
				return data[i].identity;
		}
		else if (dataProp)
			return data[i].identity;
	}
}

BrowserMetadata.prototype.searchVersion = function (dataString) {
	var index = dataString.indexOf(this.versionSearchString);
	if (index == -1) return;
	return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
}

BrowserMetadata.prototype.screenWidth = function () { 
	return screen.width;
}

BrowserMetadata.prototype.screenHeight = function () {
	return screen.height;
}

BrowserMetadata.prototype.save = function () {
    var response = new XMLHttpRequest();
    var url = this.saveUrl;
    url += "?browser=" + encodeURIComponent(this.browser);
    url += "&browserVersion=" + encodeURIComponent(this.version);
    url += "&os=" + encodeURIComponent(this.operatingSystem);
    url += "&width=" + encodeURIComponent(this.width);
    url += "&height=" + encodeURIComponent(this.height);
    // just save to cookie for now
    url += "&saveto=cookie";
    response.open("Get", url, false);
    response.send("");	
    // check code (200-299 is ok)
    var code = response.status;
    if ((code < 200 || code > 299) && code != 0) {
    	throw "Failed to save. URL: '" + url + "' returned HTTP " + code;
    }
}

/*
 * Determines the correct skin to render depending on the user's browser and
 * screen resolution.
 */
function BestSkin (browser) {
	this.browser = browser || new BrowserMetadata();
	this.url = this.getUrl();
}

BestSkin.prototype.browser;
BestSkin.prototype.url;
BestSkin.prototype.available = {
	firefox : {
		"2" : {
			lynx : {
				"/skins/lynx/1400x1050/firefox/2" : [1400, 1050],
				"/skins/lynx/1024x768/firefox/2" : [1024, 768]
			},
			ice : {
				"/skins/ice/1400x1050/firefox/2" : [1400, 1050],
				"/skins/ice/1024x768/firefox/2" : [1024, 768]
			}
		}
	} 
};
// link compatible browsers/version etc
BestSkin.prototype.available.firefox["3"] = BestSkin.prototype.available.firefox["2"];
BestSkin.prototype.available.safari = {
					"2" : BestSkin.prototype.available.firefox["2"],
					"3" : BestSkin.prototype.available.firefox["2"],
					"4" : BestSkin.prototype.available.firefox["2"]
					};
BestSkin.prototype.available.opera = {
					"8" : BestSkin.prototype.available.firefox["2"],
					"9" : BestSkin.prototype.available.firefox["2"],
					"10" : BestSkin.prototype.available.firefox["2"]
					};

BestSkin.prototype.defaultSkin = "skins/ice";

BestSkin.prototype.getUrl = function () {
	var url = this.defaultSkin;
	var app = this.browser.browser.toLowerCase();
	var ver = "" + this.browser.version;
	// trim point releases from version
	ver = ver.indexOf('.') != -1 ? ver.split('.')[0] : ver;
	var res = [this.browser.width, this.browser.height];
	// check by browser, version, and resolution (try newest skins first)
	var avail = this.available;

	// TEST CODE
	return url + (this.browser.browser == "Explorer" ? "/html/index-ie.html" : "/html/index.html");

	if (avail[app] && avail[app][ver]){
		// scan skins for a matching resolution
		var skins = avail[app][ver];
		for (var skin in skins) {			
			for (var root in skins[skin]) {				
				var resol = skins[skin][root];
				// accept the first resolution smaller than the user's screen.
				if (res[0] >= resol[0] && res[1] >= resol[1]) {
					return root + "/html/index.html";
				}
			}
		}		
	}
	return url + "/html/index.html";
}

function getProfile() {
	var url = "/profile/get/settings";
    var response = new XMLHttpRequest();
    response.open("Get", url, false);
    response.send("");	
    // check code (200-299 is ok)
    var code = response.status;
    if ((code < 200 || code > 299) && code != 0) {
    	throw "Failed to save. URL: '" + url + "' returned HTTP " + code;
    }
    var txt = response.responseText;
    return eval("(" + txt + ")");
}

/*
 * Utilities
 */
var preloadImages = function (images) {
	for (var i = 0; i < images.length; i++) {
		var img = document.createElement("img");
		img.src = images[i];
	}
}

function getTabs(tabcount) {
        tabcount = tabcount || 0;
        var str = "";
        for (var i = 0; i < tabcount; i++) {
                str += "\t";
        }
        return str;
}

function toString(obj, tabcount) {
        tabcount = tabcount || 0;
        var str = "{\n";
		var first = true;
        for (var name in obj) {
                var val = obj[name];
                if (typeof val == "object" && val) {
					// do not attempt circular references
					if (val && (val.id || val.nodeType)) {				
						val = val || {"id": "ref:node"};
						val = val.id;
					} else {
						val = toString(val, tabcount+1);
					}
                }				
				if (!first) {
					str += ",\n";
				}								
                str += getTabs(tabcount+1) + name + " : " + val;
				first = false;								
        }
        str += "\n" + getTabs(tabcount) + "}\n";
        return str;
}

Object.prototype.toString = function () {
	return toString(this, 0);
};

// Emulate XMLHttpRequest
if(!window.XMLHttpRequest){
    XMLHttpRequest = function() {
    	var list = ["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    	var impl;
    	for (var i = 0; i < list.length; i++) {
    		try {
    			 imple = new ActiveXObject(list[i]);
    		} catch (e) {
    			// YUM!! that one didn't work
    		}
    		return impl;
    	}
    	throw "Failed to find Active X implementation from list: " + list;
    };
};
