// JavaScript Document

 var tl;
 function onLoad(bepcmp) {
   var eventSource = new Timeline.DefaultEventSource();
   
   var theme = Timeline.ClassicTheme.create();
	theme.event.label.width = 250; // px
	theme.event.bubble.width = 250;
	theme.event.bubble.height = 200;
	//theme.event.tape.height = 10;
	theme.event.highlightColors[0]='#ee2424';
	theme.event.highlightColors[1]='#242eee';
	theme.event.highlightColors[2]='#24ee33';
	theme.event.highlightColors[3]='#ebfd22';
	theme.event.track.height = 0.5;
    theme.event.tape.height = 0.5;
	theme.mouseWheel = 'default'
   
   var bandInfos = [
     Timeline.createBandInfo({
		 eventSource:    eventSource,
         date:           "Jun 28 2008 00:00:00 GMT",
         width:          "85%", 
         intervalUnit:   Timeline.DateTime.MONTH, 
         intervalPixels: 100,
		 trackHeight:	 0.5,
		 trackGap:		 0.2,
		 layout:		 'original',
		 opacity: 75,
		 theme:	theme
     }),
     Timeline.createBandInfo({
		 eventSource:    eventSource,
         date:           "Jun 28 2008 00:00:00 GMT",
         width:          "15%", 
         intervalUnit:   Timeline.DateTime.YEAR, 
         intervalPixels: 100,
		 layout:		 'overview',
		 opacity: 75,
		 theme: theme
     })
   ];
  bandInfos[1].syncWith = 0;
  bandInfos[1].highlight = true;
   
    //bandInfos[1].eventPainter.setLayout(bandInfos[0].eventPainter.getLayout());
	
	for (var i = 0; i < bandInfos.length; i++) {
		bandInfos[i].decorators = [
		
			new Timeline.SpanHighlightDecorator({
				startDate: "Mon Oct 1 2007 12:30:00 GMT-0600",
				endDate: "Tue Sep 30 2008 13:00:00 GMT-0600",
				color: "#FFFFFF",
				opacity: 25,
				startLabel: "Beg FY08",
				endLabel: "End FY08",
				theme: theme
		}),
			new Timeline.PointHighlightDecorator({
			date: "Mon Oct 1 2007 12:30:00 GMT-0600",
			color: "#FFC080",
			opacity: 25,
			theme: theme
		}),
			new Timeline.PointHighlightDecorator({
			date: "Tue Sep 30 2008 13:00:00 GMT-0600",
			color: "#FFC080",
			opacity: 25,
			theme: theme
			})
		];
	}
   
   tl = Timeline.create(document.getElementById("timeline"), bandInfos);
   Timeline.loadXML("xml/kmp_" + bepcmp + ".xml", function(xml, url) { eventSource.loadXML(xml, url); });
   
   setupFilterHighlightControls(document.getElementById("controls"), tl, [0,1], theme);
 }

 var resizeTimerID = null;
 function onResize() {
     if (resizeTimerID == null) {
         resizeTimerID = window.setTimeout(function() {
             resizeTimerID = null;
             tl.layout();
         }, 500);
     }
 }
 
 
/*
 
 function centerTimeline(date) {
 	tl.getBand(0).setCenterVisibleDate(Timeline.DateTime.parseGregorianDateTime(date));
 }

  function setupFilterHighlightControls(div, timeline, bandIndices, theme) {
	 
	timeline.DOM = new Object();
	  
	var table = document.createElement("table");
	var tr = table.insertRow(0);
	var td = tr.insertCell(0);
	
	td.innerHTML = "Filter:";
 	td = tr.insertCell(1);
 	td.innerHTML = "Highlight:";

 	var handler = function(elmt, evt, target) {
 		onKeyPress(timeline, bandIndices, table);
 	};

 	tr = table.insertRow(1);
 	tr.style.verticalAlign = "top";

 	td = tr.insertCell(0);

 	var input = document.createElement("input");
 	input.type = "text";
 	timeline.DOM.registerEvent(input, "keypress", handler);
 	td.appendChild(input);

 	for (var i = 0; i < theme.event.highlightColors.length; i++) {
 		td = tr.insertCell(i + 1);

 		input = document.createElement("input");
 		input.type = "text";
 		Timeline.DOM.registerEvent(input, "keypress", handler);
 		td.appendChild(input);

 		var divColor = document.createElement("div");
 		divColor.style.height = "0.5em";
 		divColor.style.background = theme.event.highlightColors[i];
 		td.appendChild(divColor);
 	}

 	td = tr.insertCell(tr.cells.length);
	var button = document.createElement("button");
 	button.innerHTML = "Clear All";
 	Timeline.DOM.registerEvent(button, "click", function() {
 	clearAll(timeline, bandIndices, table);
 	});
 	td.appendChild(button);

 	div.appendChild(table);
}

	var timerID = null;
	function onKeyPress(timeline, bandIndices, table) {
 		if (timerID != null) {
 		window.clearTimeout(timerID);
 	}
 		timerID = window.setTimeout(function() {
 			performFiltering(timeline, bandIndices, table);
 		}, 300);
	}
	
	function cleanString(s) {
 		return s.replace(/^\s+/, '').replace(/\s+$/, '');
	}
	function performFiltering(timeline, bandIndices, table) {
 		timerID = null;

 	var tr = table.rows[1];
 	var text = cleanString(tr.cells[0].firstChild.value);

 	var filterMatcher = null;
 	if (text.length > 0) {
 	var regex = new RegExp(text, "i");
 	filterMatcher = function(evt) {
 	return regex.test(evt.getText()) || regex.test(evt.getDescription());
 	};
 }

	var regexes = [];
 	var hasHighlights = false;
 	for (var x = 1; x < tr.cells.length - 1; x++) {
 		var input = tr.cells[x].firstChild;
 		var text2 = cleanString(input.value);
 		if (text2.length > 0) {
 			hasHighlights = true;
 			regexes.push(new RegExp(text2, "i"));
 		} else {
 			regexes.push(null);
 		}
 	}
 	var highlightMatcher = hasHighlights ? function(evt) {
 	var text = evt.getText();
 	var description = evt.getDescription();
 	for (var x = 0; x < regexes.length; x++) {
 		var regex = regexes[x];
 		if (regex != null && (regex.test(text) || regex.test(description))) {
 		return x;
 	}
 }
 return -1;
 } : null;
 
  for (var i = 0; i < bandIndices.length; i++) {
 		var bandIndex = bandIndices[i];
 		timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(filterMatcher);
 		timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(highlightMatcher);
 	}
 	timeline.paint();
	}
	function clearAll(timeline, bandIndices, table) {
 		var tr = table.rows[1];
 		for (var x = 0; x < tr.cells.length - 1; x++) {
 		tr.cells[x].firstChild.value = "";
 	}

 	for (var i = 0; i < bandIndices.length; i++) {
 		var bandIndex = bandIndices[i];
 		timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(null);
 		timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(null);
 	}
 	timeline.paint();
	}
	
	*/
	
	function centerTimeline(date) {
    tl.getBand(0).setCenterVisibleDate(Timeline.DateTime.parseGregorianDateTime(date));
}


var numOfFilters = 4;

function setupFilterHighlightControls(div, timeline, bandIndices, theme) {
   
   var message = "";
    // Init Handler
    var handler = function(elmt, evt, target) {
        onKeyPress(timeline, bandIndices, table);
    };
   
   
    // Create Table
    var table = document.createElement("table");
   
    // First Row
    var tr = table.insertRow(0);
    var td = tr.insertCell(0);
	td.colSpan = "4";
	td.align = "center";
    td.innerHTML = "Click and Drag to Move Along Timeline";
   
      
    // Second Row
    tr = table.insertRow(1);
    tr.style.verticalAlign = "top";
   
    /* Create the text inputs for the filters and add eventListeners */
    for(var i=0; i<numOfFilters; i++) {     
        td = tr.insertCell(i); 
        var input = document.createElement("input");
        input.type = "text";
        //SimileAjax.DOM.registerEvent(input, "keypress", handler);
        td.appendChild(input);
        input.id = "filter"+i; 
    }
   
    // Third Row
	/*
    tr = table.insertRow(2);
    td = tr.insertCell(0);
       td.innerHTML = "Highlights:";
   
   
    // Fourth Row
       tr = table.insertRow(3);
   */
       /* Create the text inputs for the highlights and add event listeners */
	/*
       for (var i = 0; i < theme.event.highlightColors.length; i++) {
           td = tr.insertCell(i);
       
           input = document.createElement("input");
           input.type = "text";
           SimileAjax.DOM.registerEvent(input, "keypress", handler);
           td.appendChild(input);
       
        input.id = "highlight"+i;
       
        var divColor = document.createElement("div");
        divColor.style.height = "0.5em";
        divColor.style.background = theme.event.highlightColors[i];
        td.appendChild(divColor);
    }
   */
    // Fifth Row
      
    tr = table.insertRow(2);
	td = tr.insertCell(0);
    td = tr.insertCell(1);
   
    // create the filter button
    var filterButton = document.createElement("button");
    filterButton.innerHTML = "Filter";
    filterButton.id = "filter"
    filterButton.className = "buttons"
    SimileAjax.DOM.registerEvent(filterButton, "click", handler);
    td.appendChild(filterButton);
   
   
    // create the clear all button
    td = tr.insertCell(2);
    var highlightButton = document.createElement("button");
    highlightButton.innerHTML = "Clear All";
    highlightButton.id = "clearAll"
    highlightButton.className = "buttons"
    SimileAjax.DOM.registerEvent(highlightButton, "click", function() {
        clearAll(timeline, bandIndices, table);
    });
    td.appendChild(highlightButton);
   
   // Create the Legend
    tr = table.insertRow(3);
	td = tr.insertCell(0);
	td.align = "center";
	td.colSpan = "4";
	
	td.innerHTML="<img src='images/ms-dark-black-circle.png'> Legacy Migration  " + 
					"<img src='images/Check.gif'> Met  " + 
					"<img src='images/ms-dark-green-circle.png'> On Track  " + 
					"<img src='images/ms-dark-blue-circle.png'> Slipped  " + 
					"<img src='images/ms-dark-yellow-circle.png'> At Risk  " + 
					"<img src='images/ms-dark-Orange-circle.png'> Admin Correction  " + 
					"<img src='images/ms-dark-red-circle.png'> Deleted";

/*
	var img1 = document.createElement("image");
	img1.src="images/ms-dark-black-circle.png";
	td.appendChild(img1);
	
	message = " Legacy Migration  ";
	td.appendChild(document.createTextNode(message));
	
	var img2 = document.createElement("image");
	img2.src="images/Check.gif";
	td.appendChild(img2);
	
	message = " Met  ";
	td.appendChild(document.createTextNode(message));
	
	var img3 = document.createElement("image");
	img3.src="images/ms-dark-green-circle.png";
	td.appendChild(img3);
	
	message = " On Track  ";
	td.appendChild(document.createTextNode(message));
	
	var img4 = document.createElement("image");
	img4.src="images/ms-dark-blue-circle.png";
	td.appendChild(img4);

   	message = " Slipped  ";
	td.appendChild(document.createTextNode(message));
	
	var img5 = document.createElement("image");
	img5.src="images/ms-dark-yellow-circle.png";
	td.appendChild(img5);
	
	message = " At Risk  ";
	td.appendChild(document.createTextNode(message));
	
	var img5 = document.createElement("image");
	img5.src="images/ms-dark-Orange-circle.png";
	td.appendChild(img5);
	
	message = " Admin Correction  ";
	td.appendChild(document.createTextNode(message));
	
	var img6 = document.createElement("image");
	img6.src="images/ms-dark-red-circle.png";
	td.appendChild(img6);
		
	message = " Deleted  ";
	td.appendChild(document.createTextNode(message));
*/
    // Append the table to the div
    div.appendChild(table);
}

var timerID = null;
var filterMatcherGlobal = null;
var highlightMatcherGlobal = null;

function onKeyPress(timeline, bandIndices, table) {
    if (timerID != null) {
        window.clearTimeout(timerID);
    }
    timerID = window.setTimeout(function() {
        performFiltering(timeline, bandIndices, table);
    }, 300);
}
function cleanString(s) {
    return s.replace(/^\s+/, '').replace(/\s+$/, '');
}

function performFiltering(timeline, bandIndices, table) {
    timerID = null;
    var tr = table.rows[1];
   
    // Add all filter inputs to a new array
    var filterInputs = new Array();
    for(var i=0; i<numOfFilters; i++) {
      filterInputs.push(cleanString(tr.cells[i].firstChild.value));
    }
   
    var filterMatcher = null;
    var filterRegExes = new Array();
    for(var i=0; i<filterInputs.length; i++) {
        /* if the filterInputs are not empty create a new regex for each one and add them
        to an array */
        if (filterInputs[i].length > 0){
                        filterRegExes.push(new RegExp(filterInputs[i], "i"));
        }
                filterMatcher = function(evt) {
                        /* iterate through the regex's and check them against the evtText
                        if match return true, if not found return false */
                        if(filterRegExes.length!=0){
                           
                            for(var j=0; j<filterRegExes.length; j++) {
                                    if(filterRegExes[j].test(evt.getText()) == true){
                                        return true;
                                    }
                            }
                        }
                        else if(filterRegExes.length==0){
                            return true;
                        }    
                   return false;
                };
    }
   /*
    var regexes = [];
    var hasHighlights = false;
    tr=table.rows[3];
    for (var x = 0; x < tr.cells.length; x++) {
        var input = tr.cells[x].firstChild;
        var text2 = cleanString(input.value);
        if (text2.length > 0) {
            hasHighlights = true;
            regexes.push(new RegExp(text2, "i"));
        } else {
            regexes.push(null);
        }
    }
    var highlightMatcher = hasHighlights ? function(evt) {
        var text = evt.getText();
        var description = evt.getDescription();
        for (var x = 0; x < regexes.length; x++) {
            var regex = regexes[x];
            //if (regex != null && (regex.test(text) || regex.test (description))) {
            if (regex != null && regex.test(text)) {
                return x;
            }
        }
        return -1;
    } : null;*/
   
    // Set the matchers and repaint the timeline
    filterMatcherGlobal = filterMatcher;
   // highlightMatcherGlobal = highlightMatcher;   
    for (var i = 0; i < bandIndices.length; i++) {
        var bandIndex = bandIndices[i];
        timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(filterMatcher);
        //timeline.getBand(bandIndex).getEventPainter ().setHighlightMatcher(highlightMatcher);
    }
    timeline.paint();
}



function clearAll(timeline, bandIndices, table) {
   
    // First clear the filters
    var tr = table.rows[1];
    for (var x = 0; x < tr.cells.length; x++) {
        tr.cells[x].firstChild.value = "";
    }
   
    // Then clear the highlights
   // var tr = table.rows[3];
    //for (var x = 0; x < tr.cells.length; x++) {
    //   tr.cells[x].firstChild.value = "";
   // }
   
    // Then re-init the filters and repaint the timeline
    for (var i = 0; i < bandIndices.length; i++) {
        var bandIndex = bandIndices[i];
        timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(null);
        timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(null);
    }
    timeline.paint();
}