
var GeoChron = {};
var GeoChronModel = {};
GeoChron.VISITS_URI = "visits.php";
GeoChron.PLACES_URI = "places_xml.php";
GeoChron.GEOZONES_URI = "geozones.php"
GeoChron.VISITS_URI = GeoChron.VISITS_URI || "../web/visits.php";

GeoChron.ChronMenuComponent = function(elemId){
    this._name = "GeoChron.Component.CronMenuComponent";
    this.DEFAULT_START_YEAR = '1873';
    this.DEFAULT_END_YEAR = '1947';
    this.visits = new GeoChronModel.VisitList();
    this.elem = elemId;
};
GeoChron.ChronMenuComponent.prototype.init = function(){
    var me = this;
    $("#" + this.elem).append('<div class="visitForm"><form id="chronMenuForm" onsubmit="return false;">Date Range<br /><input type="text" name="sdate" id="chronMenuStartInput" size="4" value="' + this.DEFAULT_START_YEAR + '" /> - <input id="chronMenuEndInput" type="text" name="edate" size="4" value="' + this.DEFAULT_END_YEAR + '" /> <input type="submit" value="change" /><input type="submit" onclick="reset(); submit();" value="reset"/></form></div>');
    $("#chronMenuForm").bind("submit", function(event){
        me.updateDataFromForm()
    });
    this.visitList = document.createElement("div");
    this.visitList.className = "resultContainer";
    document.getElementById(this.elem).appendChild(this.visitList);
    this.queryVisitsByDate(this.DEFAULT_START_YEAR, this.DEFAULT_END_YEAR);
};
GeoChron.ChronMenuComponent.prototype.queryVisitsByDate = function(startDate, endDate){
    if (startDate.length == 4 && endDate.length == 4) {
        startDate = startDate + "-01-01"
        endDate = (Number(endDate) + 1) + "-01-01";
    }
    var owner = this;
    $.ajax({
        type: "GET",
        url: GeoChron.VISITS_URI + "?sdate=" + startDate + "&edate=" + endDate + "&format=short",
        dataType: "string",
        success: function(data){
            owner.readData(data);
        },
        error: function(){
            alert("There was a problem loading visit data from the server.");
        }
    });
};

//addding new function to call for visits by the geozone
GeoChron.ChronMenuComponent.prototype.queryVisitsByZone = function(gid){
	if (gid >0) {
		 var owner =  GeoChron.ChronMenuComponent.prototype;	 
		 owner.visits = new GeoChronModel.VisitList();
		  this.elem = "chron-menu";
		 document.getElementById(this.elem).innerHTML=''; //reset it
		  
    $("#" + this.elem).append('<div class="visitForm"><form id="chronMenuForm" onsubmit="return false;">Date Range<br /><input type="text" name="sdate" id="chronMenuStartInput" size="4" value="" /> - <input id="chronMenuEndInput" type="text" name="edate" size="4" value="" /> <input type="submit" value="change" /><input type="reset" value="reset" /></form></div>');
    $("#chronMenuForm").bind("submit", function(event){
        this.updateDataFromForm()
    });
    this.visitList = document.createElement("div");
    this.visitList.className = "resultContainer";	
    document.getElementById(this.elem).appendChild(this.visitList);
		$.ajax({
			type: "GET",
			url: GeoChron.VISITS_URI + "?gid=" + gid+"&format=short",
			dataType: "string",
			success: function(data) {
				owner.readData(data);
				//alert(this.startdate);
			},
			error:function(){
				alert("There was a problem loading visit data from the server.");
			}
		});
	}
};

GeoChron.ChronMenuComponent.prototype.updateDataFromForm = function(){
    this.queryVisitsByDate(document.getElementById('chronMenuStartInput').value, document.getElementById('chronMenuEndInput').value);
};

GeoChron.ChronMenuComponent.prototype.readData = function(data){
    if (this.visits.readObj($.xmlToJSON($.textToXML(data)))) {
        GEvent.trigger(this, 'change', this.visits.places);
        var visitHTML = this.renderVisits();
        $(this.visitList).html(visitHTML);
    }
};
GeoChron.ChronMenuComponent.prototype.selectVisit = function(data){
    GEvent.trigger(this, 'select', this.visits.getVisit(data));
}
GeoChron.ChronMenuComponent.prototype.renderVisits = function(){
    var visitList = document.createElement("ul");
    var me = this;
    while (this.visits.hasNext()) {
        var vis = this.visits.next();
        var thisA = document.createElement("a");
        thisA.href = "javascript:void(0)";
        thisA.appendChild(document.createTextNode(vis.getEnglDate()));
        var thisLi = document.createElement("li");
        thisLi.appendChild(thisA);
        thisLi.appendChild(document.createElement("br"));
        thisLi.appendChild(document.createTextNode(vis.placeName));
        $(thisLi).bind("click", vis.id, function(evnt){
            me.selectVisit(evnt.data); 
        });
        visitList.appendChild(thisLi);
    }
    return (visitList);
};
GeoChron.DefaultPlaceRenderer = function(){
    this._name = "GeoChron.DefaultPlaceRenderer";
    //this.EDIT_BASE = "http://cather.unl.edu/geochron/admin/";
	this.EDIT_BASE = "http://libresources.unl.edu/projects/cather/geochron/";
};
GeoChron.EDIT_MODE = GeoChron.EDIT_MODE | false;
GeoChron.DefaultPlaceRenderer.prototype.renderSummary = function(placeObj){
	if (placeObj.address) { var visitTo = " to "+placeObj.address;}
	else { var visitTo='';}
	if (placeObj.visitCount == 1) var visitCountText = "1 visit";
	else var visitCountText = placeObj.visitCount + " visits";
	if (placeObj.name == "Unknown") placeObj.name = "";
	if (placeObj.geoname) {
		return ("<p><br /><strong>"+ placeObj.name + "<br/>" + placeObj.address +"<br />"+placeObj.geoname+"</strong><br/>" + visitCountText + visitTo+"</p>")
	}
    else return ("<p><br /><strong>" + placeObj.name +"</strong><br/>" + visitCountText + visitTo+"</p>")
};
GeoChron.DefaultPlaceRenderer.prototype.render = function(placeObj){
    var tabs = new Array();
    var placeHeadHtml = new Array();
    placeHeadHtml.push("<div class=\"infoWindow\">");
	if (placeObj.name == "Unknown") placeObj.name = "";
    placeHeadHtml.push("<h2>" + placeObj.name);
		 if (placeObj.address != "") 
        placeHeadHtml.push("<br/><span class=\"address\">" + placeObj.address + "</span>");
	if (GeoChron.EDIT_ON) 
        placeHeadHtml.push(" <small>[<a href=\"javascript:void(0)\" onclick=\"window.open('" + this.EDIT_BASE + "addresses/edit/" + placeObj.id + "')\">edit address</a>]</small>");
   
	if (placeObj.geoname != "")
		placeHeadHtml.push("<br />" + placeObj.geoname);
    if (GeoChron.EDIT_ON) 
        placeHeadHtml.push(" <small>[<a href=\"javascript:void(0)\" onclick=\"window.open('" + this.EDIT_BASE + "geozones/edit/" + placeObj.zoneIdIndex[0] + "')\">edit geozone</a>]</small>");
   

    placeHeadHtml.push("</h2>");
	/*
	 Commented out for now until the place source and citation data is corrected.
	 
	 	placeHeadHtml.push("<span class=\"place_source\">");
		if (placeObj.placeNote || placeObj.placeCitation) placeHeadHtml.push("Source: ");
		if (placeObj.placeNote) placeHeadHtml.push(placeObj.placeNote);
		if (placeObj.placeCitation) placeHeadHtml.push("<br /><small>"+placeObj.placeCitation+"</small>");
	
	  	if (GeoChron.EDIT_ON) 
                placeHeadHtml.push("<small>[<a href=\"javascript:void(0)\" onclick=\"window.open('" + this.EDIT_BASE + "addresses/edit/" + placeObj.id + "#source')\">Edit place source</a>]</small>");
		placeHeadHtml.push("</span>");
	*/
    tabs.push(placeHeadHtml.join(""));
    if (placeObj.sources) {
		var photos = false;
		if (placeObj.sources[0].docLinks) {
			for (var m = 0; m < placeObj.sources[0].docLinks.length; m++) {
				if (placeObj.sources[0].docLinks[m].docType == "photo") 
					photos = true;
			}
			if (photos) {
				var sourcesHtml = new Array();
				sourcesHtml.push("<div class=\"sourcesWindow\" id=\"otherMedia\" style=\"display:none;\">");
				sourcesHtml.push("<div class=\"viewTab\">");
				sourcesHtml.push("<a href=\"javascript:void(0);\" onclick=\"document.getElementById('otherMedia').style.display='none';document.getElementById('visits').style.display='inline';\">Visits</a>");
				sourcesHtml.push("<span class=\"selectedTab\">Images</span> ");
				sourcesHtml.push("</div>")
				//sourcesHtml.push("<p>");
				sourcesHtml.push("<div>");
				for (var m = 0; m < placeObj.sources[0].docLinks.length; m++) {
					if (placeObj.sources[0].docLinks[m].docType == "photo") {
						var imgId = placeObj.sources[0].docLinks[m].docId;
						sourcesHtml.push("<div class='photo'><a href=\"javascript:void(0)\" onclick=\"window.open('http://contentdm.unl.edu/u/?/cather1," + imgId + "')\"><img src=\"http://contentdm.unl.edu/cgi-bin/thumbnail.exe?CISOROOT=/cather1&CISOPTR=" + imgId + "\" /></a>");
						sourcesHtml.push("<br /><span class='caption'>" + placeObj.sources[0].docLinks[m].docTitle + "</span></div>");
					}
				}
				sourcesHtml.push("<br />");
				sourcesHtml.push("</div>");
				sourcesHtml.push("</div>");
				tabs.push(sourcesHtml.join(""));
			}
		}
	}
    var visitHtml = new Array();
	visitHtml.push("<div class=\"visits\" id=\"visits\">");
	visitHtml.push("<ul>");
	visitHtml.push("<div class=\"viewTab\">");
	visitHtml.push("<span class=\"selectedTab\">Visits</span>");
	if (placeObj.sources && placeObj.sources[0].docLinks) {
		visitHtml.push("<a	href=\"javascript:void(0);\"onclick=\"document.getElementById('visits').style.display='none';document.getElementById('otherMedia').style.display='inline';\">Images</a>");
	}
	visitHtml.push("<span class=\"visitHead\">Number of visits to this address: " + placeObj.visits.length + "</span>")
	visitHtml.push("</div>")
    if (placeObj.visits) {
        for (var i = 0; i < placeObj.visits.length; i++) {
            var thisVisit = placeObj.visits[i];
            visitHtml.push("<div class=\"visit\">");
            visitHtml.push("<h3>" + thisVisit.getEnglDate() + "</h3>");
            if (GeoChron.EDIT_ON) 
                visitHtml.push("<small>[<a href=\"javascript:void(0)\" onclick=\"window.open('" + this.EDIT_BASE + "visits/edit/" + thisVisit.id + "')\">edit visit</a>]</small>");
            if (placeObj.visits[i].note) {
				 visitHtml.push("<p>" + thisVisit.note + "</p>");
				 if (GeoChron.EDIT_ON) 
                    visitHtml.push("<small>[<a href=\"javascript:void(0)\" onclick=\"window.open('" + this.EDIT_BASE + "visits/edit/" + thisVisit.id + "#note')\">edit source note</a>]</small>");
			}
              
		
            if (thisVisit.links) {
                visitHtml.push("<div class=\"sources\"><p><strong>Source:</strong> <br/>");
                for (var j = 0; j < thisVisit.links.length; j++) {
                    if (thisVisit.links[j].citation) {
                        visitHtml.push(thisVisit.links[j].citation.replace(/ID:\s(\d+)/g, " <a href=\"javascript:void(0)\" onclick=\"window.open('http://cather.unl.edu/letters.html?_letterid=$1')\">Letter $1</a> "));
                        if (GeoChron.EDIT_ON) 
                            visitHtml.push("<small>[<a href=\"javascript:void(0)\" onclick=\"window.open('" + this.EDIT_BASE + "visits/edit/" + thisVisit.id + "#citation')\">edit source citation</a>]</small> ");
                    }
                    else {
                        visitHtml.push(thisVisit.links[j].note + "; ");
               
                    }
                }
                visitHtml.push("</p>");
                visitHtml.push("</div>");
            }
            visitHtml.push("</div>");
        }
    }
    visitHtml.push("</div></div>");
    tabs.push(visitHtml.join(""));
    return (tabs.join(""));
};

GeoChron.DefaultPlaceRenderer.prototype.imageCaption = function(data){
    return data;
};
GeoChron.DefaultPlaceRenderer.prototype.createIcon = function(placeObj){
    var iSize = (placeObj.visitCount > 1) ? ((placeObj.visitCount > 5) ? (30) : 26) : 22
    var thisIcon = MapIconMaker.createMarkerIcon({
        width: iSize,
        height: iSize,
        primaryColor: "#CC6600",
        cornerColor: "#CC3300",
        strokeColor: "#181818"
    });
    thisIcon.mainImage = thisIcon.image;
    thisIcon.selectedImage = this.createIconSelected(placeObj).image;
    return thisIcon;
}
GeoChron.DefaultPlaceRenderer.prototype.createIconSelected = function(placeObj){
    var iSize = (placeObj.visitCount > 1) ? 27 : 23
    var thisIcon = MapIconMaker.createMarkerIcon({
        width: iSize,
        height: iSize,
        primaryColor: "#FF0000",
        cornerColor: "#CC3300",
        strokeColor: "#181818"
    });
    return thisIcon;
}
GeoChron.PLACES_URI = GeoChron.PLACES_URI || "../web/places_xml.php";
GeoChron.GMapComponent = function(elem){
    this._name = "GeoChron.GMapComponent";
    this.elem = elem;
    this.map = {};
    this.places = new GeoChronModel.PlaceList();
    this.placeRenderer = new GeoChron.DefaultPlaceRenderer;
    this.selectedPlace = null;
    this.contentIndex = new Object();
};
GeoChron.GMapComponent.prototype.init = function(){
    if (GBrowserIsCompatible()) {
        this.map = new GMap2(document.getElementById(this.elem), {
            mapTypes: new Array(G_PHYSICAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP, G_NORMAL_MAP)
        });
        this.map.addControl(new GLargeMapControl());
        this.map.addControl(new GMapTypeControl());
        this.map.addControl(new GOverviewMapControl());
        this.map.enableScrollWheelZoom();
        this.map.setCenter(new GLatLng(40.088333, -70), 3);
    }
    else {
        warn("Your browser is not compatable with this application.");
    }
    var owner = this;
    $.ajax({
        type: "GET",
        url: GeoChron.PLACES_URI + "?format=short",
        dataType: "string",
        success: function(data){
            owner.loadXML(data);
        },
        error: function(){
            alert("There was a problem loading visit data from the server.");
        }
    });
};
GeoChron.GMapComponent.prototype.loadXML = function(data){
    if (this.places.readObj($.xmlToJSON($.textToXML(data)))) 
        this.addPlaces(this.places);
    else 
        warn("Error reading places from server.");
};
GeoChron.GMapComponent.prototype.addPlaces = function(places){
    places.rewind();
    while (places.hasNext()) {
        try {
            var placeObj = places.next();
            this.map.addOverlay(this.createPlaceMarker(placeObj));
        } 
        catch (e) {
            warn("Could not add place: " + e);
        }
    }
};
GeoChron.GMapComponent.prototype.createPlaceMarker = function(placeObj){
    var owner = this;
    var contentNode = document.createElement("div");
    contentNode.innerHTML = "<p>Loading...</p>";
    this.contentIndex[placeObj.id] = contentNode;
    var thisIcon = this.placeRenderer.createIcon(placeObj);
    var placeMarker = new GMarker(new GLatLng(placeObj.point.lat, placeObj.point.long), {icon: thisIcon});
    placeMarker.bindInfoWindowHtml(this.placeRenderer.renderSummary(placeObj), {
        maxContent: contentNode,
        maxTitle: placeObj.name
    });
    GEvent.addListener(placeMarker, "click", function(){
        owner.selectPlace(placeObj)
    });
    GEvent.addListener(placeMarker, "dblclick", function(){
        owner.map.getInfoWindow().maximize();
    });
    placeObj.attachMarker(placeMarker);
    return placeMarker;
};
GeoChron.GMapComponent.prototype.selectPlace = function(placeObj){
    if (this.selectedPlace) 
        this.selectedPlace.getMarker().setImage(this.selectedPlace.getMarker().getIcon().mainImage);
    this.selectedPlace = placeObj;
    placeObj.getMarker().setImage(placeObj.getMarker().getIcon().selectedImage);
    if (!placeObj.hasFullRecord) 
        this.queryRecord(placeObj.id);
    GEvent.trigger(this, 'select', placeObj.id);
};
GeoChron.GMapComponent.prototype.highlightPlace = function(placeId){
    var foundPlace = this.places.getPlace(placeId + "");
    if (foundPlace) {
        GEvent.trigger(foundPlace.getMarker(), 'click');
    }
};
GeoChron.GMapComponent.prototype.queryRecord = function(placeId){
    var owner = this;
    $.ajax({
        type: "GET",
        url: GeoChron.PLACES_URI + "?id=" + placeId,
        dataType: "string",
        pid: placeId,
        success: function(data, pid){
            owner.loadRecord(data, placeId);
        },
        error: function(){
            alert("There was a problem loading place data from the server.");
        }
    });
};
GeoChron.GMapComponent.prototype.loadRecord = function(XMLdata, placeId){
    if (this.selectedPlace.id == placeId) {
        var plObj = $.xmlToJSON($.textToXML(XMLdata))['place'][0];
        this.selectedPlace.readObj(plObj);
        this.contentIndex[placeId].innerHTML = this.placeRenderer.render(this.selectedPlace);
    }
};
GeoChron.GMapComponent.prototype.unfilter = function(){
    this.places.rewind();
    while (this.places.hasNext()) 
        this.places.next().getMarker().show();
};
GeoChron.GMapComponent.prototype.filterByZone = function(zoneId){
    this.map.getInfoWindow().hide();
    this.places.rewind();
    var start = true;
    var activeMarkerLocations = new Array();
    while (this.places.hasNext()) {
        var p = this.places.next();
        if (p.zoneIdIndex.inArray(zoneId + "")) {
            activeMarkerLocations.push( p.GLatLng() );
            p.getMarker().show();
            if (start) {
                GEvent.trigger(p.getMarker(), "click");
                start = false;
            }
        }
        else {
            p.getMarker().hide()
        }
    }

    this.zoomToMarkerBoundary( activeMarkerLocations );
};
GeoChron.GMapComponent.prototype.filterByPlaceIds = function(placeArray){
    this.map.getInfoWindow().hide();
    this.places.rewind();
    var start = true;
    var activeMarkerLocations = new Array();
    while (this.places.hasNext()) {
        var p = this.places.next();
        if (placeArray.inArray(p.id)) {
            activeMarkerLocations.push( p.GLatLng() );
            p.getMarker().show();
            if (start) {
                GEvent.trigger(p.getMarker(), "click");
                start = false;
            }
        }
        else {
            p.getMarker().hide();
        }
    }

    this.zoomToMarkerBoundary( activeMarkerLocations );
};

//find the smallest possible bounding box that includes every active marker
GeoChron.GMapComponent.prototype.zoomToMarkerBoundary = function( activeMarkerLocations ) {
    var zoomBounds = new GLatLngBounds();
    var sw = zoomBounds.getSouthWest();
    var ne = zoomBounds.getNorthEast();

    while( activeMarkerLocations.length != 0 ) {
        zoomBounds.extend( activeMarkerLocations.pop() );
    }

    //TODO research why 'zoomToMarkerBoundary' is being sent no active markers
    //TODO delete this hot-fix
    //  This fixes the situation where 'zoomToMarkerBoundary' is called with no active markers,
    //  but that situation should never occur
    if( zoomBounds.getSouthWest().equals(sw) && zoomBounds.getNorthEast().equals(ne) ) {
        zoomBounds = new GLatLngBounds( new GLatLng(33, -130), new GLatLng(53,20) );
    } else {

        //TODO drop a buffer around the zoom-rectangle based on a percentage of distance between lat/long
        //TODO EDIT -- sort of works, but needs debugging

        sw = zoomBounds.getSouthWest();
        ne = zoomBounds.getNorthEast();

        percentLat = Math.abs( sw.lat() - ne.lat() ) * .02;
        percentLng = Math.abs( sw.lng() - ne.lng() ) * .02;

        sw = new GLatLng( sw.lat() - percentLat, sw.lng() - percentLng );
        ne = new GLatLng( ne.lat() + percentLat, ne.lng() + percentLng );

        zoomBounds.extend( sw );
        zoomBounds.extend( ne );
    }

    //zoom to fit around the displayed points and center the map
    this.map.setZoom( this.map.getBoundsZoomLevel(zoomBounds) );
    this.map.setCenter( zoomBounds.getCenter() );
};

GeoChron.GEOZONES_URI = GeoChron.GEOZONES_URI || "../geozones.php";
GeoChron.GeoZonesMenuComponent = function(elemId){
    this._name = "GeoChron.GeoZonesMenuComponent";
    this.elem = elemId;
    this.selectedZone = -1;
    this.geoZones = new Object();
};
GeoChron.GeoZonesMenuComponent.prototype.init = function(){
    var owner = this;
    this.rootElement = $("#" + this.elem);
    $.ajax({
        type: "GET",
        url: GeoChron.GEOZONES_URI + "?s=country",
        dataType: "string",
        gid: "init",
        success: function(data){
            owner.readInitData(data, "init");
        },
        error: function(){
            alert("There was a problem loading data from the server.");
        }
    });
};
GeoChron.GeoZonesMenuComponent.prototype.readInitData = function(data, gid){
    var zonesObj = $.xmlToJSON($.textToXML(data));
    var zArray = new Array();
    for (var each = 0; each < zonesObj['zone'].length; each++) {
        thisObj = zonesObj['zone'][each]
        var thisId = thisObj.id;
        var thisName = thisObj['name'][0].Text;
        var thisPlaceCount = thisObj['places'][0].count;
		var thisVisitCount = thisObj.visits;
        if (thisId != gid) 
            zArray.push({
                id: thisId,
                name: thisName,
                pcount: thisPlaceCount,
				vcount: thisVisitCount
            });
    }
    if (zArray.length > 0) {
        if (gid == "init") {
            this.rootElement.append(this.makeList(zArray));
        }
        else {
            $('#gz' + gid).append(this.makeList(zArray));
        }
    }
};
GeoChron.GeoZonesMenuComponent.prototype.loadList = function(gid){
    if (gid != this.selectedZone) 
        GEvent.trigger(this, 'change', gid);
    this.selectedZone = gid;
    if ($('#gz' + gid + ' > ul').length) {
        $('#gz' + gid + ' > ul').toggle();
    }
    else {
        var owner = this;
        $.ajax({
            type: "GET",
            url: GeoChron.GEOZONES_URI + "?gid=" + gid + "&showDates=1",
            dataType: "string",
            gid: gid,
            success: function(data){
                owner.readInitData(data, gid);
				//GeoChron.ChronMenuComponent.prototype.queryVisitsByZone(gid);
            },
            error: function(){
                alert("There was a problem loading data from the server.");
            }
        });
    }
};
GeoChron.GeoZonesMenuComponent.prototype.makeList = function(liArray){
    var list = document.createElement("ul");
    var me = this;
    for (var i = 0; i < liArray.length; i++) {
        var thisId = liArray[i].id;
        var thisA = document.createElement("a");
        thisA.href = "javascript:void(0)";
        if (liArray[i].scope == "county") thisA.appendChild(document.createTextNode(liArray[i].name+" County"+"("+liArray[i].pcount+"with "+liArray[i].vcount+" visits)"));
		else thisA.appendChild(document.createTextNode(liArray[i].name/*+"("+liArray[i].pcount+" addresses with "+liArray[i].vcount+" visits)"*/));
        $(thisA).bind("click", thisId, function(evnt){
            me.loadList(evnt.data)
        });
        var thisLi = document.createElement("li");
        thisLi.id = "gz" + thisId;
        thisLi.appendChild(thisA);
        list.appendChild(thisLi);
    }
    return list;
};
GeoChron.GeoChronController = function(){
    this._name = "GeoChron.GeoChronController";
    this.DEFAULT_MAP_ELEMENT_ID = "map";
    this.DEFAULT_CHRON_MENU_ELEMENT = "chron-menu";
    this.DEFAULT_GEO_MENU_ELEMENT = "geo-menu";
    this.mapComponent = new GeoChron.GMapComponent(this.DEFAULT_MAP_ELEMENT_ID);
    this.chronMenu = new GeoChron.ChronMenuComponent(this.DEFAULT_CHRON_MENU_ELEMENT);
    this.zoneMenu = new GeoChron.GeoZonesMenuComponent(this.DEFAULT_GEO_MENU_ELEMENT);
};
GeoChron.EDIT_ON = false;
//GeoChron.EDIT_BASE = "http://cather.unl.edu/geochron/admin/";
GeoChron.EDIT_BASE = "http://libresources.unl.edu/projects/cather/geochron/"
GeoChron.GeoChronController.prototype.init = function(){
    var owner = this;
    this.resize();
    this.zoneMenu.init();
    this.chronMenu.init();
    this.mapComponent.init();
	
    GEvent.addListener(this.zoneMenu, "change", function(gid){
        owner.mapComponent.filterByZone(gid);
		
    });
	GEvent.addListener(this.zoneMenu, "reset", function() {
		owner.mapComponent.unfilter();
	});
    GEvent.addListener(this.chronMenu, "change", function(placearray){
        owner.mapComponent.filterByPlaceIds(placearray);
    });
    GEvent.addListener(this.chronMenu, "select", function(sVisit){
        owner.mapComponent.highlightPlace(sVisit.placeId);
    });
};
GeoChron.GeoChronController.prototype.resize = function(){
    var contentHeight = $(window).height() - $("div#banner").height();
    $('div#menu > div').height(contentHeight - 40);
    $('div#' + this.DEFAULT_MAP_ELEMENT_ID).height(contentHeight);
};
GeoChronModel.GeoZone = function GeoZone(id, name, scope, point){
    this.id = id;
    this.name = name;
    this.scope = scope;
    this.point = point;
};
GeoChronModel.GeoZone.prototype.readObj = function(inObj){
    try {
        this.id = inObj.id;
        this.name = inObj.Text;
        this.scope = inObj.scope;
        if (inObj.lat && inObj.long){
            this.point = {
                lat: inObj.lat,
                long: inObj.long
            };
        }
    }
    catch (e) {
        warn("Error parsing 'GeoZone': " + e);
        return false;
    }
    return true;
};
GeoChronModel.GeoZone.prototype.hasGeometry = function(){
    return (!(null == this.point));
};
GeoChronModel.Place = function Place(id, name, address, geoname, placeNote,placeCitation, visits, geoZones, sources, point){
    this.id = id;
    this.name = name;
    this.address = address;
	this.geoname = geoname; //geozone combined into name
	this.placeNote = placeNote;
	this.placeCitation = placeCitation;
    this.visits = visits;
    this.geoZones = geoZones;
    this.sources = sources;
    this.point = point;
    this.zoneIdIndex = [];
    this.hasFullRecord = false;
    this.visitCount = 0;
};
GeoChronModel.Place.prototype.toString = function(){
    return (JSON.stringify(this));
};
GeoChronModel.Place.prototype.GLatLng = function(){
    return (new GLatLng(this.point.lat, this.point.long));
};
GeoChronModel.Place.prototype.readObj = function(plObj){
    try {
        if (plObj.id == undefined || plObj.id == "") {
            warn("Attempted to parse Place object without ID");
            return false;
        }
        this.hasFullRecord = plObj._children.inArray('visits') && plObj._children.inArray('geoZones');
        this.id = plObj.id;
        this.name = plObj['name'][0].Text;
        this.address = (typeof(plObj['street'][0].Text) == "undefined") ? "Unknown address" : plObj['street'][0].Text;
		this.geoname = plObj['geoname'][0].Text;
		
        this.point = {
            "lat": plObj['point'][0].lat,
            "long": plObj['point'][0].long
        };
        if (this.hasFullRecord) {
            this.zoneIdIndex = [];
            for (var i = 0; i < plObj['geoZones'][0]['zone'].length; i++) {			 
                var this_zone = new GeoChronModel.GeoZone()
                if (this_zone.readObj(plObj['geoZones'][0]['zone'][i], this.point)) {
             		this.addGeoZone(this_zone);
                    this.zoneIdIndex.push(this_zone.id);			
                }
            }
            this.visits = new Array();
            if (plObj['visits'][0]['visit']) {
                for (var i = 0; i < plObj['visits'][0]['visit'].length; i++) {
                    var this_visit = new GeoChronModel.Visit()
                    if (this_visit.readObj(plObj['visits'][0]['visit'][i])) 
                        this.addVisit(this_visit);
                }
            }
            else {
                warn("No visits for place " + this.id);
            }
            this.visitCount = this.visits.length;
            if (plObj['sources'] && (!(plObj['sources'][0]._children == undefined))) {
                this.placeNote = plObj['sources'][0]['note'][0].Text;
				this.placeCitation = plObj['sources'][0]['citation'][0].Text;
			   var this_source = new GeoChronModel.Source();
               if (this_source.readObj(plObj['sources'][0])) 
        	  		this.addSource(this_source);		
            }
        }
        else {
            this.zoneIdIndex = plObj['zoneList'][0].data.split(',');
			this.geozone ='';
            this.visitCount = plObj['countVisits'][0].value;
        }
    } 
    catch (e) {
        warn("Error parsing 'Places' file: " + e);
        return false;
    }
    return true;
};
GeoChronModel.Place.prototype.addVisit = function(newVisit){
    if (this.visits == undefined) 
        this.visits = new Array();
    this.visits.push(newVisit);
};
GeoChronModel.Place.prototype.addSource = function(newSource){
    if (this.sources == undefined) 
        this.sources = new Array();
    this.sources.push(newSource);
};
GeoChronModel.Place.prototype.addGeoZone = function(newZone){
    if (this.geoZones == undefined) 
        this.geoZones = new Array();
    this.geoZones.push(newZone);
};
GeoChronModel.Place.prototype.getZoneIds = function(){
    return this.geoZones;
};
GeoChronModel.Place.prototype.attachMarker = function(markerObj){
    this.marker = markerObj;
};
GeoChronModel.Place.prototype.getMarker = function(){
    if (this.marker) 
        return (this.marker);
    else 
        return null;
};
GeoChronModel.PlaceList = function(placesArray){
    this.places = (typeof(placesArray) == "array") ? placesArray : new Array();
    this.nextIndex = 0;
};
GeoChronModel.PlaceList.prototype.readObj = function(domIn){
    try {
        var plcsObj = domIn;
        for (var each = 0; each < plcsObj['place'].length; each++) {
            var thisPlace = new GeoChronModel.Place();
            if (thisPlace.readObj(plcsObj['place'][each])) 
                ;
            {
                this.addPlace(thisPlace);
            }
        }
        return true;
    } 
    catch (e) {
        warn("Could not add place: " + e);
        return false;
    }
};
GeoChronModel.PlaceList.prototype.addPlace = function(newPlace){
    if (typeof(this.places) == 'undefined') 
        this.places = new Array();
    this.places.push(newPlace);
};
GeoChronModel.PlaceList.prototype.getPlaces = function(){
    return this.places;
};
GeoChronModel.PlaceList.prototype.getPlace = function(pId){
    for (var i = 0; i < this.places.length; i++) {
        if (this.places[i].id == pId) 
            return this.places[i];
    }
    return null;
};
GeoChronModel.PlaceList.prototype.hasNext = function(){
    return (this.nextIndex < this.places.length);
};
GeoChronModel.PlaceList.prototype.rewrind = function(){
    this.nextIndex = 0;
};
GeoChronModel.PlaceList.prototype.rewind = function(){
    this.nextIndex = 0;
};
GeoChronModel.PlaceList.prototype.next = function(){
    if (this.hasNext()) {
        this.nextIndex++;
        return (this.places[this.nextIndex - 1]);
    }
    else {
        return null;
    }
};
GeoChronModel.Source = function Source(excerpt, docLinks){
   // this.id = id;
    this.excerpt = excerpt;
    //this.note = note;
    //this.citation = citation;
    this.docLinks = docLinks;
};
GeoChronModel.Source.prototype.addLink = function(docType, docId, docTitle){
    if (this.docLinks == undefined) 
        this.docLinks = new Array();
    this.docLinks.push({
        "docType": docType,
        "docId": docId,
		"docTitle": docTitle
    });
};
GeoChronModel.Source.prototype.readObj = function(inObj){
    //try {
      //  if (inObj.id == undefined || inObj.id == "") {
        //    warn("Attempted to parse Place object without ID");
          //  return false;
       // }
       // this.id = inObj.id
       // if (inObj._children.inArray("note")) 
         //   this.note = inObj['note'][0].Text
       // if (inObj._children.inArray("citation")) 
        //    this.citation = inObj['citation'][0].Text
        if (inObj._children.inArray("link")) {
            for (var j = 0; j < inObj['link'].length; j++) {
                if (inObj['link'][j]._children.inArray("docType") && inObj['link'][j]._children.inArray("docId") && inObj['link'][j]._children.inArray("docTitle")) 
                    this.addLink(inObj['link'][j]['docType'][0].Text, inObj['link'][j]['docId'][0].Text, inObj['link'][j]['docTitle'][0].Text);
            }
        }
   // } 
    //catch (e) {
      //  warn("Error parsing 'Source': " + e);
       // return false;
    //}
    return true;
};
GeoChronModel.Visit = function Visit(id, visitDate, note, links, placeName, placeId, source){
    this.id = id;
    this.date = visitDate;
    this.note = note;
    this.links = links;
    this.placeName = placeName;
    this.placeId = placeId;
	this.source = source;
};
GeoChronModel.Visit.prototype.addLink = function(id, note, citation){
    if (this.links == undefined) 
        this.links = new Array();
    this.links.push({
        id: id,
        note: note,
        citation: citation
    });
};
GeoChronModel.Visit.prototype.readObj = function(inObj){
    try {
        if (inObj.id == undefined || inObj.id == "") {
            warn("Attempted to parse Visit object without ID");
            return false;
        }
        this.id = inObj.id;
        this.date = inObj['date'][0].value;
        if (inObj['place']) {
            this.placeName = inObj['place'][0]['name'][0].Text;
            this.placeId = inObj['place'][0].id;
        }
        if (inObj._children.inArray("note")) 
            this.note = inObj['note'][0].Text;
        if (inObj['source'] && (!(inObj['source'][0]._children == undefined)) && inObj['source'][0]._children.length > 0) {
                var this_link = inObj['source'][0];
                var note = (this_link._children.inArray("note")) ? this_link['note'][0].Text : "";
                var citation = (this_link._children.inArray("citation")) ? this_link['citation'][0].Text : "";
               this.addLink(this_link.id, note, citation);
            
        }
    } 
    catch (e) {
        warn("Error parsing 'Visit' file: " + e);
        return false;
    }
    return true;
};
GeoChronModel.Visit.prototype.getEnglDate = function(){
    this.date = this.date.replace(/-00/g, "").replace(/-/g, "");
    if (this.date.length < 4) 
        return "Undated";
    if (this.date.length == 4) 
        return this.date;
    var year = this.date.substring(0, 4);
    var months = new Array(13);
    months[0] = "January";
    months[1] = "February";
    months[2] = "March";
    months[3] = "April";
    months[4] = "May";
    months[5] = "June";
    months[6] = "July";
    months[7] = "August";
    months[8] = "September";
    months[9] = "October";
    months[10] = "November";
    months[11] = "December";
    var month = months[this.date.substring(4, 6) - 1];
    if (this.date.length == 6) 
        return (month + ", " + year);
    var day = this.date.substring(6, 8) - 0;
    return (month + " " + day + ", " + year);
};
GeoChronModel.VisitList = function VisitList(){
    this.visits = new Array();
    this.startDate = "";
    this.endDate = "";
    this.places = new Array();
    this.nextIndex = 0;
};
GeoChronModel.VisitList.prototype.addVisit = function(visitObj){
    if (this.visits == undefined) 
        this.visits = new Array();
    this.visits.push(visitObj);
};
GeoChronModel.VisitList.prototype.readObj = function(inObj){
    try {
        this.visits = new Array();
        this.places = new Array();
        this.nextIndex = 0;
        this.startDate = inObj.startdate;
        this.endDate = inObj.enddate;
        if ((!(inObj._children == undefined)) && inObj._children.length > 0) {
            for (var j = 0; j < inObj['visit'].length; j++) {
                var visit = new GeoChronModel.Visit();
                if (visit.readObj(inObj['visit'][j])) {
                    this.addVisit(visit);
                    if (!this.places.inArray(visit.placeId)) 
                        this.places.push(visit.placeId);
                }
            }
        }
    } 
    catch (e) {
        warn("Error parsing 'Visits' file: " + e);
        return false;
    }
    return true;
};
GeoChronModel.VisitList.prototype.getVisit = function(vid){
	
    for (var i = 0; i < this.visits.length; i++) {
        if (this.visits[i].id == vid) 
            return this.visits[i];
    }
    return null;
};
GeoChronModel.VisitList.prototype.hasNext = function(){
    return (this.nextIndex < this.visits.length);
};
GeoChronModel.VisitList.prototype.rewind = function(){
    this.nextIndex = 0;
};
GeoChronModel.VisitList.prototype.next = function(){
    if (this.hasNext()) {
        this.nextIndex++;
        return (this.visits[this.nextIndex - 1]);
    }
    else {
        return null;
    }
};
GeoChronModel.VisitList.prototype.current = function(){
    if ((this.visits.length > 0) && (this.nextIndex != 0)) {
        return (this.visits[this.nextIndex - 1]);
    }
    else {
        return null;
    }
};

function toggleView(elem) {
	document.getElementById(elem).style.display = "inline";
	if (elem == 'otherMedia') {document.getElementById('visits').style.display="none";}
	else if (document.getElementById('otherMedia')){
		 {document.getElementById('otherMedia').style.display="none";}
	}
}
