﻿//<![CDATA[    

var _map = null;
var _progressBar = null;
var _timer = null;
var _priceWinnerLists = null;
var _priceWinnerList = null;
var _pwlNr = 0;
var _pwNr = 0;
var _totalMarkers = 0;
var _markersArray = [];
var _markersArrayNr = 0;
var _min = 0;
var _max = 12;
var _blXmlIsLoaded = false;

/// Init google map.
function initGoogleMap() {
    if (GBrowserIsCompatible()) {
        _map = new GMap2($get("mapContainer"));
        _map.addControl(new GLargeMapControl3D());
        _map.enableScrollWheelZoom();
        _map.setMapType(G_PHYSICAL_MAP);
        _map.setCenter(new GLatLng(52.422523, 5.339355), 8);
        _map.addControl(new monthControl());      

        // Create progress bar for the markers.
        _progressBar = new progressBarControl();
        
        // Add eventlistener to check the zoom level.
        GEvent.addListener(_map, "zoomend", checkZoomLevel);   
    
        // Load XML file
        loadXML();
    }
}
/// Load the XML file.
function loadXML() {
    GDownloadUrl("/_handlers/DataFileRequestHandler.ashx?strFile=priceWinners.xml", function(data, responseCode) {
        // Check response code.
        if (responseCode == 200) {
            
            // Get XML data.
            var xml = GXml.parse(data);
            
            // Get price winners list from XML document.
            _priceWinnerLists = xml.documentElement.getElementsByTagName("PriceWinnerList");
            
            // Create checkboxes and markers.
            createCheckBoxes();            
        } else if (responseCode == -1) {
            alert("Data request timed out. Probeer het later nog eens.");
        } else {
            alert("Er is een fout opgetreden. De prijswinnaars kunnen niet geladen worden.");
        }
    });
}
/// Check zoom level of the google map.
/// Client cannot exceed a zoomlevel of 10.
function checkZoomLevel() {
    czoomlevel = _map.getZoom();

    if (czoomlevel > 10) {
        _map.setZoom(10);
    }
}
/// Set time out to load the create the markers.
function loadMarkers() {  
    setTimeout('createMarker()', 1000);
}
/// Create the marker.
function createMarker() {
    // Set reference to list.
    _priceWinnerList = _priceWinnerLists[_pwlNr];

    // Set variables.
    var month = month = _priceWinnerList.getAttribute("month");
    var year = _priceWinnerList.getAttribute("year");

    // Check if list is visible.
    if (_priceWinnerLists[_pwlNr].getAttribute("visible") == "True") {
        
        // Set reference to pricewinner.
        var priceWinner = _priceWinnerList.childNodes[_pwNr];

        // Check if lat lng are larger than 0.
        if (!isIgnorable(priceWinner)) {
            if (parseFloat(priceWinner.getAttribute("lat")) > 0 && parseFloat(priceWinner.getAttribute("lng")) > 0) {

                // Create point.
                var point = new GLatLng(parseFloat(priceWinner.getAttribute("lat")), parseFloat(priceWinner.getAttribute("lng")));

                // Create new icon.
                var icon = new GIcon();
                var strWinnerTypeName;
                switch (priceWinner.getAttribute("winnerType")) {
                    case "1":
                        icon.image = "http://stibat.nl/_images/googleMaps/winner50.png";
                        strWinnerTypeName = "VVV Cadeaubonnen t.w.v. &euro; 50,-";
                        icon.iconSize = new GSize(15, 15);
                        break;
                    case "2":
                        icon.image = "http://stibat.nl/_images/googleMaps/winner2000.png";
                        strWinnerTypeName = "Reischeque t.w.v. &euro; 2000,-";
                        icon.iconSize = new GSize(18, 18);
                        break;
                }
                
                icon.iconAnchor = new GPoint(1, 1);
                icon.infoWindowAnchor = new GPoint(5, 6);
                icon.infoShadowAnchor = new GPoint(5, 6);
                icon.imageMap = [5, 5];

                // Create HTML for marker.
                var html = "<h1>" + priceWinner.getAttribute("placeOfResidence") + "</h1><h2>" + strWinnerTypeName + "</h2><p>" + getMonthName(month) + " - " + year + "</p>";

                // Add marker to _map.
                var marker = new GMarker(point, icon);
                GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(html);
                });

                // Init and fill array.
                _markersArray[_markersArrayNr] = new Array(2);
                _markersArray[_markersArrayNr][0] = _priceWinnerLists[_pwlNr].getAttribute("pwlId");
                _markersArray[_markersArrayNr][1] = marker;
                _markersArrayNr++;

                // Add marker to map.
                _map.addOverlay(marker);

                // Update progressBar.
                _progressBar.updateLoader(1);
            }
        }
    }
    
    _pwNr++;

    if (_pwNr < _priceWinnerList.childNodes.length && _priceWinnerLists[_pwlNr].getAttribute("visible") == "True") {
        setTimeout('createMarker()', 25);
    } else {
        _pwNr = 0;
        _pwlNr++;
        
        if (_pwlNr < _priceWinnerLists.length) {
            setTimeout('createMarker()', 25);
        } else {
            // Remove progressBar when finished.
            _progressBar.remove();
        }
    }
}
/// Remove the markers.
function removeMarkers() {
    // Remove markers based on the selected pwlId.
    if (_priceWinnerList != null) {
        for (var i = 0; i < _markersArray.length; i++) {
            if (_markersArray[i][0] == _priceWinnerList.getAttribute("pwlId")) {
                _map.removeOverlay(_markersArray[i][1]);
            }
        }
    }
}
/// Add the markers.
function addMarkers() {
    // Add markers based on the selected pwlId.
    if (_priceWinnerList != null) {
        for (var i = 0; i < _markersArray.length; i++) {
            if (_markersArray[i][0] == _priceWinnerList.getAttribute("pwlId")) {
                _map.addOverlay(_markersArray[i][1]);
            }
        }
    }
}
/// Create check boxes based on the months.
/// Count total markers.
/// Load markers.
function createCheckBoxes() {
    var monthArray = [];
    var intMonthNr = 0;

    if (_priceWinnerLists != null) {
        for (var i = 0; i < _priceWinnerLists.length; i++) {
            if (_priceWinnerLists[i].getAttribute("visible") == "True") {
				
				// Add paramenter to array.
                monthArray[intMonthNr] = _priceWinnerLists[i].getAttribute("year") + "-" + _priceWinnerLists[i].getAttribute("month") + "-" + _priceWinnerLists[i].getAttribute("pwlId");

                // Calculate total makers.
                if (navigator.appName == "Netscape") {
                    // FF 3.0 issue not solved - FF 3.0 counts whitespaces as nodes.
                    for (var ii = 0; ii < _priceWinnerLists[i].childNodes.length; ii++) {
                        if (!isIgnorable(_priceWinnerLists[i].childNodes[ii]))
                            _totalMarkers++;
                    }
                } else {
                    _totalMarkers = _totalMarkers + _priceWinnerLists[i].childNodes.length;
                }

                intMonthNr++;
            }
        }
		
        // Sort array.
        monthArray.sort(function(a,b){return a - b});
        
        // Create checkboxes.
        for (var i = 0; i < monthArray.length; i++) {
            var chars = monthArray[i].split("-");
            createCheckBox(chars[2], chars[1], chars[0]);
        }
        
        if (_totalMarkers > 0) {
            // Set progressBar.
            _progressBar.start(_totalMarkers);

            // Load markers.
            loadMarkers();
        }
    }
}

/// Create a check monthBox.
function createCheckBox(id, month, year){
    var monthBox = $get("monthBox");
    
    try {
        var cb = document.createElement("<input name=\"marker\" id=\"pwl_" + id + "\" type=\"checkbox\" onclick=\"toggleMonth(this.checked, this.id)\" style=\"margin-right:5px;\" checked>"); 
    } catch (e) {   
        var cb = document.createElement("input");   
        cb.type = "checkbox";
        cb.id = "pwl_" + id;
        cb.setAttribute("onclick", "toggleMonth(this.checked, this.id)");
        cb.checked = true;
    }

    var text = document.createTextNode(getMonthName(month) + " " + year);
    var br = document.createElement("br");
    monthBox.appendChild(cb);
    monthBox.appendChild(text);
    monthBox.appendChild(br);
}
/// Get the name of the month based on month number.
function getMonthName(intMonth) {
    var strName;

    switch (intMonth) {
        case "1":
            strName = "januari";
            break;
        case "2":
            strName = "februari";
            break;
        case "3":
            strName = "maart";
            break;
        case "4":
            strName = "april";
            break;
        case "5":
            strName = "mei";
            break;
        case "6":
            strName = "juni";
            break;
        case "7":
            strName = "juli";
            break;
        case "8":
            strName = "augustus";
            break;
        case "9":
            strName = "september";
            break;
        case "10":
            strName = "oktober";
            break;
        case "11":
            strName = "november";
            break;
        case "12":
            strName = "december";
            break;
    }

    return strName;
}
/// FF 3.0 Whitespace in the DOM issue functions.
/// https://developer.mozilla.org/en/Whitespace_in_the_DOM
function isAllWhitespace(nod) {
    // Use ECMA-262 Edition 3 String and RegExp features.
    return !(/[^\t\n\r ]/.test(nod.data));
}
// Check if node is a comment or text node.
function isIgnorable(nod) {
    return (nod.nodeType == 8) || // A comment node
         ((nod.nodeType == 3) && isAllWhitespace(nod)); // a text node, all ws.
}
/// Toggle month.
function toggleMonth(checked, id) {
    if (id.indexOf("pwl_") == 0) {
        var pwlId = id.replace("pwl_", "");

        if (_priceWinnerLists != null) {
            for (var i = 0; i < _priceWinnerLists.length; i++) {
                if (_priceWinnerLists[i].getAttribute("pwlId") == pwlId) {
                    _priceWinnerList = _priceWinnerLists[i];
                    break;
                }
            }
            if (checked && _priceWinnerList != null) {
                addMarkers();
            } else if (_priceWinnerList != null) {
                removeMarkers();
            }
        }
    }
}
/// Show monthBox with months.
function showMonthbox() {
    // clear time out.
    if (window._timer)
        clearTimeout(_timer);
        
    // Get monthBox and set display to block.
    $get("monthBox").style.display = "block";
}
/// Close month monthBox.
function closeMonthbox() {
    // Get monthbox.
    var monthBox = $get("monthBox");
    
    // Set display none.
    _timer = window.setTimeout(function() {
        monthBox.style.display = "none";
    }, 400);
}
/// Initiate month control.
function monthControl() {};
monthControl.prototype = new GControl();
monthControl.prototype.initialize = function(_map) {
    // Get month control
    var monthCtrl = $get("monthControl");
    
    // Get month button.
    var monthBtn = document.createElement("div");
    monthBtn.id = "monthControlButton";
    monthBtn.title = "Vink maanden aan/uit";
    
    // Create element container.
    var monthCtrlContainer = document.createElement("div");
    monthCtrlContainer.id = "monthControlContainer";
    
    // Create element with text.
    var monthCtrlText = document.createElement("div");
    monthCtrlText.id = "monthControlText";
    
    // Append text element to container.
    monthCtrlContainer.appendChild(document.createTextNode("Selecteer maanden"));
    
    // Append container and text.
    monthBtn.appendChild(monthCtrlContainer);
    monthBtn.appendChild(monthCtrlText);
    
    // Register Event handlers.
    monthCtrl.onmouseover = showMonthbox;
    monthCtrl.onmouseout = closeMonthbox;

    // Insert the button just after monthControl div.
    monthCtrl.insertBefore(monthBtn, $get("monthBox"));
    
    // Remove the whole div from its location and reinsert it to the _map
    _map.getContainer().appendChild(monthCtrl);
    
    // Return the control.
    return monthCtrl;
}
/// Position month control.
monthControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(395, 7));
}
/// Create progress bar control.
function progressBarMapControl() {}
progressBarMapControl.prototype = new GControl(true, false);
/// Create progress bar control.
progressBarMapControl.prototype.initialize = function() {
    var progressBarContainer = document.createElement('div');
    progressBarContainer.innerHTML = '<div id="progressBarText"></div><div id="progressBarBorder"><div id="progressBar"></div></div>';
    progressBarContainer.id = "progressBarContainer";
    _map.getContainer().appendChild(progressBarContainer);
    return progressBarContainer;
};
/// Position progress bar control.
progressBarMapControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(134, 250));
};
// Create progress bar control containers.
function progressBarControl() {
    this.progressBarControl = new progressBarMapControl();
    _map.addControl(this.progressBarControl);
    this.progressBar = $get('progressBar');
    this.progressBarText = $get('progressBarText');
    this.progressBarContainer = $get('progressBarContainer');

    this.operations = 0;
    this.current = 0;
}
/// Start progress bar control.
progressBarControl.prototype.start = function(operations) {
    this.progressBar.style.width = '0%';
    this.operations = operations || 0;
    this.current = 0;
    this.progressBarText.innerHTML = 'Bezig met laden...';
    this.progressBarContainer.style.display = "block";
};
/// Update progress.
progressBarControl.prototype.updateLoader = function(step) {
this.current += step;
    if (this.current > 0) {
        var percentage = Math.ceil((this.current / this.operations) * 100);
        if (percentage > 100) {
            percentage = 100;
        }
        this.progressBar.style.width = percentage + '%';
        this.progressBarText.innerHTML = 'Bezig met laden van prijswinnaars: ' + this.current + ' / ' + this.operations;
    }
};
/// Hide progress bar.
progressBarControl.prototype.remove = function() {
this.progressBarContainer.style.display = 'none';
};

//]]>
Sys.Application.add_load(initGoogleMap);
