///<reference path="jquery-1.3.2.min.js"/>


var map;                    //GMap object
var markers = new Array();  //array that holds all the markers
var current;                //the current visible marker
var index = 0;              //markers array next index
var linkBox;                //custom popup box for Link button
var indexToggle = true;
var isFirst = true;
var geoXml = new GGeoXml("http://www.unf.edu/map/js/doc.txt");//Code blue phones kml (needs to be on a publicly accessable web server (ie not dev or stage))
var isLoaded = false;
var qsMarkers = null;


google.load("feeds", "1"); //load the feed api


//constructs a new marker along with all the marker's associated data
function Marker(lat, lng, title, image, description, pin, id, multiple, rss) {

    this.id = id;
    this.title = title;
    this.image = image;
    this.description = description;
    this.rss = rss;
    this.rssh;
    this.tabs;
    this.hasEvents = false;
    if (multiple)
        this.multiple = multiple;
    else
        this.multiple = false;
    this.pin = pin;
    this.html = "<h3>" + title + "</h3>";
    if (image != null && image != "")
        this.html = this.html + "<img style='padding:10px' src='" + image + "' align='right' height='100' width='150'>";
    if (description != null) {
        this.html = this.html + "<p>" + description + "</p>";
        /*//formats the info box if there are css issues
        for(var i = 0; i < description.length/90; i++)
        {
        this.html = this.html + "<br/>";
        }*/
    }




    var baseIcon = new GIcon(G_DEFAULT_ICON);
    var latlng = new GLatLng(lat, lng);
    var letteredIcon = new GIcon(baseIcon);
    letteredIcon.image = pin;



    // Set up our GMarkerOptions object
    markerOptions = { icon: letteredIcon };

    this.m = new GMarker(latlng, markerOptions);

    if (this.rss != "" && this.rss != null) {
        var idx = index;
        var rsshtml = "";

        var feed = new google.feeds.Feed(this.rss);
        feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
        feed.setNumEntries(5);
        feed.load(function(result) {
            if (!result.error) {
                var mkrs = result.xmlDocument.documentElement.getElementsByTagName("item");
                var title = GXml.value(result.xmlDocument.documentElement.getElementsByTagName("title")[0]);
                rsshtml += "<B>" + title + "</B><br/><br/>";
                for (var i = 0; i < mkrs.length; i++) {
                    var d = new Date(GXml.value(mkrs[i].getElementsByTagName("pubDate")[0]));
                    var link = "";
                    var linkc = "";
                    if (GXml.value(mkrs[i].getElementsByTagName("link")[0]) != "") {
                        link = "<a target='_blank' href='" + GXml.value(mkrs[i].getElementsByTagName("link")[0]) + "'>";
                        linkc = "</a>";
                    }

                    rsshtml = rsshtml + link + GXml.value(mkrs[i].getElementsByTagName("title")[0]) + linkc + "<br/>" + d.toLocaleString() + "<br/><br/>";
                }
                markers[idx].rssh = rsshtml;
                markers[idx].tabs = [new GInfoWindowTab('Description', markers[idx].html), new GInfoWindowTab('Events', markers[idx].rssh)];
                markers[idx].hasEvents = true;
                GEvent.addListener(markers[idx].m, "click", function() {
                    markers[idx].m.openInfoWindowTabsHtml(markers[idx].tabs, { maxWidth: 600 });
                });
            }
        });

    }



    map.addOverlay(this.m);
    this.m.hide();
    
}

//Called on page load, creates the map and initializes it with overlay and markers
function initialize() {

    toggleIndex();
    //read the query string for later use in setting up the map
    var qs = window.location.search.substring(1);
    var qsVars = qs.split("&");
    var qsLat = null;
    var qsLng = null;
    var qsZoom = null;
	
	var centerLat;
	var centerLng;
	var zoomLevel;
	var overlayImage;
	var upperLat;
	var upperLng;
	var lowerLat;
	var lowerLng;  
	
    //read in query string variables to determine the initial setup of the map
    for (var i = 0; i < qsVars.length; i++) {
        if (qsVars[i].substring(0, 4) == "lat=")
            qsLat = qsVars[i].substring(4);
        else if (qsVars[i].substring(0, 4) == "lng=")
            qsLng = qsVars[i].substring(4);
        else if (qsVars[i].substring(0, 5) == "zoom=")
            qsZoom = qsVars[i].substring(5);
        else if (qsVars[i].substring(0, 8) == "markers=") {
            qsMarkers = qsVars[i].substring(8).split(",");
        }
    }
	geoXml.hide();
	
	$.getJSON('https://webapps.unf.edu/ws/Gis.svc/maps/UNF Campus Map@json?method=?', "", function(data) {
		centerLat = data.Latitude;
		centerLng = data.Longitude;
		zoomLevel = data.ZoomLevel;
		overlayImage = data.MapOverlays[0].OverlayPath;
		upperLat = data.MapOverlays[0].UpperBoundaryLatitude;
		upperLng = data.MapOverlays[0].UpperBoundaryLongitude;
		lowerLat = data.MapOverlays[0].LowerBoundaryLatitude;
		lowerLng = data.MapOverlays[0].LowerBoundaryLongitude; 
			
			
		if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));


        map.checkResize();

        //set the default map center or use the one from the query string
        map.setCenter(new GLatLng(centerLat, centerLng), zoomLevel);
        if (qsLat != null && qsLng != null && qsZoom != null) {
            map.setCenter(new GLatLng(qsLat, qsLng));
            map.setZoom(parseInt(qsZoom));
        }
		
        //set up map options and add campus map overlay
        var boundaries = new GLatLngBounds(new GLatLng(upperLat, upperLng), new GLatLng(lowerLat, lowerLng));

        //the following are different possible map overlays
        //var campusmap = EInsert.groundOverlay("images/campusOverlay.png", boundaries); //regular transparent overlay
        //var campusmap = EInsert.groundOverlay("images/campusOverlayHR.png", boundaries); //high-resolution transparent overlay
        //var campusmap = EInsert.groundOverlay("images/campusOverlayPrint.jpg", boundaries); //non-transparent overlay (high resolution)
        //var campusmap = new GGroundOverlay("images/campusOverlayPrint.jpg", boundaries); //gmaps builtin overlay method (will not print overlay)

        var campusmap = EInsert.groundOverlay(overlayImage, boundaries);


        map.enableScrollWheelZoom();
        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMapTypeControl());
        map.addOverlay(campusmap);


        map.addControl(new expandControl());

        //define the base icon for the map
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);

      

        //remove or add the overlay when the map type is changed
        GEvent.addListener(map, "maptypechanged", function() {
            var mapType = map.getCurrentMapType();
            if (mapType.getName() == "Map") {
                map.addOverlay(campusmap);
            }

            else if (mapType.getName() == "Hybrid" || mapType.getName() == "Satellite") {
                map.removeOverlay(campusmap);
            }
        });

        //When the map is clicked find the closest non-grouped marker and show it
        GEvent.addListener(map, "click", function(overlay, latlng) {
            var closestdist = null;
            var closest;

            if (latlng) {
                for (var i = 0; i < markers.length; i++) {
                    if (!markers[i].multiple) {
                        var c = markers[i].m.getLatLng().distanceFrom(latlng);
                        if (closestdist == null || c < closestdist) {
                            closestdist = c;
                            closest = markers[i].id;
                        }
                    }
                }
                show(closest);
            }
        });



        //pushpin images
        /*
        var defaultImage = 'images/markers/UNFmarker.png';
        var redBus = 'images/markers/BusIconr.png';
        var blueBus = 'images/markers/BusIcon.png';
        var parkingIcon = 'images/markers/parkingBlue.png';
        var phoneIcon = 'images/markers/phoneIcon.png';
        */

        /* To create a marker:
        createMarker(latitude:Number, 
        longitude:Number, 
        title:String, 
        image:String(url to image to appear in info box, dimensions:150x100), 
        description:String(HTML description of building), 
        icon:String(url to pushpin image, 24bit .png file), 
        id:String(unique identification for marker or group of markers), 
        multiple?:boolean(true if marker belongs to a group))
		
		
		
        */
        //jQuery syling
        $(document).ready(function() {
            $('#parkingIndex').hide();
            $("#parkingIndexToggle").toggle(function() {
                $("#parkingIndex").animate({ height: 'show', opacity: 'show' }, 'slow');
            }, function() {
                $("#parkingIndex").animate({ height: 'hide', opacity: 'hide' }, "slow");
            });

			
        });

        //Load the marker information form the database
        parseJSON();
		if(qsMarkers != null)
		{
			for (var i = 0; i < qsMarkers.length; i++) {
				if (qsMarkers[i] == "Phone") {
					show("Phone");
				}
			}
		}
    }
	});

    
}


//creates a new marker and adds it to the 'markers' array
function createMarker(lat, lng, title, image, description, pin, id, multiple, rss) {
    markers[index] = new Marker(lat, lng, title, image, description, pin, id, multiple, rss);
    var idx = index;
    GEvent.addListener(markers[idx].m, "click", function() {
        markers[idx].m.openInfoWindowHtml(markers[idx].html, { maxWidth: 600 });
    });
    if (qsMarkers != null) {
        for (var i = 0; i < qsMarkers.length; i++) {
            if (qsMarkers[i] == markers[idx].id) {
                show(markers[idx].id);
            }
        }
    }
    index++;
}


//Determine if a marker group is hidden
function isGroupHidden(id) {
    for (var i = 0; i < markers.length; i++) {
        if (markers[i].id == id) {
            return markers[i].m.isHidden();
        }

    }
}

//show or hide index div
function openIndex(id, toggleId) {
    //alert($("#"+id).innerHeight());
    //$("#" + id).animate({ height: 'hide', opacity: 'hide' }, 'slow');
    
    $("#" + toggleId).toggle(function() {
        $("#" + id).animate({ height: 'hide', opacity: 'hide' }, "slow");
    }, function() {
        $("#" + id).animate({ height: 'show', opacity: 'show' }, 'slow');
    });
    
    /*
        
    var indexDiv = document.getElementById(id);
    if (indexDiv.style.display == "block")
        indexDiv.style.display = "none";
    else
        indexDiv.style.display = "block";*/
}

//shows or hide a m arker or group of markers
function show(id) {
    //special case for kml
    if (id == "Phone") {

        if (!geoXml.isHidden() && !isFirst) {
            geoXml.hide();

        }
        else {
            if (!isLoaded)
                map.addOverlay(geoXml);
            geoXml.show();
            isFirst = false;

        }
    }
    else {
        for (var i = 0; i < markers.length; i++) {
            if (markers[i].id == id) {
                if (!markers[i].multiple) {
                    if (current != null)
                        current.hide();
                    markers[i].m.show();
                    current = markers[i].m;
                    if (markers[i].hasEvents) {
                        current.openInfoWindowTabsHtml(markers[i].tabs, { maxWidth: 600 });
                    }
                    else {
                        current.openInfoWindowHtml(markers[i].html, { maxWidth: 600 });
                    }
                    break;
                }
                else {
                    if (!markers[i].m.isHidden()) {
                        markers[i].m.hide();
                    }
                    else {
                        markers[i].m.show();
                    }
                }
            }
        }
    }
}


//checks or unchecks the checkbox of the marker then shows or hides the marker
function checkBox(id) {
    if (document.getElementById(id).checked == false) {
        document.getElementById(id).checked = true;
        show(id);
    }
    else {
        document.getElementById(id).checked = false;
        show(id);
    }
}

//create a link to the map with the appropriate query string variables
function createLink() {
    var qString;
    var queryVars = new Array();
    var indx = 0;
    for (var i = 0; i < markers.length; i++) {
        var exists = false;
        for (var j = 0; j < queryVars.length; j++) {
            if (queryVars[j] == markers[i].id)
                exists = true;
        }
        if (!markers[i].m.isHidden() && !exists) {
            queryVars[indx] = markers[i].id;
            indx++;
        }
    }
	if (!geoXml.isHidden())
		queryVars[indx] = "Phone"
    var ll;
    ll = map.getCenter().toString();
    ll = ll.substring(1, ll.length - 1);
    ll = ll.split(", ");
    qString = "?lat=" + ll[0] + "&lng=" + ll[1] + "&zoom=" + map.getZoom();
    if (queryVars.length > 0)
        qString = qString + "&markers=";
    for (var j = 0; j < queryVars.length; j++) {
        qString = qString + queryVars[j] + ",";
    }
    var url = window.location.href.replace(window.location.search, "");
    var url = url.replace("#", "");
    return url + qString;

}
//open a box with the generated link
function openLinkBox() {
    hideLinkBox();
    var d = document.getElementById("map_canvas");

    linkBox = document.createElement('div');
    linkBox.style.backgroundColor = '#5d87b7';
    linkBox.style.color = 'white';
    linkBox.style.padding = '10px';
    linkBox.style.width = '350px';
    linkBox.style.position = 'absolute';
    linkBox.style.zIndex = '5';
    //alert(d.offsetTop);
    linkBox.style.top = (parseInt(document.getElementById("content").offsetTop)) + 'px';
    linkBox.style.left = (parseInt(d.offsetLeft) + parseInt(d.clientWidth) - (100)) + 'px';
    linkBox.setAttribute('id', 'linkDiv');
    linkBox.innerHTML = "Paste link in email or IM <br/> <input type='text' value='" + createLink() + "' size='60' onFocus='this.select()'> <br/><a  onclick='hideLinkBox()' 	style='color:#FFFFFF;'>Close</a>";
    document.body.appendChild(linkBox);
}

//hide the link box            
function hideLinkBox() {
    try {
        var box = document.getElementById('linkDiv');
        document.body.removeChild(box);
    }
    catch (err) { }
}


//creates the index show/hide button
function expandControl() {
}

expandControl.prototype = new GControl();
expandControl.prototype.initialize = function(map) {
    var container = document.createElement("div");



    //create the Show/Hide Index button
    var indxDiv = document.createElement("div");
    indxDiv.innerHTML = "<img src='images/arrow_left.jpg'/>";
    this.setButtonStyle_(indxDiv);
    container.appendChild(indxDiv);
    GEvent.addDomListener(indxDiv, "click", function() {
        toggleIndex();
        if (!indexToggle)
            indxDiv.innerHTML = "<img src='images/arrow_left.jpg'/>";
        else
            indxDiv.innerHTML = "<img src='images/arrow_right.jpg'/>";
    });

    //add the conrols to the map
    map.getContainer().appendChild(container);
    return container;
}

expandControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(-21, -1));
}

// Sets the proper CSS for the given button element.
expandControl.prototype.setButtonStyle_ = function(button) {

    button.style.font = "small Arial";
    button.style.fontWeight = "bold";
    button.style.cursor = "pointer";
}

function toggleIndex() {
    if (!indexToggle) {
        $("#navigation").animate({ opacity: 'hide' }, 'slow');
        $("#content").animate({ marginLeft: "0px"}, 'slow');
       /* document.getElementById('navigation').style.display = "none";

        document.getElementById('content').style.marginLeft = "0px";*/

        indexToggle = true;
    }
    else {
        $("#navigation").animate({ opacity: 'show' }, 'slow');
        $("#content").animate({ marginLeft: "240px" }, 'slow');
        /*document.getElementById('navigation').style.display = "block";

        document.getElementById('content').style.marginLeft = "240px";*/

        indexToggle = false;
    }
}

function parseJSON() {
    
	$("#Buildings").append("<ul>");
	$("#Parking").append("<ul>");
     $.getJSON('https://webapps.unf.edu/ws/Gis.svc/campus/locations@json?method=?', "", function(data) {
        $.each(data.Markers, function(i, Marker) {
            createMarker(Marker.Lat, Marker.Lng, Marker.Title, Marker.Image, Marker.Description, Marker.Icon, Marker.Id, Marker.Multiple, Marker.RssUrl);
			if(!Marker.Multiple){
				if(Marker.Id.indexOf("Lot") >= 0 || Marker.Id.indexOf("Garage") >= 0)
					$("#Parking").append("<li ><a href=\"javascript:show('" + Marker.Id + "')\" >" + Marker.Title + "</a></li>");
				else
					$("#Buildings").append("<li ><a href=\"javascript:show('" + Marker.Id + "')\" >" + Marker.Title + "</a></li>");
			}
			
        });
	});
	$("#Buildings").append("</ul>");
	$("#Parking").append("</ul>");
		

   /* var myObj = returnJSN();
    for (var i = 0; i < myObj.Markers.length; i++) {
        createMarker(myObj.Markers[i].Lat, myObj.Markers[i].Lng, myObj.Markers[i].Title, myObj.Markers[i].Image, myObj.Markers[i].Description, myObj.Markers[i].Icon, myObj.Markers[i].Id, myObj.Markers[i].Multiple, myObj.Markers[i].RssUrl);

    }*/
}
