/***
Utility functions for ac_media. Removing dependency on Prototype and Scriptaculous. 
Currently using some functions directly from prototype to manage legacy issues.
***/

Object.extend = function(destination, source) {
	for (var property in source)
    	destination[property] = source[property];
  	return destination;
};

Object.extend(String.prototype, {
	blank: function() {
	    return /^\s*$/.test(this);
	 }		
});
	
Object.extend(Function.prototype, {
  	// argumentNamesAC: function() {
  	//    	var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
  	//    	return names.length == 1 && !names[0] ? [] : names;
  	// },

  bindAC: function() {
    if (arguments.length < 2 && typeof(arguments[0]) == undefined) return this;
    	var __method = this, args = NodeListToArr(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat(NodeListToArr(arguments)));
    }
  },

  bindAsEventListenerAC: function() {
    var __method = this, args = NodeListToArr(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  }
});

Object.extend(Object, {
	isString: function(object) {
	    return typeof object == "string";
	},
	clone: function(object) {
	    return Object.extend({ }, object);
	},
 	isHash: function(object) {
 	    return object instanceof Hash;
 	},
	isJSON: function() {
	    var str = this;
	    if (str.blank()) return false;
	    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
	    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
	},
 	evalJSON: function(sanitize) {
 	    // var json = this.unfilterJSON();
 	    try {
 	      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
 	    } catch (e) {}
 	    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
 	},
	keys: function(object) {
	    var keys = [];
	    for (var property in object)
	      keys.push(property);
	    return keys;
	},
	isArray: function(object) {
	    return object != null && typeof object == "object" &&
	      'splice' in object && 'join' in object;
	}
 });

var ACUtils={

getById: function(elem){
	if (Object.isString(elem)){
	    return document.getElementById(elem);
	}else return elem;
},
getByClass: function(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	for(var i=0; i<elements.length; i++){
		if(testClass.test(elements[i].className)){
			returnElements.push(elements[i]);
		}
	}
	return returnElements;	
},
hasClassName: function(elem,cls) {
	if (elem && elem.className)
	return elem.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
},
addClassName: function(elem,cls) {
	if (!this.hasClassName(elem,cls)) elem.className += " "+cls;
},
removeClassName: function(elem,cls) {
	if (this.hasClassName(elem,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		elem.className=elem.className.replace(reg,' ');
	}
},
hideElement: function(element) {
	if (Object.isString(element)) element = document.getElementById(element);
    element.style.display = 'none';
    return element;
},
showElement: function(element) {
	if (Object.isString(element)) element = document.getElementById(element);
   	element.style.display = '';
   	return element;
 },
addEventHandler: function(element,eventName,handlerName){
	if ( element.addEventListener ){
		element.addEventListener(eventName, handlerName, false);
	}else if ( element.attachEvent ){
		var r =element.attachEvent("on" + eventName, handlerName);
	}else{
		element["on" + eventName] = handlerName;
	}
	return element;
},
removeEventHandler: function(element,eventName,handlerName){
	if (element.removeEventListener) {
        element.removeEventListener(eventName, handlerName, false);
    } else {
        element.detachEvent("on" + eventName, handlerName);
    }
	return element;
},
getStyle: function(element, style) {
    var element = (element);
    style = style == 'float' ? 'cssFloat' : this.camelize(style);
    var value = element.style[style];
    if (!value) {
	if(document.defaultView && document.defaultView.getComputedStyle){
    	var css = document.defaultView.getComputedStyle(element, null);
	}
    	value = css ? css[style] : null;
   }
   if (style == 'opacity') return value ? parseFloat(value) : 1.0;
   return value == 'auto' ? null : value;
 },
 camelize: function(str) {
   var parts = str.split('-'), len = parts.length;
   if (len == 1) return parts[0];

   var camelized = str.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },
makePositioned: function(element) {
	var elem = ACUtils.getById(element);
	var pos = ACUtils.getStyle(element, 'position');
	if (pos == 'static' || !pos) {
	     element._madePositioned = true;
	     element.style.position = 'relative';
	     // Opera returns the offset relative to the positioning context, when an
	     // element is position relative but top and left have not been defined
	     if (window.opera) {
	        element.style.top = 0;
	        element.style.left = 0;
	     }
	}
	return element;
},
isWebKit: function(){
	var agent = navigator.userAgent.toLowerCase();;
    return !!agent.match(/AppleWebKit/i);
},
getCoords1: function(event){
	if (event.pageX == null){
      // IE case
      var d= (document.documentElement && 
              document.documentElement.scrollLeft != null) ?
             document.documentElement : document.body;
      docX= event.clientX + d.scrollLeft;
      docY= event.clientY + d.scrollTop;
   }
   else{
      // all other browsers
      docX= event.pageX;
      docY= event.pageY;
   }
   return {x:docX,y:docY};
},
getCoords:function(event){
	// console.log("from getcoords="+event.pageX +"  "+event.pageY)
	return {
        x: event.pageX || (event.clientX +
          (document.documentElement.scrollLeft || document.body.scrollLeft)),
        y: event.pageY || (event.clientY +
          (document.documentElement.scrollTop || document.body.scrollTop))
      };
},
whichClick: function(event){
if (event.which == null)
       /* IE case */
       button= (event.button < 2) ? "LEFT" : ((event.button == 4) ? "MIDDLE" : "RIGHT");
    else
       /* All others */
       button= (event.which < 2) ? "LEFT" : ((event.which == 2) ? "MIDDLE" : "RIGHT");
	return button;
},
isLeftClick: function(event){
	if(this.whichClick(event) == "LEFT") 
		return true;
	 else return false;	
},
getTarget: function(e){
	return (typeof e.target != 'undefined') ? e.target : e.srcElement;	
},
cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return this._returnOffset(valueL, valueT);
  },
_returnOffset: function(l, t) {
  	var result = [l, t];
	result.left = l;
	result.top = t;
	return result;
},
stopEvent: function(e){
	if (!e) var e = window.event;
	 if (e.stopPropagation) {
		e.stopPropagation();
	 }else{ 
		 e.cancelBubble = true;
	}

	if(e.preventDefault)e.preventDefault();
    
      e.stopped = true;
	
},
removeChildNodes: function(obj){
	try {
		if(obj.hasChildNodes() && obj.childNodes) {
			while(obj.firstChild) {
				obj.removeChild(obj.firstChild);
			}
		}
	}catch(e) {}		
},
emptyFunction: function() { },
trim: function(str) { 
   	var newstr;
	  newstr = str.replace(/^\s*/, "").replace(/\s*$/, ""); 
	  newstr = newstr.replace(/\s{2,}/, " "); 
	  return newstr;
}


}//end ACUtils

ACUtils.Detector ={

    getAgent: function()
    {
        return navigator.userAgent.toLowerCase();
    },

    isMac: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/mac/i);
    },

	isSnowLeopard: function(userAgent)
	{
		var agent = userAgent || this.getAgent();
		return !!agent.match(/mac os x 10_6/i);
	},

    isWin: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/win/i);
    },

    isWin2k: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return this.isWin(agent) && (agent.match(/nt\s*5/i));
    },

    isWinVista: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return this.isWin(agent) && (agent.match(/nt\s*6\.0([0-9]{0,2})?/i));
    },

    isWebKit: function(userAgent)
    {
        if(this._isWebKit === undefined) {
            var agent = userAgent || this.getAgent();
            this._isWebKit =  !!agent.match(/AppleWebKit/i);
            this.isWebKit = function() {
                return this._isWebKit;
            };
        }
        return this._isWebKit;
    },

    isSafari2: function(userAgent)
    {
        if(this._isSafari2 === undefined) {
            if (!this.isWebKit()) {
                this._isSafari2 = false;
            } else {
                var ua = navigator.userAgent.toLowerCase();
               var version = parseInt(parseFloat(ua.substring(ua.lastIndexOf('safari/') + 7)), 10);
                this._isSafari2 = (version >= 419);
            }
            this.isSafari2 = function() {
                return this._isSafari2;
            };
        }
        return this._isSafari2;
    },

	isChrome: function(userAgent)
	{
		if(this._isChrome === undefined) {
			var agent = userAgent || this.getAgent();
			this._isChrome = !!agent.match(/Chrome/i);
			this.isChrome = function() {
				return this._isChrome;
			};
		}
		return this._isChrome;
	},
	
    isOpera: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/opera/i);
    },

    isIE: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/msie/i);
    },

    isIEStrict: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return agent.match(/msie/i) && !this.isOpera(agent);
    },

	// Returns whether or not the browser is IE8+
	isIE8: function(userAgent) {
		var agent = userAgent || this.getAgent();

		var match = agent.match(/msie\D*([\.\d]*)/i);
     	if (match && match[1]) {
        	version = match[1];
      	}

		return +version >= 8;
	},

    isFirefox: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/firefox/i);
    },

	/*Returns an array with the version numbers*/
	iPhoneOSVersion: function(userAgent) {
		//OSString: Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_0 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/XXXXX Safari/525.20
        var agent = userAgent || this.getAgent(),
			isMobile = this.isMobile(agent),
			OSString, OSStringParts, version;
		if(isMobile) {
			//Now looks at user agent
			var OSString = agent.match(/.*CPU ([\w|\s]+) like/i);
			if(OSString && OSString[1]) {
				OSStringParts = OSString[1].split(" ");
				version = OSStringParts[2].split("_");
				return version;
			}
			else {
				//iPhone running  : Mozilla/5.0 (iPod; U; CPU iPhone OS 2_2_1 like Mac OS X; pl-pl) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5H11 Safari/525.20
				//iPod touch running iPhone OS 1.1.3 user agent string: Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3
				//iPhone running iPhone OS 1.0 user agent string: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3

				return [1];
			}

		}
		else return null;

	},

    isiPad: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
		//iPad running: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
        return !!(this.isWebKit(agent) && agent.match(/ipad/i));
    },

    isMobile: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return this.isWebKit(agent) && (agent.match(/Mobile/i) && !this.isiPad(agent));
    },

    _isQTInstalled: undefined,

    isQTInstalled: function()
    {

		if(this._isQTInstalled === undefined) {
	        var qtInstalled = false;

	        if (navigator.plugins && navigator.plugins.length) {

	            for(var i=0; i < navigator.plugins.length; i++ ) {
	                var plugin = navigator.plugins[i];

	                if (plugin.name.indexOf("QuickTime") > -1) {
	                    qtInstalled = true;
	                }
	            }
	        } else if (typeof(execScript) != 'undefined') {
	            qtObj = false; //global variable written to by vbscript for ie
	            execScript('on error resume next: qtObj = IsObject(CreateObject("QuickTimeCheckObject.QuickTimeCheck.1"))','VBScript');
	            qtInstalled = qtObj;
	        }

			this._isQTInstalled = qtInstalled;
		}
		return this._isQTInstalled;
    },

    getQTVersion: function()
    {
        var version = "0";

        if (navigator.plugins && navigator.plugins.length) {
            for (var i = 0; i < navigator.plugins.length; i++) {

                var plugin = navigator.plugins[i];

                //Match: QuickTime Plugin X.Y.Z
                var match = plugin.name.match(/quicktime\D*([\.\d]*)/i);
                if (match && match[1]) {
                    version = match[1];
                }
            }
        } else if (typeof(execScript) != 'undefined') {
            ieQTVersion=null;

            execScript('on error resume next: ieQTVersion = CreateObject("QuickTimeCheckObject.QuickTimeCheck.1").QuickTimeVersion','VBScript');

            if(ieQTVersion){
                // ieQTVersion is comes back as '76208000' when 7.6.2 is installed.
                version = ieQTVersion.toString(16);
                version = [version.charAt(0), version.charAt(1), version.charAt(2)].join('.');
            }
        }

        return version;
    },

    isQTCompatible: function(required, actual)
    {
        function areCompatible(required, actual) {

            var requiredValue = parseInt(required[0], 10);
            if (isNaN(requiredValue)) {
                requiredValue = 0;
            }

            var actualValue = parseInt(actual[0], 10);
            if (isNaN(actualValue)) {
                actualValue = 0;
            }

            if (requiredValue === actualValue) {
                if (required.length > 1) {
                    return areCompatible(required.slice(1), actual.slice(1));
                } else {
                    return true;
                }
            } else if (requiredValue < actualValue) {
                return true;
            } else {
                return false;
            }
        }

        var expectedVersion = required.split(/\./);
        var actualVersion = actual ? actual.split(/\./) : this.getQTVersion().split(/\./);

        return areCompatible(expectedVersion, actualVersion);
    },

    isValidQTAvailable: function(required)
    {
        return this.isQTInstalled() && this.isQTCompatible(required);
    },

	isSBVDPAvailable: function(required) {
        return false;
	},

    isCSSAvailable: function(property) {
        try {
            var temp = document.createElement('div').style;
            property = property.toLowerCase();
            temp.setProperty('-webkit-'+property, 'inherit', null);
            temp.setProperty('-moz-'+property, 'inherit', null);
            temp.setProperty('-o-'+property, 'inherit', null);
            temp.setProperty(property, 'inherit', null);

            return (temp.getPropertyValue('-webkit-'+property) == 'inherit' ||
                    temp.getPropertyValue('-moz-'+property) == 'inherit' ||
                    temp.getPropertyValue('-o-'+property) == 'inherit' ||
                    temp.getPropertyValue(property) == 'inherit');
        } catch(e) {
            return false;
        }
    }
	
}


function concat(a, b) {
  for (var i = 0, node; node = b[i]; i++)
    a.push(node);
  return a;
}

function NodeListToArr(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

if (navigator.userAgent.indexOf('AppleWebKit/') > -1) {
  NodeListToArr = function(iterable) {
    if (!iterable) return [];
    if (!(typeof(iterable) == "function" && iterable == '[object NodeList]') &&
        iterable.toArray) return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  };
};

var animateEffects= {};
animateEffects.opacity= function(elem, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 80); 
    var timer = 0;
	this.i =0; 
	this.opac = opac= opacStart;
	var id = ((typeof elem == "object") ? elem.id : document.getElementById(elem).id);
	
    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
		for (i =1; i<=80; i++){
            if(fadeinId)clearTimeout(fadeinId);
			var fadeoutId =setTimeout("animateEffects.changeOpac(" + opac + ",'" + id + "')",(i * speed)); 
			this.opac= opac= opacStart-((opacStart-opacEnd)/80)*i;
            timer++; 
        } 
    } else if(opacStart < opacEnd) { 
	
 		for (i =1; i<=80; i++)
            {
		    if(fadeoutId)clearTimeout(fadeoutId);
			var fadeinId=setTimeout("animateEffects.changeOpac(" + opac + ",'" + id + "')",(i * speed)); 
			this.opac= opac=opacStart+((opacEnd-opacStart)/80)*i;
			// console.log("opac="+this.opac)			
        } 
    }
}
//change the opacity for different browsers 
animateEffects.changeOpac= function(opacity, id) { 
	var agent = ACUtils.Detector.getAgent();

	if(id)
    var node = (typeof id == 'object' ? id : document.getElementById(id)); 
	if(node){
    	node.style.opacity = (opacity); 
	    node.style.MozOpacity = (opacity); 
	    node.style.KhtmlOpacity = (opacity); 
		if (ACUtils.Detector.isIEStrict() && (!node.currentStyle.hasLayout)) node.setStyle({zoom: 1});
	    node.style.filter = "alpha(opacity=" + opacity*100 + ")";
		if (ACUtils.Detector.getAgent().match(/msie 8/i)) {
			if((opacity *100) >50){//IE8 needs this
				node.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://images.apple.com/global/ac_media_player/elements/quicktime/ac_media_regular_background.png', sizingMethod='crop')";
			}
		}
	}
} 

var ACUtilsAjax =  {
	
getTransport: function(){
	var request = false;
   try {
     request = new XMLHttpRequest();
   } catch (e) {//trymicrosoft
     try {
       request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {//othermicrosoft
       try {
         request = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (e) {//failed
         request = false;
       }  
     }
   }return request;
}


};//Ajax ends
var trackingIndex =0;
ACUtilsAjax.AjaxTracker={
	responders :[]
}
ACUtilsAjax.AjaxRequest= function(url, options){
	var req = ACUtilsAjax.getTransport();
	var pass = trackingIndex++; 
	ACUtilsAjax.AjaxTracker.responders.push(pass);
	        req.onreadystatechange= function(){
	                // if(req.readyState != 4) return;
	                // if(req.status != 200) return;
	                ACUtilsAjax.AjaxResponse(req,options,pass);
	        }
	        req.open(options.method,url,true);
	        req.setRequestHeader('Content-Type',options.contentType);
	        req.send(null);		
}

ACUtilsAjax.AjaxResponse= function(req,options,pass){
	var complete = false;
	if(req.readyState == 4){
		if(req.status >= 200 && req.status < 300){
		options.onSuccess ? options.onSuccess(req) : ACUtils.emptyFunction();
		complete= true;
	}else if(req.status >= 400 && req.status < 500){
		options.onFailure ? options.onFailure(req) : ACUtils.emptyFunction();
		complete= true;
	}else if(req.status >= 300 && req.status < 400){
		//redirect
		complete = true;
	}else if(req.status >= 500 && req.status < 600){
		options.onError ? options.onError(req) : ACUtils.emptyFunction();
		complete= true;
	}	
	if(complete === true){
		options.onComplete ? options.onComplete(req) : ACUtils.emptyFunction();
		for (n=0; n<ACUtilsAjax.AjaxTracker.responders.length; n++){
			if(req){
				if(ACUtilsAjax.AjaxTracker.responders[n] == pass){
					req=null;
					ACUtilsAjax.AjaxTracker.responders.splice(n,1);
				}
			}
		}
	}
  }			
}


if (!Control) var Control = { };
//***Slider****/
// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider = function(handle, track, options){

    if (Object.isArray(handle)) {
      this.handles =handle;
    } else {
      this.handles =[ACUtils.getById(handle)];
    }
    
    this.track   = ACUtils.getById(track);
    this.options = options || { };
  this.initialize= function() {
    var slider = this;
    this.lock = false;// to lock out timer updates from clashing with setValue update
	

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || new Array(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = [0];//this.handles.map( function() { return 0 });
    // this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    // this.options.startSpan = $(this.options.startSpan || null);
    // this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range[1];
    this.minimum   = this.options.minimum || this.range[0];

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if (this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy() : false;
    if (this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListenerAC(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListenerAC(this);
    this.eventMouseMove = this.update.bindAsEventListenerAC(this);

    // Initialize handles in reverse (make sure first handle is active)
 /*
	this.handles.each( function(h,i) {
   i = slider.handles.length-1-i;
   slider.setValue(parseFloat(
     (Object.isArray(slider.options.sliderValue) ? 
       slider.options.sliderValue[i] : slider.options.sliderValue) || 
      slider.range[0]), i);
   h.makePositioned().observe("mousedown", slider.eventMouseDown);
 });*/
    slider.setValue(parseFloat(slider.options.sliderValue ?  slider.options.sliderValue : slider.range[0]));
    ACUtils.makePositioned(this.handles[0]);
	ACUtils.addEventHandler(this.handles[0],"mousedown", slider.eventMouseDown);

    
    ACUtils.addEventHandler(this.track, "mousedown", this.eventMouseDown);
    ACUtils.addEventHandler(document, "mouseup", this.eventMouseUp);
    ACUtils.addEventHandler(document, "mousemove", this.eventMouseMove);
    
    this.initialized = true;
 
	};

  this.dispose= function() {
    var slider = this;    
    this.track.removeEventHandler( "mousedown", this.eventMouseDown);
    document.removeEventHandler( "mouseup", this.eventMouseUp);
    document.removeEventHandler( "mousemove", this.eventMouseMove);
    this.handles[0].removeEventHandler("mousedown", slider.eventMouseDown);
    
  };
  this.setDisabled= function(){
    this.disabled = true;
  };
  this.setEnabled= function(){
    this.disabled = false;
  };  
  this.getNearestValue= function(value){
    if (this.allowedValues){
      if (value >= this.allowedValues.max()) return(this.allowedValues.max());
      if (value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if (currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if (value > this.range[1]) return this.range[1];
    if (value < this.range[0]) return this.range[0];//console.log("value after getNearestValue="+value+ this.range[0]+'  '+this.range[1])
    return value;
  };
  this.setValue= function(sliderValue, handleIdx, bool){//console.log('sliderValue0='+sliderValue)
	// uncomment these two lines to enable click on track
	// if(this.lock === true) return;
	// if(bool === true) this.lock = true;
    if (!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if (this.initialized && this.restricted) {
      if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
// console.log("value before getNearest="+sliderValue+"  bool="+bool);
    sliderValue = this.getNearestValue(sliderValue);
	
    this.values[handleIdx] = sliderValue;

    this.value = this.values[0]; // assure backwards compat
    // console.log('this.value='+this.value)
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = 
      this.translateToPx(sliderValue);
    
    this.drawSpans();
    if (!this.dragging || !this.event){this.updateFinished();}
	// this.lock = false;
  };
  this.setValueBy= function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  };
  this.translateToPx= function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range[1]-this.range[0])) * 
      (value - this.range[0])) + "px";
  };
  this.translateToValue= function(offset) {
	// console.log(((offset/(this.trackLength-this.handleLength)*(this.range[1]-this.range[0])) + this.range[0]))
    return ((offset/(this.trackLength-this.handleLength)*(this.range[1]-this.range[0])) + this.range[0]);
  };
  this.getRange= function(range) {
    var v = this.values.sort(); 
    range = range || 0;
    return new Array(v[range],v[range+1]);
  };
  this.minimumOffset= function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  };
  this.maximumOffset= function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignX);
  };  
  this.isVertical=  function(){
    return (this.axis == 'vertical');
  };
  this.drawSpans= function() {
    var slider = this;
   /* if (this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if (this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if (this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
*/
  };
  this.setSpan= function(span, range) {
    if (this.isVertical()) {
      span.style.top = this.translateToPx(range[0]);
      span.style.height = this.translateToPx(range[1] - range[0] + this.range[0]);
    } else {
      span.style.left = this.translateToPx(range[0]);
      span.style.width = this.translateToPx(range[1] - range[0] + this.range[0]);
    }
  };
  this.updateStyles= function() {
    // this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    for (var i=0; i<this.handles.length; i++){
    	ACUtils.removeClassName(this.handles[i],'selected');
    }
    ACUtils.addClassName(this.activeHandle, 'selected');
  };
  this.startDrag= function(event) {//console.log("event from startDrag="+ACUtils.getTarget(event).className)
    if (ACUtils.isLeftClick(event)) {//console.log('left click')
      if (!this.disabled){
        this.active = true;
        
        var handle = ACUtils.getTarget(event);
        var pointer  = [ACUtils.getCoords(event).x, ACUtils.getCoords(event).y];//[Event.pointerX(event), Event.pointerY(event)];
// console.log(ACUtils.getCoords(event).x+'  '+ ACUtils.getCoords(event).y)
        var track = handle;

        if (track==this.track) {
          var offsets  = ACUtils.cumulativeOffset(this.track); 
		 
          this.event = event;
// console.log("pointer[0]="+pointer[0]+'  offsets[0]'+offsets[0]+"  handlelength="+this.handleLength)
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = ACUtils.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
            
          if (this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();
            
            var offsets  = ACUtils.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      ACUtils.stopEvent(event);
	    //uncomment code below to enable click on track 
	  	 // if(handle.className == "loadedProgress"){
	  	 // 			this.update(event);
	  	 // 		  }
    }
  };
  this.update= function(event) {
   if (this.active) {
      if (!this.dragging) this.dragging = true;
      this.draw(event);
      if (ACUtils.isWebKit()) window.scrollBy(0,0);
      ACUtils.stopEvent(event);
   }
  };
  this.draw= function(event) {
    var pointer = [ACUtils.getCoords(event).x, ACUtils.getCoords(event).y];//[Event.pointerX(event), Event.pointerY(event)];
    var offsets =  ACUtils.cumulativeOffset(this.track); 
// console.log("from this.draw this.offsetX="+this.offsetX+' this.offsetY='+this.offsetY+" offsets[0]="+offsets[0]+'offsets[1]='+offsets[1]);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
// console.log('from draw pointer[0]='+pointer[0]+' pointer[1]='+pointer[1])
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0]));
// console.log("this.values ="+this.values+"  this.value ="+this.value)
// console.log("this.values.length>1 ? this.values : this.value="+this.values.length>1 ? this.values : this.value);
    if (this.initialized && this.options.onSlide){//console.log("going to call slide")
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
	}
  };
  this.endDrag= function(event) {//console.log('endDrag')
    if (this.active && this.dragging) {//console.log('active and dragging')
      this.finishDrag(event, true);
      ACUtils.stopEvent(event);
    }
    this.active = false;
    this.dragging = false;
  };  
  this.finishDrag= function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  };
  this.updateFinished= function() {
    if (this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  };

};
/***end Slider******/






// = Apple Gracefully Degrading Media Playback =
//
// This script provides functionality for both creating video players
// that will use modern technology if possible, but fall back on QuickTime.
//
// Part of the functionality included herein is also video controls similar 
// to those in Show Leopard's QuickTime X Player.
//

/*jsl:ignoreall*/

var existingVideo = false,
	existingVideoSrc = false,
	playExistingVideo = false,
	languageJsonComplete = false,
	movieJsonLoaded = false, 
	movieJsonComplete = false,
	ac_media_language = false,
	isStreaming = false, 
	isLiveStreaming = false,
	isHTML5 = false,
	videoReceivedMetadata= false,
	initializedCP= false,
	replay= false;


var MediaLanguage = {
	translationDictionary: {
		"bg-BG": "bg-BG.json",
		"cs-CZ": "cs-CZ.json",
		"el-GR" : "el-GR.json",
		"de-AT": "de-AT.json",
		"de-CH": "de-CH.json",
		"de-DE": "de-DE.json",
		"da-DK": "da-DK.json",
		"en": "en.json",
		"en-US": "en-US.json",
		"en-AP": "en-AP.json",
		"en-CA": "en-CA.json",
		"en-GB": "en-GB.json",
		"en-HK": "en-HK.json",
		"en-IE": "en-IE.json",
		"en-IN": "en-IN.json",
		"en-KR": "en-KR.json",
		"en-AU": "en-AU.json",
		"en-NZ": "en-NZ.json",
		"en-SG": "en-SG.json",
		"en-ZA": "en-ZA.json",
		"es": "es.json",
		"es-LA": "es-LA.json",
		"es-MX": "es-MX.json",
		"es-ES": "es-ES.json",
		"et-EE": "et-EE.json",
		"fi-FI": "fi-FI.json",
		"fr": "fr.json",
		"fr-BE": "fr-BE.json",
		"fr-CA": "fr-CA.json",
		"fr-CH": "fr-CH.json",
		"fr-FR": "fr-FR.json",
		"hr-HR": "hr-HR.json",
		"hu-HU": "hu-HU.json",
		"it-IT": "it-IT.json",
		"ja": "ja.json",
		"ja-JP": "ja-JP.json",
		"ko-KR": "ko-KR.json",
		"lt-LT": "lt-LT.json",
		"lv-LV": "lv-LV.json",
		"nl-BE": "nl-BE.json",
		"nl-NL": "nl-NL.json",
		"no-NO": "no-NO.json",
		"pl-PL": "pl-PL.json",
		"pt": "pt.json",
		"pt-BR": "pt-BR.json",
		"pt-PT": "pt-PT.json",
		"ro-RO": "ro-RO.json",
		"ru-RU": "ru-RU.json",
		"sk-SK":  "sk-SK.json",
		"sv-SE": "sv-SE.json",
		"tr-TR": "tr-TR.json",
		"zh": "zh.json",
		"zh-CN": "zh-CN.json",
		"zh-HK": "zh-HK.json",
		"zh-TW": "zh-TW.json"
	},
	
	getLangFromAttr: function(attr) {
		if(!attr) {
			return 'en-US';
		}
		switch (attr.toLowerCase()) {
			case 'bg-bg':
				return 'bg-BG';
			case 'cs-cz':
				return 'cs-CZ';																															
			case 'de-at':
				return 'de-AT';
			case 'de-ch':
				return 'de-CH';
			case 'de-de':
				return 'de-DE';
			case 'da-dk':
				return 'da-DK';
			case 'el-gr':
				return 'el-GR';
			case 'en-us':
				return 'en-US';
			case 'en-ca':
				return 'en-CA';
			case 'en-ap':
				return 'en-AP';
			case 'en-au':
				return 'en-AU';
			case 'en-gb':
				return 'en-GB';
			case 'en-hk':
				return 'en-HK';
			case 'en-ie':
				return 'en-IE';
			case 'en-in':
				return 'en-IN';
			case 'en-nz':
				return 'en-NZ';
			case 'en-sg':
				return 'en-SG';
			case 'en-kr':
				return 'en-KR';
			case 'en-za':
				return 'en-ZA';
			case 'et-ee':
				return 'et-EE';
			case 'es-es':
				return 'es-ES';
			case 'es-419':
			case 'es-la':
				return 'es-LA';
			case 'es-mx':
				return 'es-MX';
			case 'fi-fi':
				return 'fi-FI';
			case 'fr-be':
				return 'fr-BE';
			case 'fr-ca':
				return 'fr-CA';
			case 'fr-ch':
				return 'fr-CH';
			case 'fr-fr':
				return 'fr-FR';
			case 'hr-hr':
				return 'hr-HR';
			case 'hu-hu':
				return 'hu-HU';
			case 'it-it':
				return 'it-IT';
			case 'ja-jp':
				return 'ja-JP';
			case 'ko-kr':
				return 'ko-KR';
			case 'lt-lt':
				return 'lt-LT';
			case 'lv-lv':
				return 'lv-LV';
			case 'nl-be':
				return 'nl-BE';
			case 'nl-nl':
				return 'nl-NL';
			case 'no-no':
				return 'no-NO';
			case 'pl-pl':
				return 'pl-PL';
			case 'pt':
			case 'pt-br':
				return 'pt-BR';
			case 'pt-pt':
				return 'pt-PT';
			case 'ro-ro':
				return 'ro-RO';
			case 'ru-ru':
				return 'ru-RU';
			case 'sv-se':
				return 'sv-SE';	
			case 'sk-sk':
				return 'sk-SK';
			case 'tr-tr':
				return 'tr-TR';
			case 'zh-cn':
				return 'zh-CN';
			case 'zh-hk':
				return 'zh-HK';
			case 'zh-tw':
				return 'zh-TW';
			default:
				return attr;
		}
	},
	
	
	getTranslations: function(delegate) {
		var html = document.getElementsByTagName('html').item(0),
			langAttr = html.getAttribute('lang'),
			lang = this.getLangFromAttr(langAttr),
			langFile = this.langDictionary(lang);
     
		if(ac_media_language === false){
		new ACUtilsAjax.AjaxRequest('/global/ac_media_player/scripts/ac_media_languages/'+langFile, {
			method:'get',
			requestHeaders: {Accept: 'application/json'},
			onSuccess: function(transport){
				ac_media_language = new Function("return "+transport.responseText)();
				// if(delegate && typeof delegate.translationDidLoad === "function") {
				// 					delegate.translationDidLoad();
				// 				}
				//func.call(((self) ? self : window),json);
			}.bindAC(this),
			onComplete: function(){
				languageJsonComplete = true;
				if(delegate && typeof delegate.translationDidLoad === "function") {
					delegate.translationDidLoad();
				}
			}.bindAC(this),
					
			evalJS: false
		});
		}else {
				languageJsonComplete = true;
				if(delegate && typeof delegate.translationDidLoad === "function") {
					delegate.translationDidLoad();
				}
		}
	},
	
	langDictionary: function(locale) {
		var language = locale.toLowerCase().split('-')[0],
			localeInfo = this.translationDictionary[locale] || false;

		if (!localeInfo) {
			localeInfo = this.translationDictionary[language];
		}
		if (!localeInfo) {
			localeInfo = this.translationDictionary['en'];
		}

		return localeInfo;
	}
};

var Media = {
	VERSION: '3.5',
    MIN_QUICKTIME_VERSION: '7.4',
	CAPTIONS_NS: 'http://www.w3.org/2006/04/ttaf1',
	container: null,
	src :null,
	options:null,

    create: function(container, src, options) {
        var element, innerface, controls, controller, 
			shouldBuildMediaSpecVideo = true, 
			shouldBuildMediaSpecQuickTime = true,
			shouldBuildMediaSpecSBVDP = true,
			ipad = ACUtils.Detector.isiPad();
			movieJsonLoaded = false;
			movieJsonComplete = false;
			languageJsonComplete = false;
			replay = false;
			
		Media.container=container;
		Media.src=src;
		Media.options=options;	

        // Do some browser-specific setup
		switch(true) {
			case Media.Detection.Firefox():
				ACUtils.addClassName(container, 'mozilla');
				break;
			case Media.Detection.Opera():
				ACUtils.addClassName(container, 'opera');
				break;
			case Media.Detection.IE():
				Media._createEventSource();
				break;
			default:
				break;
		}
		if (options.target === 'quicktimeplayer') {
			options.spec = 'qt';
		}

        if (options.spec) {
			switch(options.spec) {
				case 'qt':
	                shouldBuildMediaSpecVideo = false;
					shouldBuildMediaSpecSBVDP = false;
					break;
				case 'video': case 'audio':
					shouldBuildMediaSpecQuickTime = false;
					shouldBuildMediaSpecSBVDP = false;
					break;
				case 'sbvdp':
					shouldBuildMediaSpecVideo = false;
	                shouldBuildMediaSpecQuickTime = false;
					break;
				default:
					break;
			}
        }

		var iPhoneOSVersion = (Media.Detection.Mobile()) ? Media.Detection.iPhoneOSVersion() : null;

		if (iPhoneOSVersion && iPhoneOSVersion[0] < 3) {
			shouldBuildMediaSpecVideo = false;
			shouldBuildMediaSpecQuickTime = true;
		}
			
		switch(true) {
		
			case (ipad || (shouldBuildMediaSpecVideo && Media._isHTML5VideoAvailable() && !Media.Detection.Firefox() && !Media.Detection.Mobile() && !Media.Detection.Chrome() && !Media.Detection.Opera()) &&  !(ACUtils.Detector.getAgent().match(/msie 9/i)) ||(iPhoneOSVersion && iPhoneOSVersion[0] >=3)):
				// Create <video> player
				
				if(options.audio == true && typeof Media.Spec.Audio !== undefined) {
					return build(Media.Spec.Audio);
				}
				return build(Media.Spec.Video);
				break;
			case (shouldBuildMediaSpecQuickTime && Media._isQuickTimeAvailable(Media.MIN_QUICKTIME_VERSION)):
			case (iPhoneOSVersion && iPhoneOSVersion[0] < 3):
				// Create QuickTime player
			
				return build(Media.Spec.QuickTime);
				break;
			case (shouldBuildMediaSpecSBVDP && Media._isSBVDPAvailable(Media.MIN_SBVDP_VERSION)):
				// Create SBVDP player
				return build(Media.Spec.SBVDP);
				break;
			case Media._shouldShowDownloadPrompt():
			default:
		        // At this point we've determined there will be no video, 
		        // so show a download prompt if we need to, then return false;
				MediaLanguage.getTranslations(this);
				// Media.createDownloadPrompt(container, src, options);
				break;
		}
  
      
        function build(Spec) {

            // First, create a new controller...
            controller = Media.Controller(container);
            if(options.disableSizeSelector){
				controller.disableSizeSelector = options.disableSizeSelector;
			}
            if(options.disableFullscreenControl){
				controller.disableFullscreenControl = options.disableFullscreenControl;
			}
			if(options.expectingMovieJson){
				controller.expectingMovieJson = options.expectingMovieJson;
			}
			if(options.replay && options.replay == true){
				replay = true;
			}
            // ...then a video player (with a corresponding video interface)...
            element = Spec.create(container, src, options);
            innerface = Media.VideoInterface(element, controller);

			
			//Got to fake autolay for iPad:
			if(ipad && (options.autoplay === true || options.autostart === true)) {
				element.forcePlay();
				// alert("ipad = "+ipad+", options.autoplay = "+options.autoplay+", options.autostart = "+options.autostart);
				// var link = document.createElement("a"),
				// 	forcePlay = function(event) {
				// 		event.preventDefault();
				// 		element.play();
				// 	},
				// 	triggerEvent;
				// 	link.addEventListener("click",forcePlay,false);
				// 	document.body.appendChild(link);
				// 	triggerEvent = document.createEvent("MouseEvents");
				// 	if (triggerEvent.initMouseEvent) {
				// 		triggerEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				// 		link.dispatchEvent(triggerEvent);
				// 	}
				// 	document.body.removeChild(link);
				// 
			}

            // Now, customize the interface with events and/or polling, and custom methods.
            var eventsToRegister = Spec.eventsToRegister;
            for (var event in eventsToRegister) {
                var name = eventsToRegister[event].name || eventsToRegister[event],
                	fn = eventsToRegister[event].callback;
                
                innerface.registerEvent(event, name, fn);
            }
            
            if (Spec.pollForChanges) {
                innerface.pollForChanges(Spec.pollForChanges);
			}
                
            if (Spec.interfaceMethods) {
                innerface.override(Spec.interfaceMethods);
			}

            innerface.setup();
    
            // Finally, attach the video interface to the controller
            controller.setVideo(innerface);
			controller.setVideoSrc(src);
			
			/*check if metadata has already loaded if so don't wait*/
			if((!Media.Detection.iPad()) && (!Media.Detection.Mobile())){
			    if(element.tagName =="VIDEO"){
			        if(replay === false){
				    if(isNaN(element.duration)){
				        videoReceivedMetadata = false;
				    }else{
					videoReceivedMetadata = true;
				    }
				} 
			    }else {
			        videoReceivedMetadata = false;
			    }
			    controller.configureSettingsControls(src);
			}
			// if((!Media.Detection.iPad()) && (!Media.Detection.Mobile()) && replay === false && (element.tagName =="VIDEO" && isNaN(element.duration)) || element.tagName !="VIDEO"){videoReceivedMetadata = false;}
			// if((!Media.Detection.iPad()) && (!Media.Detection.Mobile())) controller.configureSettingsControls(src);

			controller.container = container;
			controller.movieLoadingPanelClass = 'movie-loading-panel';
			if (typeof options.width != 'undefined' && typeof options.height != 'undefined') {
				if (typeof controller.currentWidth == 'undefined' && typeof controller.currentHeight == 'undefined') {
					controller.currentWidth = options.width;
					controller.currentHeight = options.height;
				}
				controller.movieLoadingPanelClass = 'movie-loading-panel_' + options.width + 'x' + options.height;
			}
			ACUtils.addClassName(container, controller.movieLoadingPanelClass);
			if(ACUtils.Detector.isWin() && Media.Detection.Chrome()){
				ACUtils.addClassName(container, "winchrome");
			}
       
            return controller;
        }
        
        return false;
    },   
 		
	translationDidLoad:function(){
		this.createDownloadPrompt();
	},
	
    createDownloadPrompt: function (container, src, options)
    {  
		ACUtils.removeChildNodes(container);
	
        var downloadNotice = document.createElement('a'),
			downloadNoticeTitle = document.createElement('span'),
			downloadNoticeText = document.createElement('span'),
			downloadNoticeButton = document.createElement('span'),
			downloadNoticeUrl = Media.options.downloadUrl || ac_media_language.downloadquicktimeurl || 'http://www.apple.com/quicktime/download/';

        ACUtils.addClassName(downloadNotice, 'quicktime-download');
		if (typeof Media.options.width !== 'undefined' && typeof Media.options.height !== 'undefined') {
			ACUtils.addClassName(downloadNotice, 'size' + Media.options.width + 'x' + Media.options.height);
		}

		downloadNotice.setAttribute('href', downloadNoticeUrl);
		
		ACUtils.addClassName(downloadNoticeTitle, 'quicktime-download-title');
		ACUtils.addClassName(downloadNoticeText, 'quicktime-download-text');
		ACUtils.addClassName(downloadNoticeButton, 'quicktime-download-button');
		
		downloadNoticeTitle.innerHTML = Media.options.downloadTitle || ac_media_language.downloadquicktimetitle || 'Get QuickTime.';
		downloadNoticeText.innerHTML = Media.options.downloadText || ac_media_language.downloadquicktimetext || 'Download QuickTime to view this video.<br />QuickTime is free for Mac + PC.';
		downloadNoticeButton.innerHTML = Media.options.downloadButton || ac_media_language.downloadquicktimebutton || 'Download';
		
		downloadNotice.appendChild(downloadNoticeTitle);
		downloadNotice.appendChild(downloadNoticeText);
		downloadNotice.appendChild(downloadNoticeButton);
	
        Media.container.appendChild(downloadNotice);

      /*  if ('fire' in Element) {
            Element.fire(document.body, 
				"QuickTime:noCompatibleQTAvailable", 
				{controller: this, minVersion: Media.MIN_QUICKTIME_VERSION});
        }*/
		fire(document.body, 
			"QuickTime:noCompatibleQTAvailable", 
			{controller: this, minVersion: Media.MIN_QUICKTIME_VERSION});
		function fire(element, eventName, memo){
		if (element == document && document.createEvent && !element.dispatchEvent)
		    element = document.documentElement;

		  var event;
		  if (document.createEvent) {
		    event = document.createEvent("HTMLEvents");
		    event.initEvent("dataavailable", true, true);
		  } else {
		    event = document.createEventObject();
		    event.eventType = "ondataavailable";
		  }

		  event.eventName = eventName;
		  event.memo = memo || { };

		  if (document.createEvent) {
		    bool =element.dispatchEvent(event);
		  } else {
		    bool =element.fireEvent(event.eventType, event);
		  }
		}
        return downloadNotice;
    },
    
    _isHTML5VideoAvailable: function ()
    {
        return Media.Detection.HTML5();
    },
    
    _isQuickTimeAvailable: function ()
    {
       return Media.Detection.QuickTime(Media.MIN_QUICKTIME_VERSION);
    },
    
    _isSBVDPAvailable: function ()
    {
        return Media.Detection.SBVDP(Media.MIN_SBVDP_VERSION);
    },
    
    _shouldShowDownloadPrompt: function ()
    {
        return !Media.Detection.Mobile();
    },
    
    _createEventSource: function()
    {
        var source_id = "qt_event_source",
            behavior,
            head;

        // Don't recreate it if we already have one by this id
        if (document.getElementById(source_id)) {
            return;
        }

        behavior = document.createElement('object');
        behavior.id = source_id;
        behavior.setAttribute('clsid', 'CB927D12-4FF7-4a9e-A169-56E4B8A75598');

        head = document.getElementsByTagName('head')[0];
        head.appendChild(behavior);
    }
};

Media.Detection = {
    HTML5: function () {
        if (!('HTMLMediaElement' in window)){
            return false;
		}
        
        var video = document.createElement('video');
        return (video.canPlayType && video.canPlayType('video/mp4')!=='');
    },
    QuickTime: function(version) {
        return ACUtils.Detector.isValidQTAvailable(version);
    },
    SBVDP: function(version) {
        return ACUtils.Detector.isSBVDPAvailable(version);
    },
    Mobile: function () {
        return (ACUtils.Detector.isiPad()) ? true : ACUtils.Detector.isMobile();
    },
	iPhoneOSVersion: function() {
		return ACUtils.Detector.iPhoneOSVersion();
	},
	iPad: function () {
		return ACUtils.Detector.isiPad();
	},
	Safari: function () {
		return ACUtils.Detector.isSafari2();
	},
    IE: function () {
        return ACUtils.Detector.isIEStrict();
    },
    Firefox: function () {
        return ACUtils.Detector.isFirefox();
    },
	Opera: function () {
		return ACUtils.Detector.isOpera();
	},
	Chrome: function () {
		return ACUtils.Detector.isChrome();
	},
	SnowLeopard: function () {
		return ACUtils.Detector.isSnowLeopard();
	},
	SnowLeopard1062: function () {
		var agent = ACUtils.Detector.getAgent(),
			match = agent.match(/mac\sos\sx\D*([\.\w]*)/i),
			version = false;

        if (match && match[1]) {
			version = match[1];
        }

		return (ACUtils.Detector.isWebKit() && (version === '10_6_2' || version === '10_6_1' || version === '10_6'));
	},
    CSSTransitions: function () {
		try {
			var temp = document.createElement('div').style;
			temp.setProperty('-webkit-transition', 'inherit', null);
			temp.setProperty('-moz-transition', 'inherit', null);
			temp.setProperty('-o-transition', 'inherit', null);
			temp.setProperty('transition', 'inherit', null);

			return (temp.getPropertyValue('-webkit-transition') == 'inherit' || 
			        temp.getPropertyValue('-moz-transition') == 'inherit' || 
					temp.getPropertyValue('-o-transition') == 'inherit' ||
			        temp.getPropertyValue('transition') == 'inherit');
		} catch(e) {
			return false;
		}
	},
	CSSBorderRadius1: function () {
		try {
			var temp = document.createElement('div').style;
			temp.setProperty('-webkit-border-radius', 'inherit', null);
			temp.setProperty('-moz-border-radius', 'inherit', null);
			temp.setProperty('-o-border-radius', 'inherit', null);
			temp.setProperty('border-radius', 'inherit', null);
			
			return (temp.getPropertyValue('-webkit-border-radius').match('inherit') ||
					temp.getPropertyValue('-moz-border-radius').match('inherit') ||
					temp.getPropertyValue('-o-border-radius').match('inherit') ||
					temp.getPropertyValue('border-radius').match('inherit'));
		} catch(e) {
			return false;
		}
	},
		_style: null,
		_prefixes: null,
		_preFixes: null,
		_css: null,
		CSSBorderRadius: function() {
			if (!this._style) this._style = document.createElement('div').style;
			if (!this._prefixes) this._prefixes = '-webkit- -moz- -o- -ms- -khtml- '.split(' ');
			if (!this._preFixes) this._preFixes = 'Webkit Moz O ms Khtml '.split(' ');
			if (!this._css) this._css = {};
			var property=["border-radius", "Border-radius", "borderRadius", "BorderRadius"];
			for (var i=0; i<property.length; i++){
				for (j=this._preFixes.length-1; j>=0; j--) {
					if (this._style[this._preFixes[j]+property[i]] !== undefined) {
						this._css[property] = true;
						return true;
					}
				}
			}
			return false;
		}
};


// == Media.Spec ==
//
// Media.Spec is a list of the types of media that we can support, with
// specs on how to create and interact with each.
// 
// The create function is in charge of generating DOM elements, and appending 
// them to the container.
Media.Spec = {
    
    Video: {
        create: function (container, src, options) {
            var tagName =  ( options && options.audio ) ? 'audio' : 'video',
				video,
				videoSrc = (src.indexOf('?') > 0) ? src.substring(0, src.lastIndexOf('?')): src,
				dotLastIndex = videoSrc.lastIndexOf("."),
				pathExtension = ( dotLastIndex > 0 ) ? videoSrc.substring(dotLastIndex+1,src.length) : null,
				type =  'video/mp4';

				if(pathExtension) {
					pathExtension = pathExtension.split("#")[0];
					type = tagName+'/'+pathExtension;
				}
			// var _iOSVersion = (AC.Detector.isMobile() || AC.Detector.isiPad()) ? parseFloat(navigator.userAgent.match(/os ([\d_]*)/i)[1].replace('_', '.')) : false;	
			//Not re-using the video for iPad takes care of rdar://problem/8065412, tha forces a reload of the movie
			if (!ACUtils.Detector.isiPad() && existingVideo != false/* && (!ACUtils.Detector.isMobile() && _iOSVersion != 4.2)*/) {
								
			//if (existingVideo != false) {				
				if (existingVideoSrc == videoSrc) {
					//console.log('using existing video');
					video = existingVideo;
					container.appendChild(video);
					playExistingVideo = true;
					return video;
				} else {
					existingVideoSrc = false;
				}
			}

			video = document.createElement(tagName);
	
			video.playerType = tagName;
			if ((video.playerType === "video" && (video.canPlayType('video/mp4') || video.canPlayType('application/x-mpegURL'))) || (video.playerType === "audio" && ( ((ACUtils.Detector.isWebKit() ||  ACUtils.Detector.isMobile() || ACUtils.Detector.isiPad()) && pathExtension === "mov") || video.canPlayType(type)) )) {
					
				if(video.playerType === "video") {
					type =  'video/mp4';
				}
				
                var id = options.id || (container.id ? container.id+'_video' : ''),
					fileExtension = (src.indexOf('?') > 0) ? src.substring(src.lastIndexOf('.'),src.lastIndexOf('?')) : src.substring(src.lastIndexOf('.'),src.length);

                video.setAttribute('id', id);

                ACUtils.addClassName(video, video.playerType);

				if(video.playerType === "video") {

					switch(fileExtension) {
						case '.m3u8':
							video.setAttribute('src', src);
							isStreaming = true;
							break;
						default:
							video.setAttribute('type', type);
							video.setAttribute('src', src);
							break;
					}
				}
				else {
					video.setAttribute('src', src);
				}
               video.setAttribute('x-webkit-airplay', 'allow');
               this._configure(video, videoSrc, options);

                ACUtils.addEventHandler(window, 'unload', function () {
                     try {
                         video.stop();
                     } catch(e) {}

                     video.style.display = 'none';
                     
                     video = null;
                 });
              
               
                if(ACUtils.Detector.isiPad() || ACUtils.Detector.isMobile()){//fix for airplay
	        	container.innerHTML = video.outerHTML;
			delete video;
			var video = container.getElementsByTagName('video')[0];
		} else {
			container.appendChild(video);
		}

		existingVideoSrc = videoSrc;
		existingVideo = video;
		isHTML5 = true;

            } else {
                // We need to create our fallback in case the browser supports <video>, but not our codec.
                // So... do that now
                video = this._createFallback(container, src, options);
            }
			
            return video;
        },
  
        eventsToRegister: {
            load: 'load',
	    loadedmetadata: 'loadedmetadata',
            timeupdate: 'timeupdate',
            durationchange: 'durationchange',
            progress: 'progress',
            playing: 'playing',
            play: 'play',
            pause: 'pause',
            ended: 'ended',
	    webkitendfullscreen: 'webkitendfullscreen'
        },
        
		_captions: null,
		_fullscreen: false,
		
        interfaceMethods: {
			readystate: function () {
				return this.readyState;
			},
			autoplay: function() {
				return this.autoplay;
			},
            duration: function () {
                return this.duration;
            },
            time: function () {
				if (!this.webkitClosedCaptionsVisible && this._captionsEnabled === true) {
					// update the closedcaptions display if we're playing
					if (typeof Media.Spec.Video._captions !== 'undefined') {
						var closedcaptions = Media.Spec.Video._captions.getElementsByTagName('p');

						if (closedcaptions.length > 0) {
							var caption = '';
							
							function convertTime(oldTime) { 
								var newTime = 0.0; 
								if (oldTime) { 
									var timeArr = oldTime.split(':'); 

									switch (timeArr.length) { 
										case 3: 
											for (var i=0; i < 3; i++) 
											newTime = newTime * 60 + parseFloat(timeArr[i].replace(',', '.')); 
											break; 
										case 4: 
											for (var i=0; i < 3; i++) 
											newTime = newTime * 60 + parseFloat(timeArr[i].replace(',', '.')); 
											// @@ ignore frames 
											break;
										default:
											break;
									} 
								} 
								return newTime; 
							}

							for (var index = 0, closedcaption; closedcaption = closedcaptions[index]; index++) {
								var begin = convertTime(closedcaption.getAttribute('begin')), 
									end = convertTime(closedcaption.getAttribute('end')); 

								if (this.currentTime < begin) {
									break;
								}

								if (this.currentTime >= begin && this.currentTime < end) {
									caption = closedcaption; 
								}
							}

							if (typeof caption != 'undefined' && caption != this.currentCaption) { 
								this.currentCaption = caption; 

								var children = caption.childNodes, 
									length = (typeof children != 'undefined') ? children.length : 0, 
									captionString = ''; 

								for (var i = 0; i < length; i++) { 
									var child = children.item(i); 
									if (child.nodeType == 3) { 
										captionString += '<span>'+child.nodeValue+'</span>';                                                                 
									} 
								} 
                   
								if (captionString === '') { 
									this.trackTextSpan.style.display = 'none'; 
								} else { 
									this.trackTextSpan.style.display = 'inline-block'; 
									this.trackTextSpan.innerHTML = captionString; 
								}
							}
						}
					}
				}
				
                return this.currentTime;
            },
            setTime: function(value) {
				try{
					this.currentTime = value;
					// this.currentTime = (value <= this.buffered.end(0)) ? value : this.buffered.end(0);
				}catch(e){};
            },
            volume: function () {
                return this.volume;
            },
            setVolume: function(value) {
                this.volume = value;
            },
            muted: function () {
                return this.muted;
            },
            setMuted: function(value) {
                this.muted = value;
            },
            rate: function () {
                return this.playbackRate;
            },
            setRate: function (value) {
                this.playbackRate = value;
            },
			seekToTime: function(seekTimeObj){ 
				this.currentTime = this.currentTime-30;
			},
            defaultRate: function () {
            	return this.defaultPlaybackRate;
            },
            src: function () {
            	return this.src;
            },
            setSrc: function (src) {
	// console.log('in video spec setting src');
            	this.src = src;
		this.load();
            },
            status: function () {
                return this.status;
            },
            percentLoaded: function () {
				var percentLoaded = 0;
				try {
                	percentLoaded = this.buffered.end(0) / this.duration;
				} catch(e) {}
				return percentLoaded;
            },
            pause: function () {
                this.pause();
            },
            play: function () {
	            this.play();
            },
            paused: function () {
                return this.paused;
            },
            ended: function () {
                return this.ended;
            },
            timeScale: function () {
            	return 2997;
            },
			movieType: function () {
				return 'Video';
			},
			supportsFullscreen: function() {
				return !!this.webkitSupportsFullscreen;
			},
			getContainer: function () {
				return this.parentNode;
			},
			setTrackTextSpan: function(span) {
				this.trackTextSpan = span;
			},
			
			setCaptionsAvailable: function(func, url) {
				if ((typeof Media.Spec.Video._captions != 'undefined' && Media.Spec.Video._captions != null) || typeof this.webkitClosedCaptionsVisible != 'undefined') {
					func();
					return;
				}

				var videoText;

				if (url.match(/\w+:\/\//i)) {
					url = url.replace(/\w+:\/\/[^\/]+/i,"");
				}

				// for debugging uncomment the line below
				//url = '/global/scripts/sbvdp/caption_export.xml';
				//console.log('captions url: '+url);

				new ACUtilsAjax.checkURL(url, func);
			
				videoText = document.createElement('text');
				videoText.setAttribute('type', 'application/ttaf+xml');
				videoText.setAttribute('src', url);
			
				this.appendChild(videoText); 

				new ACUtilsAjax.AjaxRequest(url, {
					method:'get',
					requestHeaders: {Accept: 'application/ttaf+xml'},
					onSuccess: function(httpResponse) {
						var captionsDocument = httpResponse.responseXMLValue().documentElement;

						if (ACUtils.Detector.isIEStrict()) {
							captionsDocument = captionsDocument.ownerDocument;
						}

						var language = captionsDocument.getAttribute('xml:lang'); 
						videoText.setAttribute('lang', language);
					
						Media.Spec.Video._captions = captionsDocument.getElementsByTagNameNS(Media.CAPTIONS_NS, 'body').item(0);
						Media.Spec.Video._captions.currentIndex = 0;
						//console.log('got captionsxml');
					}.bindAC(this),
					
					onFailure: function() {},
					onException: function() {},

					onCreate: function(httpResponse) { 
						httpResponse.request.overrideMimeType('application/ttaf+xml'); 
					}
				});
				
			},
			enableCaptions: function() {
				var enableCaptionsTextDisplay = this._videoClosedCaptionsEnabled;
				try{
					if (this._videoClosedCaptionsEnabled === true) {
						this.webkitClosedCaptionsVisible = true;
					}
				} catch(e) {}
				this._captionsEnabled = true;
			},
			disableCaptions: function() {
				try {
					if (this._videoClosedCaptionsEnabled === true) {
						this.webkitClosedCaptionsVisible = false;
					}
				} catch (e) {}
				
				if ('' != this.currentCaption) {
					this.currentCaption = this.trackTextSpan.innerHTML = '';
				}
				this._captionsEnabled = false;
			},
			_videoClosedCaptionsEnabled: false,
			videoClosedCaptionsEnabled: function() {
				this._videoClosedCaptionsEnabled = (typeof this.webkitClosedCaptionsVisible != 'undefined') ? true : false;
				return this._videoClosedCaptionsEnabled;
			},
			// enableCaptionsTextDisplay: function() {
			// 	return (typeof this.webkitClosedCaptionsVisible != 'undefined') ? true : false;
			// 
			// 	// if (typeof this.webkitClosedCaptionsVisible != 'undefined') {
			// 	// 	return true;
			// 	// } else {
			// 	// 	return false;
			// 	// }
			// },

			enableFullscreen: function() {
				try {
					if (this._captionsEnabled === true) {
						this.webkitClosedCaptionsVisible = true;
					}
					this.webkitEnterFullScreen();
				} catch(e) {}
			},
			disableFullscreen: function() {
				try {
					if (this._captionsEnabled === true) {
						this.webkitClosedCaptionsVisible = false;
					}
					this.webkitExitFullScreen();
				} catch(e) {}
			}
        },
        
        _configure: function (video, src, options)
        {
            if (!options) {
                return;
            }

            var property,
                attributeName;

            for (property in options) {

                if (options.hasOwnProperty(property)) {
					if(typeof options[property] == undefined) {
						continue;
					}

                    attributeName = property.toLowerCase();

                    switch(attributeName) {
                        case 'type':
                        case 'src':
                        case 'data':
                        case 'classid':
                        case 'name':
                        case 'id':
                        case 'postdomevents':
                        case 'saveembedtags':
                        case 'factory':
                        case 'aggressiveCleanup':
                        case 'innerId':
                        case 'cache':
                        case 'aggressivecleanup':
                        case 'showlogo':
                            //do nothing as these shouldn't be overridden or set
                        break;
                        case('class'):
                            ACUtils.addClassName(video, options[property]);
                        break;
                        case('controller'):
                            if (options[property] || (Media.Detection.iPad() && video.tagName === "VIDEO") ) {
                                video.setAttribute("controls", "controls");
                            }
                        break;
                        case('autoplay'):
                        case('autostart'):
                            if (options[property]) {
                                video.setAttribute("autoplay", "autoplay");
                            }
                        break;
			case('posterframe'):
				if (options[property]) {
					video.setAttribute("poster", options[property]);
				}
				break;
                        default:
				if(typeof options[property] !== "undefined") {
	                            video.setAttribute(attributeName, options[property]);
				}
                        break;
                    }
                }
            }
        },
        
        _createFallback: function (container, src, options)
        {
            if (Media._isQuickTimeAvailable()) {
                return Media.Spec.QuickTime.create(container, src, options);
            }
            
            if (Media._isSBVDPAvailable()) {
                return Media.Spec.SBVDP.create(container, src, options);
            }
            
            if (Media._shouldShowDownloadPrompt()) {
		MediaLanguage.getTranslations(this);
                // return Media.createDownloadPrompt(container, src, options);
            }
            
            return false;
        }
    },
    
     QuickTime: {
        create: function(container, src, options) {
            var outerObject = this._createObject(src, options),
                innerObject = null,
				id = options.id || (container.id ? container.id+'_video' : '');
				
            outerObject.setAttribute('id', id);
            
            if (!Media.Detection.IE() && !Media.Detection.Mobile()) {

                // Note:
                // Creating an inner object in IE results in a "# items remaining" 
                // status which makes the page appear as if it never finishes loading. 
                // So, we won't create one for IE.

				if (options.target === 'quicktimeplayer') {
					innerObject = this._innerObject = this._createInnerObject(src, options);
				} else {
                	innerObject = this._embed = this._createEmbed(src, options);
				}
                outerObject.appendChild(innerObject);
            } else {
                outerObject.style.behavior = "url(#qt_event_source)";
                
                if (options.aggressiveCleanup !== false){

                    //knowing it's IE at this point, make sure we clear the movie when the page closes
                    //we also set our reference to null for good measure
                    ACUtils.addEventHandler(window, 'unload', function () {
                        try {
                            outerObject.Stop();
                        } catch(e) {}

                        outerObject.style.display = 'none';
                        outerObject = null;
                    });
                }
            }
            if(innerObject)innerObject.setAttribute("airplay", "allow");
            this._configure(innerObject, outerObject, options);

            // Needs to be last so IE sees all the parameters appended to
            // the object prior to loading the activex control
            outerObject.setAttribute('classid', 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B');
            
            // We're adding that in order to be able to specialize the CSS for movie-loading for the Quicktime plugin only.
            ACUtils.addClassName(outerObject, (outerObject.playerType = 'quicktime'));
            //console.log(outerObject.innerHTML);
            container.appendChild(outerObject);

            return innerObject || outerObject;
        },

		pollForChanges: [
			'loadedmetadata',
			'load',
        	'timeupdate',
        	'durationchange',
       		'progress',
        	'playing',
        	'play',
        	'pause',
       		'ended'		
		],
        
		_captions: null,
		
        interfaceMethods: {
            setup: function () {
            },
            duration: function () {
                var duration = 0;
                try {
                    duration = this.GetDuration() / this.GetTimeScale();
                } catch(e) {}
                return duration || 0;
            },
            time: function () {
                var time = 0;
                try {
                    time = this.GetTime() / this.GetTimeScale();
                } catch(e) {}
				
                return time || 0;
            },
            setTime: function(value) {
				try {
                	this.SetTime(value * this.GetTimeScale());
				} catch(e) {} 
            },
            volume: function () {
                return this.GetVolume() / 255;
            },
            setVolume: function(value) {
                this.SetVolume(value * 255);
            },
            muted: function () {
                return this.GetMute();
            },
            setMuted: function(value) {
                this.SetMute(value);
            },
            rate: function () {
                var rate;
                try {
                    rate = this.GetRate();
                } catch(e) {}
                
                return rate || 1;
            },
            setRate: function (value) {
				this.SetRate(value);
            },
            status: function () {
                this.GetPluginStatus();
            },
            percentLoaded: function () {
				var percent = 0;
				try {
					percent = this.GetMaxBytesLoaded()/this.GetMovieSize();
				} catch(e) {}
                return percent;
            },
            pause: function () {
				try {
                	this.Stop();
				} catch(e) {}
            },
            play: function () {
				try {
	                this.Play();
				} catch(e) {}
            },
            paused: function () {
				try {
                	return this.GetRate()===0;
				} catch(e) {}
            },
            ended: function () {
                return this.ended;
            },
			src: function () {
				// console.log("getting src")
				
				var src;
				try {
					src = this.GetURL();
				} catch(e) {}
			
				return src || '';
			},
			setSrc: function (src) {
				//Needs cleaning up after QT plugin version 7.6.9 where SetURL() is expected to work.
				if(ACUtils.Detector.getQTVersion() >= "7.6.9"){
					this.SetURL(src);
				}else{
					this.src = src;
				}
				this.controller = false;
				if (ACUtils.Detector.isIEStrict()) {
					this.SetControllerVisible(false);
				}
			},
            timeScale: function () {
            	return this.GetTimeScale();
            },
			movieType: function () {
				return 'QuickTime';
			},
			supportsFullscreen: function() {
				return false;
			},
			getContainer: function() {
				return this._container;
			},
			setTrackTextSpan: function(span) {

			},
			setCaptionsAvailable: function(func, url) {
				try {
					// Try to find the closed caption trackCount
			        // (tragically the index starts at 1, not 0)
			        var trackCount = this.GetTrackCount(),
			            i;
			
			        for (i = 1; i <= trackCount; i++) {
			            if ('Closed Caption' === this.GetTrackType(i)) {
			                Media.Spec.QuickTime._captions = i;
			                if (typeof func != 'undefined') {
								func();
							}
			            }
			        }
				} catch(e) {}
			},
			enableCaptions: function() {
				try {
					if (Media.Spec.QuickTime._captions === 'undefined') {
						this.setCaptionsAvailable();
					}

					this.SetTrackEnabled(Media.Spec.QuickTime._captions, true);
					this._captionsEnabled = true;
				} catch(e) {}
			},
			disableCaptions: function() {
				try {
					this.SetTrackEnabled(Media.Spec.QuickTime._captions, false);
					this._captionsEnabled = false;
				} catch(e) {}
			},
			videoClosedCaptionsEnabled: function() {
				return false;
			}
        },
        
        _configure: function(innerObject, outerObject, options)
        {
            if (!options) {
                return;
            }

            var property = null,
                attributeName = null;

            for (property in options) {
                if (options.hasOwnProperty(property)) {

					if(typeof options[property] == undefined) {
						continue;
					}
					
                    attributeName = property.toLowerCase();

                    switch(attributeName) {
                        case('type'):
                        case('src'):
                        case('data'):
                        case('classid'):
                        case('name'):
                        case('id'):
                        case('postdomevents'):
                        case('saveembedtags'):
                        case('factory'):
                        case('aggressiveCleanup'):
                            //do nothing as these shouldn't be overridden or set
                        break;
                        case('class'):
                            ACUtils.addClassName(outerObject, options[property]);
                        break;
                        case('innerId'):
                            if (innerObject) {
                                innerObject.setAttribute('id', options[property]);
                            }
                        break;
                        case('autoplay'):
                            this._addParameter(outerObject, 'autostart', options[property]);
                            this._addParameter(innerObject, 'autostart', options[property]);
                        break;
                        case('width'):
                        case('height'):
                            outerObject.setAttribute(attributeName, options[property]);
                            if (innerObject) {
                                innerObject.setAttribute(attributeName, options[property]);
                            }
                        break;
                        default:
                            this._addParameter(outerObject, attributeName, options[property]);
                            this._addParameter(innerObject, attributeName, options[property]);
                        break;
                    }
                }
            }
        },
        
        /**
        * Adds an object param tag to the specified parent
        * Note that the attributes are added in this seemingly odd order
        * so they show up in the logical order in the dom
        */
        _addParameter: function(parent, name, value)
        {
            if (!parent) {
                return;
            }

            var param = document.createElement('param');
            param.setAttribute('value', value);
            param.setAttribute('name', name);
            parent.appendChild(param);

            param = null;
        },

        /**
        * Adds an object embed tag to the specified parent
        * only used for displaying controller over the movie
        */
        _createEmbed: function(url, options) {
            var embed = document.createElement('embed');
            embed.setAttribute('src', url);
            embed.setAttribute('type', 'video/quicktime');
            if (!Media.Detection.Firefox() && !Media.Detection.Opera())
                embed.setAttribute('wmode', 'transparent');
            embed.setAttribute('postdomevents', true);
            embed.setAttribute('controller', options.controller);
            embed.setAttribute('showlogo', false);
            embed.setAttribute('scale', 'tofit');
            
            if (options) {
                if (!isNaN(parseInt(options.width, 10))) {
                    embed.setAttribute('width', options.width);
				}
                if (!isNaN(parseInt(options.height, 10))) {
                    embed.setAttribute('height', options.height);
				}
				if (typeof options.target != 'undefined') {
					embed.setAttribute('target', options.target);
				}
            }
            
            return embed;
        },

		/**
		* Adds an inner object tag to the specified parent
		* only used for targeting QuickTime player
		*/
		_createInnerObject: function(url, options) {
			var object = document.createElement('object');
			
			object.setAttribute('type', 'video/quicktime');
			object.setAttribute('id', options.id+'Inner');
			object.setAttribute('name', options.id);
			object.setAttribute('width', '1');
			object.setAttribute('height', '1');
			object.setAttribute('data', url);
			
			this._addParameter(object, 'target', options.target);
			this._addParameter(object, 'postdomevents', 'true');
			
			return object;
		},
		
        /**
        * Creates the IE friendly outer object
        * NOTE Safari and Opera both seem to be able to use this one as well
        */
        _createObject: function(url, options)
        {
        
            var object = document.createElement('object'),
                activexVersion = '7,3,0,0';

            if (Media.Detection.Mobile() && options.posterFrame) {
            
                this._addParameter(object, 'src', options.posterFrame);
                this._addParameter(object, 'href', url);
                this._addParameter(object, 'target', 'myself');
            } else {
                this._addParameter(object, 'src', url);
                if (!Media.Detection.Firefox() && !Media.Detection.Opera()) {
                
                    this._addParameter(object, 'wmode', 'transparent');
				}
            }
          
            object.setAttribute('id', name);
			
			if (!Media.Detection.Mobile()) {
	            this._addParameter(object, 'showlogo', false);
				this._addParameter(object, 'scale', 'tofit');
	            this._addParameter(object, 'saveembedtags', true);
	            this._addParameter(object, 'postdomevents', true);
			}

            if (null !== options && (typeof options.codebase !== 'undefined') && '' !== options.codebase) {
                activexVersion = options.codeBase;
            }

            object.setAttribute('codebase', 'http://www.apple.com/qtactivex/qtplugin.cab#version=' + activexVersion);

            return object;
        }

	}
};	


if(ACUtils.Detector.isiPad()) {
	HTMLMediaElement.prototype.forcePlay = function() {
		//alert("ipad = forcePlay");
		var self = this,
			link = document.createElement("a"),
			forcePlay = function(event) {
				event.preventDefault();
				self.play();
			},
			triggerEvent;
			link.addEventListener("click",forcePlay,false);
			document.body.appendChild(link);
			triggerEvent = document.createEvent("MouseEvents");
			if (triggerEvent.initMouseEvent) {
				triggerEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				link.dispatchEvent(triggerEvent);
			}
			document.body.removeChild(link);
	};
	HTMLMediaElement.prototype.forcePause = function() {
		var self = this,
			link = document.createElement("a"),
			forcePause = function(event) {
				event.preventDefault();
				self.pause();
			},
			triggerEvent;
			link.addEventListener("click",forcePause,false);
			document.body.appendChild(link);
			triggerEvent = document.createEvent("MouseEvents");
			if (triggerEvent.initMouseEvent) {
				triggerEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				link.dispatchEvent(triggerEvent);
			}
			document.body.removeChild(link);
	};
	
}

// == Media.VideoInterface ==
//
// Media.VideoInterface does the work of talking with the media element.
// It takes cues from Media.Spec to operate on the video element itself.
Media.VideoInterface = function(videoElement, delegateObject) {

    var video = videoElement,
        delegate = delegateObject,
        pollTimeout,
		videoTitle,
		videoUrl,
		videoDescription,
		videoPosterFrame;

    return {
		videoTitle: function() {
			return videoTitle;
		},
		
		setVideoTitle: function(newTitle) {
			videoTitle = newTitle;
		},
		
		videoUrl: function() {
			return videoUrl;
		},
		
		setVideoUrl: function(newUrl) {
			videoUrl = newUrl;
		},
		
		videoDescription: function() {
			return videoDescription;
		},
		
		setVideoDescription: function(newDescription) {
			videoDescription = newDescription;
		},
		
		videoPosterFrame: function() {
			return videoPosterFrame;
		},
		
		setVideoPosterFrame: function(newPosterFrame) {
			videoPosterFrame = newPosterFrame;
		},
	
        object: function () {
            return video;
        },

        setObject: function (newVideo) {
            video = newVideo;
        },
        
        setDelegate: function (newDelegate) {
            delegate = newDelegate;
        },

        setup: function() {},
        
        /**
         * Override default values (and optionally add new ones), subscribing the 
         * standard media interface to a customized one.
         */
        override: function (functions) {
            var member;
            
            function wrap(name, fn) {
                return function() {
                    return fn.apply(video, arguments);
                };
            }
            
            for (member in functions) {
                this[member] = wrap(member, functions[member]);
            }
            return this;
        },
        
        registerEvent: function (functionName, eventName, auxFunction) {
            if (!auxFunction && typeof(eventName)=='function') {
                auxFunction = eventName;
                eventName = null;
            }
        
            var e = eventName || functionName;
            
            ACUtils.addEventHandler(video, e, function (event) {
                if (auxFunction) {
                    auxFunction.apply(this);
                }
                this.messageDelegate(functionName);
            }.bindAC(this));
        },
    
        pollForChanges: function (functions) {
            if (pollTimeout) {
                window.clearInterval(pollTimeout);
			}

            if (functions) {
                pollTimeout = window.setInterval(function(){
					for(var i = 0, func; func = functions[i]; i++) {
						this.messageDelegate(func);
					}
                }.bindAC(this), 480);
            }
        },
    
        messageDelegate: function(eventName) {
            if (!delegate) {
                return;
			}
                
            eventName = eventName.charAt(0).toUpperCase()+eventName.substring(1);
            var callback = 'videoReceived'+eventName+'Event';
        
            if (callback in delegate) {
                delegate[callback](this);
            }
        }
    };
};

Media.Controller = function (containerElement) {	
    var container = containerElement,
        delegate,
        video,
		videoSrc,
        controlPanel,
        timeout,
		sizeTimeout,
        duration,
        seeking = false,
        wasPlayingBeforeSeek,
        hasBegunPlaying = false,
        hasEndedPlaying = false,
	playing = false,
	playAcknowledged = true,
	pauseAcknowledged = true,
	isPlayAdvanced = false,
	currentlyChangingSize = false,
	sizeAnimation = false,
	controlPanelConfigurationsSet = false,
	currentSize = null, 
	replay = false,
	largestMovieBuffered= false,
	processedControlPanel = false;

	
    function containerMouseMove(e) {
        if (!controlPanel || currentlyChangingSize || !hasBegunPlaying) {
            return;
		}
            
        controlPanel.show();
        window.clearTimeout(timeout);
        
        var controls = controlPanel.element;
            mouseElement = e.target || e.srcElement;        
        
        if (mouseElement == controls) {
            timeout = window.setTimeout(function(){
                if (controlPanel && typeof controlPanel != 'undefined') {
					controlPanel.hide();
				}
            }, 2500);
        }
    }
    function containerMouseOut(e) {
        if (!controlPanel || !hasBegunPlaying) {
            return;
		}
        
        window.clearTimeout(timeout);
        timeout = window.setTimeout(function(){
            if (controlPanel) {
				controlPanel.hide();
			}
        },50);
    }
    function containerMouseOver(e) {
        if (!controlPanel || !hasBegunPlaying) {
            return;
		}
            
        window.clearTimeout(timeout);
        timeout = window.setTimeout(function(){
            if (controlPanel) {
				controlPanel.hide();
			}
        },50);
    }
    function containerMouseOver(e) {
        if (!controlPanel || currentlyChangingSize || !hasBegunPlaying) {
            return;
		}
            
        window.clearTimeout(timeout);
        controlPanel.show();
    }
	function menuMouseOver(e) {
		if (!controlPanel) {
			return;
		}
			
		window.clearTimeout(timeout);
		controlPanel.show();
	}
    
    return {
		isReplaying:function(){
			return replay;
		},
		setReplaying:function(bool){
			replay = bool;
		},
        _send: function (msg, params) {
            if (delegate && msg in delegate) {
                params = [this].concat(params);
                return delegate[msg].apply(delegate, params);
            }
        },
        
        _fireEvent: function (event, data) {
            Media.Controller.fireEvent(event, data);
        },
        
        reset: function () {
            seeking = false;
            hasBegunPlaying = false;
            hasEndedPlaying = false;
    		playing = false;
        },
        
        setDelegate: function (newDelegate) {
            delegate = newDelegate;
        },
        
        setVideo: function (vid) {
            hasBegunPlaying = false;
            hasEndedPlaying = false;
            
            video = vid;
            duration = video.duration() || 0;

            if (controlPanel && controlPanel.videoObjectHasChanged) {
                controlPanel.videoObjectHasChanged(video);
            }

            return this;
        },

		setVideoSrc: function(src) {
			videoSrc = src;
		},

		video: function() {
			return video;
		},
		
		translationDidLoad: function() {
			languageJsonComplete = true;
			this.processControlPanel();
			// this._setControlPanel();
		},
		
		_setControlPanel: function() {
          if (controlPanel) {
				if (existingVideo != false && playExistingVideo === true) {
					video.play();
				}
				
                controlPanel.delegate = this;
                ACUtils.addEventHandler(containerElement, 'mousemove', containerMouseMove);
                ACUtils.addEventHandler(containerElement, 'mouseout', containerMouseOut);
				ACUtils.addEventHandler(containerElement, 'mouseover', containerMouseOver);
				if(controlPanel.settingsMenu) {
					ACUtils.addEventHandler(controlPanel.settingsMenu, 'mouseover', menuMouseOver);
				}
				video.setTrackTextSpan(controlPanel.trackText);
				if (!controlPanel.settingsControlsAreSet && (video.tagName === "VIDEO")) {
					this.configureSettingsControls(videoSrc);
					controlPanel.settingsControlsAreSet = true;
				}
				if(controlPanel.element) {
					controlPanel.element.parentNode.parentNode.style.width = this.currentWidth + 'px';
					controlPanel.element.parentNode.parentNode.style.height = this.currentHeight + 'px';
				}
				if(video.object().tagName.toLowerCase() === "video") {
					this.setSizeAnimation(true);
				}
				this.setVideoSizeForWidthAndHeight(this.currentWidth, this.currentHeight);
				controlPanel.setFocus();
            } else {
                ACUtils.removeEventHandler(containerElement, 'mousemove', containerMouseMove);
                ACUtils.removeEventHandler(containerElement, 'mouseout', containerMouseOut);   
                ACUtils.removeEventHandler(containerElement, 'mouseover', containerMouseOver);
            }
        
            return this;
		},
		
        setControlPanel: function (cp) {
		    //reversing order to make sure control panel is set before size controls are enabled
	        controlPanel = (video.object().tagName === "VIDEO" && Media.Detection.iPad()) ? false : cp;
			if(controlPanel != null && controlPanel != false)  MediaLanguage.getTranslations(this);
        },

        beginSeeking: function () {
            if (seeking) {
                return;
			}

            seeking = true;
            wasPlayingBeforeSeek = !video.paused() && this.rate()==1;
            
            this.pause();
            
            var time = video.time();
            this._send('didStartJogging', time);
            this._fireEvent("QuickTime:didStartJogging", {controller: this, time: time});
        },
        
        endSeeking: function () {
			var time = video.time(),
				duration = video.duration();
			
		    seeking = false;

            this._send('didStopJogging', time);
            this._fireEvent("QuickTime:didStopJogging", {controller: this, time: time});
	
            if (wasPlayingBeforeSeek) {
				if (time != duration) {
                	this.play();
				} else {
					// ending the movie if user scrubs past the end of the movie
					// also, have to set hasEndedPlaying to false, since it hasn't ended yet
					hasEndedPlaying = false;
				   	this.videoReceivedEndedEvent(this);
				}
            }
        },
		supportsFullscreen: function() {
//			console.log('going to see if fullscreen is supported');
			return video.supportsFullscreen();
		},    

        time: function () {
            return video.time() || this._lastTime || 0;
        },
        
        setTime: function(newTime) {
            video.setTime(newTime);
            this.videoReceivedTimeupdateEvent();
        },

        duration: function () {
            if ( !duration ) {
                duration = video.duration();
            }
           	return duration;
        },

        volume: function() {
            return video.volume();
        },

        setVolume: function(level) {
			video.setMuted(false);
            video.setVolume(level);
			if (typeof controlPanel != 'undefined' && controlPanel != null) {
				controlPanel.volumeControlSetting = level;
			}
        },

		setMuted: function(mute) {
			video.setMuted(mute);
			if (typeof controlPanel != 'undefined' && controlPanel != null) {
				controlPanel.volumeControlSetting = 0;
			}
		},
		
        toggleMute: function () {
			var isMuted = video.muted();

			if ( isMuted ) {
				this.setMuted(false);
			} else {
				this.setMuted(true);
			}
			
			return !isMuted;
        },
    
        playPause: function () {
            var isPaused = video.paused(),
				rate = this.rate();
            
            if (isPaused && rate === 1) {
                this.play();
            } else if (rate !== 1) {
				this.setRate(1);
			} else {
                this.pause();
            }
            
            return video.paused();
        },
		
		playing: function() {
			return playing;
		},

        play: function () {
			video.play();
			playing = true;
			playAcknowledged = false;
        },
    
        playing: function () {	
			return playing;
		},
        pause: function () {
        	video.pause();
			playing = false;
			pauseAcknowledged = false;
        },
	
        stop: function () {
           	video.pause();
			playing = false;
			pauseAcknowledged = false;
			hasEndedPlaying = true;
        },
        
        setRate: function (newRate) {
            video.setRate(newRate);
			if (newRate !== 1 || newRate !== 0) {
				isPlayAdvanced = true;
			} else {
				isPlayAdvanced = false;
			}
        },
		seekToTime: function(seekTime){
			return video.seekToTime(seekTime);
		},
        rate: function () {
            return video.rate();
        },

		src: function () {
			return video.src();
		},
		
		setSrc: function (src) {
			video.setSrc(src);
			this._currentSrc = src;
		},
		
		setSizeAnimation: function(bool) {
			sizeAnimation = bool;
		},
		_currentPosition: false,
		_currentSrc: null,
		_currentVolume: null,
		getNewWidthAndNewHeightFromSrc: function(src) {
			var props = {};
			var path = this.moviePath();
			var filename = src.substring(src.lastIndexOf('/')+1, src.length);
			props.srcToSet = path + filename;
			props.newWidth = filename.substring(filename.lastIndexOf('_')+1, filename.lastIndexOf('x'));
			props.newHeight = filename.substring(filename.lastIndexOf('x')+1, filename.lastIndexOf('.'));
			return props;
		},
		setVideoSizeForSrc: function(src) {
			var largeSize = false;
			var currentWidth = video.object().videoWidth || video.object().width;
			var props = this.getNewWidthAndNewHeightFromSrc(src);
			var largestSizeOfMovie = this.getLargestSizeOfMovie();
		    var newSize = this.getCurrentSize(props.newWidth, props.newHeight);
			if(newSize.width == currentWidth && newSize.type == "large"){
				largeSize = true; 
			}
			if(largestMovieBuffered === true || (video.percentLoaded() >= 1 && props.newWidth < currentWidth)){
				this.setVideoSizeForWidthAndHeight(props.newWidth, props.newHeight);
			} else {
				// if the video isn't fully loaded or the video is fully loaded and it has been resized (meaning it could be a size other than largest)
				if (sizeAnimation === true) {
					this.setSizeAnimation(false);
				}
				this._currentPosition = video.time();
				this._currentVolume = controlPanel.volumeControlSetting;
				video.pause();
				if (video.movieType() === 'Video') this.createFrame();
				// work around scope issue
				var obj = this;
				// short delay allows us time to place the canvas before changing the movie source (changing the movie source
				// makes it go to an empty white frame while it's buffering, which causes a flicker)
				window.setTimeout(function() {
					obj.setSrc(props.srcToSet);
				}, 10);
				this.setVideoSizeForWidthAndHeight(props.newWidth, props.newHeight);
			}
		},
		getCurrentSize: function(width, height){
		var sizesList = this.configSettings.metadata.sizes;
		var currentSize = new Array();
		if (typeof sizesList != 'undefined') {
			for (var i=0;i<sizesList.length;i++) {
				if (width == sizesList[i].width && height == sizesList[i].height){
					currentSize.type = sizesList[i].type;
					currentSize.width = sizesList[i].width;
				    break;
				}
			}
		}
		return currentSize;
		},
		getLargestSizeOfMovie: function(){
			var sizesList = this.configSettings.metadata.sizes;
			if (typeof sizesList != 'undefined') {
				return sizesList[sizesList.length-1].type;
			}
		},
		checkIfLargestMovieIsBuffered: function(){
			if(this.configSettings && this.configSettings.metadata){
				var movieSize = this.getCurrentSize(video.object().width, video.object().height);
				var largestSize = this.getLargestSizeOfMovie();
				if(movieSize.type == largestSize) largestMovieBuffered = true;
			}
		},
		
		setVideoSizeForWidthAndHeight: function(width, height) {
			var videoObject = video.object() || video.object().parentNode;
			if(this.configSettings != undefined){
				currentSize = this.getCurrentSize(width, height);
			}
			if (typeof controlPanel != 'undefined' && typeof videoObject != 'undefined') {
				//var videoObject = video.object();
				function setControlPanelType() {
					if (typeof controlPanel != 'undefined') {
						controlPanel.setControllerType();
					// if (typeof controlPanel != 'undefined' && (controlPanel.controllerType === 'slim' || controlPanel.controllerType === 'short-slim')) {
					// 	if (controlPanel.controllerType === 'short-slim' && width > 450) {
					// 		ACUtils.removeClassName(controlPanel.container, 'short-slim');
					// 		controlPanel.controllerType = 'slim';
					// 	}
					// 	if (controlPanel.controllerType === 'slim' && width <= 450) {
					// 		ACUtils.addClassName(controlPanel.container, 'short-slim');
					// 		controlPanel.controllerType = 'short-slim';
					// 	}
						controlPanel.setTrackContainerWidth();
					}
				}
		
				// if the browser supports full screen and the movie allows it at this size, re-enable the control, otherwise disable it
				if (this.supportsFullscreen() === true && (this.configSettings && this.configSettings.version && this.configSettings.version >=3)) {
					var sizesList = this.configSettings.metadata.sizes;
					if (typeof sizesList != 'undefined') {
						if(sizesList[sizesList.length-1].allowFullScreen === true && largestMovieBuffered === true){
							controlPanel.enableFullscreenControl();
						}else{
							for (var i=0;i<sizesList.length;i++) {
								if (width == sizesList[i].width && sizesList[i].allowFullScreen === true){			
									controlPanel.enableFullscreenControl();
									break;
								}else if (width == sizesList[i].width && sizesList[i].allowFullScreen === false){
									controlPanel.disableFullscreenControlForCurrentSize();
									break;
								}
							}
						}	
					}
				}
			
				if (ACUtils.Detector.isIEStrict() &&!(ACUtils.Detector.getAgent().match(/msie 9/i))) {
					var top = parseInt(height / 2);
					videoObject.style.marginTop = '-' +top + 'px';
					controlPanel.element.style.marginTop = '-' + top + 'px';
				}
				if (video.percentLoaded() < 1 || sizeAnimation === false || Media.Detection.Chrome()) {
					videoObject.width = width;
					videoObject.height = height;
					videoObject.style.width = width + "px";
					videoObject.style.height = height+ "px";
					

					var canvasFrame = ACUtils.getByClass('canvasFrame')[0];
					if(canvasFrame){
						canvasFrame.style.width = width + 'px';
						canvasFrame.style.height = height + 'px';
					}
					
					if (video.movieType() != 'Video' && typeof videoObject.parentNode != null) {
						videoObject.parentNode.width = width;
						videoObject.parentNode.height = height;
					}
					// alert("set src");
					controlPanel.container.style.width = width + 'px';
					controlPanel.container.style.height = height + 'px';
					if(controlPanel.element) {
						controlPanel.element.style.width = width + 'px';
						controlPanel.element.style.height = height + 'px';
					}
					
					if (ACUtils.Detector.isIEStrict()) {
					/*	var top = parseInt(height / 2);
						videoObject.style.marginTop = '-' + top + 'px';	
						controlPanel.element.style.marginTop = '-' + top + 'px';*/
						// if (ACUtils.Detector.getAgent().match(/msie 8/i)) {
							var left = parseInt(width/2, 10);
							//videoObject.style.left = '50%';
						/*	videoObject.parentNode.style.left = '50%';
							controlPanel.element.style.left = '0';
							videoObject.style.marginLeft = '-' + left + 'px';
							controlPanel.element.style.marginLeft = '-' + left + 'px';
							// 	videoObject.parentNode.style.left = '50%';*/
							// 	videoObject.style.left = '0';
							// 	controlPanel.element.style.left = '0';
							// 	videoObject.style.marginLeft = '-' + left + 'px';
							// 	controlPanel.element.style.marginLeft = '-' + left + 'px';
						// }
						/*First time you enter, the movie takes up the full size of the contatiner
						so no need to position it.. but resizing should ensure proper centering
						--hence the check*/
						 // alert(controlPanel.originalElementWidth+"     "+videoObject.width+'  '+left);
						if(controlPanel.originalElementWidth != 0 && controlPanel.originalElementWidth != videoObject.width){
							videoObject.style.left = "50%";
							videoObject.style.marginLeft = "-"+left+"px";
							controlPanel.element.style.left = "50%";
							controlPanel.element.style.marginLeft = '-' + left + 'px';	
						}else {
							videoObject.style.left = "";
							videoObject.style.marginLeft = "";
							controlPanel.element.style.left = "";
							controlPanel.element.style.marginLeft = "";
						}
					/*touch the dom to make IE recover its senses and get out of the blackout mode*/
					if (ACUtils.Detector.getAgent().match(/msie 6/i)) {document.body.style.display="none";document.body.style.display="block";}
					}
				} else {
					// add transition
					if (Media.Detection.CSSTransitions() === true && video.movieType() !== 'QuickTime') {
						videoObject.style.width = width + 'px';
						videoObject.style.height = height + 'px';
						if(controlPanel) {
							controlPanel.container.style.width = width + 'px';
							controlPanel.container.style.height = height + 'px';
							if(controlPanel.element) {
								controlPanel.element.style.width = width + 'px';
								controlPanel.element.style.height = height + 'px';
							}
						}
					} else {
						var morphEffects = [];

						if(controlPanel && (controlPanel.controllerType === 'slim' || controlPanel.controllerType === 'short-slim')) {
							controlPanel._hiding = true;
					        controlPanel._showing = false;
					
							controlPanel.fadeElement.style.opacity = '0';
							controlPanel.fadeElement.style.visibility = 'hidden';
							if(controlPanel.settingsMenu) {
								ACUtils.removeClassName(controlPanel.settingsMenu, controlPanel.settingsMenu.baseClassName+'-hovered');	
							}
							
							currentlyChangingSize = true;
						}
						if(controlPanel) {
							controlPanel.resetSettingsMenus();
						}

						morphEffects.push(new Effect.Morph(videoObject, {sync:true, style:{width:width+'px', height:height+'px'}}));
						if (video.movieType != 'Video' && typeof videoObject.parentNode != null) {
							morphEffects.push(new Effect.Morph(videoObject.parentNode, {sync:true, style:{width:width+'px', height:height+'px'}}));
						}
						
						if(controlPanel) {
							if(controlPanel.container) {
								morphEffects.push(new Effect.Morph(controlPanel.container, {sync:true, style:{width:width+'px', height:height+'px'}}));
							}
							if(controlPanel.element) {
								morphEffects.push(new Effect.Morph(controlPanel.element, {sync:true, style:{width:width+'px', height:height+'px'}}));
							}
						}
						
						var redraw = document.createElement('div');
						ACUtils.addClassName(redraw, 'ACMediaRedraw');
						
						var agent = ACUtils.Detector.getAgent();
						
						var forceIERedraw = function() {
							//if (!agent.match(/msie 8/i)) {
								// having to do a redraw on these elements to force IE6 not to show a black screen
								videoObject.style.outline = "1px solid transparent"; // adding an outline on the movie so the movie isn't black
								document.body.appendChild(redraw); // adding an element above the movie to remove black on and around movie
								controlPanel.mouseoverSettingsControl(controlPanel.sizesControl); // adding settings menu to remove black on edges of screen

								// removing all added CSS and elements
								videoObject.style.outline = 'none';
								document.body.removeChild(redraw);
								controlPanel.hide();
								controlPanel.resetSettingsMenus();
							//}
						}

						new Effect.Parallel(morphEffects, {
							duration:0.4,
							beforeStart: function() {
								if (ACUtils.Detector.isIEStrict()) {
									var top = parseInt(videoObject.offsetHeight/2);
									videoObject.parentNode.style.top = '50%';
									videoObject.style.top = '0';
									controlPanel.element.style.top = '0';
									videoObject.style.marginTop = '-' + top + 'px';
									controlPanel.element.style.marginTop = '-' + top + 'px';
									// if (agent.match(/msie 8/i)) {
									// 	var left = parseInt(videoObject.offsetWidth/2);
									// 	videoObject.parentNode.style.left = '50%';
									// 	videoObject.style.left = '0';
									// 	controlPanel.element.style.left = '0';
									// 	videoObject.style.marginLeft = '-' + left + 'px';
									// 	controlPanel.element.style.marginLeft = '-' + left + 'px';
									// }
									
									// force a redraw
									forceIERedraw();
								}								
							},
							afterUpdate: function() {
								currentlyChangingSize = true;
								if (ACUtils.Detector.isIEStrict()) {
									var top = parseInt(videoObject.offsetHeight/2);
									videoObject.parentNode.style.top = '50%';
									videoObject.style.top = '0';
									controlPanel.element.style.top = '0';
									videoObject.style.marginTop = '-' + top + 'px';
									controlPanel.element.style.marginTop = '-' + top + 'px';
									// if (agent.match(/msie 8/i)) {
									// 	var left = parseInt(videoObject.offsetWidth/2);
									// 	videoObject.parentNode.style.left = '50%';
									// 	videoObject.style.left = '0';
									// 	controlPanel.element.style.left = '0';
									// 	videoObject.style.marginLeft = '-' + left + 'px';
									// 	controlPanel.element.style.marginLeft = '-' + left + 'px';
									// }
								
									forceIERedraw();
								}
							},
							afterFinish: function() {
								if (ACUtils.Detector.isIEStrict()) {
									var top = parseInt(height/2);
									//video.object().parentNode.parentNode.style.marginTop = '-' + top + 'px';
									videoObject.parentNode.style.top = '50%';
									videoObject.style.top = '0';
									controlPanel.element.style.top = '0';
									videoObject.style.marginTop = '-' + top + 'px';
									controlPanel.element.style.marginTop = '-' + top + 'px';
									// if (agent.match(/msie 8/i)) {
									// 	var left = parseInt(width/2);
									// 	videoObject.parentNode.style.left = '50%';
									// 	videoObject.style.left = '0';
									// 	controlPanel.element.style.left = '0';
									// 	videoObject.style.marginLeft = '-' + left + 'px';
									// 	controlPanel.element.style.marginLeft = '-' + left + 'px';
									// }
									
									// force a redraw
									controlPanel.mouseoutSettingsControl(controlPanel.sizesControl);
									controlPanel.hide();
								}
								
								setControlPanelType();
								
								window.clearTimeout(sizeTimeout);
						        sizeTimeout = window.setTimeout(function(){
									if (controlPanel && (controlPanel.controllerType === 'slim' || controlPanel.controllerType === 'short-slim')) {
									
										controlPanel.fadeElement.style.visibility = 'visible';
										controlPanel.fadeElement.style.opacity = '1';
									
										controlPanel._hiding = false;
								        controlPanel._showing = false;
									}
							
									currentlyChangingSize = false;
						        },50);
							}
						});

					}//end else of if supports css transitions

				}//end handling for buffered video 
			
				setControlPanelType();
			}//end if controlpanel is defined
			this.currentWidth = width;
			this.currentHeight = height;
		},
		timeScale: function () {
			return video.timeScale();
		},
		
		movieType: function() {
			return video.movieType();
		},

		moviePath: function() {
			var url,
				path = '';

			if (typeof videoSrc != 'undefined' && videoSrc.length > 0) {
				url = videoSrc.substring(0, videoSrc.lastIndexOf('_')) + '.html';
			} else {
				return;
			}
		
			if (url.match(/\w+:\/\//i)) {
				// comment out the if section if not debugging
				if ((window.location.href.match(/\w+:\/\/ic/i) || window.location.href.match(/\w+:\/\/17/i) || window.location.href.match(/\w+:\/\/192/i) || window.location.href.match(/\w+:\/\/www-dev/i)) && url.indexOf('/105') < 0) {
					url = url.replace(/\w+:\/\/[^\/]+/i,"/105");
				} else {
					url = url.replace(/\w+:\/\/[^\/]+/i,"");
				}
			}
		
			path = url.substring(0, (url.lastIndexOf('/')+1));
			
			return path;
		},
		
		setCaptionsAvailable: function(url) {
			var func = this.enableCaptionsControl.bindAC(this);
			video.setCaptionsAvailable(func, url);
		},
		
		enableCaptionsControl: function() {
			if (controlPanel && typeof controlPanel.enableCaptionsControl !== 'undefined') {
				controlPanel.enableCaptionsControl();
				return true;
			}
			return false;
		},
		
		enableCaptions: function() {
			video.enableCaptions();
			this._fireEvent("QuickTime:didSetClosedCaptions", {controller: this, enabled: true});
		},
		
		disableCaptions: function() {
			video.disableCaptions();
			this._fireEvent("QuickTime:didSetClosedCaptions", {controller: this, enabled: false});
		},
		
		enableCaptionsTextDisplay: function() {
			return video.videoClosedCaptionsEnabled();
		},
		
		resetCaptions: function() {
			video.disableCaptions();
		},
		
		setSizesAvailable: function(list) {
			this.sizesMenuOptions = list;
			
			for (var i=0, option; option=this.sizesMenuOptions[i]; i++) {
				this.sizesMenuOptions['size_'+option.type] = option;
			}
			
			this.enableSizesControl();
		},
				
		enableSizesControl: function() {
			//console.log();
			if (controlPanel && typeof controlPanel.enableSizesControl !== 'undefined' && this.disableSizeSelector === false) {
				if (this.sizesMenuOptions && this.sizesMenuOptions.length > 1) {
					controlPanel.buildSizesMenu(this.sizesMenuOptions);
					controlPanel.setSizesAvailable();
					controlPanel.enableSizesControl();
					return true;
				}
			}
			return false;
		},
		
		setDownloadAvailable: function(list) {
			this.downloadMenuOptions = list;
			
			for (var i=0, option; option=this.downloadMenuOptions[i]; i++) {
				this.downloadMenuOptions['download_'+option.type] = option;
			}
			
			this.enableDownloadControl();
		},

		enableDownloadControl: function() {
			if (controlPanel && typeof controlPanel.enableDownloadControl !== 'undefined') {
				if (this.downloadMenuOptions.length > 0) {
					controlPanel.buildDownloadMenu(this.downloadMenuOptions);
					controlPanel.setDownloadAvailable();
					controlPanel.enableDownloadControl();
					return true;
				}
			}
			return false;
		},
		
		setShareAvailable: function(movie) {
			if (controlPanel && typeof controlPanel.enableShareControl !== 'undefined' && ac_media_language.sharemenu) {
				var head = document.getElementsByTagName('head').item(0),
					sharemenu = ac_media_language.sharemenu, self = this;

				for (var i=0, sharemenuitem; sharemenuitem=sharemenu[i]; i++) {
					var localScript = document.createElement('script'), shareMenuSetup;
					localScript.setAttribute('type', 'text/javascript');
					localScript.pluginName = sharemenuitem.id;
					
					shareMenuSetup = function() {
					
						//1) Get the class of the plugin that just loaded
						//2) Create an instance
						//3) Register it to controlPanel.registerPluginForMenu(newPlugin);

						if (typeof window.event != 'undefined') {
							var target = window.event.srcElement;

							if (!window.event || ((target = window.event.srcElement) && (target.isLoaded || ( (typeof target.isLoaded === "undefined") && ((target.readyState == 'complete') || (target.readyState == 'loaded'))) ) )) {
								if (target && !target.isLoaded) {
									target.onreadystatechange = null;
									target.isLoaded = true;
								}

								Event._domReady();
							}
						}
									
					}
					
					if (localScript.addEventListener) {
						localScript.addEventListener("load",shareMenuSetup,false);
					} else {
					
						if (typeof localScript.onreadystatechange === "function") {
							localScript.onreadystatechange = function () {
								if (this.readyState == 'complete') {
									shareMenuSetup();
								}
							}
						} else {
							localScript.onreadystatechange = shareMenuSetup;
						}
					}

					localScript.setAttribute('src', sharemenuitem.plugin);
					head.appendChild(localScript);
					
					sharemenu[i].localScript = localScript;
				}
			}
		},
		setFullscreenAvailable: function() {
			// console.log('setting fullscreen available');
			this.enableFullscreenControl();
		},
		enableFullscreenControl: function() {
			if (controlPanel && typeof controlPanel.enableFullscreenControl !== 'undefined') {
				controlPanel.enableFullscreenControl();
				return true;
			}
			return false;
		},
		enableFullscreen: function() {
			video.enableFullscreen();
			this._fireEvent("QuickTime:didSetClosedFullscreen", {controller: this, enabled: true});
		},
		disableFullscreen: function() {
			video.disableFullscreen();
			this._fireEvent("QuickTime:didSetClosedFullscreen", {controller: this, enabled: false});
		},
		language: null,
		path:null,
		configureSettingsControls: function(videoSrc) {
			if (existingVideo != false && controlPanelConfigurationsSet === true) return;
			
			var url,
				langAttr = document.body.parentNode.getAttribute('lang');
				this.language = language = MediaLanguage.getLangFromAttr(langAttr);
				//language = document.getElementsByTagName('html').item(0).getAttribute('lang'),
				this.path =  path = this.moviePath();
			if(isStreaming === true) this.expectingMovieJson=false;
			if(this.expectingMovieJson === true){
				if (typeof videoSrc != 'undefined' && videoSrc.length > 0) {
						url = videoSrc.substring(0, videoSrc.lastIndexOf('_')) + '.json';
					// url = videoSrc.substring(0, videoSrc.lastIndexOf('_')) + '.html';
				} else {
					return;
				}
		
			
				if (url.match(/\w+:\/\//i)) {
					// comment out the if section if not debugging
				if ((window.location.href.match(/\w+:\/\/ic/i) || window.location.href.match(/\w+:\/\/17/i) || window.location.href.match(/\w+:\/\/192/i) || window.location.href.match(/\w+:\/\/www-dev/i)) && url.indexOf('/105') < 0) {
						url = url.replace(/\w+:\/\/[^\/]+/i,"/105");
					} else {
						url = url.replace(/\w+:\/\/[^\/]+/i,"");
					}
				}
		
				//path = url.substring(0, (url.lastIndexOf('/')+1));
			
				// for debugging uncomment the lines below
				// if (location.href.match('test-without-share')){
				// 	url = '/tests/quicktime/snow_leopard_controls/configure-test-without-share.html';
				// } else {
				// 	url = '/tests/quicktime/snow_leopard_controls/configure-test.html';
				// }
		
				// new Ajax.checkURL(url, function() {
				// 	this.checkedForConfigXML = true;
				// }.bindAC(this));
				//  url = '/105'+url;
				// if (url.match(/\/105\/105/i)) {
				// 	url = url.replace(/\/105\/105/, "/105");
				// }
			
				// JSON request for configuration file
				new ACUtilsAjax.AjaxRequest(url, {
					method:'get',
					requestHeaders: {Accept: 'application/json'},
					onSuccess: function(transport) {
							this.configSettings = new Function("return "+transport.responseText)();
							this.setVideoId();
							movieJsonLoaded= true;
							// this.setSettingsControlsAvailableForLanguageAndPath(language, path);
					}.bindAC(this),
					onFailure: function() {
						if (typeof controlPanel != 'undefined' && controlPanel != null) {
							controlPanel.setTrackContainerWidth();
						}
					}.bindAC(this),
					// onException: function() {console.log("exception")},
					onComplete: function(){
						movieJsonComplete= true;
						this.processControlPanel();
					}.bindAC(this),
					evalJS: false
				});
		  	}	
		},
		
		processControlPanel: function(){
		// console.log("cp ="+controlPanel+'mv='+movieJsonComplete+' lang='+languageJsonComplete+' metad='+videoReceivedMetadata+ 'existingVideo='+existingVideo)
		/*wait for both json calls to return and then call the functions 
		trying to beat the timing issue between the two jsons
		_setupControls is being called from here so that it has ac_media_language 
		available for populating the different language text*/
		if(processedControlPanel !== true){
			if((movieJsonComplete === true || this.expectingMovieJson ===false) && languageJsonComplete === true &&(videoReceivedMetadata === true)){
				if(initializedCP === false) {
                   controlPanel._setupControls();
                }
				if(isStreaming === true){
					controlPanel.handleStreaming();
				}
	               // if(movieJsonLoaded === true){
	                   this.setSettingsControlsAvailableForLanguageAndPath(this.language, this.path);
	               // }
	               this._setControlPanel();
			processedControlPanel = true;
		
           		}
		}
	
		},
		
		/*Adding this code for new json format with video id. Immediate requirement-Analytics*/
		/*json with version>=2 will have a vid. If vid exists, expose it for analytics*/
		_videoId : null,
		setVideoId: function(){
			if(this.configSettings && this.configSettings.version && (this.configSettings.version >=2)){
				if(this.configSettings.vid) this._videoId = this.configSettings.vid;
			}else{
				this._videoId = null;
			}
		},

		videoID: function(){
			return this._videoId; 
		},
				
		disableSizeSelector: false,
		disableFullscreenControl: false,
		expectingMovieJson: true,
		setSettingsControlsAvailableForLanguageAndPath: function(language, path) {
			if(this.configSettings){
				var captionsWithPath = this.configSettings.metadata.captions,
					sizesList = this.configSettings.metadata.sizes,
					downloadList = this.configSettings.metadata.downloads,
					shareToggle = this.configSettings.metadata.share || true,
					movieLanguage = this.configSettings.metadata.lang,
					movieTitle = this.configSettings.metadata.title,
					movieDescription = this.configSettings.metadata.description,
					movieUrl = this.configSettings.src,
					moviePosterframe = this.configSettings.posterframe || 'http://images.apple.com/global/elements/overlay/overlay_movie_endstate_640x400_20081014.jpg';
			}
			if (typeof movieTitle != 'undefined') {
				video.setVideoTitle(movieTitle);
			}
			if (typeof movieUrl != 'undefined') {
				video.setVideoUrl(movieUrl);
			}
			if (typeof movieDescription != 'undefined') {
				video.setVideoDescription(movieDescription);
			}
			if (typeof moviePosterframe != 'undefined') {
				video.setVideoPosterFrame(moviePosterframe);
			}
			if(typeof controlPanel != 'undefined'){//IE needs this check
				if (typeof captionsWithPath != 'undefined') {
					var captionsFile = captionsWithPath.substring(captionsWithPath.lastIndexOf('/'), captionsWithPath.length),
						captionsUrl = path + ((captionsFile[0] === '/') ? captionsFile.substring(1, captionsFile.length) : captionsFile);

					controlPanel.captionsUrl = captionsUrl;
					this.setCaptionsAvailable(controlPanel.captionsUrl);
				}
			}

			if (typeof sizesList != 'undefined' && this.disableSizeSelector === false) {
				this.setSizesAvailable(sizesList);
			}
			if (typeof downloadsList != 'undefined') {
				this.setDownloadAvailable(downloadList);
			}
			if (shareToggle) {
				this.setShareAvailable();
			}
			
			/*Adding this code for new json format with allowsFullScreen. Immediate requirement-Full screen*/
			/*json with version>=3 will have a allowsFullScreen. If allowsFullScreen exists, expose it*/
			var movieAllowsFullscreen = false;
			// if we don't have configSettings, it's either a standalone or live stream, so we want full screen. Authors of standalone versions who don't want full screen must explicitly disable it.
			if (!this.configSettings) {
				movieAllowsFullscreen = true;
			} else if (this.configSettings.version && this.configSettings.version >=3) {
				// if we have configSettings and it's at least version 3 (when we added the full screen option),
				// check if the JSON allows any full screen movies. If we have at least one, enable it.
				if (typeof sizesList != 'undefined') {
					for (var i=0;i<sizesList.length;i++) {
						if(sizesList[i].allowFullScreen === true) movieAllowsFullscreen = true;
					}
				}
			}
			
			// if the browser supports full screen and at least one movie size allows full screen and the page author hasn't disabled it, set full screen as available
			if (this.supportsFullscreen() === true && movieAllowsFullscreen === true && (this.disableFullscreenControl === false || this.disableFullscreenControl === 'false')) {
				this.setFullscreenAvailable();
			}
			
			if (typeof captionsUrl == 'undefined' && typeof sizesList == 'undefined' && typeof downloadsList == 'undefined' && !shareToggle && this.supportsFullscreen() === false && typeof controlPanel != 'undefined') {
				controlPanel.setTrackContainerWidth();
			}
			
			controlPanelConfigurationsSet = true;
		},
		
        videoReceivedPlayingEvent: function (evt) { 
			if(video && this._currentPosition !== false && this._currentSrc !== null){
				this.pause();
			}
		
			//this is a hack.. TODO need to find a way to make this work only once
			if(this.movieType() == 'QuickTime' && (!Media.Detection.iPad()) && (!Media.Detection.Mobile())){
				try{
					video.object().SetControllerVisible(false);	
				}catch(e){}
			}
			
            if (!hasBegunPlaying && (this.movieType() == 'Video' || (this.time() > 0 && this.duration != 0))) {
                if (controlPanel && typeof controlPanel.mediaDidBecomePlayable !== 'undefined') {
    				controlPanel.mediaDidBecomePlayable();
				}

                if (controlPanel && typeof controlPanel.enableBasicControls !== 'undefined' && videoReceivedMetadata===true) {
                // 					if((!Media.Detection.iPad()) && (!Media.Detection.Mobile())){
                // 						this.processControlPanel();
                // 					}
					// give the settings config file a moment to load
    				controlPanel.enableBasicControls();
					controlPanel.setSettingsControls();
					if (typeof controlPanel.captionsUrl != 'undefined' && (!!controlPanel.captionsControl && !controlPanel.captionsControl.isEnabled)) {
						this.setCaptionsAvailable(controlPanel.captionsUrl);
					}
					
					switch(true) {
						case (typeof controlPanel.captionsControlSetting != 'undefined' && controlPanel.captionsControlSetting === true):
							video.enableCaptions();
							break;
						default:
							break;
					}
						
                }

				// if (Media.Detection.SnowLeopard1062() && this.movieType() == 'Video') {
				// 	var state = video.readystate(),
				// 		autoplay = video.autoplay();
				// 	console.log('videoReceivedPlayingEvent - state: '+state);
				// 	console.log('videoReceivedPlayingEvent - autoplay: '+autoplay);
				// }

    			playing = true;

				if(this.container)ACUtils.removeClassName(this.container, this.movieLoadingPanelClass);

                hasBegunPlaying = true;
                this._send('didBecomePlayable');
                this._fireEvent("QuickTime:canplaythrough", {controller: this});
                this._send('didBegin');
				this._fireEvent("QuickTime:begin", {controller: this});
				
				timeout = window.setTimeout(function(){
					if (controlPanel && typeof controlPanel != 'undefined') {
						controlPanel.hide();
					}
				}, 500);
				
            }
        },
        
        videoReceivedLoadEvent: function (evt) {
            if (controlPanel) {
				var percentLoaded = video.percentLoaded();
                		controlPanel.updatePercentLoaded(percentLoaded);
				 
				if(this._currentVolume != null && controlPanel.volumeControlSetting != 'undefined' && controlPanel.volumeControlSetting !=1){
					if(controlPanel.volumeControlSetting == 0){
						controlPanel.muteVolume();
					}else{
					     if(controlPanel.setVolume != 'undefined')
						this.setVolume(controlPanel.volumeControlSetting);
					}
					this._currentVolume = null;
				}

				// if (Media.Detection.SnowLeopard1062() && this.movieType() == 'Video') {
				// 	var state = video.readystate(),
				// 		autoplay = video.autoplay();
				// 	// console.log('videoReceivedLoadEvent - state: '+state);
				// 	// console.log('videoReceivedLoadEvent - autoplay: '+autoplay);
				// }
				
				if (percentLoaded <= 1 && typeof controlPanel.captionsUrl != 'undefined' && !controlPanel.captionsControl.isEnabled) {
					this.setCaptionsAvailable(controlPanel.captionsUrl);
				}
				
				// if (percentLoaded >= 1 && Media.Detection.SnowLeopard1062()) {
				// 	controlPanel.removeClickToPlay();
				// }
            }
            
        },
		
		videoReceivedLoadedmetadataEvent: function (evt) {
		// console.log('from videoReceivedLoadedmetadataEvent0='+controlPanel+'  '+videoReceivedMetadata);
			//The movie header information has been loaded or created. 
			// The duration, dimensions, looping state, and so on are now known.
			// Earliest point in the movie where we can determine the movie duration.  
			// if duration is set to Infinity.. it is a  live stream 
			var trackCount = null;
			if((!Media.Detection.iPad()) && (!Media.Detection.Mobile())){
				if(videoReceivedMetadata === false){
					if(isHTML5 === false){
						try {
				         	trackCount = video.object().GetTrackCount();
				    	}catch (e){}
			
					}else{
						videoReceivedMetadata = true;
					}
				}
				if(videoReceivedMetadata === false && trackCount != null){
					var i;
					if(trackCount >0){
			        	for (i = 1; i <= trackCount; i++) {
				            if ('Streaming' === video.object().GetTrackType(i)) {
				               isStreaming = true;
				            }
				        }
					}
					videoReceivedMetadata = true;	
				}
				if(isStreaming === true){
		        	if(video.duration() === Infinity){
		            	isLiveStreaming = true; 
		        	}
		    	}
			 if (controlPanel && typeof controlPanel.enableBasicControls !== 'undefined' && videoReceivedMetadata===true) {
				this.processControlPanel();				
			}
		     }
		},
		 
        videoReceivedEndedEvent: function (evt) {
            var time = video.time();
                duration = video.duration();
            
            if (hasEndedPlaying) {
                return;
			}
            if (hasBegunPlaying && !seeking && ((time >= duration && duration != 0) || (video.movieType() == "SBVDP" && duration != 0 && time >= (duration - 0.5)))) {
	
		hasEndedPlaying = true;
                this.videoReceivedTimeupdateEvent(this);

				if (controlPanel) {
					controlPanel.resetSettingsMenus();
			
					if (ACUtils.Detector.isIEStrict()) {
						// clean up video sizing for IE
						var videoObject = video.object();
						
						videoObject.parentNode.style.width = '';
						videoObject.parentNode.style.height = '';
						videoObject.parentNode.style.top = '';
						videoObject.style.top = '';
						controlPanel.element.style.top = '';
						videoObject.style.marginTop = '';
						controlPanel.element.style.marginTop = '';
						
						// if (ACUtils.Detector.getAgent().match(/msie 8/i)) {
							videoObject.parentNode.style.left = '';
							videoObject.style.left = '';
							controlPanel.element.style.left = '';
							videoObject.style.marginLeft = '';
							controlPanel.element.style.marginLeft = '';
						// }
					}
				}
			
				// if (!seeking) {
	                this._send('onMovieFinished');
	                this._send('didEnd');
	                this._fireEvent("QuickTime:end", {controller: this});
				// }
            }
        },
        
        videoReceivedPlayEvent: function (evt) {
			this._currentPlayState = 'playing';
			
            if (playAcknowledged) {
                return;
			}
             
            playAcknowledged = true;
           


			this._send('didStart');
            this._fireEvent("QuickTime:start", {controller: this});
        },

        videoReceivedPauseEvent: function (evt) {
			this._currentPlayState = 'paused';
            if (pauseAcknowledged) {
                return;
			}
                
            pauseAcknowledged = true;
			
			this._send('didStop');
            this._fireEvent("QuickTime:stop", {controller: this});
        },

        videoReceivedTimeupdateEvent: function (evt) {
			
			var time = video.time() || 0;
			//console.log("time = "+time);
            if (controlPanel) {
                controlPanel.updateTime(time);
	        }
            if (this._lastTime != time) {
                this._fireEvent("QuickTime:didPlayProgress", {
                    controller: this, 
                    currentTime: time, 
                    duration: this.duration()
                });
            }
            
            this._lastTime = time;
        },
    
        videoReceivedProgressEvent: function (evt) {
            if (controlPanel) {
                controlPanel.updatePercentLoaded(video.percentLoaded());
			}
			if(video.percentLoaded() >= 1 && largestMovieBuffered === false){
				this.checkIfLargestMovieIsBuffered();
			}
			//currentPosition and currentSrc only get value from resize function.
			if(video && this._currentPosition !== false && this._currentSrc !== null){	
				try{
					// unify the time scales to seconds
					var secondsLoaded = (this.movieType() === "Video") ? video.object().buffered.end(0) : video.object().GetMaxTimeLoaded()/video.object().GetTimeScale();
			    }catch (e){}
			}		
			// reset the playhead after resizing the video, ensuring the source has been set    
			if(video && this._currentPosition !== false && this._currentSrc !== null && secondsLoaded != 'undefined'&&(this._currentPosition < secondsLoaded)) {
				
				// only move the playhead to the saved position once the video is buffered to that point
				if (this._currentPosition < secondsLoaded) {
					video.setTime(this._currentPosition);
					this.play();
					this._currentPosition = false;
					var that = this;
					//destroy the canvas element that holds the interim screenshot
					if (video.movieType() === 'Video') {
						window.setTimeout(function() {
						that.destroyFrame();
						},600);
					}	
				} else {
					// pause until we're ready to play based on above condition
					if(playing === true) this.pause();
				}
			}
			
			// console.log('videoReceivedProgressEvent - state: '+video.readystate()+' - '+video.percentLoaded());
			switch(true) {
				case (!hasBegunPlaying && Media.Detection.SnowLeopard() && this.movieType() == 'Video' && video.autoplay() === true && video.readystate() >= 3 && video.percentLoaded() > 0.4):
					// console.log('should start playing');
					this.play();
					//this.videoReceivedPlayingEvent();
					break;
				default:
					break;
			}
			
        },

        videoReceivedDurationchangeEvent: function (evt) {
            if (controlPanel) {
                controlPanel.updateRemainingTime(this.duration() - this.time());
			}
        },
		videoReceivedWebkitendfullscreenEvent: function (evt) {
			if (controlPanel) {
				if (typeof this._currentPlayState != 'undefined' && this._currentPlayState === 'playing') {
					controlPanel.play();
				} else if (typeof this._currentPlayState != 'undefined' && this._currentPlayState === 'paused') {
					controlPanel.pause();
				}
				
				var currentVolume = this.volume();
				if (controlPanel.volumeScrubber) controlPanel.volumeScrubber.setValue(currentVolume);
				this.setVolume(currentVolume);
			}
		},
		captureFrame: function (targetVideo,w,h) {
			/**
			 * Captures a image frame from the provided video element.
			 * @param {Video} video HTML5 video element from where the image frame will be captured.
			 * @return {Canvas}
			 */
			var canvas = document.createElement('canvas');
				canvas.width  = w;
			    canvas.height = h;
			var ctx = canvas.getContext('2d');
			// note drawImage only works with video, img, and canvas elements
			ctx.drawImage(targetVideo, 0, 0, w, h);
		    return canvas;
		},
		_isLoading: false,
		createFrame: function () {
			/**
			 * Invokes the captureFrame function and attaches the canvas and/or loading elements
			 * to the DOM between the video and controller elements.
			 */
			if (this._isLoading !== true) {
				var targetVideo = (video.movieType() === 'Video' || video.object().tagName === 'OBJECT') ? video.object() : video.object().parentNode;
				
				var w = targetVideo.videoWidth,
					h = targetVideo.videoHeight,
					loadingIndicator = document.createElement('div'),
					loadingIndicatorAnime = document.createElement('div');
				
				if (video.movieType() === 'Video') {
					var canvasFrame = this.captureFrame(targetVideo,w,h);
					ACUtils.addClassName(canvasFrame,'canvasFrame');
					canvasFrame.style.width = w + "px";
					canvasFrame.style.height = h + "px";
					targetVideo.parentNode.insertBefore(canvasFrame,targetVideo.parentNode.lastChild)
				}

				loadingIndicator.id = 'loadingIndicator';
				loadingIndicator.style.opacity = '0';
				loadingIndicator.appendChild(loadingIndicatorAnime);
				targetVideo.parentNode.insertBefore(loadingIndicator,targetVideo.parentNode.lastChild);
				
				//position the loading frame center
				loadingIndicator.style.left = parseInt(targetVideo.parentNode.clientWidth)/2-parseInt(loadingIndicator.offsetWidth)/2+"px";
				loadingIndicator.style.top = parseInt(targetVideo.parentNode.clientHeight)/2-parseInt(loadingIndicator.offsetHeight)/2+"px";
			
				if (video.movieType() === 'Video') {
					loadingIndicator.style.opacity = '1';
				} else {
					new animateEffects.opacity(loadingIndicator,0,1,300);
				};

				this._isLoading = true;
			}
		},
		destroyFrame: function () {
			/**
			 * Destroys the canvas and/or loading elements in the DOM once the playhead is set after resize.
			 */
			if (this._isLoading !== false) {
				var canvasFrame = $$('.canvasFrame')[0] || false,
					loadingIndicator = document.getElementById('loadingIndicator');

				if (video.movieType() === 'Video') {
					canvasFrame.style.opacity = '0';
					loadingIndicator.style.opacity = '0';
				} else {
					if (loadingIndicator) new animateEffects.opacity(loadingIndicator,1,0,300);
				};
				window.setTimeout(function() {
					if (canvasFrame) canvasFrame.parentNode.removeChild(canvasFrame);
					loadingIndicator.parentNode.removeChild(loadingIndicator);
				},1000);

				this._isLoading = false;
			}
		}
    };
};

Media.Controller.fireEvent = function (event, data) {
    var body = document.getElementsByTagName("body")[0];
    if ('fire' in body) {
        body.fire(event, data);
    }
};

Media.ControlsWidget = function (containerElement, delegateObject, options) {
	this.settingsControlsAreSet = false;
	this.container = containerElement;
    this.delegate = delegateObject;
	this.options = options;
	//Adds itself as an observer of the plugin loaded notification.
	//process any plugin that are already loaded.
	// and call this.registerPluginClass() //The instance level method.
	ACUtils.addEventHandler(document.body, 'PluginClass:Added', this.registerPluginClass.bindAC(this));

	for (var i=0, pluginType; pluginType=Media.ControlsWidget.pluginTypes[i]; i++) {
		for (var j=0, pluginClass; pluginClass=pluginType[j]; j++) {
			this.registerPluginClass(pluginClass);
		}
	}
 
	if (!Media.Detection.iPad()) {
		this._createTemplate();
		initializedCP = false;
		this._setupControls();
	}
};

Media.ControlsWidget.registerPluginClass = function(aPluginClass) {
	//Structure plugins by pluginType: pluginType -> [plugin1, plugin2, plugin3]
	//Send an event to tell that a new plugin class is available
	//Instances need to register for that event, and when they get it, they add the menu for themselves.

	var pluginName = aPluginClass.prototype.name(),
		pluginType = aPluginClass.prototype.pluginType(),
		pluginTypeArray;
	
	this.pluginTypes(pluginType);
	this.pluginClassesForType
	
	if (!(pluginTypeArray = Media.ControlsWidget._pluginTypes[pluginType]) || !Media.ControlsWidget._pluginTypes.hasOwnProperty(pluginType)) {
		pluginTypeArray = [];
		Media.ControlsWidget._pluginTypes[pluginType] = pluginTypeArray;
		Media.ControlsWidget._pluginTypes.push(pluginType);
	}
	
	if (!pluginTypeArray.hasOwnProperty(pluginName)) {
		pluginTypeArray[pluginName] = pluginName;
		pluginTypeArray.push(pluginName);
	}
	
	Media.Controller.fireEvent('PluginClass:Added', {
		'plugin': aPluginClass,
		'name': pluginName,
		'type': pluginType
	});
};
Media.ControlsWidget._pluginTypes = [];
Media.ControlsWidget.pluginTypes = function(aPluginType) {
	return this._pluginTypes;
};
Media.ControlsWidget.pluginClassesForType = function(aPluginType) {
	return this.pluginTypes[aPluginType];
};

Media.ControlsWidget.TEMPLATE = '\
<div id="ACMedia-controls" class="ACMediaControls" tabindex="0">\
	<a href="#video"></a>\
	<div id="ACMedia-alert-display-container" class="ACMediaAlertDisplay"></div>\
	<div id="ACMedia-track-text" class="ACMediaTrackText"><span id="ACMedia-track-text-span"></span></div>\
    <div id="ACMedia-controls-panel" class="mediaControllerPanel">\
		<div class="slim-left-cap"></div>\
        <div id="ACMedia-media-controller" class="ACMediaController">\
            <div id="ACMedia-volume-mute" class="volumeMute"></div>\
            <div class="volumePanel">\
                <div id="ACMedia-volume-track" class="volumeTrack">\
                    <div id="ACMedia-control-volume-progress" class="volumeTrackProgress"></div>\
                    <div id="ACMedia-volume-handle" class="volumePlayHead"></div>\
                </div>\
            </div>\
			<div id="ACMedia-volume-full" class="volumeFull"></div>\
            <div id="ACMedia-control-fastbackward" class="fastBackward"></div>\
            <div id="ACMedia-control-play-pause"></div>\
            <div id="ACMedia-control-fastforward" class="fastForward"></div>\
			<div id="ACMedia-track-container" class="track-container">\
      	      <div id="ACMedia-control-time-display" class="timeDisplay"><span id="ACMedia-min-played">00</span>:<span id="ACMedia-sec-played">00</span></div>\
	            <div class="trackPanel">\
	                <div id="ACMedia-control-track" class="track">\
	                    <div id="ACMedia-control-loaded-progress" class="loadedProgress"></div>\
	                    <div id="ACMedia-control-track-progress" class="trackProgress"></div>\
	                    <div id="ACMedia-control-playhead" class="playHead"></div>\
	                </div>\
					<div id="ACMedia-track-end-cap" class="track-right-cap"></div>\
	            </div>\
	            <div id="ACMedia-control-duration-display" class="durationDisplay">-<span id="ACMedia-min-remain">00</span>:<span id="ACMedia-sec-remain">00</span></div>\
			</div>\
			<div id="ACMedia-settings-controls" class="settingsControls">\
				<div id="ACMedia-captions-control" class="captionsControl"></div>\
				<div id="ACMedia-sizes-control" class="sizesControl"></div>\
				<div id="ACMedia-download-control" class="downloadControl"></div>\
				<div id="ACMedia-share-control" class="shareControl"></div>\
				<div id="ACMedia-fullscreen-control" class="fullscreenControl"></div>\
			</div>\
			<div id="ACMedia-stream-control" class="streamText"></div>\
        </div>\
		<div class="slim-right-cap"></div>\
    </div>\
</div>';


Media.ControlsWidget.show = function(controls) {
    if (controls.fadeElement && !controls._showing) {
	if (controls._effect) {delete controls._effect;}
       /* if (controls._effect) {
            try {
				controls._effect.cancel();
			} catch(e) {}
            delete controls._effect;
        }*/

        controls._showing = true;
        controls._hiding = false;

		if (controls.fadeElement) {
			if (Media.Detection.CSSTransitions() === true) {
				controls._effect = function() {
					ACUtils.removeClassName(controls.fadeElement, 'fade');
				};
				controls._effect();
			} else {//console.log("else of show")
				controls._effect= new animateEffects.opacity(controls.fadeElement,0,1, 500);
		      /*  controls._effect = new Effect.Opacity(controls.fadeElement, {
		            to: 1, 
		            duration: 0.5,
		            afterFinish: function(){controls._showing=false;}
		        });*/
			}
		}
    }
};
Media.ControlsWidget.hide = function(controls) {
    if (controls.fadeElement && !controls._hiding) {
		if (controls._effect) {delete controls._effect;}
       /* if (controls._effect) {
            try {
				controls._effect.cancel();
			} catch(e) {}
            delete controls._effect;
        }*/
        
        controls._hiding = true;
        controls._showing = false;
		if (controls.fadeElement) {
			if (Media.Detection.CSSTransitions() === true) {
				controls._effect = function() {
					controls.resetSettingsMenus();
					//controls._unselectControl(controls._currentSettingsControl);
					ACUtils.addClassName(controls.fadeElement, 'fade');
				};
				controls._effect();
			} else {//console.log("else of hide")
				controls._effect= new animateEffects.opacity(controls.fadeElement, 1,0,500);
			/*	controls._effect = new Effect.Opacity(controls.fadeElement, {
					to: 0,
					duration: 0.5,
					beforeStart: function(){
						controls.resetSettingsMenus();
						//controls._unselectControl(controls._currentSettingsControl);
					},
					afterFinish: function(){
						controls._hiding=false;
					}
				});*/
			}
		}
    }
};

Media.ControlsWidget.prototype = {
    delegate: null,
    element: null,
    _plugins: [],

	_buildControlWithTitleOptions: function(title, menuOptions) {
		var control = document.createElement('li'),
			anchor = document.createElement('a');

		ACUtils.addClassName(control, title);
		// console.log('menuOptions.url: '+menuOptions.url+' menuOptions.name: '+menuOptions.name);
		if (typeof menuOptions != 'undefined' && typeof menuOptions.url != 'undefined' && typeof menuOptions.name != 'undefined') {
			anchor.setAttribute('href', menuOptions.url);
			anchor.innerHTML = menuOptions.name;
			control.appendChild(anchor);
		} else {
			return;
		}

		control.baseClassName = control.baseClassName || control.className;
	
		ACUtils.addEventHandler(control, 'mousedown', function(evt) {
			ACUtils.addClassName(this, this.baseClassName+'-active');
		});
		ACUtils.addEventHandler(control, 'mouseup', function(evt) {
			ACUtils.removeClassName(this, this.baseClassName+'-active');
		});
		ACUtils.addEventHandler(document.documentElement, 'mouseup', function(evt) {
			ACUtils.removeClassName(this, this.baseClassName+'-active');
		});
		ACUtils.addEventHandler(control, 'mouseover', function(evt) {
			ACUtils.addClassName(this, this.baseClassName+'-hover');
		});
		ACUtils.addEventHandler(control, 'mouseout', function(evt) {
			ACUtils.removeClassName(this, this.baseClassName+'-hover');
		});

		return control;
	},
	
	_sizesMenuControls: [],
	selectSizeFromMenu: function(control) {
		if (typeof control != 'undefined') {
			this._unselectMenu();
			this._unselectControl(this.sizesControl);
			for (var i=0, sizeControl; sizeControl=this._sizesMenuControls[i]; i++) {
				// (sizeControl === control) ? this._selectControl(sizeControl) : this._unselectControl(sizeControl);
				((ACUtils.trim(sizeControl.className.toString()).split(" ")[0]) === (ACUtils.trim(control.className.toString()).split(" ")[0])) ? this._selectControl(sizeControl) : this._unselectControl(sizeControl);
			}
			this._send('setVideoSizeForSrc', control.optionsUrl);
			this.sizesControlSetting = control;
		}
	},
	_getSizesMenuControl: function(size, title, options) {
		var control = this.temp=this._buildControlWithTitleOptions('size'+title, {
			'url': options.src,
			'name': (ac_media_language[size] || title) + ' ' + options.width + 'x' + options.height
		});
		control.appendChild(document.createElement('span'));
		control.optionsUrl = options.src;
		var that = this;
		ACUtils.addEventHandler(control, 'click', function(evt) {
			ACUtils.stopEvent(evt);
			that.selectSizeFromMenu(control);
			return false;
		});
				 		
		
		// this.mouseclickedEvent = this.handleMouseDownOnSizeSelector.bindAsEventListenerAC(this)
		// ACUtils.addEventHandler(control, 'click', this.mouseclickedEvent);
		if (this.element.offsetWidth == options.width && this.element.offsetHeight == options.height) {
			this._selectControl(control);
		}

		return control;
	},
	
	_firstLoad: false,
	originalElementWidth: 0,
	buildSizesMenu: function(options) {
		var mySizesMenu = this.sizesMenu;
		if(mySizesMenu.firstChild) {
			 while (mySizesMenu.firstChild)
				 mySizesMenu.removeChild(mySizesMenu.firstChild);
		}
		if(!this._firstLoad){
			this.originalElementWidth = this.element.offsetWidth;
			this.originalElementHeight = this.element.offsetHeight;
			this._firstLoad = true;
		}

		if (Media.Detection.CSSTransitions() === true) {
			this.element.style.width = this.originalElementWidth + 'px';
			this.element.style.height = this.originalElementHeight + 'px';
		}
		
		if (typeof options.size_hd != 'undefined' && this.originalElementWidth >= options.size_hd.width && this.originalElementHeight >= options.size_hd.height) {
			this.sizesHDControl = this._getSizesMenuControl('hd', 'HD', options.size_hd);
			this._sizesMenuControls.push(this.sizesHDControl);
			mySizesMenu.appendChild(this.sizesHDControl);
		}

		if (typeof options.size_large != 'undefined' && this.originalElementWidth >= options.size_large.width && this.originalElementHeight >= options.size_large.height) {
			this.sizesLargeControl = this._getSizesMenuControl('large', 'Large', options.size_large);
			this._sizesMenuControls.push(this.sizesLargeControl);
			mySizesMenu.appendChild(this.sizesLargeControl);
		}
		
		if (typeof options.size_medium != 'undefined' && this.originalElementWidth >= options.size_medium.width && this.originalElementHeight >= options.size_medium.height) {
			this.sizesMediumControl = this._getSizesMenuControl('medium', 'Medium', options.size_medium);
			this._sizesMenuControls.push(this.sizesMediumControl);
			mySizesMenu.appendChild(this.sizesMediumControl);
		}
		
		if (typeof options.size_small != 'undefined' && this.originalElementWidth >= options.size_small.width && this.originalElementHeight >= options.size_small.height) {
			this.sizesSmallControl = this._getSizesMenuControl('small', 'Small', options.size_small);
			this._sizesMenuControls.push(this.sizesSmallControl);
			mySizesMenu.appendChild(this.sizesSmallControl);
		}
		
		return this._sizesMenuControls;
	},
	
	_downloadMenuControls: [],
	_getDownloadMenuControl: function(size, title, options) {
		var controlTitle = (title.match(/\//)) ? title.substring(0, title.indexOf('/')) : title,
			unit = 'mb';
		var control = this._buildControlWithTitleOptions('download'+controlTitle, {
			'url': options.src,
			'name': (ac_media_language[size] || title) + ' ' + options.size + (ac_media_language[unit] || 'MB')
		});
		ACUtils.addEventHandler(control, 'click', function(evt) {
			 ACUtils.stopEvent(evt);
			this._unselectMenu();
			this._unselectControl(this.downloadControl);
			document.location.href = options.src;
		}.bindAsEventListenerAC(this));
		
		return control;
	},
	buildDownloadMenu: function(options) {
		if (typeof options.download_hd != 'undefined') {
			this.downloadHDControl = this._getDownloadMenuControl('hd', 'HD', options.download_hd);
			this._downloadMenuControls.push(this.downloadHDControl);
			this.downloadMenu.appendChild(this.downloadHDControl);
		}
		if (typeof options.download_large != 'undefined') {
			this.downloadLargeControl = this._getDownloadMenuControl('large', 'Large', options.download_large);
			this._downloadMenuControls.push(this.downloadLargeControl);
			this.downloadMenu.appendChild(this.downloadLargeControl);
		}
		if (typeof options.download_ipod != 'undefined') {
			this.downloadiPodControl = this._getDownloadMenuControl('ipod', 'iPod/iPhone', options.download_ipod);
			this._downloadMenuControls.push(this.downloadiPodControl);
			this.downloadMenu.appendChild(this.downloadiPodControl);
		}

		return this._downloadMenuControls;
	},
	
	_shareMenuControls: [],
	buildShareMenu: function(pluginClass) {
			var pluginName = pluginClass.name(),
				pluginUrl = pluginClass.url();
			//	pluginShare = pluginClass.share();
			
			var control = this[pluginName.toLowerCase()+'Control'] = this._buildControlWithTitleOptions(pluginName, {
				'url': pluginUrl,
				'name': pluginName
			});
			
			var video = this._send('video');
			
			ACUtils.addEventHandler(control, 'click', function(evt) {
				 ACUtils.stopEvent(evt);
				pluginClass.share(video);
			});
			//ACUtils.addEventHandler(control, 'click', pluginShare);
			this._shareMenuControls.push(control);
			this.shareMenu.appendChild(control);
			
			ACUtils.addClassName(control, control.baseClassName + '-enabled');
		//}

		//this.shareMenuControls = this.menuControls;

		return this._shareMenuControls;
	},
	
	_registeredPlugins: [],
	registerPluginClass: function(evt) {
		var plugin = new evt.memo.plugin(),
			pluginName = plugin.name(),
			pluginActionName = plugin.actionName(),
			pluginType = plugin.pluginType();
					
		
		this._registeredPlugins.push(plugin);
		
		this.buildShareMenu(plugin);

		//Add an item in menu menuName and set plugin as the recipient for the action. Share plugins need to receive as an argument:
		//	- the title of the video
		//	- a description
		//	- The URL of the video.

		if (!this.shareEnabled) {
			this.setShareAvailable();
			this.enableShareControl();
		}

	},
	
    _createTemplate: function () {
        function templateToNode(str) {
            var temporary = document.createElement('div'),
                node;
            temporary.innerHTML = str;
            node = temporary.firstChild;
            return node;
        }
			
		this.setControllerType();
		
		var datetime = new Date();
		this.timestamp = datetime.getTime();
		
       	this.container.appendChild(templateToNode(Media.ControlsWidget.TEMPLATE));
		
       	this.element = document.getElementById('ACMedia-controls');
		this.element.id = 'ACMedia-controls_'+this.timestamp;
		this.element.style.outline = 'none';
	
		ACUtils.addEventHandler(this.element, 'keydown', this.keyDownHandler.bindAsEventListenerAC(this));
		// Click to Play for Snow Leopard < 10.6.3
		// if (Media.Detection.SnowLeopard1062()) {		
		// 	this.fadeElement = document.getElementById('ACMedia-controls-panel');
		// 	this.fadeElement.style.visibility = 'hidden';
		// 
		// 	this.clickToPlayElement = document.createElement('ul');
		// 	var clickToPlayItem = document.createElement('li'),
		// 		clickToPlaySpanButton = document.createElement('span'),
		// 		clickToPlaySpan = document.createElement('span'),
		// 		clickToPlayBold = document.createElement('b');
		// 	
		// 	ACUtils.addClassName(clickToPlaySpanButton, 'pillbutton');
		// 	clickToPlaySpan.innerHTML = ac_media_language.play || 'Play';
		// 	clickToPlayBold.innerHTML = '>';
		// 	ACUtils.addEventHandler(this.clickToPlayElement, 'click', this.clickToPlay.bindAsEventListenerAC(this));
		// 
		// 	clickToPlaySpanButton.appendChild(clickToPlaySpan);
		// 	clickToPlaySpanButton.appendChild(clickToPlayBold);
		// 	clickToPlayItem.appendChild(clickToPlaySpanButton);
		// 	this.clickToPlayElement.appendChild(clickToPlayItem);
		// 
		// 	this.element.appendChild(this.clickToPlayElement);
		// }
    },

	_setRegularControllerType: function() {
		ACUtils.removeClassName(this.container, 'slim');
		ACUtils.removeClassName(this.container, 'short-slim');
		this.controllerType = 'regular';
	},
	_setSlimControllerType: function() {
		ACUtils.addClassName(this.container, 'slim');
		ACUtils.removeClassName(this.container, 'short-slim');
		this.controllerType = 'slim';
	},
	_setShortSlimControllerType: function() {
		ACUtils.addClassName(this.container, 'slim');
		ACUtils.addClassName(this.container, 'short-slim');
		this.controllerType = 'short-slim';
	},
	setControllerType: function() {
		switch (true) {
			case Media.Detection.Firefox():
			case Media.Detection.Opera():
			case (typeof this.options != 'undefined' && this.options.slimController === true):
			case (typeof this.options != 'undefined' && this.options.controllerType === 'slim'):
				if (this.container.offsetWidth < 450) {
					this._setShortSlimControllerType();
				} else {
					this._setSlimControllerType();
				}
				break;
			case (this.container.offsetWidth < 450 && !ACUtils.Detector.isIEStrict()):
				this._setShortSlimControllerType();
				break;
			default:
				this._setRegularControllerType();
		}
		
		if (!this.volumeScrubber) {
			this.createVolumeScrubber();
		}
	},
	
	setFocus: function() {
		if(this.element) {
			window.setTimeout(function() {
				try{
					this.element.focus();
				} catch(e) {
					this.setFocus();
				}
			}.bindAC(this), 50);
		}
	},

	// clickToPlay: function() {
	// 	this.removeClickToPlay();
	// 	this.play();
	// },
	// removeClickToPlay: function() {
	// 	this.fadeElement.style.visibility = 'visible';
	// 	this.clickToPlayElement.style.display = 'none';
	// },
	
    _setupControls: function () {
		var timestamp = this.timestamp;
		this.fadeElement = get('ACMedia-controls-panel');
		this.trackEndCap = get('ACMedia-track-end-cap');

		function addTimeStamp(element) {
			var currentId = element.id;
			element.id = currentId+'_'+timestamp;
			return element.id;
		}
		
		function addBaseClassName(element) {
			element.baseClassName = element.baseClassName || element.className;
		}
		
        function addActiveStateSwitching(element) {
            addBaseClassName(element);

            function onmousedown(event) {
	//console.log('adding active to: '+this.baseClassName);
                ACUtils.addClassName(this, this.baseClassName+'-active');
            }
            function onmouseup(event) {
                ACUtils.removeClassName(this, this.baseClassName+'-active');            
            }
            
            ACUtils.addEventHandler(element, 'mousedown', onmousedown.bindAC(element));
            ACUtils.addEventHandler(element, 'mouseup', onmouseup.bindAC(element));
            ACUtils.addEventHandler(document.documentElement, 'mouseup', onmouseup.bindAC(element));
        }
        
		function addHoverStateSwitching(element) {
			if (!element.baseClassName) {
				addBaseClassName(element);
			}
			
			function onmouseover(event) {
				ACUtils.addClassName(this, element.baseClassName+'-hover');
			}
			function onmouseout(event) {
				ACUtils.removeClassName(this, element.baseClassName+'-hover');
			}
			
			ACUtils.addEventHandler(element, 'mouseover', onmouseover.bindAC(element));
			ACUtils.addEventHandler(element, 'mouseout', onmouseout.bindAC(element));
		}
		
        function get(id) {
			var element = document.getElementById(id),
				newId = addTimeStamp(element);
			
			return element;
		}
        
        // Play/pause button
		this.toggleControl = get('ACMedia-control-play-pause');
		
        this.playControl = document.createElement('div');
		ACUtils.addClassName(this.playControl, 'play');
        addActiveStateSwitching(this.playControl);
		this.playControl.id = 'ACMedia-play-control_'+this.timestamp;
        ACUtils.addEventHandler(this.playControl, 'click', this.play.bindAC(this));
		this.playControl.innerHTML = ac_media_language.play || 'Play';
		this.playControl.style.display = 'none';

		this.pauseControl = document.createElement('div');
		ACUtils.addClassName(this.pauseControl, 'pause');
		addActiveStateSwitching(this.pauseControl);
		this.pauseControl.id = 'ACMedia-pause-control_'+this.timestamp;
		ACUtils.addEventHandler(this.pauseControl, 'click', this.pause.bindAC(this));
		this.pauseControl.innerHTML = ac_media_language.pause || 'Pause';
		this.pauseControl.style.display = 'none';
		
		ACUtils.showElement(this._send('playing') ? this.pauseControl : this.playControl);        
        //var playpause = get('ACMedia-control-play-pause');
		var playpause = this.toggleControl;
        playpause.appendChild(this.playControl);
        playpause.appendChild(this.pauseControl);
        
        // Fast Backward
        this.fastBackwardControl = get('ACMedia-control-fastbackward');
		this.fastBackwardControl.innerHTML = ac_media_language.fastreverse || 'Fast Reverse';
        ACUtils.addEventHandler(this.fastBackwardControl, 'click', this.fastBackward.bindAC(this));
        addActiveStateSwitching(this.fastBackwardControl);
        
        // Fast Forward
        this.fastForwardControl = get('ACMedia-control-fastforward');
		this.fastForwardControl.innerHTML = ac_media_language.fastforward || 'Fast Forward';
        ACUtils.addEventHandler(this.fastForwardControl, 'click', this.fastForward.bindAC(this));
        addActiveStateSwitching(this.fastForwardControl);
        
        // Volume Mute
		this.volumeMuteControl = get('ACMedia-volume-mute');
		this.volumeMuteControl.innerHTML = ac_media_language.mutevolume || 'Mute Volume';
		ACUtils.addEventHandler(this.volumeMuteControl, 'click', this.muteVolume.bindAC(this));
		addActiveStateSwitching(this.volumeMuteControl);
		
		// Volume Full
		this.volumeFullControl = get('ACMedia-volume-full');
		this.volumeFullControl.innerHTML = ac_media_language.fullvolume || 'Full Volume';
		ACUtils.addEventHandler(this.volumeFullControl, 'click', this.fullVolume.bindAC(this));
		addActiveStateSwitching(this.volumeFullControl);
		
		// Settings Controls
		this.settingsControls = get('ACMedia-settings-controls');
		addBaseClassName(this.settingsControls);
		
		this.captionsControl = get('ACMedia-captions-control');
		if (!ACUtils.Detector.isIEStrict()) {
			this.captionsControl.innerHTML = ac_media_language.captionscontrol || 'Closed Captions';
		}
		ACUtils.addEventHandler(this.captionsControl, 'click', this.toggleCaptions.bindAC(this));
		addActiveStateSwitching(this.captionsControl);
		
		this.sizesControl = get('ACMedia-sizes-control');
		if (!ACUtils.Detector.isIEStrict()) {
			this.sizesControl.innerHTML = ac_media_language.sizescontrol || 'Video Size';
		}
		this.sizesControl.controlName = 'sizes';
		ACUtils.addEventHandler(this.sizesControl, 'click', this.toggleSizesMenu.bindAC(this), false);
		addActiveStateSwitching(this.sizesControl);
		ACUtils.addEventHandler(this.sizesControl, 'mouseover', this.mouseoverSettingsControl.bindAC(this, this.sizesControl),false);
		ACUtils.addEventHandler(this.sizesControl, 'mouseout', this.mouseoutSettingsControl.bindAsEventListenerAC(this, this.sizesControl), false);
		
		this.downloadControl = get('ACMedia-download-control');
		if (!ACUtils.Detector.isIEStrict()) {
			this.downloadControl.innerHTML = ac_media_language.downloadcontrol || 'Download Video';
		}
		this.downloadControl.controlName = 'download';
		ACUtils.addEventHandler(this.downloadControl, 'click', this.toggleDownloadMenu.bindAC(this));
		addActiveStateSwitching(this.downloadControl);
		ACUtils.addEventHandler(this.downloadControl, 'mouseover', this.mouseoverSettingsControl.bindAC(this, this.downloadControl));
		ACUtils.addEventHandler(this.downloadControl, 'mouseout', this.mouseoutSettingsControl.bindAsEventListenerAC(this, this.downloadControl));
		
		this.shareControl = get('ACMedia-share-control');
		if (!ACUtils.Detector.isIEStrict()) {
			this.shareControl.innerHTML = ac_media_language.sharecontrol || 'Share Video';
		}
		this.shareControl.controlName = 'share';
		ACUtils.addEventHandler(this.shareControl, 'click', this.toggleShareMenu.bindAC(this));
		addActiveStateSwitching(this.shareControl);
		ACUtils.addEventHandler(this.shareControl, 'mouseover', this.mouseoverSettingsControl.bindAC(this, this.shareControl));
		ACUtils.addEventHandler(this.shareControl, 'mouseout', this.mouseoutSettingsControl.bindAsEventListenerAC(this, this.shareControl));

		this.fullscreenControl = get('ACMedia-fullscreen-control');
		if (!ACUtils.Detector.isIEStrict()) {
			this.fullscreenControl.innerHTML = ac_media_language.fullscreencontrol || 'Full Screen';
		}
		ACUtils.addEventHandler(this.fullscreenControl, 'click', this.toggleFullscreen.bindAC(this));
		addActiveStateSwitching(this.fullscreenControl);
		
		this.settingsMenu = document.createElement('div');
		if (Media.Detection.CSSBorderRadius() === false) {
			this.settingsMenuRoundRect = this.getRoundRectForArcAndOpacity(0.05, 0.9);
			this.settingsMenu.appendChild(this.settingsMenuRoundRect);
		}

		this.settingsMenu.id = 'ACMedia-settings-menu_'+this.timestamp;
		ACUtils.addClassName(this.settingsMenu, 'ACMediaSettingsMenu');
		document.body.appendChild(this.settingsMenu);
		this.settingsMenu.baseClassName = 'ACMediaSettingsMenu';
		if (ACUtils.Detector.isIEStrict()) {
			ACUtils.addEventHandler(this.settingsMenu, 'click', function(evt){
				if(!evt) evt = window.event;
				var tgt = ACUtils.getTarget(evt);
				if(tgt && tgt.tagName !=null &&  tgt.tagName != "A" ){ ACUtils.stopEvent(evt);}});
		}

		this.settingsMenuCarrot = document.createElement('div');
		ACUtils.addClassName(this.settingsMenuCarrot, 'ACMediaSettingsMenuCarrot');
		this.settingsMenu.appendChild(this.settingsMenuCarrot);
		
		this.settingsMenuTitle = document.createElement('div');
		ACUtils.addClassName(this.settingsMenuTitle, 'ACMediaSettingsMenuTitle');
		this.settingsMenu.appendChild(this.settingsMenuTitle);
		
		this.mediaController = get('ACMedia-media-controller');
		this.streamTextContainer = get('ACMedia-stream-control');
		this.handleStreaming();
		
		this.speedDisplayAlert = document.createElement('div');
		this.captionsDisplayAlert = document.createElement('div');
		ACUtils.addClassName(this.captionsDisplayAlert, 'ACMediaCaptionsDisplay');
		
		this.alertDisplayContainer = get('ACMedia-alert-display-container');
		this.trackText = get('ACMedia-track-text');
		this.trackTextSpan = get('ACMedia-track-text-span');
		this.volumeThumb = get('ACMedia-volume-handle');
		this.volumeTrack = get('ACMedia-volume-track');
		this.volumeProgress = get('ACMedia-control-volume-progress');
		this.trackContainer = get('ACMedia-track-container');
		this.playhead = get('ACMedia-control-playhead');
		this.track = get('ACMedia-control-track');
		this.trackProgress = get('ACMedia-control-track-progress');
		this.controlLoadedProgress = get('ACMedia-control-loaded-progress');
		this.mediaTimeDisplay = get('ACMedia-control-time-display');
		this.minutesPlayed = get('ACMedia-min-played');
	    this.secondsPlayed = get('ACMedia-sec-played');
		this.mediaDurationDisplay = get('ACMedia-control-duration-display');
	    this.minutesRemaining = get('ACMedia-min-remain');
	    this.secondsRemaining = get('ACMedia-sec-remain');
	
		this.settingsMenuList = document.createElement('div');
		this.settingsMenu.appendChild(this.settingsMenuList);

		this.sizesMenu = document.createElement('ul');
		this.sizesMenu.menuName = 'sizes';
		this.sizesMenu.menuTitle = this.sizesControl.menuTitle = ac_media_language.sizescontrol || 'Video Size';
		
		this.downloadMenu = document.createElement('ul');
		this.downloadMenu.menuName = 'download';
		this.downloadMenu.menuTitle = this.downloadControl.menuTitle = ac_media_language.downloadcontrol || 'Download Video';
		
		this.shareMenu = document.createElement('ul');
		this.shareMenu.menuName = 'share';
		this.shareMenu.menuTitle = this.shareControl.menuTitle = ac_media_language.sharecontrol || 'Share Video';
		
		addBaseClassName(this.alertDisplayContainer);
		addBaseClassName(this.trackText);
		addBaseClassName(this.mediaTimeDisplay);
		addBaseClassName(this.mediaDurationDisplay);

		switch (this.controllerType) {
			case 'slim':
			case 'short-slim':
				var trackContainerWidth = +(this.container.offsetWidth - 235);
				if (ACUtils.Detector.isWin()) {
					trackContainerWidth = trackContainerWidth - 10;
				}
				this.trackContainer.style.width = trackContainerWidth + 'px';
				break;
			default:
				break;
		}
		// if (this.controllerType === 'slim' || this.controllerType === 'short-slim') {
		// 	var trackContainerWidth = parseInt(this.container.offsetWidth - 235);
		// 	if (ACUtils.Detector.isWin()) {
		// 		trackContainerWidth = trackContainerWidth - 10;
		// 	}
		// 	this.trackContainer.style.width = trackContainerWidth + 'px';
		// }
		
		addActiveStateSwitching(this.volumeThumb);
		//this.createVolumeScrubber();
		
		
		if (!this.scrubber && this.element !== null) {
		    addActiveStateSwitching(this.playhead);
		}
		initializedCP = true;
    },

	/*
	Basically, enables the 30 sec rewind for vods and hide both ff and rewind for live streams
	*/
	handleStreaming: function(){
		if(isStreaming === true){
			if(isLiveStreaming === true){
				if(isHTML5 === false){
					ACUtils.addClassName(this.mediaController, "ACMediaLiveStreamingQT");
				}else{
					ACUtils.addClassName(this.mediaController, "ACMediaLiveStreaming");
				}
				this.streamTextContainer.innerHTML = ac_media_language.livestreamdisplay || "Live Broadcast";
			}else {
				if(isHTML5 === false){
					ACUtils.addClassName(this.mediaController, "ACMediaStreamingQT");
				}else{
					ACUtils.addClassName(this.mediaController, "ACMediaStreamingVideo");
				}	
			}
		}
	},

	SPECIAL_KEYS: [ "ESC", "COMMAND", "CONTROL", "OPTION", "ALT", "SHIFT" ],
	KEYS: {
			KEY_TAB: 9,
			KEY_ESCAPE: 27,
			KEY_SPACE: 32,
			KEY_PAGE_UP: 33,
			KEY_PAGE_DOWN: 34,
			KEY_END: 35,
			KEY_HOME: 36,
			KEY_LEFT_ARROW: 37,
			KEY_UP_ARROW: 38,
			KEY_RIGHT_ARROW: 39,
			KEY_DOWN_ARROW: 40,
			KEY_0: 48,
			KEY_1: 49,
			KEY_2: 50,
			KEY_C: 67,
			KEY_F: 70,
			KEY_R: 82,
			KEY_T: 84
		},
	_keyHandlerTimeout: null,
	keyDownHandler: function (evt) {
		var oEvent = window.event ? window.event : evt;
		var keyCode = (oEvent.keyCode) ? oEvent.keyCode : ( (oEvent.which) ? oEvent.which : 0);

		// for (var i =0;i<this.SPECIAL_KEYS.length;i++) {  // Quick reset
		// 	showOrHide( this.SPECIAL_KEYS[i], false );
		// }

		// if (oEvent.shiftKey) { showOrHide( "SHIFT", true ); }
		// if (oEvent.ctrlKey) { showOrHide( "CONTROL", true ); }
		// if (oEvent.altKey) { showOrHide( "ALT", true ); }
		// if (oEvent.metaKey) { showOrHide( "COMMAND", true ); }
		// if (keyCode==this.KEYS.KEY_ESCAPE) { showOrHide( "ESC", true ); }

		window.clearTimeout(this._keyHandlerTimeout);
		
		var theAction = "";
		switch (true) {
			// Display size
			case ((keyCode == this.KEYS.KEY_0) && oEvent.ctrlKey):
				 ACUtils.stopEvent(evt);
				this.selectSizeFromMenu(this.sizesSmallControl);
				break;
			case ((keyCode == this.KEYS.KEY_1) && oEvent.ctrlKey):
				 ACUtils.stopEvent(evt);
				this.selectSizeFromMenu(this.sizesMediumControl);
				break;
			case ((keyCode == this.KEYS.KEY_2) && oEvent.ctrlKey):
				 ACUtils.stopEvent(evt);
				this.selectSizeFromMenu(this.sizesLargeControl);
				break;
			case ((keyCode == this.KEYS.KEY_3) && oEvent.ctrlKey):
				 ACUtils.stopEvent(evt);
				this.selectSizeFromMenu(this.sizesHDControl);
				break;
			case ((keyCode == this.KEYS.KEY_F) && (oEvent.ctrlKey || oEvent.metaKey)):
				 ACUtils.stopEvent(evt);
				this.toggleFullscreen();
				break;
			
			// Playback
			case (!Media.Detection.Firefox() && ((keyCode == this.KEYS.KEY_T) && oEvent.metaKey && oEvent.altKey)):
			case ((keyCode == this.KEYS.KEY_C) && oEvent.ctrlKey && oEvent.shiftKey):
				 ACUtils.stopEvent(evt);
				this.toggleCaptions();
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				//timeout = window.setTimeout(this.removeAlertDisplay.bindAC(this), 2500);
				break;
			case ((keyCode == this.KEYS.KEY_RIGHT_ARROW) && oEvent.metaKey):
				 ACUtils.stopEvent(evt);
				this.show();
				this.fastForward();
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case ((keyCode == this.KEYS.KEY_LEFT_ARROW) && oEvent.metaKey):
				 ACUtils.stopEvent(evt);
				this.show();
				this.fastBackward();
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case ((keyCode == this.KEYS.KEY_RIGHT_ARROW) && oEvent.altKey):  // Note: Windows should technically be (oEvent.ctrlKey && oEvent.altKey) here
				 ACUtils.stopEvent(evt);
				this.show();
				this.pause();
				var value = +(1);
				this.scrubber.setValue(value);
				
				if (!this._seeking) {
                    this._seeking = true;
                    this._send('beginSeeking');
                    this.resetRate();
                }
                this._send('setTime',+(value*this._send('duration')-0.1));
				
				window.setTimeout(function() {
                	this.trackProgress.style.width = +((this.scrubber.maximum*value)-4) + 'px';
					this.playhead.style.left = +((this.scrubber.maximum*value)-4) + 'px';
				}.bindAC(this), 50);
				
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case ((keyCode == this.KEYS.KEY_LEFT_ARROW) && oEvent.altKey):  // Note: Windows should technically be (oEvent.ctrlKey && oEvent.altKey) here
				 ACUtils.stopEvent(evt);
				this.show();
				this.pause();
				var value = +(0);
				this.scrubber.setValue(value);
				
				if (!this._seeking) {
                    this._seeking = true;
                    this._send('beginSeeking');
                    this.resetRate();
                }

                this._send('setTime',+(value*this._send('duration')+0.1));
				window.setTimeout(function() {
                	this.trackProgress.style.width = value + 'px';
					this.playhead.style.left = value + 'px';
				}.bindAC(this), 50);
				
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case ((keyCode == this.KEYS.KEY_RIGHT_ARROW)):
				break;
			case ((keyCode == this.KEYS.KEY_LEFT_ARROW)):
				break;
			case (keyCode == this.KEYS.KEY_SPACE):
				 ACUtils.stopEvent(evt);
				this.show();
				this.togglePlaying();
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
				
			// Volume
			case ((keyCode == this.KEYS.KEY_UP_ARROW) && oEvent.altKey):    // Note: Windows should technically be (oEvent.ctrlKey && oEvent.altKey) here
				 ACUtils.stopEvent(evt);
				this.show();
				this.fullVolume();
				this.volumeControlSetting = 1;
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case ((keyCode == this.KEYS.KEY_DOWN_ARROW) && oEvent.altKey):    // Note: Windows should technically be (oEvent.ctrlKey && oEvent.altKey) here
				 ACUtils.stopEvent(evt);
				this.show();
				this.muteVolume();
				this.volumeControlSetting = 0;
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case (keyCode == this.KEYS.KEY_UP_ARROW):
				 ACUtils.stopEvent(evt);
				this.show();
				var volume = this._send('volume'),
					volNumber = +(volume + .1),
					newVolume = (volNumber < 1) ? volNumber : 1;
				this._send('setVolume', newVolume);
				this.volumeScrubber.setValue(newVolume);
				this.volumeControlSetting = newVolume;
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
			case (keyCode == this.KEYS.KEY_DOWN_ARROW):
				 ACUtils.stopEvent(evt);
				this.show();
				var volume = this._send('volume'),
					volNumber = +(volume - .1),
					newVolume = (volNumber > 0) ? volNumber : 0;
				this._send('setVolume', newVolume);
				this.volumeScrubber.setValue(newVolume);
				this.volumeControlSetting = newVolume;
				this._keyHandlerTimeout = window.setTimeout(this.hide.bindAC(this), 2500);
				break;
				
			// reload
			case ((keyCode == this.KEYS.KEY_R) && oEvent.metaKey):
				 ACUtils.stopEvent(evt);
				window.location.reload(false);
				break;
			default:
				return true;
				break;

		}
		

	},

	createTrackScrubber: function() {
		// Playback Slider
		if(this.track) {
			var max = this.track.offsetWidth;
			if (!this.scrubber && this.element !== null) {
		        this.scrubber = new Control.Slider(this.playhead, this.track, {
		            alignX: -5,
					increment: 1,
					sliderValue: 0,
					minimum: 0,
					maximum: max,
		            onSlide: function (value) {
		                if (!this._seeking) {
		                    this._seeking = true;
		                    this._send('beginSeeking');
		                    this.resetRate();
		                }
		                this._send('setTime',value*this._send('duration'));
						var time = this._send('time');
						if (!(parseInt(time) == parseInt(value*this._send('duration')))){
							this._send('setTime',value*this._send('duration'));
						}
						
		                this.trackProgress.style.width = this.playhead.style.left;
		            }.bindAC(this),
		            onChange: function (value) {
		                if (this._seeking) {
		                    this._seeking = false;
		                    this._send('endSeeking');
		                }
		                this.trackProgress.style.width = this.playhead.style.left;
		            }.bindAC(this)
		        });
				this.scrubber.initialize();
			}
		}
	},
	createVolumeScrubber: function() {
		// Volume Slider
		if (!this.volumeScrubber && this.element !== null) {
			var max = this.volumeTrack.offsetWidth;
	        this.volumeScrubber = new Control.Slider(this.volumeThumb, this.volumeTrack, {
	            alignX: -3,
				increment: 1,
				sliderValue: 0,
				minimum: 0,
				maximum: max,
	            onSlide: function (value) {
	                this._volSeeking = true;
	                this._send('setVolume', value);
	                this.volumeProgress.style.width = this.volumeThumb.style.left;
	            }.bindAC(this),
	            onChange: function (value) {
	                this._volSeeking = false;
	                this.volumeProgress.style.width = this.volumeThumb.style.left;
	            }.bindAC(this)
	        });
			this.volumeScrubber.initialize();
			if (typeof this.volumeControlSetting == 'undefined') {
				this.volumeControlSetting = 1;
			}
			
			this.volumeScrubber.setValue(this.volumeControlSetting);
		}
	},
	
	getRoundRectForArcAndOpacity: function(arc, opacity) {
		if (Media.Detection.CSSBorderRadius() !== false) {
			return false;
		}
		
		if (typeof this.hasVMLNameSpaceDefined == 'undefined' || this.hasVMLNameSpaceDefined == false) {
			this.setVML();
		}

		var roundRect = document.createElement('v:roundrect'),
			fill = document.createElement('v:fill');
		
		roundRect.setAttribute('arcsize', arc);
		roundRect.setAttribute('fill', 'true');
		roundRect.setAttribute('fillcolor', '#000000');
		roundRect.setAttribute('stroked', 'false');
		roundRect.className = 'border-radius-box';
		
		fill.setAttribute('type', 'background');
		fill.setAttribute('opacity', opacity);
		fill.className = 'border-radius-fill';

		if (typeof roundRect == 'object') {
			roundRect.appendChild(fill);
			return roundRect;
		} else {
			return false;
		}
		
		//return (typeof roundRect == 'object') ? roundRect : false;
	},
	
	setVML: function() {
		if (!document.namespaces) {
			return;
		}
		
	    var i, countI, style, 
			head = document.getElementsByTagName('head')[0];
			
		this.hasVMLNameSpaceDefined = false;

		for (i=0, countI=document.namespaces.length; i<countI; i++) { 
			if (document.namespaces(i).name == 'v') {
				this.hasVMLNameSpaceDefined = true;
				break;
			}
		}
		//<xml:namespace ns="urn:schemas-microsoft-com:vml" prefix="v" />

		if (!this.hasVMLNameSpaceDefined) {
			document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');
	    }
		

	},
	
	setCaptionsAvailable: function() {
		this._send('setCaptionsAvailable', this.captionsUrl);
	},
	_setControlsAvailableForMenu: function(mainControl, controls) {
		mainControl.menuListHeight = 0;
		
		for (var i=0, control; control=controls[i]; i++) {
			this._enableControl(control);
			mainControl.menuListHeight += 25;
		}
		
		switch(mainControl) {
			case this.sizesControl:
				this.enableSizesControl();
				break;
			case this.downloadControl:
				this.enableDownloadControl();
				break;
			case this.shareControl:
				this.enableShareControl();
				break;
			default:
				break;
		}
	},
	setSizesAvailable: function() {
		this._setControlsAvailableForMenu(this.sizesControl, this._sizesMenuControls);
	},
	setDownloadAvailable: function() {
		this._setControlsAvailableForMenu(this.downloadControl, this._downloadMenuControls);
	},
	setShareAvailable: function() {
		this._setControlsAvailableForMenu(this.shareControl, this._shareMenuControls);
	},
	setFullscreenAvailable: function() {
		this._send('setFullscreenAvailable', this.fullscreenUrl);
	},
	
	enableBasicControls: function() {
	    if(this.playControl) {
			ACUtils.hideElement(this.playControl);
		}
		if(this.pauseControl) {
		    ACUtils.showElement(this.pauseControl);
		}
        
		this._enableControl(this.volumeMuteControl);
		this._enableControl(this.volumeFullControl);
        this._enableControl(this.volumeThumb);
        this._enableControl(this.playControl);
		this._enableControl(this.pauseControl);
        this._enableControl(this.playhead);
        this._enableControl(this.fastBackwardControl);
        this._enableControl(this.fastForwardControl);

		this.createTrackScrubber();
		
		this._enableControl(this.mediaTimeDisplay);
		this._enableControl(this.mediaDurationDisplay);
	},
	enableCaptionsControl: function() {
		if (this.captionsControl && !this.captionsControl.isEnabled && this.controllerType !== 'short-slim' && !this.captionsControl.isEnabled && !(typeof this.options != 'undefined' && this.options.captionsControlOff === true)) {

			ACUtils.addClassName(this.captionsControl, this.captionsControl.baseClassName + '-enabled');
			this.captionsControl.isEnabled = true;
			
			this.setSettingsControlsClass();
		}
	},
	_enableSettingsControlWithMenu: function(control, menu) {
		if (!control.isEnabled && this.controllerType !== 'short-slim' && !(typeof this.options != 'undefined' && this.options[control.name+'Off'] === true)) {
			this.settingsMenuList.appendChild(menu);
			control.menuListWidth = (ACUtils.Detector.isIEStrict()) ? 165 : this.settingsMenuList.offsetWidth;
			this.settingsMenuList.removeChild(menu);

			ACUtils.addClassName(control, control.baseClassName + '-enabled');
			control.isEnabled = true;
			
			this.setSettingsControlsClass();
		}
	},
	enableSizesControl: function() {
		this.sizesControl.name = 'sizesControl';
		this._enableSettingsControlWithMenu(this.sizesControl, this.sizesMenu);
	},
	enableDownloadControl: function() {
		this.downloadControl.name = 'downloadControl';
		this._enableSettingsControlWithMenu(this.downloadControl, this.downloadMenu);
	},
	enableShareControl: function() {
		this.shareControl.name = 'shareControl';
		this._enableSettingsControlWithMenu(this.shareControl, this.shareMenu);
	},
	enableFullscreenControl: function() {
		if (!this.fullscreenControl.isEnabled && this.controllerType !== 'short-slim') {
			ACUtils.addClassName(this.fullscreenControl, this.fullscreenControl.baseClassName + '-enabled');
			ACUtils.removeClassName(this.fullscreenControl, this.fullscreenControl.baseClassName + '-disabled');
			this.fullscreenControl.isEnabled = true;
			this.setSettingsControlsClass();
		}
	},
	disableFullscreenControlForCurrentSize: function() {
		if (this.fullscreenControl.isEnabled && this.controllerType !== 'short-slim') {
			ACUtils.addClassName(this.fullscreenControl, this.fullscreenControl.baseClassName + '-disabled');
			ACUtils.removeClassName(this.fullscreenControl, this.fullscreenControl.baseClassName + '-enabled');
			this.fullscreenControl.isEnabled = false;
		}
	},
    togglePlaying: function () {
        var isPlaying = this._send('playing');

        if (isPlaying) {
			this.pause();
		} else {
			this.resetRate();
			this.play();
        }
    },
	toggleCaptions: function() {
		if (!ACUtils.hasClassName(this.captionsControl, this.captionsControl.baseClassName + '-selected') && !this.resettingController && this.captionsControl.isEnabled === true) {
			this._selectControl(this.captionsControl);
			if (this._send('movieType') === 'Video' && this._send('enableCaptionsTextDisplay') === false) {
				this._enableControl(this.trackText);
			}
			this._send('enableCaptions');
			var captionsText = ac_media_language.captionsturnedon || 'Closed Captions On';

			// using while loops to remove children of elements so they aren't completely erased in IE6
			while (typeof this.alertDisplayContainer.firstChild != 'undefined' && this.alertDisplayContainer.firstChild != null) {
				this.alertDisplayContainer.removeChild(this.alertDisplayContainer.firstChild);
			}
			
			if (Media.Detection.CSSBorderRadius() === false) {
				var roundRect = this.getRoundRectForArcAndOpacity(0.19, 0.5);
			}
			
			if (typeof roundRect != 'undefined' && roundRect !== false) {
				var textSpan = document.createElement('span');
				
				this.captionsDisplayAlert.innerHTML = '';
				textSpan.appendChild(document.createTextNode(captionsText));
				roundRect.appendChild(textSpan);
				this.captionsDisplayAlert.appendChild(roundRect);
			} else {
				this.captionsDisplayAlert.innerHTML = captionsText;
			}

			this.alertDisplayContainer.appendChild(this.captionsDisplayAlert);
			ACUtils.addClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
			this.captionsControlSetting = true;
		} else if (this.captionsControl.isEnabled === true) {
			this._unselectControl(this.captionsControl);
			this._disableControl(this.trackText);
			this.captionsControlSetting = false;
			if (this.resettingController === true) {
				this._send('resetCaptions');
			} else { 
				this._send('disableCaptions');
				var captionsText = ac_media_language.captionsturnedoff || 'Closed Captions Off';

				while (typeof this.alertDisplayContainer.firstChild != 'undefined' && this.alertDisplayContainer.firstChild != null) {
					this.alertDisplayContainer.removeChild(this.alertDisplayContainer.firstChild);
				}

				var roundRect = this.getRoundRectForArcAndOpacity(0.19, 0.5);
				
				if (roundRect !== false) {
					var textSpan = document.createElement('span');
					
					this.captionsDisplayAlert.innerHTML = '';
					textSpan.appendChild(document.createTextNode(captionsText));
					roundRect.appendChild(textSpan);
					this.captionsDisplayAlert.appendChild(roundRect);
				} else {
					this.captionsDisplayAlert.innerHTML = captionsText;
				}

				this.alertDisplayContainer.appendChild(this.captionsDisplayAlert);
				ACUtils.addClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
			}
		}
	},
	_toggleMenuForControlAndMenuControls: function(menu, control, menuControls) {
		if (!ACUtils.hasClassName(control, control.baseClassName + '-selected') && !this.resettingMenus && !this.resettingController) {
			this._selectControl(control);
			this._selectSettingsMenuForMenu(menu);
			this.positionSettingsMenuForControl(control);
		} else {
			this._unselectControl(control);
			this._unselectMenu();
			if (this.resettingController === true) {
				for (var i=0, menuControl; menuControl = menuControls[i]; i++) {
					this._unselectControl(menuControl);
				}
			}
		}
	},
	toggleSizesMenu: function() {
		if (this.sizesControl && this.sizesControl.isEnabled === true && this.sizesMenu) {
			this._toggleMenuForControlAndMenuControls(this.sizesMenu, this.sizesControl, this._sizesMenuControls);
		}
	},
	toggleDownloadMenu: function() {
		if (this.downloadControl && this.downloadControl.isEnabled === true && this.downloadMenu) {
			this._toggleMenuForControlAndMenuControls(this.downloadMenu, this.downloadControl, this._downloadMenuControls);
		}
	},
	toggleShareMenu: function() {
		if (this.shareControl && this.shareControl.isEnabled === true && this.shareMenu) {
			this._toggleMenuForControlAndMenuControls(this.shareMenu, this.shareControl, this._shareMenuControls);
		}
	},
	toggleFullscreen: function() {
		if (!this.resettingController && this.fullscreenControl.isEnabled === true) {
			this._send('enableFullscreen');
		}
	},
	
	volumeControlSetting: 1,
	fullscreenControlSetting: false,
	sizesControlSetting: false,
	setSettingsControls: function() {
		if (typeof this.fullscreenControlSetting != 'undefined' && this.fullscreenControlSetting != false) {
			this._send('enableFullscreen');
		}
		if (typeof this.sizesControlSetting != 'undefined' && this.sizesControlSetting != false) {
			this.selectSizeFromMenu(this.sizesControlSetting);
		}
		if (typeof this.volumeControlSetting != 'undefined' && this.volumeControlSetting != 1) {
			this.volumeScrubber.setValue(this.volumeControlSetting);
			this._send('setVolume', this.volumeControlSetting);
		}
	},
	
	mouseoverSettingsControl: function(control) {
		this.settingsMenuTitle.innerHTML = ac_media_language.sizescontrol || control.menuTitle;
		if (typeof this.currentMenu != 'undefined' && this.currentMenu != false) {
			if (this.settingsMenuList.childNodes.length > 0) {
				this.settingsMenuList.removeChild(this.currentMenu);
			}
			this.currentMenu = false;
		}

		this.positionSettingsMenuForControl(control);
		ACUtils.addClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');
		ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName);
		this._unselectControl(this.sizesControl);
		this._unselectControl(this.downloadControl);
		this._unselectControl(this.shareControl);
	},
	mouseoutSettingsControl: function(evt, control) {
		var evt = evt || window.event,
			menuTop = ACUtils.cumulativeOffset(this.settingsMenu).top,
			menuLeft = ACUtils.cumulativeOffset(this.settingsMenu).left,
			menuWidth = this.settingsMenu.offsetWidth,
			menuHeight = this.settingsMenu.offsetHeight,
			mouseX, mouseY;

		if (evt) {
			mouseX = evt.pageX || (evt.clientX + (document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft);
			mouseY = evt.pageY || (evt.clientY + (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop);
			
			if (!(mouseX > menuLeft && mouseX < (menuLeft + menuWidth) && mouseY > menuTop && mouseY < (menuTop + menuHeight + 14))) {
				ACUtils.addClassName(this.settingsMenu, this.settingsMenu.baseClassName);
				ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');			
			}
		}
	},
	
	positionSettingsMenuForControl: function(control) {
		this.positionCarrotForControl(control);
		if (typeof this.settingsMenuRoundRect != 'undefined' && this.settingsMenuRoundRect !== false) {
			var items = this.settingsMenuList.getElementsByTagName('li'),
				width = control.menuListWidth,
				height = parseInt(((items.length > 0) ? 22 : 0) + this.settingsMenuTitle.offsetHeight + (items.length * 25)),
				arc = Math.min((7 / Math.min(height, width)), 1).toFixed(2),
				settingsMenuChildren = this.settingsMenu.childNodes,
				node = this.settingsMenu.node;

			try{
				while(typeof this.settingsMenuRoundRect != 'undefined' && this.settingsMenuRoundRect.firstChild) {
					this.settingsMenuRoundRect.removeChild(this.settingsMenuRoundRect.firstChild);
				}
			} catch(e) {}
			
			this.settingsMenu.removeChild(this.settingsMenuRoundRect);

			//alert('in positionSettingsMenuForControl')
			this.settingsMenuRoundRect = this.getRoundRectForArcAndOpacity(arc, 0.9);
			
			this.settingsMenu.insertBefore(this.settingsMenuRoundRect, this.settingsMenu.firstChild);
			
			if (width && height) {
				this.settingsMenuList.style.display = 'block';
				this.settingsMenu.style.width = width + 'px';
				this.settingsMenu.style.height = height + 'px';
			} else {
				this.settingsMenu.style.display = 'none';
			}
		
		} else if (typeof control.menuListWidth != 'undefined') {
			this.settingsMenuList.style.width = control.menuListWidth + 'px';
		}
		
		var carrotTop = parseInt(this.settingsMenuCarrot.style.top),
			carrotLeft = parseInt(this.settingsMenuCarrot.style.left),
			menuHeight = this.settingsMenu.offsetHeight,
			menuWidth = this.settingsMenu.offsetWidth,
			mediaControllerLeft = ACUtils.cumulativeOffset(this.mediaController).left,
			mediaControllerWidth = this.mediaController.offsetWidth,
			carrotHeight = this.settingsMenuCarrot.offsetHeight,
			carrotWidth = this.settingsMenuCarrot.offsetWidth,
			menuTop = carrotTop - menuHeight + carrotHeight,
			menuLeft = (mediaControllerLeft + mediaControllerWidth) - menuWidth,
			controlLeft = ACUtils.cumulativeOffset(control).left,
			controlCenter = controlLeft + (control.offsetWidth / 2),
			newMenuLeft, newMenuBottom, newCarrotTop, newCarrotLeft, menuListWidth;
			
		switch (this.controllerType) {
			case 'slim':
			case 'short-slim':
				var slimMenuLeft = (mediaControllerLeft + mediaControllerWidth + 20) - menuWidth;
				this.settingsMenu.style.top = (carrotTop + carrotHeight) + 'px';
				this.settingsMenu.style.left = ((slimMenuLeft < carrotLeft) ? slimMenuLeft : carrotLeft) + 'px';
				break;
			default:
				this.settingsMenu.style.top = menuTop + 'px';
				this.settingsMenu.style.left = ((menuLeft - 7 < carrotLeft) ? (menuLeft - 7) : carrotLeft) + 'px';
				break;
		}		
		// if (this.controllerType === 'slim' || this.controllerType === 'short-slim') {
		// 	var slimMenuLeft = (mediaControllerLeft + mediaControllerWidth + 20) - menuWidth;
		// 	this.settingsMenu.style.top = (carrotTop + carrotHeight) + 'px';
		// 	this.settingsMenu.style.left = ((slimMenuLeft < carrotLeft) ? slimMenuLeft : carrotLeft) + 'px';
		// } else {
		// 	this.settingsMenu.style.top = menuTop + 'px';
		// 	this.settingsMenu.style.left = ((menuLeft - 7 < carrotLeft) ? (menuLeft - 7) : carrotLeft) + 'px';
		// 	//this.settingsMenu.style.left = parseInt(controlCenter - (menuWidth / 2)) + 'px';
		// }
				
		newMenuLeft = parseInt(this.settingsMenu.style.left);
		
		newCarrotTop = menuHeight;
		newCarrotLeft = parseInt(this.settingsMenuCarrot.style.left) - newMenuLeft;
		
		switch (this.controllerType) {
			case 'slim':
			case 'short-slim':
				this.settingsMenuCarrot.style.top = (0 - (carrotHeight + 6)) + 'px';
				break;
			default:
				this.settingsMenuCarrot.style.top = ((ACUtils.Detector.isIEStrict()) ? ((menuHeight - carrotHeight) + 8) : (menuHeight - carrotHeight)) + 'px';
				break;
		}
		// if (this.controllerType === 'slim' || this.controllerType === 'short-slim') {
		// 	this.settingsMenuCarrot.style.top = (0 - (carrotHeight + 6)) + 'px';
		// } else {
		// 	this.settingsMenuCarrot.style.top = (ACUtils.Detector.isIEStrict()) ? ((menuHeight - carrotHeight) + 8) + 'px' : (menuHeight - carrotHeight) + 'px';
		// }
		this.settingsMenuCarrot.style.left = (newCarrotLeft - (carrotWidth / 2)) + 'px';
		
		this.settingsMenu.style.overflow = 'visible';

	},
	positionCarrotForControl: function(control) {
		
		var mediaControllerTop = ACUtils.cumulativeOffset(this.mediaController).top,
			mediaControllerWidth = this.mediaController.offsetWidth,
			mediaControllerHeight = this.mediaController.offsetHeight,
			controlLeft = ACUtils.cumulativeOffset(control).left,
			controlWidth = control.offsetWidth,
			carrotWidth = this.settingsMenuCarrot.offsetWidth,
			carrotHeight = this.settingsMenuCarrot.offsetHeight,
			carrotTop = mediaControllerTop - carrotHeight,
			carrotLeft = controlLeft + ((controlWidth - carrotWidth) / 2);
			
		this.settingsMenu.style.overflow = 'hidden';
		switch (this.controllerType) {
			case 'slim':
			case 'short-slim':
				ACUtils.addClassName(this.settingsMenuCarrot, 'slim-menu-carrot');
				this.settingsMenuCarrot.style.top = (mediaControllerTop + mediaControllerHeight) + 'px';
				break;
			default:
				this.settingsMenuCarrot.style.top = carrotTop + 'px';
				break;
		}
		// if (this.controllerType === 'slim' || this.controllerType === 'short-slim') {
		// 	ACUtils.addClassName(this.settingsMenuCarrot, 'slim-menu-carrot');
		// 	this.settingsMenuCarrot.style.top = (mediaControllerTop + mediaControllerHeight) + 'px';
		// } else {
		// 	this.settingsMenuCarrot.style.top = carrotTop + 'px';
		// }
		this.settingsMenuCarrot.style.left = carrotLeft + 'px';
	},
	
	_selectSettingsMenuForMenu: function(menu) {
		var menuTitle = menu.menuTitle,
			menuName = menu.menuName;

		this.settingsMenuTitle.innerHTML = menuTitle;

		if (typeof this.currentMenu != 'undefined' && this.currentMenu != false) {
			if (this.settingsMenuList.childNodes > 0) {
				this.settingsMenuList.removeChild(this.currentMenu);
			}
		}

		this.settingsMenuList.appendChild(menu);
		this.currentMenu = menu;
	},
	_unselectMenu: function() {
		ACUtils.addClassName(this.settingsMenu, this.settingsMenu.baseClassName);
		ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-selected');
		ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');
	},
	_selectControl: function(control) {
		ACUtils.addClassName(control, control.baseClassName+'-selected');
		if (control === this.sizesControl || control === this.downloadControl || control === this.shareControl) {
			ACUtils.addClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-selected');
			ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName);
			ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');
			this._currentSettingsControl = control;
		}
	},
	_unselectControl: function(control) {
		if(control) {
			ACUtils.removeClassName(control, control.baseClassName+'-selected');
		}
	},
	_enableControl: function(control) {
		if(control) {
	        ACUtils.addClassName(control, control.baseClassName+'-enabled');
		}
	},
	_disableControl: function(control) {
		if(control) {
        	ACUtils.removeClassName(control, control.baseClassName+'-enabled');
 		}
	},
	
	reset: function () {
		if (typeof this.scrubber != 'undefined') {
			this.playhead.style.left = '0px';
			this.trackProgress.style.width = this.playhead.style.left;
		
			this.show();
		
			if(this.playControl) {
		        ACUtils.showElement(this.playControl);
			}
			if(this.pauseControl) {
			    ACUtils.hideElement(this.pauseControl);
			}
        
			this._disableControl(this.volumeMuteControl);
			this._disableControl(this.volumeFullControl);
	        this._disableControl(this.volumeThumb);
	        this._disableControl(this.playControl);
			this._disableControl(this.pauseControl);
	        this._disableControl(this.playhead);
	        this._disableControl(this.fastBackwardControl);
	        this._disableControl(this.fastForwardControl);
        
			this.removeAdvancedPlayDisplay();
		}
	},
	resetSettingsControls: function() {
		this.resetSettingsMenus();
	},
	resetSettingsMenus: function() {
		this.resettingMenus = true;
		if(this.alertDisplayContainer) {
			ACUtils.removeClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
		}
		if(this.settingsMenu) {
			ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');
			ACUtils.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-selected');
		}
		this.toggleSizesMenu();
		this.toggleDownloadMenu();
		this.toggleShareMenu();
		this.resettingMenus = false;
	},
	resetRate: function() {
		if (this._send('rate') !== 1) {		
			this._send('setRate', 1);
		}
		this.removeAdvancedPlayDisplay();		
	},
	
	removeAdvancedPlayDisplay: function() {
		this.removeAlertDisplay();
		ACUtils.removeClassName(this.fastBackwardControl, 'fastBackward-active');
		ACUtils.removeClassName(this.fastForwardControl, 'fastForward-active');
	},
	removeAlertDisplay: function () {
		if(this.fastBackwardControl) {
			this.setRateDisplay(this.fastBackwardControl, null);
		}
		if(this.fastForwardControl) {
			this.setRateDisplay(this.fastForwardControl, null);
		}
		if(this.alertDisplayContainer) {
			//alert(this.alertDisplayContainer.baseClassName + '-active')
			ACUtils.removeClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');	
		}
	},
	
	setSettingsControlsClass: function() {
		var settingsControlsClass = this.settingsControls.baseClassName,
			buttonCount = 0;
		if (typeof this.captionsControl.isEnabled != 'undefined' && this.captionsControl.isEnabled === true) {
			settingsControlsClass += '-captions';
			buttonCount++;
		}
		if (typeof this.sizesControl.isEnabled != 'undefined' && this.sizesControl.isEnabled === true) {
			settingsControlsClass += '-sizes';
			buttonCount++;
		}		
		if (typeof this.downloadControl.isEnabled != 'undefined' && this.downloadControl.isEnabled === true) {
			settingsControlsClass += '-download';
			buttonCount++;
		}
		if (typeof this.shareControl.isEnabled != 'undefined' && this.shareControl.isEnabled === true) {
			settingsControlsClass += '-share';
			buttonCount++;
		}
		if (typeof this.fullscreenControl.isEnabled != 'undefined' && this.fullscreenControl.isEnabled === true) {
			settingsControlsClass += '-fullscreen';
			buttonCount++;
		}
		
		this.settingsControls.className = '';
		ACUtils.addClassName(this.settingsControls, this.settingsControls.baseClassName);
		ACUtils.addClassName(this.settingsControls, settingsControlsClass);
		
		this.setTrackContainerWidth();
	},
	
	setTrackContainerWidth: function() {
		if (this.controllerType === 'regular' || !this.settingsControls || !this.trackContainer ) {
			return;
		}
		// if (this.controllerType === 'slim' || this.controllerType === 'short-slim') {

			var buttonWidth = (this.settingsControls.offsetWidth > 0) ? parseInt(this.settingsControls.offsetWidth + 10) : 0,
				controllerLeft = this.mediaController.offsetLeft,
				controllerWidth = this.mediaController.offsetWidth,
				controllerRight = parseInt(controllerLeft + controllerWidth);
				newTrackWidth = parseInt(((controllerRight - this.trackContainer.offsetLeft) <= 600) ? (controllerRight - this.trackContainer.offsetLeft) : 600),
				newTrackContainerWidth = parseInt(newTrackWidth - (buttonWidth + 10));
			
			// this is to make sure that the track doesn't go past the right edge for the slim controller
			if (this.controllerType === 'slim') {
				var trackRight = parseInt(this.trackContainer.offsetLeft + newTrackContainerWidth + 20);
				if (controllerRight < trackRight) {
					newTrackContainerWidth = parseInt(newTrackContainerWidth - (trackRight - controllerRight));
				}
			}
			
			this.trackContainer.style.width =  newTrackContainerWidth + 'px';
			this.track.parentNode.style.width = (this.controllerType === 'short-slim') ? newTrackContainerWidth + 'px' : parseInt(newTrackContainerWidth - 80) + 'px';
			this.scrubberMax = (this.controllerType === 'short-slim') ? newTrackContainerWidth : parseInt(newTrackContainerWidth - 80);
			this.volumeScrubber = null;
			this.createVolumeScrubber();
			this.scrubber = null;
			this.createTrackScrubber();
		// }
	},
	
    _send: function (msg, params) {
        if (this.delegate && msg in this.delegate) {
            params = [].concat(params);
            return this.delegate[msg].apply(this.delegate, params);
        }
    },
    
    show: function () {
        Media.ControlsWidget.show(this);
    },
    
    hide: function () {
        if (this._seeking || this._volSeeking) {
            return;
		}
		
        Media.ControlsWidget.hide(this);

		this.removeAlertDisplay();
    },

	play: function() {
		this.resetRate();

		if (this._send('playing') === false) {
			if(ACUtils.Detector.isiPad()) {
				this._send('forcePlay');
			}
			else {
				this._send('play');
			}
		}
		
		if(this.playControl) {
			ACUtils.hideElement(this.playControl);
		}
		if(this.pauseControl) {
		    ACUtils.showElement(this.pauseControl);
		}
	},
	
	pause: function() {
		this.resetRate();
		
		if (this._send('playing') === true) {
			if(ACUtils.Detector.isiPad()) {
				this._send('forcePause');
			}
			else {
				this._send('pause');
			}
		}
		
		if(this.pauseControl) {
			ACUtils.hideElement(this.pauseControl);
		}
		if(this.playControl) {
		    ACUtils.showElement(this.playControl);
		}
	},

    fastBackward: function () {
		if(isStreaming === true && isLiveStreaming === false){
			this._send('seekToTime', 'fb');
			return;
		}
        var currentRate = this._send('rate'),
			speedText = '';

		if (this._send('playing') === false) {
			this._send('play');
		} else {
			if(this.pauseControl) {
				ACUtils.hideElement(this.pauseControl);
			}
			if(this.playControl) {
	    	    ACUtils.showElement(this.playControl);
			}
		}
				
        switch(currentRate) {
            case -2:
                this._send('setRate', -4);
				speedText = '4x';
				this.setRateDisplay(this.speedDisplayAlert, 'four-times-speed-display');
				this.setRateDisplay(this.fastBackwardControl, 'four-times-fast-backward');
                break;
            case -4:
                this._send('setRate', -8);
				speedText = '8x';
				this.setRateDisplay(this.speedDisplayAlert, 'eight-times-speed-display');
				this.setRateDisplay(this.fastBackwardControl, 'eight-times-fast-backward');
                break;
            default:
                this._send('setRate', -2);
				speedText = '2x';
				this.setRateDisplay(this.speedDisplayAlert, 'two-times-speed-display');
				this.setRateDisplay(this.fastBackwardControl, 'two-times-fast-backward');			
                break;
        }
		
		this.setRateDisplay(this.fastForwardControl, null);

		while (typeof this.alertDisplayContainer.firstChild != 'undefined' && this.alertDisplayContainer.firstChild != null) {
			this.alertDisplayContainer.removeChild(this.alertDisplayContainer.firstChild);
		}
		
		this.speedDisplayAlert.innerHTML = '';
		//alert('in fastBackward');
		var roundRect = this.getRoundRectForArcAndOpacity(0.19, 0.5);
		
		if (roundRect !== false) {
			var textSpan = document.createElement('span');
			
			textSpan.appendChild(document.createTextNode(speedText));
			roundRect.appendChild(textSpan);
			this.speedDisplayAlert.appendChild(roundRect);
		} else {
			this.speedDisplayAlert.appendChild(document.createTextNode(speedText));
		}
		
		this.alertDisplayContainer.appendChild(this.speedDisplayAlert);
		ACUtils.addClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
		ACUtils.removeClassName(this.fastForwardControl, 'fastForward-active');
		ACUtils.addClassName(this.fastBackwardControl, 'fastBackward-active');
    },

    fastForward: function () {
        var currentRate = this._send('rate'),
			speedText = '';

		if (this._send('playing') === false) {
			this._send('play');
		} else {
			if(this.pauseControl) {
				ACUtils.hideElement(this.pauseControl);
			}
			if(this.playControl) {
	    	    ACUtils.showElement(this.playControl);
			}
		}
		
        switch(currentRate) {
            case 2:
                this._send('setRate', 4);
				speedText = '4x';
				this.setRateDisplay(this.speedDisplayAlert, 'four-times-speed-display');
				this.setRateDisplay(this.fastForwardControl, 'four-times-fast-forward');
                break;
            case 4:
                this._send('setRate', 8);
				speedText = '8x';
				this.setRateDisplay(this.speedDisplayAlert, 'eight-times-speed-display');
				this.setRateDisplay(this.fastForwardControl, 'eight-times-fast-forward');
                break;
            default:
                this._send('setRate', 2);
				speedText = '2x';
				this.setRateDisplay(this.speedDisplayAlert, 'two-times-speed-display');
				this.setRateDisplay(this.fastForwardControl, 'two-times-fast-forward');
                break;
        }
		
		this.setRateDisplay(this.fastBackwardControl, null);

		while (typeof this.alertDisplayContainer.firstChild != 'undefined' && this.alertDisplayContainer.firstChild != null) {
			this.alertDisplayContainer.removeChild(this.alertDisplayContainer.firstChild);
		}
		
		this.speedDisplayAlert.innerHTML = '';
		//alert('in fastForward');
		var roundRect = this.getRoundRectForArcAndOpacity(0.19, 0.5);
		
		if (roundRect !== false) {
			var textSpan = document.createElement('span');
			
			textSpan.appendChild(document.createTextNode(speedText));
			roundRect.appendChild(textSpan);
			this.speedDisplayAlert.appendChild(roundRect);
		} else {
			this.speedDisplayAlert.appendChild(document.createTextNode(speedText));
		}
		
		this.alertDisplayContainer.appendChild(this.speedDisplayAlert);
		ACUtils.addClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
		ACUtils.removeClassName(this.fastBackwardControl, 'fastBackward-active');
		ACUtils.addClassName(this.fastForwardControl, 'fastForward-active');
    },
    
	setRateDisplay: function(control, rate) {
		if(!control) return;
		switch(true) {
			case (typeof control.currentRateDisplay != 'undefined' && control.currentRateDisplay !== rate):
				ACUtils.removeClassName(control, control.currentRateDisplay);
				break;
			default:
				break;
		}
		
		switch(rate) {
			case null:
				break;
			default:
				ACUtils.addClassName(control, rate);
				break;
		}
		
		control.currentRateDisplay = rate;
	},
	
	muteVolume: function() {
		this._send('setMuted', true);
		this.volumeScrubber.setValue(0);
	},
	
	fullVolume: function() {
		this._send('setMuted', false);
		this._send('setVolume', 1);
		this.volumeScrubber.setValue(1);
	},
	
    updatePercentLoaded: function (newPercent) {
        if (typeof this.controlLoadedProgress !== 'undefined' && newPercent) {
			this.controlLoadedProgress.style.width = newPercent*100 + '%';
		}
		if (newPercent === 1) {//Control debug	
			ACUtils.addClassName(this.trackEndCap, 'track-right-cap-loaded');
			ACUtils.removeClassName(this.trackEndCap, 'track-right-cap');
		}
    },
    
    updateTime: function (newTime) {
        var duration = this._send('duration'),
			remainingTime = (duration - newTime);

		if ((newTime < 1 || remainingTime < 1) && this._send('rate') !== 1) {
			this.resetRate();
			this._send('pause');
			ACUtils.removeClassName(this.fastBackwardControl, 'fastBackward-active');
			ACUtils.removeClassName(this.fastForwardControl, 'fastForward-active');
		}

		try {
        	if(this.scrubber)this.scrubber.setValue((newTime / duration) || 0);
		} catch(e) {}
        this.updateElapsedTime(newTime);
        this.updateRemainingTime(remainingTime);
    },
    
    _setTimeForReadout: function(time, minutes, seconds) {
		if(minutes && seconds) {
	        var min = parseInt(time / 60, 10),
	            sec = parseInt(time % 60, 10);
	        if (min < 10) {
	            min = '0'+min;
	        }
	        if (sec < 10) {
	            sec = '0'+sec;
	        }

	        minutes.innerHTML = min;
	        seconds.innerHTML = sec;
		}
    },
    
    updateElapsedTime: function (newTime) {
        var minutes = this.minutesPlayed,
            seconds = this.secondsPlayed;
            
        this._setTimeForReadout(newTime, minutes, seconds);
    },
    
    updateRemainingTime: function (newTime) {
        var minutes = this.minutesRemaining,
            seconds = this.secondsRemaining;
            
        this._setTimeForReadout(newTime, minutes, seconds);
    }
};

/* adding a method to check that the URL exists using http HEAD so that the file doesn't load */
ACUtilsAjax.checkURL = function(url, callback) {
	var transport = ACUtilsAjax.getTransport();
	transport.onreadystatechange = function() {
		if (this.readyState === 4 && this.status === 200) {
			callback();
		}
	};
	
	transport.open('HEAD', url, true);
	transport.send(null);
};

ACUtilsAjax.AjaxRequest.prototype._overrideMimeType = null; 
ACUtilsAjax.AjaxRequest.prototype.overrideMimeType = function(overrideMimeTypeValue) { 
	this._overrideMimeType = overrideMimeTypeValue; 
	if (this.transport.overrideMimeType) { 
		this.transport.overrideMimeType(overrideMimeTypeValue); 
	} 
}; 

ACUtilsAjax.AjaxResponse.prototype.responseXMLValue = function() { 
	if (ACUtils.Detector.isIEStrict()) { 
		var xmlDocument = this.transport.responseXML.documentElement; 
		if (!xmlDocument && this.request._doesOverrideXMLMimeType()) { 
			this.transport.responseXML.loadXML(this.transport.responseText); 
		} 
	} 
	return this.transport.responseXML; 
};

Media.ControlsWidget.SharePlugin = function(){}
Media.ControlsWidget.SharePlugin.prototype.name = function() {
	return this._name;
}
Media.ControlsWidget.SharePlugin.prototype.actionName = function() {
	return "share";
}
Media.ControlsWidget.SharePlugin.prototype.pluginType = function() {
	return "Share";
}

