/**
 *  Quicktime plugin for converting anchors into Quicktime objects.
 *  @author:  M. Alsup (malsup at gmail dot com)
 *  @version: 1.1.0 (3/21/2007)
 *  http://www.malsup.com/jquery/media/
 *  Free beer and free speech. Enjoy!
 *
 *  This plugin converts anchor tags into Quicktime objects.
 *  Examples and documentation at: http://malsup.com/jquery/media/
 *
 *  Options are passed to the 'quicktime' function using an object literal.
 *  The following option keys are supported:
 *
 *  Options:
 *  -------
 *  width:       width of quicktime player[1] (default: 200)
 *  height:      height of quicktime player[1] (default: 200)
 *  version:     version of quicktime player required (default: '6,0,2,0')
 *  cls:         classname(s) to be applied to new element (default: anchor's classname)
 *  src:         source location of quicktime .mov file (default: value of href attr)
 *  caption:     text to be used as caption; use false for no caption (default: value of anchor text)
 *  attrs:       hash of attributes for the object/embed tags; eg: { autoplay: false } (default: empty object)
 *  elementType: type of element to replace anchor (span, div, etc) (default: 'div')
 *
 *  [1] height and width values can be embedded in the classname like this: <a class="quicktime w:450 h:450></a>
 *
 *  Example: convert all anchors with class of 'quicktime' to quicktime objects:
 *  $('a.quicktime').quicktime();
 *
 *  Example: convert myMovie anchor to quicktime object with no caption and explicit values 
 *           for autoplay, tabindex and title:
 *  $('#myMovie').quicktime( {
 *      attrs:   { autoplay: false, tabindex: 10, title: 'My Title' },
 *      caption: false
 *  } );
 */
jQuery.fn.quicktime = function(options) {
    return this.each(function() {
        var $this = jQuery(this);
        var cls = this.className;

		var qtplug ={
			classID: "02BF25D5-8C17-4B23-BC80-D3488ABDDC6B", 
			progID: ["QuickTimeCheckObject.QuickTimeCheck.1", "QuickTime.QuickTime"], 
			description: ["QuickTime"], 
			mimeType: ["video/quicktime"], 
			pluginsPage: "http://www.apple.com/quicktime/download/",  
			codeBase: "http://www.apple.com/qtactivex/qtplugin.cab"	
		};


        var opts = jQuery.extend({
            width:        ((cls.match(/w:(\d+)/)||[])[1]) || 200,
            height:       ((cls.match(/h:(\d+)/)||[])[1]) || 200,
            version:      '6,0,2,0',
            cls:          'qt_movie',
			id:			  'qt_div' + (this.id || this.className),  
            src:          $this.attr('href') || $this.attr('src'),
            caption:      $this.text(),
            attrs:        {controls:'ControlPanel',maintainaspect:true,autostart:true},
			closeTxt:	  'close',
			errTxt: 	  'You need a current <a href="#link" title="download QuickTime Plugin">QuickTime Plugin<\/a>',
            elementType:  'div'
        }, options || {});

        var allowObjectAtts = 'name,id,accesskey,title,class,tabindex,noexternaldata';
        var skip = 'width,height,src,classid,codebase';
        var skipEmbedAttrs  = skip + ',id,class,title,accesskey,noexternaldata,pluginspage';

        var objectAttrs = [], objectParms = [], embedAttrs = [];
        for (var key in opts.attrs) {
            if (allowObjectAtts.indexOf(key) > -1)
                objectAttrs.push(key +'="' + opts.attrs[key] + '"');
            else if (skip.indexOf(key) == -1)
                objectParms.push('<param name="'+ key +'" value="' + opts.attrs[key] + '">');
            if (skipEmbedAttrs.indexOf(key) == -1)
                embedAttrs.push(key +'="' + opts.attrs[key] + '"');
        }

        if (jQuery.browser.msie) {
            var a = ['<object width="' + opts.width + '" height="' + opts.height + '" '];
            if (objectAttrs) a.push(objectAttrs.join(' '));
            a.push(' classid="clsid:'+qtplug.classID+'"');
            a.push(' codebase="'+qtplug.codeBase+'#version=' + opts.version + '">');
            a.push('</ob'+'ject'+'>');
			
            var p = ['<param name="src" value="' + opts.src + '">'];
            if (objectParms.length) p.push(objectParms.join(''));
            
            var o = document.createElement(a.join(''));
            for (var i=0; i < p.length; i++)
                o.appendChild(document.createElement(p[i]));
        }
        else {
            var a = ['<embed width="' + opts.width + '" height="' + opts.height + '" src="' + opts.src + '" '];
            if (embedAttrs) a.push(embedAttrs.join(' '));
            a.push(' pluginspage="'+qtplug.pluginsPage+'"> </em'+'bed>');
        }

		var version=detectPluginVersion(qtplug);
		$this.attr("href","#");
		
		if(checkVersion(opts.version,version)==true){
			$this.click(function(){

		        // convert anchor to span/div/whatever...
				var $el = $("#"+ opts.id);
				if($el.length) $el.show();
				else {
			        var $el = jQuery('<' + opts.elementType + ' id="' + opts.id + '" class="' + opts.cls + '">');
	
					$el.hide();
					$(".qt_closebtn", $el).remove();
					var _closecon=$("<span></span>");;
					$(_closecon).addClass("qt_closebtn");
					//$(_closecon).css({width:moptions.width});
					var _closebtn=$('<a href="#">'+opts.closeTxt+'</a>');
					$(_closecon).append($(_closebtn));
					$(_closebtn).click(function(){
						var obj = $("object", $el)[0] || $("embed", $el)[0];
						obj.Stop();
						$el.hide();
						return false;
					  });
					
					$this.after($el);
					$el.show();
					jQuery.browser.msie ? $el.append(o) : $el.html(a.join(''));
					$el.prepend($(_closecon));
					}
				 return false;
				});
        } else {
			$this.click(function(){
				$(".qt_onfailure").remove();
				var errtxt='<div class="qt_onfailure">'+opts.errTxt.replace(/#link/,qtplug.pluginsPage)+'</div>';
				//console.log("err=%s", errtxt);
				$this.after($(errtxt));
				return false;
			});
		}	


 function checkVersion (reqver,uaver){
	if (typeof(uaver)=='undefined' || uaver=='not installed')return false;
	else {
		if(uaver=='unknown') return true;	// wmedia && npapi
		var _uav = uaver.split(",");
		var _rqv = reqver.toString().replace(/\./,",").split(",");
		for(var i = 0; i < 3; i++) {
			_uav[i] = parseInt(_uav[i] || 0);
			_rqv[i] = parseInt(_rqv[i] || 0);
			if(_uav[i] < _rqv[i]) return false;
			if(_uav[i] > _rqv[i]) return true;
		}
		return true;
}};

function detectPluginVersion(qt){
	var _np=navigator.plugins;
	if (_np && _np.length){
		for (var _i = 0; _i < _np.length; _i++){
			var _p = _np[_i];
			// var _sl= qt.description.length;
			for (var _ii = 0; _ii < 1; _ii++){
				if (_p.name.indexOf(qt.description[_ii]) != -1) {
					var test = 1;
					var ver = _p.name.replace(/([a-zA-Z]|\s|-)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").replace(/(\.)/g,",");
					return ver;
				}
			}
		}
	}
	if(window.ActiveXObject) {
	  for (_i = 0; _i < qt.progID.length; _i++){
			var _axon= qt.progID[_i];
			try {
				var _axo = new ActiveXObject(_axon);
				return _axo.QuickTimeVersion.toString(16).replace(/(\d)/g,"$1,").toString().replace(/\./,",");
				} catch (e) {}
	  }
	}
	return 'not installed'; 
};
 
});
	
};
