//Timeline overide function  -- exact copy of whats in the simile code, but for some 
//reason overriding here stops bubbles form being corrupted when they are above.
Timeline.Graphics.createBubbleForPoint = function(doc, pageX, pageY, contentWidth, contentHeight) {
    function getWindowDims() {
        if (typeof window.innerWidth == 'number') {
	    return { w:window.innerWidth, h:window.innerHeight }; // Non-IE
	} else if (document.documentElement && document.documentElement.clientWidth) {
	    return { // IE6+, in "standards compliant mode"
		w:document.documentElement.clientWidth,
		h:document.documentElement.clientHeight
	    };
	} else if (document.body && document.body.clientWidth) {
	    return { // IE 4 compatible
		w:document.body.clientWidth,
		h:document.body.clientHeight
	    };
	}
    }

    var bubble = {
        _closed:    false,
        _doc:       doc,
        close:      function() { 
            if (!this._closed) {
                this._doc.body.removeChild(this._div);
                this._doc = null;
                this._div = null;
                this._content = null;
                this._closed = true;
            }
        }
    };

    var dims = getWindowDims();
    var docWidth = dims.w;
    var docHeight = dims.h;

    var margins = Timeline.Graphics._bubbleMargins;
    contentWidth = parseInt(contentWidth, 10); // harden against bad input bugs
    contentHeight = parseInt(contentHeight, 10); // getting numbers-as-strings
    var bubbleWidth = margins.left + contentWidth + margins.right;
    var bubbleHeight = margins.top + contentHeight + margins.bottom;

    var pngIsTranslucent = Timeline.Graphics.pngIsTranslucent;
    var urlPrefix = Timeline.urlPrefix;
    
    var setImg = function(elmt, url, width, height) {
        elmt.style.position = "absolute";
        elmt.style.width = width + "px";
        elmt.style.height = height + "px";
        if (pngIsTranslucent) {
            elmt.style.background = "url(" + url + ")";
        } else {
            elmt.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url +"', sizingMethod='crop')";
        }
    }
    var div = doc.createElement("div");
    div.style.width = bubbleWidth + "px";
    div.style.height = bubbleHeight + "px";
    div.style.position = "absolute";
    div.style.zIndex = 1000;
    bubble._div = div;
    
    var divInner = doc.createElement("div");
    divInner.style.width = "100%";
    divInner.style.height = "100%";
    divInner.style.position = "relative";
    div.appendChild(divInner);
    
    var createImg = function(url, left, top, width, height) {
        var divImg = doc.createElement("div");
        divImg.style.left = left + "px";
        divImg.style.top = top + "px";
        setImg(divImg, url, width, height);
        divInner.appendChild(divImg);
    }
    
    createImg(urlPrefix + "images/bubble-top-left.png", 0, 0, margins.left, margins.top);
    createImg(urlPrefix + "images/bubble-top.png", margins.left, 0, contentWidth, margins.top);
    createImg(urlPrefix + "images/bubble-top-right.png", margins.left + contentWidth, 0, margins.right, margins.top);
    
    createImg(urlPrefix + "images/bubble-left.png", 0, margins.top, margins.left, contentHeight);
    createImg(urlPrefix + "images/bubble-right.png", margins.left + contentWidth, margins.top, margins.right, contentHeight);
    
    createImg(urlPrefix + "images/bubble-bottom-left.png", 0, margins.top + contentHeight, margins.left, margins.bottom);
    createImg(urlPrefix + "images/bubble-bottom.png", margins.left, margins.top + contentHeight, contentWidth, margins.bottom);
    createImg(urlPrefix + "images/bubble-bottom-right.png", margins.left + contentWidth, margins.top + contentHeight, margins.right, margins.bottom);
    
    var divClose = doc.createElement("div");
    divClose.style.left = (bubbleWidth - margins.right + Timeline.Graphics._bubblePadding - 16 - 2) + "px";
    divClose.style.top = (margins.top - Timeline.Graphics._bubblePadding + 1) + "px";
    divClose.style.cursor = "pointer";
    setImg(divClose, urlPrefix + "images/close-button.png", 16, 16);
    Timeline.DOM.registerEventWithObject(divClose, "click", bubble, bubble.close);
    divInner.appendChild(divClose);
        
    var divContent = doc.createElement("div");
    divContent.style.position = "absolute";
    divContent.style.left = margins.left + "px";
    divContent.style.top = margins.top + "px";
    divContent.style.width = contentWidth + "px";
    divContent.style.height = contentHeight + "px";
    divContent.style.overflow = "auto";
    divContent.style.background = "white";
    divInner.appendChild(divContent);
    bubble.content = divContent;
    
    (function() {
        if (pageX - Timeline.Graphics._halfArrowWidth - Timeline.Graphics._bubblePadding > 0 &&
            pageX + Timeline.Graphics._halfArrowWidth + Timeline.Graphics._bubblePadding < docWidth) {
            
            var left = pageX - Math.round(contentWidth / 2) - margins.left;
            left = pageX < (docWidth / 2) ?
                Math.max(left, -(margins.left - Timeline.Graphics._bubblePadding)) : 
                Math.min(left, docWidth + (margins.right - Timeline.Graphics._bubblePadding) - bubbleWidth);
                
            if (pageY - Timeline.Graphics._bubblePointOffset - bubbleHeight > 0) { // top
                var divImg = doc.createElement("div");
                
                divImg.style.left = (pageX - Timeline.Graphics._halfArrowWidth - left) + "px";
                divImg.style.top = (margins.top + contentHeight) + "px";
                setImg(divImg, urlPrefix + "images/bubble-bottom-arrow.png", 37, margins.bottom);
                divInner.appendChild(divImg);
                
                div.style.left = left + "px";
                div.style.top = (pageY - Timeline.Graphics._bubblePointOffset - bubbleHeight + 
                    Timeline.Graphics._arrowOffsets.bottom) + "px";
                
                return;
            } else if (pageY + Timeline.Graphics._bubblePointOffset + bubbleHeight < docHeight) { // bottom
                var divImg = doc.createElement("div");
                
                divImg.style.left = (pageX - Timeline.Graphics._halfArrowWidth - left) + "px";
                divImg.style.top = "0px";
                setImg(divImg, urlPrefix + "images/bubble-top-arrow.png", 37, margins.top);
                divInner.appendChild(divImg);
                
                div.style.left = left + "px";
                div.style.top = (pageY + Timeline.Graphics._bubblePointOffset - 
                    Timeline.Graphics._arrowOffsets.top) + "px";
                
                return;
            }
        }
        
        var top = pageY - Math.round(contentHeight / 2) - margins.top;
        top = pageY < (docHeight / 2) ?
            Math.max(top, -(margins.top - Timeline.Graphics._bubblePadding)) : 
            Math.min(top, docHeight + (margins.bottom - Timeline.Graphics._bubblePadding) - bubbleHeight);
                
        if (pageX - Timeline.Graphics._bubblePointOffset - bubbleWidth > 0) { // left
            var divImg = doc.createElement("div");
            
            divImg.style.left = (margins.left + contentWidth) + "px";
            divImg.style.top = (pageY - Timeline.Graphics._halfArrowWidth - top) + "px";
            setImg(divImg, urlPrefix + "images/bubble-right-arrow.png", margins.right, 37);
            divInner.appendChild(divImg);
            
            div.style.left = (pageX - Timeline.Graphics._bubblePointOffset - bubbleWidth +
                Timeline.Graphics._arrowOffsets.right) + "px";
            div.style.top = top + "px";
        } else { // right
            var divImg = doc.createElement("div");
            
            divImg.style.left = "0px";
            divImg.style.top = (pageY - Timeline.Graphics._halfArrowWidth - top) + "px";
            setImg(divImg, urlPrefix + "images/bubble-left-arrow.png", margins.left, 37);
            divInner.appendChild(divImg);
            
            div.style.left = (pageX + Timeline.Graphics._bubblePointOffset - 
                Timeline.Graphics._arrowOffsets.left) + "px";
            div.style.top = top + "px";
        }
    })();
    
    doc.body.appendChild(div);
    
    return bubble;
};

//Another timeline override that will allow me to put custom stuff in the bubble
Timeline.DefaultEventSource.Event.prototype.fillInfoBubble = function(elmt, theme, labeller) {
        var doc = elmt.ownerDocument;
        
        var title = this.getText();
        var link = this.getLink();
        var image = this.getImage();
		
		urchinTracker('/timeline/bubbleshown');
		//Get the video id from the link
		id = link.slice(link.indexOf('videos/watch/videoid/') + 21,link.lastIndexOf("'"));
		        

        if (image != null) {
        	
            var img = doc.createElement("img");
            img.src = image;
            theme.event.bubble.imageStyler(img);

        	//Create a link so we can make the image clickable
			var a = doc.createElement("a");
	        a.href = link;        	
			a.appendChild(img);        	


            elmt.appendChild(a);
        }
        
        var divTitle = doc.createElement("div");
        var textTitle = doc.createTextNode(title);
        if (link != null) {
            var a = doc.createElement("a");
            a.href = link;
            a.appendChild(textTitle);
            divTitle.appendChild(a);
        } else {
            divTitle.appendChild(textTitle);
        }
        theme.event.bubble.titleStyler(divTitle);
        elmt.appendChild(divTitle);
        
        var divBody = doc.createElement("div");
        this.fillDescription(divBody);
        theme.event.bubble.bodyStyler(divBody);
        elmt.appendChild(divBody);
        


        var divActions = doc.createElement("div");

		//Play now
        var img = doc.createElement("img");
        img.src = "/images/icons/playertoolbar/play.gif";
        img.title = "Play Now";
        img.className = "bubble-toolbar-image";
        var a = doc.createElement("a");
        a.href = link;
        a.appendChild(img);
		divActions.appendChild(a);

		//Play later
		playlaterLink = "javascript:VideoManager.queueVideo('" + id + "');" 
        var img = doc.createElement("img");
        img.src = "/images/icons/playertoolbar/fastforward.gif";
        img.title = "Play Later";
        img.className = "bubble-toolbar-image";
        var a = doc.createElement("a");
        a.href = playlaterLink;
        a.appendChild(img);
		divActions.appendChild(a);


		//Comments
		commentsLink = "javascript:MyTimeline.closeBubble();VideoManager.showComments('" + id + "');" 	        
        var img = doc.createElement("img");
        img.src = "/images/icons/playertoolbar/user.gif";
        img.title = "Comments";
        img.className = "bubble-toolbar-image";
        var a = doc.createElement("a");
        a.href = commentsLink;
        a.appendChild(img);
		divActions.appendChild(a);


		
		if (Application.hasPermission('admin')) {
			
			
			//Edit
			editLink = "javascript:VideoManager.editVideo('" + id + "');" 
	        var img = doc.createElement("img");
	        img.src = "/images/icons/playertoolbar/edit.gif";
	        img.title = "Edit";
			img.className = "bubble-toolbar-image";
	        var a = doc.createElement("a");
	        a.href = editLink;
	        a.appendChild(img);
			divActions.appendChild(a);

			//Exclude
			excludeLink = "javascript:VideoManager.excludeVideo('" + id + "');" 	
	        var img = doc.createElement("img");
	        img.src = "/images/icons/playertoolbar/against.gif";
	        img.title = "Exclude";
	        img.className = "bubble-toolbar-image";
	        var a = doc.createElement("a");
	        a.href = excludeLink;
	        a.appendChild(img);
			divActions.appendChild(a);

			
		}
				
		elmt.appendChild(divActions);				
        //var divTime = doc.createElement("div");
        //this.fillTime(divTime, labeller);
        //theme.event.bubble.timeStyler(divTime);
        //elmt.appendChild(divTime);
        
        var divWiki = doc.createElement("div");
        this.fillWikiInfo(divWiki);
        theme.event.bubble.wikiStyler(divWiki);
        elmt.appendChild(divWiki);
    }


MyTimeline = function(){        	
		var tl;
		var resizeTimerID = null;
		var eventSource;
		var currentNodeid;
		var currentBandType;
		var currentFocusDate;

		var localtimeZone;
        return {
            init : function(){
              eventSource = new Timeline.DefaultEventSource();			              			
              var mydate = new Date();
              localtimeZone = mydate.getTimezoneOffset()/-60;
			  var bandInfos = [
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	eventSource: 	eventSource,
					    	date: mydate,
					    	trackHeight:	1.3,
					    	trackGap:		.1,
					        width:          "80%", 
					        intervalUnit:   Timeline.DateTime.HOUR, 
					        intervalPixels: 30
					    }),
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	showEventText:  false,
						    trackHeight:    0.3,
						    trackGap:       0.1,
		   			    	eventSource: 	eventSource,
					        width:          "20%", 
					        intervalUnit:   Timeline.DateTime.DAY, 
					        intervalPixels: 80
					    })
					  ];
			  
			  bandInfos[1].syncWith = 0;
			  bandInfos[1].highlight = true;

			  MyTimeline.tl = Timeline.create(document.getElementById("timeline-wrapper"), bandInfos);
			  
			  //Load the defautl data
			  MyTimeline.reloaddata(2,"","hour"); 

			},
		
			focusDate : function(ddate) {
				
				tl.getBand(0).setCenterVisibleDate(ddate);					
			},
			
			closeBubble : function(){
				tl.getBand(0).closeBubble();
			},
			
			changeBands : function(topBandType, thedate){
				//var stringdate = this.formatDate(thedate);
				var stringdate = thedate;
				tl = null;
				
				if (topBandType =='') {
					topBandType = 'day';
				}

				//Should return if we are trying to change to the same one				
				
				if (topBandType == 'month') {
					var bandInfos = [
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	eventSource: 	eventSource,
					    	date: stringdate,
					    	trackHeight:	1.3,
					    	trackGap:		.1,
					        width:          "80%", 
					        intervalUnit:   Timeline.DateTime.MONTH, 
					        intervalPixels: 50
					    }),
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	showEventText:  false,
						    trackHeight:    0.3,
						    trackGap:       0.1,
		   			    	eventSource: 	eventSource,
					        width:          "20%", 
					        intervalUnit:   Timeline.DateTime.YEAR, 
					        intervalPixels: 100
					    })
					  ];
				} else if (topBandType == "week") {
					
					var bandInfos = [
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	eventSource: 	eventSource,
					    	date: stringdate,
					    	trackHeight:	1.3,
					    	trackGap:		.1,
					        width:          "80%", 
					        intervalUnit:   Timeline.DateTime.WEEK, 
					        intervalPixels: 50
					    }),
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	showEventText:  false,
						    trackHeight:    0.3,
						    trackGap:       0.1,
		   			    	eventSource: 	eventSource,
					        width:          "20%", 
					        intervalUnit:   Timeline.DateTime.MONTH, 
					        intervalPixels: 100
					    })
					  ];
					
				} else if (topBandType == "day") {
					
					var bandInfos = [
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	eventSource: 	eventSource,
					    	date: stringdate,
					    	trackHeight:	1.3,
					    	trackGap:		.1,
					        width:          "80%", 
					        intervalUnit:   Timeline.DateTime.DAY, 
					        intervalPixels: 50
					    }),
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	showEventText:  false,
						    trackHeight:    0.3,
						    trackGap:       0.1,
		   			    	eventSource: 	eventSource,
					        width:          "20%", 
					        intervalUnit:   Timeline.DateTime.WEEK, 
					        intervalPixels: 100
					    })
					  ];
					
				}
				 else if (topBandType == "hour") {
					var bandInfos = [
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	eventSource: 	eventSource,
					    	date: stringdate,
					    	trackHeight:	1.3,
					    	trackGap:		.1,
					        width:          "80%", 
					        intervalUnit:   Timeline.DateTime.HOUR, 
					        intervalPixels: 30
					    }),
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	showEventText:  false,
						    trackHeight:    0.3,
						    trackGap:       0.1,
		   			    	eventSource: 	eventSource,
					        width:          "20%", 
					        intervalUnit:   Timeline.DateTime.DAY, 
					        intervalPixels: 80
					    })
					  ];
					
				} else if (topBandType == "minute") {
					var bandInfos = [
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	eventSource: 	eventSource,
					    	date: stringdate,
					    	trackHeight:	1.3,
					    	trackGap:		.1,
					        width:          "80%", 
					        intervalUnit:   Timeline.DateTime.HOUR,
					        multiple: 1, 
					        intervalPixels: 125
					    }),
					    Timeline.createBandInfo({
					    	timeZone: localtimeZone,
					    	showEventText:  false,
						    trackHeight:    0.3,
						    trackGap:       0.1,
		   			    	eventSource: 	eventSource,
					        width:          "20%", 
					        intervalUnit:   Timeline.DateTime.DAY, 
					        intervalPixels: 80
					    })
					  ];
					
				}
							  
	
				  this.currentBandType = topBandType;
				  
				  bandInfos[1].syncWith = 0;
				  bandInfos[1].highlight = true;
	
				  tl = Timeline.create(document.getElementById("timeline-wrapper"), bandInfos);
			},
			
			zoomIn : function(){
				
				//Need to get centered date from the tl control
				var focusDate = tl.getBand(0).getCenterVisibleDate();
				switch(this.currentBandType)
				{
					case "year":
						this.changeBands("month", focusDate);
						break;
					case "month":
						this.changeBands("week", focusDate);
						break;
					case "week":
						this.changeBands("day", focusDate);
						break;
					case "day":
						this.changeBands("hour", focusDate);
						break;
					case "hour":
						this.changeBands("minute", focusDate);
						break;
				}	
				tl.getBand(0).setCenterVisibleDate(focusDate);
			},
			
			zoomOut : function(){
				
				var focusDate = tl.getBand(0).getCenterVisibleDate();
				switch(this.currentBandType)
				{
					case "minute":
						this.changeBands("hour", focusDate);
						break;
					case "hour":
						this.changeBands("day", focusDate);
						break;
					case "day":
						this.changeBands("week", focusDate);
						break;
					case "week":
						this.changeBands("month", focusDate);
						break;
					case "month":
//						this.changeBands('year', focusDate);

				}
				tl.getBand(0).setCenterVisibleDate(focusDate);	
			},
			
			formatDate : function(date){				
				return date.getMonth() + ' ' + date.getDate() + ' ' + date.getYear();
			},
									
			reloaddata : function(nodeid, focusDate, topBandType){
				//Set current node id
				this.currentNodeid = nodeid;
				this.currentFocusDate = focusDate;
				this.currentBandType = topBandType;
				//Clear loaded data
				eventSource.clear();
				//Reload the data for the timeline that is appropriate for the selected node
				
				MyTimeline.tl.loadXML("timeline/getTimelines?node=" + nodeid,MyTimeline.dataReloaded); 							
				
			},
			
			dataReloaded : function(xml,url){
				eventSource.loadXML(xml,url);

				if (MyTimeline.currentFocusDate == "") {
					var ddate = new Date();
				} else {
					var ddate = new Date(MyTimeline.currentFocusDate);					
				}
				MyTimeline.changeBands(MyTimeline.currentBandType, ddate);
				MyTimeline.focusDate(ddate);

			},
			
			resize : function(){
			    if (resizeTimerID == null) {
			        if (undefined != tl ){
				        resizeTimerID = window.setTimeout(function() {
				            resizeTimerID = null;
				            tl.layout();
				        }, 500);
			        }
			    }
			}
        }
}();
Ext.EventManager.onDocumentReady(MyTimeline.init, MyTimeline, true);
Ext.EventManager.onWindowResize(MyTimeline.resize, MyTimeline, true);


  
