
Array.prototype.exists = function (x) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
    }
    return false;
}

// Get the HTTP Object
function getHTTPObject() {

    if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
    else if (window.XMLHttpRequest) return new XMLHttpRequest();
    else {
        alert("Your browser does not support AJAX.");
        return null;
    }
}


// Change the value of the outputText field
function setOutputHiddenDiv() {
    if (httpObject.readyState == 4) {
        document.getElementById('hiddendiv').innerHTML = httpObjectHiddenDiv.responseText;
    }

}

// Change the value of the outputText field
function setOutput() {
    if (httpObject.readyState == 4) {
        document.getElementById('station_desc').innerHTML = httpObject.responseText;
    }

}

// Change the value of the outputText field
function setGraphOutput() {
    if (httpObject2.readyState == 4) {
        document.getElementById('graph_content').innerHTML = httpObject2.responseText;
    }

}

function updateHiddenDiv(source){
	httpObjectHiddenDiv = getHTTPObject();

    if (httpObjectHiddenDiv != null) {
        httpObjectHiddenDiv.open("GET", source, true);
        httpObjectHiddenDiv.send(null);
        httpObjectHiddenDiv.onreadystatechange = setOutputHiddenDiv;
    }
}

function updateStationDisplay(stationid){
	httpObject = getHTTPObject();

    if (httpObject != null) {
        httpObject.open("GET", "Ajax_StationInfo.php?stationid="+stationid, true);
        httpObject.send(null);
        httpObject.onreadystatechange = setOutput;
    }
}

function updateGraphDisplay(stationid, chartMode, chartType, dataType, chartDate){
	
	//alert(dataType.length);
	if (dataType.length > 0){
		httpObject2 = getHTTPObject();

    	if (httpObject2 != null) {
        	httpObject2.open("GET", "Ajax_ChartDisplay.php?stationid="+stationid+"&chartmode="+chartMode+"&chartType="+chartType+"&dataType="+dataType+"&chartDate="+chartDate, true);
        	httpObject2.send(null);
        	httpObject2.onreadystatechange = setGraphOutput;
    	}
	} else {
		alert("Please, select a valid type of graph");
	}

}

// Implement business logic
function doWork(stationid) {
	
	updateStationDisplay(stationid);
	updateGraphDisplay(stationid, "rt", "station", "nbBikes", "today");

}

function showHidden (source){
	
	updateHiddenDiv(source);
	document.getElementById('hiddendiv').style.zIndex=2000;
	
}

function hideHidden (){
	document.getElementById('hiddendiv').style.zIndex=0;
	document.getElementById('hiddendiv').innerHTML = '';
}

var httpObject = null;

//Useful extention of the GMarker class
GMarker.prototype.markerCategory = "DEFAULT";
GMarker.prototype.stationId = 0;


var CAT_LIST = [];
var CAT_ICONS = [];
//The index of publicMarkerArray is the station ID. But there are holes in station Id... so not easy to go thru it
var publicMarkerArray = [];
//counterToStationIdArray is there to "fill" the holes of publicMarkerArray. 
var counterToStationIdArray = [];
// Call publicMarkerArray to interact directly with the station Id, call counterToStationIdArray to iterate thru all the markers...
var mode = "normal";


function generateIcons(mode, xmlArray){
    for (var i = 0; i < xmlArray.length; i++) {
        var xmlMode = xmlArray[i].getAttribute("mode");
        var order = xmlArray[i].getAttribute("order");
        var description = xmlArray[i].getAttribute("desc");
        var iconFile = xmlArray[i].getAttribute("name");
		if(xmlMode == mode){
			myImage = new Image();
		    var myIcon = new GIcon(G_DEFAULT_ICON);
			myImage.src = "http://dataholic.ca/bix/icons/"+ iconFile;
		    myIcon.image = "http://dataholic.ca/bix/icons/"+ iconFile;
		    myIcon.shadow = "http://dataholic.ca/bix/icons/ICON_station_small_shadow.png";

		    myIcon.iconSize = new GSize(27, 29);
		    myIcon.iconAnchor = new GPoint(8, 24);
		    myIcon.markerCategory = description;
					
			CAT_LIST[order] = description;
			CAT_ICONS[description] = myIcon;
		}

    }
}

var iterator = 0;

function timeLapse(){
	//alert(iterator);
	GDownloadUrl("XML/TimelapseData_20091123.xml",
    function(timelapstdata, responseCode) {
    	var timelaspsexml = GXml.parse(timelapstdata);
		var xmlElements = timelaspsexml.documentElement.getElementsByTagName("segment");
		var time = xmlElements[iterator].getAttribute("time");
		document.getElementById('station_desc').innerHTML = time;
		//alert("time xml : " + time);
		
		//var pointList = xmlElements[iterator].childNodes;
		var pointList = xmlElements[iterator].getElementsByTagName("point");
		for (i=0; i<pointList.length; i++){
			var str = "http://dataholic.ca/bix/icons/ICON_station_small_" + pointList[i].getAttribute("color") + ".png";
			publicMarkerArray[pointList[i].getAttribute("id")].setImage(str);
		}

		
		//alert("Nombre d'enfants: " +pointList[0].getAttribute("color"));
		iterator++;
		//timeLapse(iterator);
		setTimeout('timeLapse()',500);		
		//myMarkerManager.startTimeLapse();
	});

	
}

//Object containing an array of all the markers of the map
function markerManager(map, division) {

    this.markerArray = [];

    var inputTag = [];

    for (var i = 0; i < CAT_LIST.length; i++) {

        var catDiv = document.createElement("div");
        catDiv.className = "catDiv";
        division.appendChild(catDiv);

        var icon = document.createElement('img');
        icon.src = CAT_ICONS[CAT_LIST[i]].image;
        icon.alt = "Icon";
        catDiv.appendChild(icon);

        inputTag[i] = document.createElement("input");
        inputTag[i].type = "checkbox"
        inputTag[i].checked = true;
        inputTag[i].name = "catList";
        inputTag[i].id = CAT_LIST[i];
        catDiv.appendChild(inputTag[i]);

        var label = document.createTextNode(CAT_LIST[i]);
        catDiv.appendChild(label);

        //var sautligne = document.createElement('br');
        //division.appendChild(sautligne);

    }


    this.pushMarker = function(marker) {
		counterToStationIdArray.push(marker.stationId);
        this.markerArray[marker.stationId] = marker;
		//this.markerArray.push(marker);
        //map.addOverlay(marker);
        publicMarkerArray = this.markerArray;
    };

    function updateMarkers() {
        for (var i = 0; i < counterToStationIdArray.length; i++) {
            if (document.getElementById(publicMarkerArray[counterToStationIdArray[i]].markerCategory).checked) {
                publicMarkerArray[counterToStationIdArray[i]].show();
            } else {
                publicMarkerArray[counterToStationIdArray[i]].closeInfoWindow();
                publicMarkerArray[counterToStationIdArray[i]].hide();
            }
        }
    }

    for (var i = 0; i < inputTag.length; i++) {
        inputTag[i].onclick = updateMarkers;
    }

    this.inputTag = inputTag;
}



//Object containing all the marker info
function markerObject(xmlElement, category, map) {
    this.theIcon = CAT_ICONS[category];
    this.point = new GLatLng(parseFloat(xmlElement.getAttribute("lat")), parseFloat(xmlElement.getAttribute("lng")));

    this.marker = new GMarker(this.point, {
        icon: this.theIcon
    });
    this.marker.markerCategory = category;
    this.marker.stationId = xmlElement.getAttribute("id");

    map.addOverlay(this.marker);


    var infoWindowsText = "<b>" + xmlElement.getAttribute("name");
    infoWindowsText += "</b> (" + this.marker.stationId + ")";
    infoWindowsText += "<br/><i>Velos:</i> " + xmlElement.getAttribute("bikes");
    infoWindowsText += "<br/><i>Places:</i> " + xmlElement.getAttribute("avail");

	var myMarker = this.marker; 
    GEvent.addListener(myMarker, "click", function() {
              doWork(myMarker.stationId);
    });

    this.marker.bindInfoWindow(infoWindowsText);


    return this.marker;
}


//Main function called onload of the document
function initialize() {
	
	updateGraphDisplay("", "rt", "network", "nbBikes", "");
	updateStationDisplay("network");
	
    if (GBrowserIsCompatible()) {
        var division = document.getElementById('cat_content');
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(45.5114, -73.56977), 13);
        map.setUIToDefault();
		
        GDownloadUrl("XML/markerdata_RT.xml",
        function(data, responseCode) {
            var xml = GXml.parse(data);

			var iconXmlElements = xml.documentElement.getElementsByTagName("icon");
			if (mode == "normal"){
				generateIcons(mode, iconXmlElements);
			}
			

            var myMarkerManager = new markerManager(map, division);
            var xmlElements = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < xmlElements.length; i++) {

                var theCat = xmlElements[i].getAttribute("cat");
                var marker = new markerObject(xmlElements[i], theCat, map);
                myMarkerManager.pushMarker(marker);

            }


			if (mode == "timelapse"){
				setTimeout('timeLapse()',15000);
			}
			


        });

    }
}

