/**
* Displays all properties available in XML file on a map
* v. 26-Sep-2011
*/

window.addEvent('load', function(){

var container = $E(allContainer);

    if (container) {
        // Defining containers for map and stuff
        var c_hpmapscanvas = new Element('div', {id: 'hpmapscanvas'});

        // Map container
        var c_map_canvas = new Element('div', {
            id: 'map_canvas',
            styles: {
                width: mapwidth,
                height: mapheight,
                margin: '5px 0px'
            }
        });
        c_map_canvas.inject(c_hpmapscanvas);
        c_hpmapscanvas.inject(container, mapPosition);

        if (iconType == 1) { // icon for each type
            // icons legend container
            var el = new Element('div', {'id': 'legend', 'style': 'width:100%;'});
            var legend   = new Element('div', {'style': 'float:left; padding:10px 5px 0 0'}).setHTML(mesLegend).injectInside(el);
            var check = []; // keep track of used types
        }

    } else { // terminate
        return;
    }


    if (mapcenter == 1) var bounds = new google.maps.LatLngBounds(); // fit bounds
    var myOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var infowindow;
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (mapcenter > 1) map.setZoom(allZoom); // average & fixed coordinates


    downloadUrl(xmlurl, function(doc) {
        var avrlat = 0;
        var avrlng = 0;
        var xmlDoc = xmlParse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
            var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
            if (mapcenter == 1) { // fit bounds
                bounds.extend(latlng);
                map.fitBounds(bounds);
            }
            avrlat = avrlat + parseFloat(markers[i].getAttribute("lat"));
            avrlng = avrlng + parseFloat(markers[i].getAttribute("lng"));
            if (seflinks == 1) {
                var html = '<a href="' + markers[i].getAttribute("sefurl") + '">';
            } else {
                var html = '<a href="' + hpurl + markers[i].getAttribute("id") + '&Itemid=' + itemid + '">';
            }
            html = html + markers[i].getAttribute("name") + '</a><br /><small>' + markers[i].getAttribute("address") + '</small>'
            createMarker(html, latlng, markers[i].getAttribute("type"));
        }

        if (mapcenter > 1) {
            if (centerlatlgn > '') { // fixed coordinates
                coor = centerlatlgn.split(',');
                var myLatLng = new google.maps.LatLng(parseFloat(coor[0]), parseFloat(coor[1]));
            } else { // average center
                var myLatLng = new google.maps.LatLng(avrlat/markers.length, avrlng/markers.length);
            }
            map.setCenter(myLatLng);
        }

        if (iconType == 1) { // icon for each type
            el.injectAfter($('hpmapscanvas')); // end legend creation
        }

    });


    function createMarker(html, latlng, type) {

        if (iconType == 1) { // display custom icons assigned for each property type
            var icon = iconArray[type] || {};
            if (!check[type] && icon.img != null && icon.title != null) {
                var img = new Element('img', {'src': icon.img, 'title': icon.title}).injectInside(el); // add new image to legend
                check[type] = 1;
            }
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: icon.img,
                title: icon.title
            });
        } else if (iconType == 2 && iconCustom) { // one custom icon for all properties
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: iconCustom
            });
        } else { // default Google icons
            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });
        }

        google.maps.event.addListener(marker, "click", function() {
            if (infowindow) infowindow.close();
            infowindow = new google.maps.InfoWindow({content: html});
            infowindow.open(map, marker);
        });
        return marker;
    }
}
);

/************** UTILS **************/

/**
* Returns an XMLHttp instance to use for asynchronous
* downloading. This method will never throw an exception, but will
* return NULL if the browser does not support XmlHttp for any reason.
* @return {XMLHttpRequest|Null}
*/
function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

/**
* This functions wraps XMLHttpRequest open/send function
* It lets you specify a URL and runs the callback if status code is 200
*
* @param    {String}    url         The URL to retrieve
* @param    {Function}  callback    The function to call once retrieved
*/
function downloadUrl(xmlurl, callback) {
    var status = -1;
    var request = createXmlHttpRequest();
    if (!request) {
        return false;
    }

    request.onreadystatechange = function() {
    if (request.readyState == 4) {
        try {
            status = request.status;
        } catch (e) {
        // Usually indicates request timed out in FF
        }
        if ((status == 200) || (status == 0)) {
            callback(request.responseText, request.status);
            request.onreadystatechange = function() {};
            }
        }
    }

    request.open('GET', xmlurl, true);
    try {
        request.send(null);
    } catch (e) {
        changeStatus(e);
    }
};


/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string
 * @return {Element|Document} DOM
 */
function xmlParse(str) {
    if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    }
    if (typeof DOMParser != 'undefined') {
        return (new DOMParser()).parseFromString(str, 'text/xml');
    }
    return createElement('div', null);
}


/**
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a text
 * that will be a more readable version of the given array/hash/object
 * Usage: alert(dump(array));
 * @param {array,hash(associative array),object}
 * @param {int} optional, level
 * @return {string} textual representation of the array
 */
function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') { //Array/Hashes/Objects
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}


/**
* A javascript function to emulate PHP's print_r function
* Usage: print_r(array);
*/
function print_r(theObj){
    if(theObj.constructor == Array || theObj.constructor == Object){
        document.write("<ul>")
        for(var p in theObj){
            if(theObj[p].constructor == Array||
                theObj[p].constructor == Object){
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
                document.write("<ul>")
                print_r(theObj[p]);
                document.write("</ul>")
            } else {
                document.write("<li>["+p+"] => "+theObj[p]+"</li>");
        }
        }
        document.write("</ul>")
    }
}
