// CoreKit - Developed by Andreas Gotfredsen for generic use for client WebSites ...


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

var Core = {
	MIN_QUICKTIME_VERSION: '7.4',
	_isHTML5VideoAvailable: function ()
    {
        return Core.Detect.HTML5();
    },
    
    _isQuickTimeAvailable: function ()
    {
       return Core.Detect.QuickTime(Core.MIN_QUICKTIME_VERSION);
    },
    _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);
    }

	
};



Core.Detect = {
    HTML5: function () {
        if (!('HTMLMediaElement' in window)){
            return false;
        }
        
        var video = document.createElement('video');
        return (video.canPlayType && video.canPlayType('video/mp4')!=='');
    },
    QuickTime: function(version) {
        return this.isValidQTAvailable(version);
    },
    isValidQTAvailable: function(required)
    {
        return this.isQTInstalled() && this.isQTCompatible(required);
    },
    _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);
    },
    isSnowLeopard: function()
    {
        var agent = this.getAgent();
        return !!agent.match(/mac os x 10_6/i);
    },
    SnowLeopard: function()
    {
        return this.isSnowLeopard();
    },
    isMobile: function(b){
    	var a=this.getAgent();
    	return this.isWebKit(a)&&(a.match(/Mobile/i)&&!this.isiPad(a));
	},
	Mobile: function () {
        return (this.isiPad()) ? true : this.isMobile();
    },
    isChrome: function(){
    	if(this._isChrome===undefined){
    		var a=this.getAgent();
			this._isChrome=!!a.match(/Chrome/i);
			this.isChrome=function()
			{
				return this._isChrome;
			}
		}
		return this._isChrome;
	},
    Chrome: function () {
        return this.isChrome();
    },
    iPad: function () {
		var a = this.getAgent();
       	return !!(this.isWebKit(a)&&a.match(/ipad/i));
    },
    isiPad:function(){
    	return this.iPad();
    },
    getAgent:function(){
    	return navigator.userAgent.toLowerCase();
    },
    isWebKit:function(){
    	if(this._isWebKit===undefined){
    		var a = this.getAgent();
			this._isWebKit=!!a.match(/AppleWebKit/i);
			this.isWebKit=function(){
				return this._isWebKit;
			}
		}
		return this._isWebKit;
	},
	Firefox:function(){
		var a=this.getAgent();
		return !!a.match(/firefox/i);
	},
	Opera:function(){
		var a=this.getAgent();
		return !!a.match(/opera/i);
	},
	isOpera: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/opera/i);
    },
	IE: function () {
        return this.isIEStrict();
    },
	isIE: function(userAgent)
    {
        var agent = userAgent || this.getAgent();
        return !!agent.match(/msie/i);
    },
	isIEStrict:function(){
		var a=this.getAgent();
		return a.match(/msie/i)&&!this.isOpera(a);
	},
	isWin: function()
    {
        var agent = this.getAgent();
        return !!agent.match(/win/i);
    },
    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;
        }
    },
	_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;
	}
};



var CoreLanguage = {
    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(core_language === false){
        new Ajax.Request('/global/scripts/languages/'+langFile, {
            method:'get',
            requestHeaders: {Accept: 'application/json'},
            onSuccess: function(transport){
                core_language = new Function("return "+transport.responseText)();
            }.bind(this),
            onComplete: function(){
                languageJsonComplete = true;
                if(delegate && typeof delegate.translationDidLoad === "function") {
                    delegate.translationDidLoad();
                }
            }.bind(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;
    }
};


Core.showElement = function(elm){
	$(elm).show();
}
Core.hideElement = function(elm){
	$(elm).hide();
}

Core.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;
                }
           
            if (!Core.Detect.isiPad() && existingVideo != false) {
                                
                       
                if (existingVideoSrc == videoSrc) {
                    
                    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" && ( ((Core.Detect.isWebKit() ||  Core.Detect.isMobile() || Core.Detect.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);

                Element.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);

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

                     video.style.display = 'none';
                     
                     video = null;
                 });
              
               
                if(Core.Detect.isiPad() || Core.Detect.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'):
                            Element.addClassName(video, options[property]);
                        break;
                        case('controller'):
                            if (options[property] || (Core.Detect.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 (Core._isQuickTimeAvailable()) {
                return Core.Spec.QuickTime.create(container, src, options);
            }
            
            if (Core._isSBVDPAvailable()) {
                return Core.Spec.SBVDP.create(container, src, options);
            }
            
            if (Core._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 (!Core.Detect.IE() && !Core.Detect.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.

                // Temporary fix for FireFox 4's video caching bug.
                // We need to append a unique string to the end of the src so that the browser
                // does not try to pull the video from the cache.
                // https://bugzilla.mozilla.org/show_bug.cgi?id=644253
                if(!!navigator.userAgent.toLowerCase().match('firefox/4')){
                    src += '&' + new Date().getTime();
                }

                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.
            Element.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'):
                            Element.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 (!Core.Detect.Firefox() && !Core.Detect.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 (Core.Detect.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 (!Core.Detect.Firefox() && !Core.Detect.Opera()) {
                
                    this._addParameter(object, 'wmode', 'transparent');
                }
            }
          
            object.setAttribute('id', name);
            
            if (!Core.Detect.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(Core.Detect.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);
    };
    
}


Core.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;
            
            Event.observe(video, e, function (event) {
                if (auxFunction) {
                    auxFunction.apply(this);
                }
                this.messageDelegate(functionName);
            }.bind(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);
                    }
                }.bind(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);
            }
        }
    };
};


Core.VideoPlayer = Class.create({
	VERSION: '0.1 Beta',
    MIN_QUICKTIME_VERSION: '7.4',
    container: null,
    src :null,
    options:null,
    ipad : Core.Detect.isiPad(),
    replay : false,
	initialize: function (container, src, options){
	
		var shouldBuildMediaSpecVideo = true, 
            shouldBuildMediaSpecQuickTime = true,
            shouldBuildMediaSpecSBVDP = true,
            ipad = Core.Detect.isiPad();
            
		this.container = container;
		this.src = src;
		this.options = options;
		
		// Do some browser-specific setup
        switch(true) {
            case Core.Detect.Firefox():
                Element.addClassName(container, 'mozilla');
                break;
            case Core.Detect.Opera():
                Element.addClassName(container, 'opera');
                break;
            case Core.Detect.IE():
                Core._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 = (Core.Detect.Mobile()) ? Core.Detect.iPhoneOSVersion() : null;

        if (iPhoneOSVersion && iPhoneOSVersion[0] < 3) {
            shouldBuildMediaSpecVideo = false;
            shouldBuildMediaSpecQuickTime = true;
        }

		
		switch(true) {
        
            case (ipad || (shouldBuildMediaSpecVideo && Core._isHTML5VideoAvailable() && !Core.Detect.Firefox() && !Core.Detect.Mobile() && !Core.Detect.Chrome() && !Core.Detect.Opera()) &&  !(Core.Detect.getAgent().match(/msie 9/i)) ||(iPhoneOSVersion && iPhoneOSVersion[0] >=3)):
                // Create <video> player
                
                if(options.audio == true && typeof Core.Spec.Audio !== undefined) {
                    return this.build(Core.Spec.Audio);
                }
                return this.build(Core.Spec.Video);
                break;
            case (shouldBuildMediaSpecQuickTime && Core._isQuickTimeAvailable(Core.MIN_QUICKTIME_VERSION)):
            case (iPhoneOSVersion && iPhoneOSVersion[0] < 3):
                // Create QuickTime player
            
                return this.build(Core.Spec.QuickTime);
                break;
            
            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;
        }
	},
	getController: function(){
		return this.controller;
	},
	build: function(Spec){
		this.controller = new Core.VideoController(this.container);
		
		this.element = Spec.create(this.container, this.src, this.options);
		this.innerface = Core.VideoInterface(this.element, this.controller);
		
		 if(this.ipad && (this.options.autoplay === true || this.options.autostart === true)) {
                this.element.forcePlay(); 
            }
            
            
        // 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;
                    
                this.innerface.registerEvent(event, name, fn);
            }
		
		if (Spec.pollForChanges) {
			this.innerface.pollForChanges(Spec.pollForChanges);
		}
                
		if (Spec.interfaceMethods) {
			this.innerface.override(Spec.interfaceMethods);
		}
            
		this.innerface.setup();
		
		this.controller.setVideo(this.innerface);
		this.controller.setVideoSrc(this.src);
		
		
		/*check if metadata has already loaded if so don't wait*/
            if((!Core.Detect.iPad()) && (!Core.Detect.Mobile())){
                if(this.element.tagName =="VIDEO"){
                    if(this.replay === false){
                    if(isNaN(this.element.duration)){
                        videoReceivedMetadata = false;
                    }else{
                    videoReceivedMetadata = true;
                    }
                } 
                }else {
                    videoReceivedMetadata = false;
                }
                this.controller.configureSettingsControls(this.src);
            }
            
            
             this.controller.container = this.container;
            this.controller.movieLoadingPanelClass = 'movie-loading-panel';
            if (typeof this.options.width != 'undefined' && typeof this.options.height != 'undefined') {
                if (typeof this.controller.currentWidth == 'undefined' && typeof this.controller.currentHeight == 'undefined') {
                    this.controller.currentWidth = this.options.width;
                    this.controller.currentHeight = this.options.height;
                }
                this.controller.movieLoadingPanelClass = 'movie-loading-panel_' + this.options.width + 'x' + this.options.height;
            }
            Element.addClassName(this.container, this.controller.movieLoadingPanelClass);
            if(Core.Detect.isWin() && Core.Detect.Chrome()){
                Element.addClassName(this.container, "winchrome");
            }

	
	}
});


Core.VideoController = Class.create({
	
	delegate:null,
	video:null,
	videoSrc:null,
	controlPanel:null,
	timeout:null,
	sizeTimeout:null,
	duration:null,
	seeking:false,
	wasPlayingBeforeSeek:null,
	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,
    expectingMovieJson: true,
    _currentPosition : false,
    _currentSrc: null,
    _currentVolume: null,
	initialize: function (container){
		this.container = container;
	},
	containerMouseMove: function(e) {
        if (!this.controlPanel || this.currentlyChangingSize || !this.hasBegunPlaying) {
            return;
        }
            
        this.controlPanel.show();
        window.clearTimeout(this.timeout);
        
        var controls = this.controlPanel.element;
            mouseElement = e.target || e.srcElement;        
        
        if (mouseElement == controls) {
            timeout = window.setTimeout(function(){
                if (controlPanel && typeof controlPanel != 'undefined') {
                    controlPanel.hide();
                }
            }, 2500);
        }
    },
    containerMouseOut: function(e) {
        if (!this.controlPanel || !this.hasBegunPlaying) {
            return;
        }
        
        window.clearTimeout(timeout);
        this.timeout = window.setTimeout(function(){
            if (this.controlPanel) {
                this.controlPanel.hide();
            }
        },50);
    },
    containerMouseOver: function(e) {
        if (!this.controlPanel || !this.hasBegunPlaying) {
            return;
        }
            
        window.clearTimeout(this.timeout);
        this.timeout = window.setTimeout(function(){
            if (this.controlPanel) {
                this.controlPanel.hide();
            }
        },50);
    },
    containerMouseOver: function(e) {
        if (!this.controlPanel || this.currentlyChangingSize || !this.hasBegunPlaying) {
            return;
        }
            
        window.clearTimeout(this.timeout);
        this.controlPanel.show();
    },
    menuMouseOver: function(e) {
        if (!this.controlPanel) {
            return;
        }
            
        window.clearTimeout(this.timeout);
        this.controlPanel.show();
    },
	translationDidLoad: function() {
		languageJsonComplete = true;
		
		this.processControlPanel();
		// this._setControlPanel();
	},
	moviePath: function() {
            var url,
                path = '';

            if (typeof this.videoSrc != 'undefined' && this.videoSrc.length > 0) {
                url = this.videoSrc.substring(0, this.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;
	},
	configureSettingsControls: function(videoSrc) {
			
			//console.log(videoSrc);
			/* console.log("---- configure settings controls-----"); */
            if (existingVideo != false && this.controlPanelConfigurationsSet === true) return;
            
            var url, language,
                langAttr = document.body.parentNode.getAttribute('lang');
                
                this.language = language = CoreLanguage.getLangFromAttr(langAttr);
                
                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';
                    
                } else {
                    return;
                }
        //console.log("hello");
            	//console.log(url);
                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,"");
                    }
                }
        
                            
                // JSON request for configuration file
                new Ajax.Request(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);
                    }.bind(this),
                    onFailure: function() {
                        if (typeof this.controlPanel != 'undefined' && this.controlPanel != null) {
                            this.controlPanel.setTrackContainerWidth();
                        }
                    }.bind(this),
                    // onException: function() {console.log("exception")},
                    onComplete: function(){
                        movieJsonComplete= true;
                        this.processControlPanel();
                    }.bind(this),
                    evalJS: false
                });
            }   
	},
	processControlPanel: function(){
        /* console.log("---- process controls-----"); */
        if(this.processedControlPanel !== true){
        
       		/*
console.log(movieJsonComplete);
       		console.log(this.expectingMovieJson);
       		console.log(languageJsonComplete);
       		console.log(videoReceivedMetadata);
*/
       		
            if((movieJsonComplete === true || this.expectingMovieJson ===false) && languageJsonComplete === true &&(videoReceivedMetadata === true)){
             	
                if(initializedCP === false) {
                   this.controlPanel._setupControls();
                }
                if(isStreaming === true){
                    this.controlPanel.handleStreaming();
                }
                   // if(movieJsonLoaded === true){
                       this.setSettingsControlsAvailableForLanguageAndPath(this.language, this.path);
                   // }
                   this._setControlPanel();
            this.processedControlPanel = true;
        
                }
        }
    
	},
	_setControlPanel: function() {
		
		
          if (this.controlPanel) {
                if (existingVideo != false && playExistingVideo === true) {
                    this.video.play();
                }
                
                this.controlPanel.delegate = this;
                Event.observe(this.container, 'mousemove', this.containerMouseMove);
                Event.observe(this.container, 'mouseout', this.containerMouseOut);
                Event.observe(this.container, 'mouseover', this.containerMouseOver);
                if(this.controlPanel.settingsMenu) {
                    Event.observe(this.controlPanel.settingsMenu, 'mouseover', this.menuMouseOver);
                }
                this.video.setTrackTextSpan(this.controlPanel.trackText);
                if (!this.controlPanel.settingsControlsAreSet && (this.video.tagName === "VIDEO")) {
                    this.configureSettingsControls(videoSrc);
                    this.controlPanel.settingsControlsAreSet = true;
                }
                if(this.controlPanel.element) {
                    this.controlPanel.element.parentNode.parentNode.style.width = this.currentWidth + 'px';
                    this.controlPanel.element.parentNode.parentNode.style.height = this.currentHeight + 'px';
                }
               
                if(this.video.object().tagName.toLowerCase() === "video") {
                    this.setSizeAnimation(true);
                }
                
                 
                this.setVideoSizeForWidthAndHeight(this.currentWidth, this.currentHeight);
                this.controlPanel.setFocus();
            } else {
                Event.stopObserving(this.container, 'mousemove', this.containerMouseMove);
                Event.stopObserving(this.container, 'mouseout', this.containerMouseOut);   
                Event.stopObserving(this.container, 'mouseover', this.containerMouseOver);
            }
        
       return this;
    },
	setControlPanel: function (cp) {
            //reversing order to make sure control panel is set before size controls are enabled
            this.controlPanel = (this.video.object().tagName === "VIDEO" && Core.Detect.iPad()) ? false : cp;
            if(this.controlPanel != null && this.controlPanel != false)  CoreLanguage.getTranslations(this);
    },
    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') {
                this.video.setVideoTitle(movieTitle);
            }
            if (typeof movieUrl != 'undefined') {
                this.video.setVideoUrl(movieUrl);
            }
            if (typeof movieDescription != 'undefined') {
                this.video.setVideoDescription(movieDescription);
            }
            if (typeof moviePosterframe != 'undefined') {
                this.video.setVideoPosterFrame(moviePosterframe);
            }
            if(typeof this.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);

                    this.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 this.controlPanel != 'undefined') {
                this.controlPanel.setTrackContainerWidth();
            }
            
            controlPanelConfigurationsSet = true;
    },
    setShareAvailable: function(movie) {
           /* if (this.controlPanel && typeof this.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;
                }
            }*/
        },
        videoReceivedPlayEvent: function (evt) {
            this._currentPlayState = 'playing';
            
            if (this.playAcknowledged) {
                return;
            }
             
            this.playAcknowledged = true;
           


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

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

        videoReceivedTimeupdateEvent: function (evt) {
            
            var time = this.video.time() || 0;
            //console.log("time = "+time);
            if (this.controlPanel) {
                this.controlPanel.updateTime(time);
            }
            if (this._lastTime != time) {
                /*this._fireEvent("QuickTime:didPlayProgress", {
                    controller: this, 
                    currentTime: time, 
                    duration: this.duration()
                });*/
            }
            
            this._lastTime = time;
        },
    videoReceivedPlayingEvent: function (evt) { 
    	
    		/*
console.log(this.video);
    		console.log(this._currentPosition);
    		console.log(this._currentSrc);
*/
    	
            if(this.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' && (!Core.Detect.iPad()) && (!Core.Detect.Mobile())){
                try{
                    this.video.object().SetControllerVisible(false); 
                }catch(e){}
            }
            
            if (!this.hasBegunPlaying && (this.movieType() == 'Video' || (this.time() > 0 && this._duration != 0))) {
                if (this.controlPanel && typeof this.controlPanel.mediaDidBecomePlayable !== 'undefined') {
                    this.controlPanel.mediaDidBecomePlayable();
                }

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

              

                this._playing = true;

                if(this.container)Element.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 (this.controlPanel && typeof this.controlPanel != 'undefined') {
                        this.controlPanel.hide();
                    }
                }, 500);
                
            }
        },
        movieType: function() {
            return this.video.movieType();
        },

    videoReceivedLoadEvent: function (evt) {
       if (this.controlPanel) {
                var percentLoaded = this.video.percentLoaded();
                        this.controlPanel.updatePercentLoaded(percentLoaded);
                 
                if(this._currentVolume != null && this.controlPanel.volumeControlSetting != 'undefined' && this.controlPanel.volumeControlSetting !=1){
                    if(this.controlPanel.volumeControlSetting == 0){
                        this.controlPanel.muteVolume();
                    }else{
                         if(this.controlPanel.setVolume != 'undefined')
                        this.setVolume(this.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 this.controlPanel.captionsUrl != 'undefined' && !this.controlPanel.captionsControl.isEnabled) {
                    this.setCaptionsAvailable(this.controlPanel.captionsUrl);
                }
                
                // if (percentLoaded >= 1 && Media.Detection.SnowLeopard1062()) {
                //  controlPanel.removeClickToPlay();
                // }
            }  
            
    },
     videoReceivedProgressEvent: function (evt) {
            if (this.controlPanel) {
                this.controlPanel.updatePercentLoaded(this.video.percentLoaded());
            }
            if(this.video.percentLoaded() >= 1 && this.largestMovieBuffered === false){
                this.checkIfLargestMovieIsBuffered();
            }
            //currentPosition and currentSrc only get value from resize function.
            if(this.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(this.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) {
                    this.video.setTime(this._currentPosition);
                    this.play();
                    this._currentPosition = false;
                    var that = this;
                    //destroy the canvas element that holds the interim screenshot
                    if (this.video.movieType() === 'Video') {
                        window.setTimeout(function() {
                        that.destroyFrame();
                        },600);
                    }   
                } else {
                    // pause until we're ready to play based on above condition
                    if(this._playing === true) this.pause();
                }
            }
            
            // console.log('videoReceivedProgressEvent - state: '+video.readystate()+' - '+video.percentLoaded());
            switch(true) {
                case (!this.hasBegunPlaying && Core.Detect.SnowLeopard() && this.movieType() == 'Video' && this.video.autoplay() === true && this.video.readystate() >= 3 && this.video.percentLoaded() > 0.4):
                     
                    this.play();
                    //this.videoReceivedPlayingEvent();
                    break;
                default:
                    break;
            }
            
        }, 
    videoReceivedLoadedmetadataEvent: function (evt) {
		var trackCount = null;
		
		if((!Core.Detect.iPad()) && (!Core.Detect.Mobile())){
		
			if(videoReceivedMetadata === false){
				if(isHTML5 === false){
					try {
						trackCount = this.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' === this.video.object().GetTrackType(i)) {
                               isStreaming = true;
                            }
                        }
                    }
                    videoReceivedMetadata = true;   
                }
                if(isStreaming === true){
                    if(this.video.duration() === Infinity){
                        isLiveStreaming = true; 
                    }
                }
             if (this.controlPanel && typeof this.controlPanel.enableBasicControls !== 'undefined' && videoReceivedMetadata===true) {
                this.processControlPanel();             
            }
             }
             
             
	},
	videoReceivedDurationchangeEvent: function (evt) {
            if (this.controlPanel) {
                this.controlPanel.updateRemainingTime(this.duration() - this.time());
            }
        },
        videoReceivedWebkitendfullscreenEvent: function (evt) {
            if (this.controlPanel) {
                if (typeof this._currentPlayState != 'undefined' && this._currentPlayState === 'playing') {
                    this.controlPanel.play();
                } else if (typeof this._currentPlayState != 'undefined' && this._currentPlayState === 'paused') {
                    this.controlPanel.pause();
                }
                
                var currentVolume = this.volume();
                if (this.controlPanel.volumeScrubber) this.controlPanel.volumeScrubber.setValue(currentVolume);
                this.setVolume(currentVolume);
            }
        },
	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(this.video.object().width, this.video.object().height);
                var largestSize = this.getLargestSizeOfMovie();
                if(movieSize.type == largestSize) this.largestMovieBuffered = true;
            }
        },

    setVideoSizeForWidthAndHeight: function(width, height) {
    		/*
console.log(width, height);
    		console.log("--- part 1 ----");
*/
            var videoObject = this.video.object() || this.video.object().parentNode;
            if(this.configSettings != undefined){
                currentSize = this.getCurrentSize(width, height);
            }
            	/*
console.log(currentSize);
            	console.log("--- part 2 ----");
*/
            if (typeof this.controlPanel != 'undefined' && typeof videoObject != 'undefined') {
                //var videoObject = video.object();
                var self = this;
                function setControlPanelType()
                {
                    if (typeof self.controlPanel != 'undefined')
                    {
                    	/* console.log("--- part 1111 ----"); */
                        self.controlPanel.setControllerType();
                        self.controlPanel.setTrackContainerWidth();
                    }
                }
        
        	/* console.log("--- part 3 ----"); */
                // 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 && this.largestMovieBuffered === true){
                            this.controlPanel.enableFullscreenControl();
                        }else{
                            for (var i=0;i<sizesList.length;i++) {
                                if (width == sizesList[i].width && sizesList[i].allowFullScreen === true){          
                                    this.controlPanel.enableFullscreenControl();
                                    break;
                                }else if (width == sizesList[i].width && sizesList[i].allowFullScreen === false){
                                    this.controlPanel.disableFullscreenControlForCurrentSize();
                                    break;
                                }
                            }
                        }   
                    }
                }
            
                if (Core.Detect.isIEStrict() &&!(Core.Detect.getAgent().match(/msie 9/i))) {
                    var top = parseInt(height / 2);
                    videoObject.style.marginTop = '-' +top + 'px';
                    this.controlPanel.element.style.marginTop = '-' + top + 'px';
                }
                if (this.video.percentLoaded() < 1 || this.sizeAnimation === false || Core.Detect.Chrome()) {
                    videoObject.width = width;
                    videoObject.height = height;
                    videoObject.style.width = width + "px";
                    videoObject.style.height = height+ "px";
                    

                    //var canvasFrame = ACUtils.getByClass('canvasFrame')[0];
                     var canvasFrame = $$('canvasFrame')[0];
                    if(canvasFrame){
                        canvasFrame.style.width = width + 'px';
                        canvasFrame.style.height = height + 'px';
                    }
                    
                    if (this.video.movieType() != 'Video' && typeof videoObject.parentNode != null) {
                        videoObject.parentNode.width = width;
                        videoObject.parentNode.height = height;
                    }
                    // alert("set src");
                    this.controlPanel.container.style.width = width + 'px';
                    this.controlPanel.container.style.height = height + 'px';
                    if(this.controlPanel.element) {
                        this.controlPanel.element.style.width = width + 'px';
                        this.controlPanel.element.style.height = height + 'px';
                    }
                    
                    if (Core.Detect.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(this.controlPanel.originalElementWidth != 0 && this.controlPanel.originalElementWidth != videoObject.width){
                            videoObject.style.left = "50%";
                            videoObject.style.marginLeft = "-"+left+"px";
                            this.controlPanel.element.style.left = "50%";
                            this.controlPanel.element.style.marginLeft = '-' + left + 'px';  
                        }else {
                            videoObject.style.left = "";
                            videoObject.style.marginLeft = "";
                            this.controlPanel.element.style.left = "";
                            this.controlPanel.element.style.marginLeft = "";
                        }
                    /*touch the dom to make IE recover its senses and get out of the blackout mode*/
                    if (Core.Detect.getAgent().match(/msie 6/i)) {document.body.style.display="none";document.body.style.display="block";}
                    }
                } else {
                    // add transition
                    if (Core.Detect.CSSTransitions() === true && this.video.movieType() !== 'QuickTime') {
                        videoObject.style.width = width + 'px';
                        videoObject.style.height = height + 'px';
                        if(this.controlPanel) {
                            this.controlPanel.container.style.width = width + 'px';
                            this.controlPanel.container.style.height = height + 'px';
                            if(this.controlPanel.element) {
                                this.controlPanel.element.style.width = width + 'px';
                                this.controlPanel.element.style.height = height + 'px';
                            }
                        }
                    } else {
                        var morphEffects = [];

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

                        morphEffects.push(new Effect.Morph(videoObject, {sync:true, style:{width:width+'px', height:height+'px'}}));
                        if (this.video.movieType != 'Video' && typeof videoObject.parentNode != null) {
                            morphEffects.push(new Effect.Morph(videoObject.parentNode, {sync:true, style:{width:width+'px', height:height+'px'}}));
                        }
                        
                        if(this.controlPanel) {
                            if(controlPanel.container) {
                                morphEffects.push(new Effect.Morph(this.controlPanel.container, {sync:true, style:{width:width+'px', height:height+'px'}}));
                            }
                            if(controlPanel.element) {
                                morphEffects.push(new Effect.Morph(this.controlPanel.element, {sync:true, style:{width:width+'px', height:height+'px'}}));
                            }
                        }
                        
                        var redraw = document.createElement('div');
                        Element.addClassName(redraw, 'ACMediaRedraw');
                        
                        var agent = Core.Detect.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
                                this.controlPanel.mouseoverSettingsControl(this.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);
                                this.controlPanel.hide();
                                this.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';
                                    this.controlPanel.element.style.top = '0';
                                    videoObject.style.marginTop = '-' + top + 'px';
                                    this.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';
                                    this.controlPanel.element.style.top = '0';
                                    videoObject.style.marginTop = '-' + top + 'px';
                                    this.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';
                                    this.controlPanel.element.style.top = '0';
                                    videoObject.style.marginTop = '-' + top + 'px';
                                    this.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
                                    this.controlPanel.mouseoutSettingsControl(controlPanel.sizesControl);
                                    this.controlPanel.hide();
                                }
                                
                                setControlPanelType();
                                
                                window.clearTimeout(sizeTimeout);
                                sizeTimeout = window.setTimeout(function(){
                                    if (this.controlPanel && (this.controlPanel.controllerType === 'slim' || this.controlPanel.controllerType === 'short-slim')) {
                                    
                                        this.controlPanel.fadeElement.style.visibility = 'visible';
                                        this.controlPanel.fadeElement.style.opacity = '1';
                                    
                                        this.controlPanel._hiding = false;
                                        this.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;
	},
    setDelegate: function (newDelegate) {
		this.delegate = newDelegate;
    },
    setVideo: function (vid) {
		this.hasBegunPlaying = false;
		this.hasEndedPlaying = false;
            
		this.video = vid;
		this._duration = this.video.duration() || 0;

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

		return this;
	},
	setVideoSrc: function(src) {
		this.videoSrc = src;
	},
	  beginSeeking: function () {
            if (this.seeking) {
                return;
            }

            this.seeking = true;
            wasPlayingBeforeSeek = !this.video.paused() && this.rate()==1;
            
            this.pause();
            
            var time = this.video.time();
            this._send('didStartJogging', time);
           // this._fireEvent("QuickTime:didStartJogging", {controller: this, time: time});
        },
        
        endSeeking: function () {
            var time = this.video.time(),
                duration = this.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() {

            return this.video.supportsFullscreen();
        },    

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

            if ( !this._duration ) {
                this._duration = this.video.duration();
            }
            return this._duration;
        },

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

	setVolume: function(level) {
		this.video.setMuted(false);
		this.video.setVolume(level);
		if (typeof this.controlPanel != 'undefined' && this.controlPanel != null) {
			this.controlPanel.volumeControlSetting = level;
		}
	},
	setMuted: function(mute) {
		this.video.setMuted(mute);
		if (typeof this.controlPanel != 'undefined' && this.controlPanel != null) {
			this.controlPanel.volumeControlSetting = 0;
		}
	},
	toggleMute: function () {
		var isMuted = this.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() {
		/* console.log('is this tshit playing at all ??? '); */
		/* console.log(this._playing); */
		return this._playing;
	},
	play: function () {
		/* console.log('should start playing'); */
		this.video.play();
		this._playing = true;
		this.playAcknowledged = false;
	},
	pause: function () {
	/* console.log('should pause '); */
		this.video.pause();
		this._playing = false;
		this.pauseAcknowledged = false;
	},
	stop: function () {
	
		this.video.pause();
		this._playing = false;
		this.pauseAcknowledged = false;
		this.hasEndedPlaying = true;
	},
	setRate: function (newRate) {
		this.video.setRate(newRate);
		if (newRate !== 1 || newRate !== 0) {
			this.isPlayAdvanced = true;
		} else {
			this.isPlayAdvanced = false;
		}
	},
	seekToTime: function(seekTime){
		return this.video.seekToTime(seekTime);
	},
	rate: function () {
		return this.video.rate();
	},
	src: function () {
		return this.video.src();
	},
	setSrc: function (src) {
		this.video.setSrc(src);
		this._currentSrc = src;
	},
	setSizeAnimation: function(bool) {
		this.sizeAnimation = bool;
	},
	_send: function (msg, params) {
            if (this.delegate && msg in this.delegate) {
                params = [this].concat(params);
                return this.delegate[msg].apply(this.delegate, params);
            }
	}
});


Core.VideoPanelWidget = Class.create({
	element:null,
	initialize: function(container, delegate, options) {
		this.settingsControlsAreSet = false;
		this.container = container;
		this.delegate = delegate;
		this.options = options;

   
		if (!Core.Detect.iPad()) {
			this._createTemplate();
			initializedCP = false;
			this._setupControls();
		}
    },
    _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(Core.VideoPanelWidget.TEMPLATE));
        
        this.element = document.getElementById('ACMedia-controls');
        this.element.id = 'ACMedia-controls_'+this.timestamp;
        this.element.style.outline = 'none';    
	},
	 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;
        }
    },
	resetRate: function() {
        if (this._send('rate') !== 1) {     
            this._send('setRate', 1);
        }
        this.removeAdvancedPlayDisplay();       
    },
    removeAdvancedPlayDisplay: function() {
        this.removeAlertDisplay();
        Element.removeClassName(this.fastBackwardControl, 'fastBackward-active');
        Element.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')
            Element.removeClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');  
        }
    },
     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();
        // }
    },
	play: function() {
		/* console.log("--- play click ----"); */
        this.resetRate();
			
        if (this._send('playing') === false) {
            if(Core.Detect.isiPad()) {
                this._send('forcePlay');
            }
            else {
                this._send('play');
            }
        }
        
        if(this.playControl) {
            Core.hideElement(this.playControl);
        }
        if(this.pauseControl) {
            Core.showElement(this.pauseControl);
        }
    },
    pause: function() {
        this.resetRate();
        /* console.log("--- pause click ----"); */
        if (this._send('playing') === true) {
            if(Core.Detect.isiPad()) {
                this._send('forcePause');
            }
            else {
                this._send('pause');
            }
        }
        
        if(this.pauseControl) {
            Core.hideElement(this.pauseControl);
        }
        if(this.playControl) {
            Core.showElement(this.playControl);
        }
    },
    fastBackward: function () {
        if(this.isStreaming === true && this.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) {
                Core.hideElement(this.pauseControl);
            }
            if(this.playControl) {
                Core.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);
        Element.addClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
        Element.removeClassName(this.fastForwardControl, 'fastForward-active');
        Element.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) {
                Core.hideElement(this.pauseControl);
            }
            if(this.playControl) {
                Core.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);
        Element.addClassName(this.alertDisplayContainer, this.alertDisplayContainer.baseClassName + '-active');
        Element.removeClassName(this.fastBackwardControl, 'fastBackward-active');
        Element.addClassName(this.fastForwardControl, 'fastForward-active');
    },
    setRateDisplay: function(control, rate) {
        if(!control) return;
        switch(true) {
            case (typeof control.currentRateDisplay != 'undefined' && control.currentRateDisplay !== rate):
                Element.removeClassName(control, control.currentRateDisplay);
                break;
            default:
                break;
        }
        
        switch(rate) {
            case null:
                break;
            default:
                Element.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  
            Element.addClassName(this.trackEndCap, 'track-right-cap-loaded');
            Element.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');
            Element.removeClassName(this.fastBackwardControl, 'fastBackward-active');
            Element.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);
    },
    _toggleMenuForControlAndMenuControls: function(menu, control, menuControls) {
        if (!Element.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');
        }
    },
    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);
        Element.addClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');
        Element.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 = Element.cumulativeOffset(this.settingsMenu).top,
            menuLeft = Element.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))) {
                Element.addClassName(this.settingsMenu, this.settingsMenu.baseClassName);
                Element.removeClassName(this.settingsMenu, this.settingsMenu.baseClassName+'-hovered');         
            }
        }
    },
    handleStreaming: function(){
    	
    	var isHTML5 = Core.Detect.HTML5();
    	var isLiveStreaming = false;
    	var isStreaming = false;
    	
        if(isStreaming === true){
            if(isLiveStreaming === true){
                if(isHTML5 === false){
                    Element.addClassName(this.mediaController, "ACMediaLiveStreamingQT");
                }else{
                    Element.addClassName(this.mediaController, "ACMediaLiveStreaming");
                }
                this.streamTextContainer.innerHTML = ac_media_language.livestreamdisplay || "Live Broadcast";
            }else {
                if(isHTML5 === false){
                    Element.addClassName(this.mediaController, "ACMediaStreamingQT");
                }else{
                    Element.addClassName(this.mediaController, "ACMediaStreamingVideo");
                }   
            }
        }
    },
	_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);
                Element.addClassName(this, this.baseClassName+'-active');
            }
            function onmouseup(event) {
                Element.removeClassName(this, this.baseClassName+'-active');            
            }
            
            Element.observe(element, 'mousedown', onmousedown.bind(element));
            Element.observe(element, 'mouseup', onmouseup.bind(element));
            Element.observe(document.documentElement, 'mouseup', onmouseup.bind(element));
        }
        
        function addHoverStateSwitching(element) {
            if (!element.baseClassName) {
                addBaseClassName(element);
            }
            
            function onmouseover(event) {
                Element.addClassName(this, element.baseClassName+'-hover');
            }
            function onmouseout(event) {
                Element.removeClassName(this, element.baseClassName+'-hover');
            }
            
            Element.observe(element, 'mouseover', onmouseover.bind(element));
            Element.observe(element, 'mouseout', onmouseout.bind(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');
        Element.addClassName(this.playControl, 'play');
        addActiveStateSwitching(this.playControl);
        this.playControl.id = 'ACMedia-play-control_'+this.timestamp;
        Element.observe(this.playControl, 'click', this.play.bind(this));
        //this.playControl.innerHTML = ac_media_language.play || 'Play';
        this.playControl.style.display = 'none';

        this.pauseControl = document.createElement('div');
        Element.addClassName(this.pauseControl, 'pause');
        addActiveStateSwitching(this.pauseControl);
        this.pauseControl.id = 'ACMedia-pause-control_'+this.timestamp;
        Element.observe(this.pauseControl, 'click', this.pause.bind(this));
        //this.pauseControl.innerHTML = ac_media_language.pause || 'Pause';
        this.pauseControl.style.display = 'none';
        
        Core.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';
        Element.observe(this.fastBackwardControl, 'click', this.fastBackward.bind(this));
        addActiveStateSwitching(this.fastBackwardControl);
        
        // Fast Forward
        this.fastForwardControl = get('ACMedia-control-fastforward');
       // this.fastForwardControl.innerHTML = ac_media_language.fastforward || 'Fast Forward';
        Element.observe(this.fastForwardControl, 'click', this.fastForward.bind(this));
        addActiveStateSwitching(this.fastForwardControl);
        
        // Volume Mute
        this.volumeMuteControl = get('ACMedia-volume-mute');
       // this.volumeMuteControl.innerHTML = ac_media_language.mutevolume || 'Mute Volume';
        Element.observe(this.volumeMuteControl, 'click', this.muteVolume.bind(this));
        addActiveStateSwitching(this.volumeMuteControl);
        
        // Volume Full
        this.volumeFullControl = get('ACMedia-volume-full');
       // this.volumeFullControl.innerHTML = ac_media_language.fullvolume || 'Full Volume';
        Element.observe(this.volumeFullControl, 'click', this.fullVolume.bind(this));
        addActiveStateSwitching(this.volumeFullControl);
        
        // Settings Controls
        this.settingsControls = get('ACMedia-settings-controls');
        addBaseClassName(this.settingsControls);
        
        this.captionsControl = get('ACMedia-captions-control');
        /*if (!Core.Detect.isIEStrict()) {
            this.captionsControl.innerHTML = ac_media_language.captionscontrol || 'Closed Captions';
        }*/
       // Element.observe(this.captionsControl, 'click', this.toggleCaptions.bind(this));
       // addActiveStateSwitching(this.captionsControl);
        
        this.sizesControl = get('ACMedia-sizes-control');
       /* if (!Core.Detect.isIEStrict()) {
            this.sizesControl.innerHTML = ac_media_language.sizescontrol || 'Video Size';
        }*/
        this.sizesControl.controlName = 'sizes';
        Element.observe(this.sizesControl, 'click', this.toggleSizesMenu.bind(this), false);
        addActiveStateSwitching(this.sizesControl);
        Element.observe(this.sizesControl, 'mouseover', this.mouseoverSettingsControl.bind(this, this.sizesControl),false);
        Element.observe(this.sizesControl, 'mouseout', this.mouseoutSettingsControl.bindAsEventListener(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';
        Element.observe(this.downloadControl, 'click', this.toggleDownloadMenu.bind(this));
        addActiveStateSwitching(this.downloadControl);
        Element.observe(this.downloadControl, 'mouseover', this.mouseoverSettingsControl.bind(this, this.downloadControl));
        Element.observe(this.downloadControl, 'mouseout', this.mouseoutSettingsControl.bindAsEventListener(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';
        Element.observe(this.shareControl, 'click', this.toggleShareMenu.bind(this));
        addActiveStateSwitching(this.shareControl);
        Element.observe(this.shareControl, 'mouseover', this.mouseoverSettingsControl.bind(this, this.shareControl));
        Element.observe(this.shareControl, 'mouseout', this.mouseoutSettingsControl.bindAsEventListener(this, this.shareControl));

        this.fullscreenControl = get('ACMedia-fullscreen-control');
       /* if (!ACUtils.Detector.isIEStrict()) {
            this.fullscreenControl.innerHTML = ac_media_language.fullscreencontrol || 'Full Screen';
        }*/
        Element.observe(this.fullscreenControl, 'click', this.toggleFullscreen.bind(this));
        addActiveStateSwitching(this.fullscreenControl);
        
        this.settingsMenu = document.createElement('div');
        if (Core.Detect.CSSBorderRadius() === false) {
            this.settingsMenuRoundRect = this.getRoundRectForArcAndOpacity(0.05, 0.9);
            this.settingsMenu.appendChild(this.settingsMenuRoundRect);
        }

        this.settingsMenu.id = 'ACMedia-settings-menu_'+this.timestamp;
        Element.addClassName(this.settingsMenu, 'ACMediaSettingsMenu');
        document.body.appendChild(this.settingsMenu);
        this.settingsMenu.baseClassName = 'ACMediaSettingsMenu';
        if (Core.Detect.isIEStrict()) {
            Element.observe(this.settingsMenu, 'click', function(evt){
                if(!evt) evt = window.event;
              //  var tgt = ACUtils.getTarget(evt);
               var tgt = evt.target;
                if(tgt && tgt.tagName !=null &&  tgt.tagName != "A" ){ Event.stop(evt);}});
        }

        this.settingsMenuCarrot = document.createElement('div');
        Element.addClassName(this.settingsMenuCarrot, 'ACMediaSettingsMenuCarrot');
        this.settingsMenu.appendChild(this.settingsMenuCarrot);
        
        this.settingsMenuTitle = document.createElement('div');
        Element.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');
        Element.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 = 'Video Size';
        
        this.downloadMenu = document.createElement('ul');
        this.downloadMenu.menuName = 'download';
        this.downloadMenu.menuTitle = this.downloadControl.menuTitle = 'Download Video';
        
        this.shareMenu = document.createElement('ul');
        this.shareMenu.menuName = 'share';
        this.shareMenu.menuTitle = this.shareControl.menuTitle = '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 (Core.Detect.isWin()) {
                    trackContainerWidth = trackContainerWidth - 10;
                }
                this.trackContainer.style.width = trackContainerWidth + 'px';
                break;
            default:
                break;
        }
        
        
        addActiveStateSwitching(this.volumeThumb);
        
        
        if (!this.scrubber && this.element !== null) {
            addActiveStateSwitching(this.playhead);
        }
        initializedCP = true;
    },
	_setRegularControllerType: function() {
        Element.removeClassName(this.container, 'slim');
        Element.removeClassName(this.container, 'short-slim');
        this.controllerType = 'regular';
    },
    _setSlimControllerType: function() {
        Element.addClassName(this.container, 'slim');
        Element.removeClassName(this.container, 'short-slim');
        this.controllerType = 'slim';
    },
    _setShortSlimControllerType: function() {
        Element.addClassName(this.container, 'slim');
        Element.addClassName(this.container, 'short-slim');
        this.controllerType = 'short-slim';
    },
    _enableControl: function(control) {
        if(control) {
            Element.addClassName(control, control.baseClassName+'-enabled');
        }
    },
    _disableControl: function(control) {
        if(control) {
            Element.removeClassName(control, control.baseClassName+'-enabled');
        }
    },
    enableBasicControls: function() {
        if(this.playControl) {
            Core.hideElement(this.playControl);
        }
        if(this.pauseControl) {
            Core.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);
    },
	setControllerType: function() {
        switch (true) {
            case Core.Detect.Firefox():
            case Core.Detect.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 && !Core.Detect.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();
                }
            }.bind(this), 50);
        }
    },
    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;
                    }.bind(this),
                    onChange: function (value) {
                        if (this._seeking) {
                            this._seeking = false;
                            this._send('endSeeking');
                        }
                        this.trackProgress.style.width = this.playhead.style.left;
                    }.bind(this)
                });
                //this.scrubber.initialize();
            }
        }
    },
    createVolumeScrubber: function() {
    
    	/* console.log("--- want to make a slider-----"); */
    	
    	/*
console.log(this.volumeScrubber);
    	console.log(this.element);
*/
        // Volume Slider
        if (!this.volumeScrubber && this.element !== null) {
      		/* console.log("--- making the slider-----"); */
            var max = this.volumeTrack.offsetWidth;
            
           /*  console.log(max); */
            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;
                }.bind(this),
                onChange: function (value) {
                    this._volSeeking = false;
                    this.volumeProgress.style.width = this.volumeThumb.style.left;
                }.bind(this)
            });
            
           
            /* console.log("--- done with that 2 -----"); */
           // this.volumeScrubber.initialize();
            
            if (typeof this.volumeControlSetting == 'undefined') {
                this.volumeControlSetting = 1;
            }
            
            this.volumeScrubber.setValue(this.volumeControlSetting);
            
              /* console.log("--- okeli dokeli-----"); */
        }
    },
    getRoundRectForArcAndOpacity: function(arc, opacity) {
        if (Core.Detect.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');
        }
        

    },
    _send: function (msg, params) {
   /* console.log(this.delegate);
    	console.log(msg);
    	console.log(params);*/
        if (this.delegate && msg in this.delegate) {
            params = [].concat(params);
            return this.delegate[msg].apply(this.delegate, params);
        }
    }
});

Core.VideoPanelWidget.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>';




