/**
 * Unobtrusive QuickTime Objects (UQTO) v0.1 <http://www.cyberspacement.com/uqto/>
 * 
 * @projectDescription UQTO is a DOM script that detects the QuickTime plug-in and 
 * embeds QuickTime Objects (files with the .mov extension). It has its roots in 
 * the Web Standards community and is designed to support W3C standards compliant, 
 * accesible and search engine friendly web design.
 * 
 * @version 0.1
 * 
 * @author Frederik Krautwald
 * @copyright Copyright 2006 Cyberspacement Ltd. All rights Reserved.
 * @license This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
 */

var UQTO = {
	req: ["movie", "height", "width", "majorversion", "minorversion"],
	opt: ["controller", "cache", "bgcolor", "scale", "kioskmode", "fov"],
	optAtt: ["id", "name", "align"],
	optExc: [],
	_ximovie: "uqto.mov",
	_xiwidth: "215",
	_xiheight: "138",
	_ua: navigator.userAgent.toLowerCase(),
	_pluginType: "",
	_qtv: [0, 0],
	_qtoList: [],
	
	create: function(QTO, id) {
		if (!UQTO.uaHas("w3cdom") || UQTO.uaHas("ieMac")) return;
		UQTO.getQTVersion();
		UQTO._qtoList[id] = UQTO.updateQTO(QTO);
		UQTO.createCSS("#" + id, "visibility:visible");
		UQTO.DOMLoad(id);
	},
	
	updateQTO: function(QTO) {
		if (typeof QTO.xi != "undefined" && QTO.xi == "true") {
			if (typeof QTO.ximovie == "undefined") QTO.ximovie = UQTO._ximovie;
			if (typeof QTO.xiwidth == "undefined") QTO.xiwidth = UQTO._xiwidth;
			if (typeof QTO.xiheight == "undefined") QTO.xiheight = UQTO._xiheight;
		}
		QTO.mainCalled = false;
		return QTO;
	},
	
	createCSS: function(selector, declaration) {
		var _head = document.getElementsByTagName("head")[0];
		var _style = UQTO.createElement("style");
		if (!UQTO.uaHas("ieWin")) _style.appendChild(document.createTextNode(selector + "{" + declaration + "}")); // bugs in IE/Win
		_style.setAttribute("type", "text/css");
		_style.setAttribute("media", "screen"); 
		_head.appendChild(_style);
		if (UQTO.uaHas("ieWin") && document.styleSheets && document.styleSheets.length > 0) {
			var _ls = document.styleSheets[document.styleSheets.length - 1];
			if (typeof _ls.addRule == "object") _ls.addRule(selector, declaration);
		}
	},
	
	setContainerCSS: function(id) {
		var _qto = UQTO._qtoList[id];
		var _w = /%/.test(_qto.width) ? "" : "px";
		var _h = /%/.test(_qto.height) ? "" : "px";
		UQTO.createCSS("#" + id, "width:" + _qto.width + _w +"; height:" + _qto.height + _h +";");
		if (_qto.width == "100%") {
			UQTO.createCSS("body", "margin-left:0; margin-right:0; padding-left:0; padding-right:0;");
		}
		if (_qto.height == "100%") {
			UQTO.createCSS("html", "height:100%; overflow:hidden;");
			UQTO.createCSS("body", "margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0; height:100%;");
		}
	},

	createElement: function(el) {
		return (UQTO.uaHas("xml") && typeof document.createElementNS != "undefined") ?  document.createElementNS("http://www.w3.org/1999/xhtml", el) : document.createElement(el);
	},

	createObjParam: function(el, aName, aValue) {
		var _p = UQTO.createElement("param");
		_p.setAttribute("name", aName);	
		_p.setAttribute("value", aValue);
		el.appendChild(_p);
	},
	
	DOMLoad: function(id) {
		var _t = setInterval(function() {
			if ((document.getElementsByTagName("body")[0] != null || document.body != null) && document.getElementById(id) != null) {
				UQTO.main(id);
				clearInterval(_t);
			}
		}, 250);
		if (typeof document.addEventListener != "undefined") {
			document.addEventListener("DOMContentLoaded", function() { UQTO.main(id); clearInterval(_t); } , null); // Gecko, Opera 9+
		}
	},
	
	main: function(id) {
		var _qto = UQTO._qtoList[id];
		if (_qto.mainCalled) return;
		UQTO._qtoList[id].mainCalled = true;
		document.getElementById(id).style.visibility = "hidden";
		if (UQTO.hasRequired(id)) {
			if (UQTO.hasQTVersion(parseInt(_qto.majorversion, 10), parseInt(_qto.minorversion, 10))) {
				if (typeof _qto.setcontainercss != "undefined" && _qto.setcontainercss == "true") UQTO.setContainerCSS(id);
				UQTO.writeMOV(id);
			}
			else if (_qto.xi == "true" && UQTO.hasQTVersion(4, 1)) {
				UQTO.createDialog(id);
			}
		}
		document.getElementById(id).style.visibility = "visible";
	},

	uaHas: function(feat) {
		var _ua = UQTO._ua;
		switch(feat) {
			case "w3cdom":
				return (typeof document.getElementById != "undefined" && typeof document.getElementsByTagName != "undefined" && (typeof document.createElement != "undefined" || typeof document.createElementNS != "undefined"));
			case "xml":
				var _m = document.getElementsByTagName("meta");
				var _l = _m.length;
				for (var i = 0; i < _l; i++) {
					if (/content-type/i.test(_m[i].getAttribute("http-equiv")) && /xml/i.test(_m[i].getAttribute("content"))) return true;
				}
				return false;
			case "ieMac":
				return /msie/.test(_ua) && !/opera/.test(_ua) && /mac/.test(_ua);
			case "ieWin":
				return /msie/.test(_ua) && !/opera/.test(_ua) && /win/.test(_ua);
			case "gecko":
				return /gecko/.test(_ua) && !/applewebkit/.test(_ua);
			case "opera":
				return /opera/.test(_ua);
			case "safari":
				return /applewebkit/.test(_ua);
			default:
				return false;
		}
	},
	
	getQTVersion: function() {
		if (UQTO._qtv[0] != 0) return;
		if (navigator.plugins.length) {
			for (var i = 0; i < navigator.plugins.length; i++) {
				var _n = navigator.plugins[i].name;
				var _d = navigator.plugins[i].description;
				if (_n.indexOf("QuickTime") >= 0 || _d.indexOf("QuickTime") >= 0) {
					_n = _n.replace(/^.*\s+(\S+$)/, "$1");
					var _major = parseInt(_n.replace(/^(.*)\..*$/, "$1"), 10);
					var _minor = parseInt(_n.replace(/^(\d*\.)/, ""), 10);
					var _patch = parseInt(_n.match(/(\d)/g)[2]) ? parseInt(_n.match(/(\d)/g)[2]) : 0;
					var _r = /r/.test(_n) ? parseInt(_n.replace(/^.*r(.*)$/, "$1"), 10) : 0;
					UQTO._qtv = [_major, _minor];
					UQTO._pluginType = "npapi";
				}
			}
		} else if (window.ActiveXObject) {
			UQTO._pluginType = "ax";
			try {
				var _a = new ActiveXObject("QuickTimeCheckObject.QuickTimeCheck.1");
			} catch(e) {
				alert(e);
			}
			if (typeof _a == "object") {
				_a.IsQuickTimeAvailable(0);
				var qtv = _a.QuickTimeVersion;
				qtv = from10toradix(qtv, 16);
				var _major = parseInt(qtv / 1000000, 10);
				var _minor = parseInt((qtv - _major * 1000000) / 100000, 10);
				var _patch = parseInt((qtv - (_major * 1000000 + _minor * 100000)) / 10000, 10);
				var _r = (qtv - parseInt(qtv / 10000, 10) * 10000) / 100;
				UQTO._qtv = [_major, _minor];
			}
		}
	},
	
	hasRequired: function(id) {
		var _l = UQTO.req.length;
		for (var i = 0; i < _l; i++) {
			if (typeof UQTO._qtoList[id][UQTO.req[i]] == "undefined") return false;
		}
		return true;
	},
	
	hasQTVersion: function(major, minor) {
		return (UQTO._qtv[0] > major || (UQTO._qtv[0] == major && UQTO._qtv[1] >= minor)) ? true : false;
	},
	
	writeMOV: function(id) {
		var _qto = UQTO._qtoList[id];
		var _e = document.getElementById(id);
		if (UQTO._pluginType == "npapi") {
			if (UQTO.uaHas("gecko") || UQTO.uaHas("xml")) {
				while(_e.hasChildNodes()) {
					_e.removeChild(_e.firstChild);
				}
				var _obj = UQTO.createElement("object");
				_obj.setAttribute("class", "mov");
				_obj.setAttribute("type", "video/quicktime");
				_obj.setAttribute("data", _qto.movie);
				_obj.setAttribute("width", _qto.width);
				_obj.setAttribute("height", _qto.height);
				var _l = UQTO.optAtt.length;
				for (var i = 0; i < _l; i++) {
					if (typeof _qto[UQTO.optAtt[i]] != "undefined") _obj.setAttribute(UQTO.optAtt[i], _qto[UQTO.optAtt[i]]);
				}
				var _o = UQTO.opt.concat(UQTO.optExc);
				var _l = _o.length;
				for (var i = 0; i < _l; i++) {
					if (typeof _qto[_o[i]] != "undefined") UQTO.createObjParam(_obj, _o[i], _qto[_o[i]]);
				}
				_e.appendChild(_obj);
			}
		} else if (UQTO._pluginType == "ax") {
			var _objAtt = "";
			var _l = UQTO.optAtt.length;
			for (var i = 0; i < _l; i++) {
				if (typeof _qto[UQTO.optAtt[i]] != "undefined") _objAtt += ' ' + UQTO.optAtt[i] + '="' + _qto[UQTO.optAtt[i]] + '"';
			}
			var _objPar = "";
			var _l = UQTO.opt.length;
			for (var i = 0; i < _l; i++) {
				if (typeof _qto[UQTO.opt[i]] != "undefined") _objPar += '<param name="' + UQTO.opt[i] + '" value="' + _qto[UQTO.opt[i]] + '" />';
			}
			var _p = window.location.protocol == "https:" ? "https:" : "http:";
			_str = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"' + ' codebase="' + _p + '//www.apple.com/qtactivex/qtplugin.cab"' + _objAtt + ' width="' + _qto.width + '" height="' + _qto.height + '"><param name="src" value="' + _qto.movie + '" />' + _objPar + '</object>';
			_e.innerHTML = _str;
			//_e.innerHTML = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"' + ' codebase="' + _p + '//www.apple.com/qtactivex/qtplugin.cab"' + _objAtt + ' width="' + _qto.width + '" height="' + _qto.height + '"><param name="src" value="' + _qto.movie + '" />' + _objPar + '</object>';
		}
	},

	cleanupIELeaks: function() {
		var _o = document.getElementsByTagName("object");
		var _l = _o.length
		for (var i = 0; i < _l; i++) {
			_o[i].style.display = "none";
			for (var x in _o[i]) {
				if (typeof _o[i][x] == "function") {
					_o[i][x] = null;
				}
			}
		}
	}
};

if (typeof window.attachEvent != "undefined" && UQTO.uaHas("ieWin")) {
	window.attachEvent("onunload", UQTO.cleanupIELeaks);
}

/**
 * Utility functions
 */
function initArray() {
    this.length = initArray.arguments.length;
    for (var i = 0; i < this.length; i++)
        this[i] = initArray.arguments[i];
}

function from10toradix(value,radix){
    var retval = '';
    var ConvArray = new initArray(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F');
    var intnum;
    var tmpnum;
    var i = 0;

    intnum = parseInt(value,10);
    if (isNaN(intnum)){
        retval = 'NaN';
    }else{
        while (intnum > 0.9){
            i++;
            tmpnum = intnum;
            // cancatinate return string with new digit:
            retval = ConvArray[tmpnum % radix] + retval;  
            intnum = Math.floor(tmpnum / radix);
            if (i > 100){
                // break infinite loops
                retval = 'NaN';
                break;
            }
        }
    }
    return retval;
}
