//overload function from bundle.js in timeline to add an id to event

var proto = Timeline.DefaultEventSource.Event.prototype

Timeline.DefaultEventSource.Event=function(id, start, end, latestStart, earliestEnd, instant,
											text, toptext, description, image, link,
											icon, color, textColor, ams_wiki, loc){

	this._id=id;
	
	this._instant=instant||(end==null);
	
	this._start=start;
	this._end=(end!=null)?end:start;
	
	this._latestStart=(latestStart!=null)?latestStart:(instant?this._end:this._start);
	this._earliestEnd=(earliestEnd!=null)?earliestEnd:(instant?this._start:this._end);
	
	this._text=Timeline.HTML.deEntify(text);
	this._toptext=Timeline.HTML.deEntify(toptext);
	this._description=Timeline.HTML.deEntify(description);
	this._image=(image!=null&&image!="")?image:null;
	this._link=(link!=null&&link!="")?link:null;
	
	this._icon=(icon!=null&&icon!="")?icon:null;
	this._color=(color!=null&&color!="")?color:null;
	this._textColor=(textColor!=null&&textColor!="")?textColor:null;
	
	this._wikiURL=null;
	this._wikiSection=null;
	this._ams_wiki = ams_wiki;
	this._loc = loc;
};

Timeline.DefaultEventSource.Event.prototype = proto;

Timeline.DefaultEventSource.Event.prototype.getTopText = function(){
	return this._toptext;
}

Timeline.DefaultEventSource.Event.prototype.getAmsWiki = function(){
	return this._ams_wiki;
}

Timeline.DefaultEventSource.Event.prototype.getLocation = function(){
	return this._loc;
}

Timeline.DefaultEventSource.Event.prototype.fillTime = function(elmt, labeller){
	if(this._instant){
		if(this.isImprecise()){
			elmt.appendChild(elmt.ownerDocument.createTextNode("From: "  + this.ams_prepareDate(this._start)));
			elmt.appendChild(elmt.ownerDocument.createElement("br"));
			elmt.appendChild(elmt.ownerDocument.createTextNode("To: "  + this.ams_prepareDate(this._end)));
		} else {
			elmt.appendChild(elmt.ownerDocument.createTextNode("On: "  + this.ams_prepareDate(this._start)));
		}
	} else {
		if(this.isImprecise()){
			elmt.appendChild(elmt.ownerDocument.createTextNode("From: "  + this.ams_prepareDate(this._start) + " ~ " + this.ams_prepareDate(this._latestStart)));
			elmt.appendChild(elmt.ownerDocument.createElement("br"));
			elmt.appendChild(elmt.ownerDocument.createTextNode("To: " + this.ams_prepareDate(this._earliestEnd) + " ~ " + this.ams_prepareDate(this._end)));
		} else {
			elmt.appendChild(elmt.ownerDocument.createTextNode("From: "  + this.ams_prepareDate(this._start)));
			elmt.appendChild(elmt.ownerDocument.createElement("br"));
			elmt.appendChild(elmt.ownerDocument.createTextNode("To: " + this.ams_prepareDate(this._end))); 
		}
	}
}

Timeline.DefaultEventSource.Event.prototype.ams_prepareDate = function (dte){
	return (dte.getDate()<10 ? "0"+(dte.getDate()) : dte.getDate()) + "/"
				+ (dte.getMonth()<9 ? "0"+(dte.getMonth() + 1) : (dte.getMonth() + 1)) + "/" 
				+ (dte.getYear() + 1900);
}

Timeline.DefaultEventSource.prototype.loadJSON=function(data,url){
	var base=this._getBaseURL(url);
	var added=false;
	if(data&&data.events){
		var wikiURL = null;
		var wikiSection = null;
		
		var dateTimeFormat=("dateTimeFormat"in data)?data.dateTimeFormat:null;
		var parseDateTimeFunction=this._events.getUnit().getParser(dateTimeFormat);
		
		for(var i=0;i<data.events.length;i++){
			var event=data.events[i];
			var evt=new Timeline.DefaultEventSource.Event(event.id,
			parseDateTimeFunction(event.start),
			parseDateTimeFunction(event.end),
			parseDateTimeFunction(event.latestStart),
			parseDateTimeFunction(event.earliestEnd),
			event.isDuration||false,
			event.title,
			event.toptitle,
			event.description,
			this._resolveRelativeURL(event.image,base),
			this._resolveRelativeURL(event.link,base),
			this._resolveRelativeURL(event.icon,base),
			event.color,
			event.textColor,
			event.wiki,
			event.elocation);
	
			evt._obj=event;
			evt.getProperty=function(name){
				return this._obj[name];
			};

			evt.setWikiInfo(wikiURL,wikiSection);

			this._events.add(evt);
			added=true;
		}
	}

	if(added){
		this._fire("onAddMany",[]);
	}
};

Timeline.DurationEventPainter.prototype._onClickDurationEvent=function(domEvt,evt,target){
	domEvt.cancelBubble=true;
	if("pageX"in domEvt){
		var x=domEvt.pageX;
		var y=domEvt.pageY;
	}else{
		var c=Timeline.DOM.getPageCoordinates(target);
		var x=domEvt.offsetX+c.left;
		var y=domEvt.offsetY+c.top;
	}
	if(evt.getID() != 0){
		if(entitymanager){
			entitymanager.editTimelineEvent(evt.getID());
		}
	}
	else{
		this._showBubble(x,y,evt);
	}
};

Timeline.DefaultEventSource.Event.prototype.fillInfoBubble = function(elmt, theme, labeller) {
	var doc = elmt.ownerDocument;

	var link = this.getLink();
	var image = this.getImage();
	var toptitle = this.getTopText();
	var wiki = this.getAmsWiki();
	var loc = this.getLocation();
	
	if (image != null) {
	    var img = doc.createElement("img");
	    img.src = image;
	    
	    theme.event.bubble.imageStyler(img);
	    elmt.appendChild(img);
	}
	
	var divTitle = doc.createElement("div");
	var textTitle = doc.createTextNode(toptitle);
	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 divLoc = doc.createElement("div");
	divLoc.innerHTML = "Location: " + loc + "<br /><br />";
	elmt.appendChild(divLoc);
	
	var divTime = doc.createElement("div");
	this.fillTime(divTime, labeller);
	theme.event.bubble.timeStyler(divTime);
	elmt.appendChild(divTime);
	
	var divBody = doc.createElement("div");
	divBody.innerHTML = "<br />" + wiki;
	elmt.appendChild(divBody);
}

var tl = Array();
var eventSource = Array();


function resetTimeLine(edit){
	if(edit){
		eventSource['edit'] = new Timeline.DefaultEventSource(0);
	}
	else {
		eventSource['preview'] = new Timeline.DefaultEventSource(0);
	}
	
	var srckey = 'preview';
    if(edit){
    	srckey = 'edit';
    }
	
	if(!document.getElementById("timeline_edit") && !document.getElementById("my-timeline")){
		return false;
	}
    
    var theme = Timeline.ClassicTheme.create();
    theme.event.bubble.width = 300;
    theme.event.bubble.height = 150;
    //theme.ether.backgroundColors[1] = theme.ether.backgroundColors[0];
    var d = Timeline.DateTime.parseGregorianDateTime("2008");
    var bandInfos = [
        Timeline.createBandInfo({
            width:          "70%", 
            intervalUnit:   Timeline.DateTime.MONTH, 
            intervalPixels: 200,
            trackHeight:    3,
            eventSource:    eventSource[srckey],
            date:           d,
            theme:          theme
        }),
        Timeline.createBandInfo({
            width:          "30%", 
            intervalUnit:   Timeline.DateTime.YEAR, 
            intervalPixels: 200,
            date:           d,
            trackHeight:    0.4,
            eventSource:    eventSource[srckey],
            showEventText:  false,
            theme:          theme
        })                
	];
	
	bandInfos[1].syncWith = 0;
	bandInfos[1].highlight = true;
 
    
    for (var i = 0; i < bandInfos.length; i++) {
		bandInfos[i].decorators = [
			new Timeline.SpanHighlightDecorator({
				startDate:  new Date(),
				endDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 2),
				color: "#FFC080",
				startLabel: "",
            	endLabel:   "",
				opacity: 50,
				theme: theme
			})
		 ];
	}
	
	return bandInfos;
}

function onLoadAgenda(iid, preview, edit) {
	
	if(!document.getElementById("timeline_edit") && !document.getElementById("my-timeline")){
		return false;
	}

	var srckey = 'preview';
    if(edit){
    	srckey = 'edit';
    }
    
	var curl = "";
	if(!edit){
		if(!document.getElementById("my-timeline"))
			return false;
			
		tl["preview"] = Timeline.create(document.getElementById("my-timeline"), resetTimeLine(edit));
		if(!preview){
			curl = window.app_config.backend + "/index.php?module=timeline&action=populatetimeline&itemid=" + iid;
		}
		else{
			curl = window.app_config.backend + "/index.php?module=timeline&action=populatetimeline&preview=yes&itemid=" + iid;
		}
		tl["preview"].layout();
		Timeline.loadJSON(curl, function(data, url) {eventSource[srckey].loadJSON(data, url); });
	}
	else {
		if(!document.getElementById("timeline_edit"))
			return false;
			
		tl["edit"] = Timeline.create(document.getElementById("timeline_edit"), resetTimeLine(edit));
		curl =  window.app_config.backend + "/index.php?module=timeline&action=populatetimeline&backend=yes&itemid=" + iid;
		tl["edit"].layout();
	}
	
	centerTimeLine(new Date(), edit); 	
	
	return true;
}

var resizeTimerID = null;

function backendRefresh(timelines){
		tl["edit"] = Timeline.create(document.getElementById("timeline_edit"), resetTimeLine(true));
		var curl =  window.app_config.backend + "/index.php?module=timeline&action=populatetimeline&backend=yes&timelineids=" + timelines;
		tl["edit"].loadJSON(curl, function(data, url) { eventSource['edit'].loadJSON(data, url); });
}

function TimeLineonResize() {
	if (resizeTimerID == null && (document.getElementById("timeline_edit") || document.getElementById("my-timeline"))) {
		resizeTimerID = window.setTimeout(function() {
			resizeTimerID = null;
			
			for(var i in tl){
            	tl[i].layout();
			}
			
        }, 500);
    }
}

function doCenterTimeLine(elem, edit) {
	//used in frontend
	
	if(elem && elem.value){
		var parts = elem.value.split("-");
		var cdte = new Date();
		cdte.setDate(parts[2]);
		cdte.setMonth(parts[1] - 1);
		cdte.setYear(parts[0]);
		
		centerTimeLine(cdte, edit);
	}
}

function centerTimeLine(date, edit){
	var key = edit?"edit":"preview";
	var curtl = tl[key];
	curtl.getBand(0).setCenterVisibleDate(date); 
	curtl.getBand(1).setCenterVisibleDate(date);// new Date(year, 0, 1)
}

Timeline._Band.prototype.getViewWidth=function(){
	if(this._timeline.isHorizontal()){
		return this._div.offsetHeight==0?4:this._div.offsetHeight;
	}else{
		return this._div.offsetWidth==0?4:this._div.offsetWidth;;
	}
};

Timeline.Debug.exception=function(e){
	alert(e.message);
	//debugger;
};

Timeline.DefaultEventSource.prototype._fire=function(handlerName,args){
	for(var i=0;i<this._listeners.length;i++){
		var listener=this._listeners[i];
		if(handlerName in listener){
			listener[handlerName].apply(listener,args);
		}
	}
};

Timeline.XmlHttp._onReadyStateChange=function(xmlhttp,fError,fDone){
	switch(xmlhttp.readyState){
		case 4:
			if(xmlhttp.status==0 ||xmlhttp.status==200){
				if(fDone){
					fDone(xmlhttp);
				}
			}else{
				if(fError){
					fError(xmlhttp.statusText, xmlhttp.status,xmlhttp);
				}
			}
		
		break;
	}
};

Timeline._Band.prototype.removeLayerDiv=function(div){
	try{
		this._innerDiv.removeChild(div.parentNode);
	}
	catch(e){
		try {
			this._innerDiv.removeChild(div); //ie hack
		}
		catch(e2){}
	}
};
