﻿/***** Begin tab change functions *****/
function initMapTabbing(){	
	var tabs = getElementsByClass("tab",null,null);	//Get elements with a class of "tab"
    var tabSections = getElementsByClass("map-tab-section",null,null);   //Get tab body sections
	
	if (tabs.length > 0){		//If there is at least one element with a class "tab"
		for(var i=0;i<tabs.length;i++){	//Loop through all elements with class "tab"
			addEvent(tabs[i],"click",mapTabClick);	//Attach click event
		}		
	}
}

function mapTabClick(event,tab){    
    var tabs = getElementsByClass("tab",null,null);	//Get tabs
    var tabSections = getElementsByClass("map-tab-section",null,null);   //Get tab body sections
   
	var newImgSrc;
		
	for(var t=0;t<tabs.length;t++){ //Loop through all tabs
	    var tabObj = tabs[t];
	    var tabSectionObj = tabSections[t];
	    	    
	    if((tabObj == this) || (t == tab)){ //Change clicked tab on
            tabObj.setAttribute(classAttribute, "tab selected");
            tabSectionObj.style.display = "block";
            
            var imgSrc = getImgSrc(tabObj);            
	        newImgSrc = imgSrc.replace('off.','on.','gi');
		    tabObj.setAttribute('src',newImgSrc);
		    
		    
		    removeEvent(tabObj,"mouseover",rollover);	//Attach mouseover event
			removeEvent(tabObj,"mouseout",rollover);	//Attach mouseout event	
	    }
	    else {	//Change other tabs off	        
            tabObj.setAttribute(classAttribute, "tab");
            tabSectionObj.style.display = "none";
            
            var imgSrc = getImgSrc(tabObj);            
	        newImgSrc = imgSrc.replace('on.','off.','gi');
		    tabObj.setAttribute('src',newImgSrc);
		    addEvent(tabObj,"mouseover",rollover);	//Attach mouseover event
			addEvent(tabObj,"mouseout",rollover);	//Attach mouseout event		    
	    }
	}
}

/***** End tab change functions *****/

/***** Begin mapping helper functions *****/
//Global variables
var map;
var zoom = 10;
var gdir;
var geocoder = null;
var defaultLat = 41.884387437207835; 
var defaultLng = -87.62781143188477;
var nearestLat = defaultLat; 
var nearestLng = defaultLng; 
var mapsResults = "maps-results"   
var resultsContent = "results-content";
var directionsHeader = "directions-header";
var directionsLinks = "directions-links";
var directionsExtras = "directions-extras";
var loadingMessage = null;
var svClient = null;
var svButton = null;
var svOverlay = null;
var svMarker;
var svIcon = null;
var panorama = null;
var lastMarkerLocation = null;
var tOverlay = null;
//mapTimer holds the setTimeout for mapping members so we can cancel it if user quickly clicks again
var mapTimer;
var memberResults = [];
var fromAddress = _gel('fromAddress');
var toAddress = _gel('toAddress');
var reverseFromAddress = null;
var reverseToAddress = null;
    
//fullMemberList Array positions
var memCat = 0;
var memHood = 1;
var memLat = 2; 
var memLong = 3;
var memNum = 4;
var memName = 5;
var memAddr = 6;
var memCity = 7;
var memState = 8;
var memZip = 9;
var memPhone = 10;
var memUrl = 11;
var memSendUrl = 12;

//fullMemberList filtered
var filtMemberList = [];
var resultsDiv = "maps-results";

function initGetFilters(){
    var filterContainer = _gel('maps-filter');
    var input = filterContainer.getElementsByTagName('input');
    
    if (input.length > 0){
		for(var i=0;i<input.length;i++){		    
			addEvent(input[i],"click",getValue);
		}		
	}
}

function getValue(){
    // clear the loading message when users clicks again
	clearTimeout(mapTimer);
	
	// reset street view marker location
	setNearestLatLng(defaultLat,defaultLng);
    
    // Create a HtmlControl to contain a 'map loading' message and add it to the map first create the HTML	
    var html='<div id="map-loading"><img src="_layouts/images/cctb/ajax_loader.gif" width="32" height="32" alt="" />Please wait while the map is loading.</div>';
    //	second create the HtmlControl, no optional arguments passed so default settings will be used for visible(true), selectable(false) and printable(false)
    loadingMessage=new HtmlControl(html);
    //	last we add the new control to the map, overriding HtmlControl's default map position
    //	HtmlControl's default map position is GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7))
    map.addControl(loadingMessage, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(165, 160)));

    //Change zoom level
    zoom = 10;    
    //Set map center to the nearest latitude and longitude
    map.setCenter(new GLatLng(defaultLat,defaultLng), zoom);
    
    var totalChecks = 0;
    var catFilters = _gel('category-filters').getElementsByTagName('input');
    var hoodFilters = _gel('neighborhood-filters').getElementsByTagName('input');
    var catValues = [];
    var hoodValues = [];
    
    for(i=0;i<catFilters.length;i++){
        if(catFilters[i].checked == true){
            var catValue = catFilters[i].parentNode.getAttribute(classAttribute);
            catValues.push(catValue);
            totalChecks++;
        }
    }        
    
    if (catValues.length == 0) {
        catValues = null;
    }
    
    for(j=0;j<hoodFilters.length;j++){
        if(hoodFilters[j].checked == true){
            var hoodValue = hoodFilters[j].parentNode.getAttribute(classAttribute);
            hoodValues.push(hoodValue);
            totalChecks++;
        }
    }
    
    if (hoodValues.length == 0) {
        hoodValues = null;
    }
    
    if(totalChecks > 0){  
        var m = function(){    
            mapMembers(catValues,hoodValues);
        };
        mapTimer = window.setTimeout(m, 100); 
    }
    else {
        populateResults("","","none");
    }

}

function mapMembers(catValues,hoodValues){    
    //Clear the map of all markers
    map.clearOverlays();
    
    //Reset traffic and streetview
    mapButtonsOff();
       
    var memberArray = getMemberArray(catValues,hoodValues);
    
    if (memberArray){
        mapCoords(memberArray);
	    listMembers(memberArray);
	}
}

function searchNearby(hood){
    var catFilters = _gel('category-filters').getElementsByTagName('input');
    var hoodFilters = _gel('neighborhood-filters').getElementsByTagName('input');
    var hoodValues = [hood];
    var catValues = null;
    
    //Change zoom level
    zoom = 13;
    //Set map center to the nearest latitude and longitude
    map.setCenter(new GLatLng(nearestLat,nearestLng), zoom);
    
    mapMembers(catValues,hoodValues);
    
    //Uncheck all filters
    unCheckAll();
    
    //Check the current neighborhood
    for(j=0;j<hoodFilters.length;j++){
        var hoodValue = hoodFilters[j].parentNode.getAttribute(classAttribute);
        if(hoodValue == hood){
            hoodFilters[j].checked = true;
        }
    }
}

function getMemberArray(catValues,hoodValues){
    var catFilters = catValues;
    var hoodFilters = hoodValues;
    var filter1 = null;
    var filter2 = null;
    var filterType1 = null;
    var filterType2 = null;
    var arrPos1 = null;
    var arrPos2 = null;
    var filterArray1 = [];
    var filterArray2 = [];
    var memberArray = [];
    
    for(var i=0;i<fullMemberList.length;i++){
        var m = i;
        
        if ((catFilters) && (hoodFilters)){
            filter1 = catFilters;
            filter2 = hoodFilters;
            filterType1 = "category";
            filterType2 = "hood";
        }
        else if (((catFilters) && (hoodFilters == null))){
            filter1 = catFilters;
            filter2 = null;
            filterType1 = "category";
        }
        else if (((catFilters == null) && (hoodFilters))){
            filter1 = hoodFilters;
            filter2 = null;
            filterType1 = "hood";
        }
        else {
        }
        
        if(filter1){
            for(j=0;j<filter1.length;j++){
                switch(filterType1){
                    case "category":
                        arrPos1 = getCategory(fullMemberList[m]);
                        break;
                    case "hood":
                        arrPos1 = getHood(fullMemberList[m]);
                        break;
                    default:
                        break;
                }
                
                if(arrPos1.indexOf(filter1[j]) > -1){
                    var coords = getLatLong(fullMemberList[m]);
                    if(coords.indexOf("0,0") > -1){
                        //There is no latitude and longitude
                    }
                    else {
                        filterArray1.push(fullMemberList[m]);            
                    }
                }
            }
            memberArray = filterArray1;
        }
    }
    
    if(filter2){
        for(var i=0;i<filterArray1.length;i++){
            var m = i;
            
            switch(filterType2){
                case "category":
                    arrPos2 = getCategory(filterArray1[m]);
                    break;
                case "hood":
                    arrPos2 = getHood(filterArray1[m]);
                    break;
                default:
                    break;
            }
            
            for(j=0;j<filter2.length;j++){
                if(arrPos2.indexOf(filter2[j]) > -1){
                    var coords = getLatLong(filterArray1[m]);
                    if(coords.indexOf("0,0") > -1){
                        //There is no latitude and longitude
                    }
                    else {
                        filterArray2.push(filterArray1[m]);            
                    }
                }
            }
            memberArray = filterArray2;
        }
    }
    
    if (memberArray.length >= 1){
        filtMemberList = memberArray;
        return memberArray;
    }    
    else {
        var errorMsg = "There are no members matching this criteria.";
        
        //Show error msg
        populateNoResults(errorMsg);
        return null;
    }
}

function getCategory(strArray){
    var infoArray = strArray.split(";;");
    var _category = infoArray[memCat];
    return _category;
}

function getHood(strArray){
    var infoArray = strArray.split(";;");
    var _hood = infoArray[memHood];
    return _hood;
}

function getMemberCoords(memberArray){
    var members = memberArray;
    var coordsArray = [];
    
    for(var i=0;i<members.length;i++){
        var coords = getLatLong(members[i]);
        coordsArray.push(coords);
    }
    return coordsArray;
}

function getBubbleInfo(str,links){
    var infoArray = [];
    var newStr = "";
    
    infoArray = str.split(";;");
        
    newStr += "<div class=\"bubble-info\">";
    newStr += "<h4 class=\"member-name\">" + infoArray[memName] + "</h4>";
    newStr += "<address>" + infoArray[memAddr] + "<br />";
    newStr += infoArray[memCity] + ", " + infoArray[memState] + ", " + infoArray[memZip] + "</address>";
    newStr += infoArray[memPhone] + "<br />";
    newStr += "<a href=\"http://" + infoArray[memUrl] + "\" target=\"_blank\">Website</a>";
    if(links == true){
        newStr += "<div class=\"direction-links\">";
        newStr += "<strong>Get directions:</strong> <a href=\"javascript://\" onclick=\"setToAddress('" + infoArray[memAddr] + ", " + infoArray[memCity] + ", " + infoArray[memState] + ", " + infoArray[memZip] + "');\">To here</a> - ";
        newStr += "<a href=\"javascript://\" onclick=\"setFromAddress('" + infoArray[memAddr] + ", " + infoArray[memCity] + ", " + infoArray[memState] + ", " + infoArray[memZip] + "');\">From here</a>";
        newStr += "</div>";
        newStr += "<div>";
        newStr += "<a href=\"javascript://\" onclick=\"searchNearby('" + infoArray[memHood] + "');\">Search nearby</a> - ";
        newStr += "<a href=\"" +sendToFriendURL+ "?" + infoArray[memSendUrl] + "\" onclick=\"popWindow(this.href,'friend','yes','500','550'); return false;\">Send to friend</a> - ";
        newStr += "<a href=\"javascript://\" onclick=\"addToNotebook('" + infoArray[memSendUrl]+ "', '" + infoArray[memName] + "')\">Add to my notebook</a>";
        newStr += "</div>";
    }
    newStr += "<div id=\"sv-panorama\" style=\"width: 240px; height: 200px;display: none;\"></div>"; 
    newStr += "</div>";            
    return newStr;
}

function getMemberResults(str){
    var strArray = str.split(",");
    var infoArray = [];
    var newStr = "";
    var cat = null;
    var image = null;
    var imageW = "17";
    var imageH = "21";
    
    for(var i=0;i<strArray.length;i++){
        infoArray = strArray[i].split(";;");
        cat = infoArray[memCat];
        switch(cat){
            case "ATTRACT":
                image = "tour_icon";
                break;
            case "DINING":
                image = "dining_icon";
            case "HOTEL":
                image = "accommodation_icon";
                break;
            case "MUSEUM":
                image = "museum_icon";
                break;
            case "NIGHTLIFE":
                image = "nightlife_icon";
                break;
            case "SHOP":
                image = "shopping_icon";
                break;
            case "THEATER":
                image = "theater_icon";
                break;
            case "TRANS":
                image = "transportation_icon";
                break;
            case "CONV_SUPP":
                image = "meeting_icon";
                break;
            case "CONV_SERV":
                image = "convention_icon"; 
                break;
            default:
                image = "generic";
                imageW = "13";
                imageH = "23";  
                break;
        } 
        newStr += "<div class=\"result-item clearfix\">";
        newStr += "<div class=\"result-number\">";
        newStr += "<img src=\"/_layouts/images/cctb/results_" + image + ".png\" class=\"tpng\" width=\"" + imageW + "\" height=\"" + imageH + "\" alt=\"" + image + "\" />";
        newStr += "</div>";
        newStr += "<div class=\"result-info\">";
        newStr += "<h4 class=\"member-name\">" + infoArray[memName] + "</h4>";
        newStr += "<address>" + infoArray[memAddr] + "<br />";
        newStr += infoArray[memCity] + ", " + infoArray[memState] + ", " + infoArray[memZip] + "</address>";
        newStr += infoArray[memPhone] + "<br />";
        newStr += "<a href=\"http://" + infoArray[memUrl] + "\" target=\"_blank\">website</a>";
        newStr += "</div>";
        newStr += "</div>";
    }
    return newStr;
}

function getLatLong(str){
    var strArray = str.split(",");
    var infoArray;
    var newStr = "";
    
    for(var i=0;i<strArray.length;i++){
        infoArray = strArray[i].split(";;");
        newStr = infoArray[memLat] + "," + infoArray[memLong];
    }
    return newStr;
}

function parseStaticAddress(str){
    var strArray = str.split(",");
    var newStr = "";
    
    for(var i=0;i<strArray.length;i++){
        newStr += strArray[i];
        if (i == 0){
            newStr += ",<br />";
        }
        else if (i < eval(strArray.length - 1)){
            newStr += ", ";
        }
    }
    return newStr;
}

function populateResults(uls,pagination,state){
    //Remove all child elements from the results container
    clean(resultsContent);
    
    //Remove the directions-links and directions-header elements if they exist
    if(_gel(directionsLinks)){
        var results = _gel(mapsResults);
        results.removeChild(_gel(directionsHeader));
        results.removeChild(_gel(directionsLinks));
    }
    
    //Remove Google's default inline styles
    _gel(resultsContent).style.padding = "0";
    
    //Clear the member results array    
    memberResults = [];
    
    //Show maps-results
    _gel(mapsResults).style.display = state;
    
    //Hide maps extras
    _gel(directionsExtras).style.display = "none";
    
    if(state == "block"){
        _gel(resultsDiv).style.display = state;
        for(var i=0;i<uls.length;i++){
            _gel(resultsContent).appendChild(uls[i]);
        }
        _gel(resultsContent).appendChild(pagination);
    }
    else if(state == "none") {
        //clear the loading message when users clicks again
	    clearTimeout(mapTimer);
        map.removeControl(loadingMessage);
        
        //Clear the map of all markers
        map.clearOverlays();
        
        //Reset traffic and streetview
        mapButtonsOff();
     }
     else {
     }
}

function populateNoResults(msg){
    //First remove all child elements from the results container
    clean(resultsContent);
    
    //Remove Google's default inline styles
    _gel(resultsContent).style.padding = "0";
    
    //Clear the member results array    
    memberResults = [];
        
    //Show maps-results and results-content
    _gel(mapsResults).style.display = "block";    
    _gel(resultsDiv).style.display = "block";
    
    // Hide directions extras
    _gel(directionsExtras).style.display = "none";
    
    //Remove loading message
    map.removeControl(loadingMessage);
    
    var noResults = document.createElement("div");
    noResults.setAttribute(classAttribute, "no-results");
    noResults.innerHTML = msg;
    _gel(resultsContent).appendChild(noResults);
}

function listMembers(memberArray){
    var resultsStr = "";//Results HTML
    var count = 0; //Counter for pages of results
    var olStart = 0; //Used to set the numbering on <ol> elements
    var page = 1; //Keeps track of the number of pages of results
    var pageSize = 5; //Number of results per page
    var totalMembers = memberResults.length; //Total number of members in the results
    var pageArray = [];
    
    for(var i=0;i<totalMembers;i++){
        count++;
        olStart++;
        
        if((count==1)){
            var pageContainer = document.createElement("div");
            pageContainer.setAttribute("id", "page" + page);
            pageContainer.setAttribute(classAttribute, "results-page");
            
            var header = document.createElement("h4");
            header.setAttribute(classAttribute, "results-header");
                        
            var ol = document.createElement("ol");
            ol.setAttribute("start", olStart);
            
            var rangeStart = olStart;
        } 
        
        header.innerHTML = "Results " + rangeStart + " through " + eval((i + 1)) + " of " + totalMembers;
        pageContainer.setAttribute(classAttribute, ((page>1)?"results-page hidden":"results-page"));
         
        ol.appendChild(memberResults[i]);
        if((count==pageSize)||(i==eval(totalMembers-1))){
            count=0;
            ((i==eval(totalMembers-1))? null:page++);
            pageContainer.appendChild(header);
            pageContainer.appendChild(ol);
            pageArray.push(pageContainer);
        }
    }
    
    var pager = "";//pagination HTML
    var totalPages = page; //Total number of pages of results
    var count2 = 0;//Counter for pages of links
    var p = 0; //Number of links to build
    var linkPage = 1; //Keeps track of the number of pages of links
    var linkPageBack = 1;
    var linksSize = 5; //Number of links on each page of link
    
    while(p<totalPages){
        p++;
        count2++;
        if((count2==1)){
            linkPageBack = linkPage - 1;
            pager +="<div id=\"pager-container" + linkPage + "\" class=\"";
            pager += ((linkPage>1)?"hidden":"");
            pager += "\">";
            pager += ((linkPage>1)?"<a href=\"javascript://\" onclick=\"pageLinks(" + linkPageBack + ")\" id=\"page-link-previous" + linkPage + "\"><strong>&lt;</strong></a>":""); 
        }
        pager += "<a href=\"javascript://\" onclick=\"pageResults(" + p + ")\" id=\"page-link" + p + "\" class=\"page-link";
        pager += ((p==1)?" selected":"");
        pager += "\">" + p + "</a>";
        if((count2==linksSize)||(p==totalPages)){
            linkPage++;
            pager += ((count2==linksSize)?"<a href=\"javascript://\" onclick=\"pageLinks(" + linkPage + ")\" id=\"page-link-next" + linkPage + "\"><strong>&gt;</strong></a>":"");
            pager +="</div>";
            count2=0;
        }
    }
    
    var paginationDiv = document.createElement("div");
    paginationDiv.setAttribute(classAttribute, "pagination");
    paginationDiv.innerHTML = pager;
    
    populateResults(pageArray,paginationDiv,"block");
}

function initPaging(){
    var pageLinks = getElementsByClass("page-link",null,null);
    
    if (pageLinks.length > 0){
		for(var i=0;i<pageLinks.length;i++){
			addEvent(pageLinks[i],"click",pageResults);
		}		
	}
}

function pageResults(page){
    var linkID = "page-link";
    var pages = getElementsByClass("results-page",null,null);
    var links = getElementsByClass("page-link",null,null);
    var totalPages = pages.length;    
    
    for(var i=0;i<totalPages;i++){
        if(i == eval(page-1)){
            pages[i].style.display = "block";
            _gel(linkID + page).setAttribute(classAttribute, "page-link selected");
        }
        else {
            pages[i].style.display = "none";
            links[i].setAttribute(classAttribute, "page-link");
        }
    }
}

function pageLinks(page){
    var pagerID = "pager-container" + page;
    var pages = getElementsByClass("pagination",null,null)[0].getElementsByTagName("div");
    var totalPages = pages.length;
    
    for(var i=0;i<totalPages;i++){
        if (pages[i].getAttribute("id") == pagerID){
            pages[i].style.display = "block";
        }
        else {
            pages[i].style.display = "none";
        }
    }
}

function unCheckAll(){
    var filterContainer = _gel('maps-filter');
    var input = filterContainer.getElementsByTagName('input');
    
    if (input.length > 0){
		for(var i=0;i<input.length;i++){		    
			input[i].checked = false;
		}		
	}
}
/*	Google Maps API HtmlControl v1.1.1
	based on code posted on Google Maps API discussion group
	last updated/modified by Martin Pearman 20th January 2008
	
	http://googlemapsapi.martinpearman.co.uk/htmlcontrol
	
	This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

function HtmlControl($html, $options){
	this._html=$html;
	this.isVisible=true;
	this._isPrintable=false;	
	this._isSelectable=false;
	if($options){
		this.isVisible=($options.visible===false)?false:true;
		this._isPrintable=($options.printable===true)?true:false;
		this._isSelectable=($options.selectable===true)?true:false;
	}
	this.setVisible=function($bool){
		this._div.style.display=($bool)? 'block':'none';
		this.isVisible=$bool;
	};
}
if( typeof GControl != 'undefined') HtmlControl.prototype=new GControl();
HtmlControl.prototype.initialize=function($map){
	this.selectable=function(){
		return this._isSelectable;
	};
	this.printable=function(){
		return this._isPrintable;
	};
	this._div=document.createElement('div');
	this._div.innerHTML=this._html;
	this.setVisible(this.isVisible);
	$map.getContainer().appendChild(this._div);
	return this._div;
};
HtmlControl.prototype.getDefaultPosition=function(){
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7));
};

/***** End mapping helper functions *****/

/***** Begin mapping functions *****/     
function initialize() 
{      
    if (GBrowserIsCompatible()) 
    {        
        //builds basic map
        map = new GMap2(document.getElementById("map_canvas"));        
        map.setCenter(new GLatLng(defaultLat,defaultLng), zoom);
        map.enableScrollWheelZoom();
        
        //adds left navigation
        map.addControl(new GLargeMapControl());
        
        //adds mini overview draggable map       
        //map.addControl(new GOverviewMapControl());
        
        //adds map types
        map.addControl(new GMapTypeControl());
        
        //adds Google Earth button
        //map.addMapType(G_SATELLITE_3D_MAP);
        
        //Create Streetview Client client
        svClient = new GStreetviewClient();
        
        //Create Streetview Icon
        svIcon = new GIcon(G_DEFAULT_ICON);
        svIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
        svIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
        svIcon.imageMap = [
            26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
            16,20, 16,14, 19,13, 22,8
         ];
        svIcon.iconSize = new GSize(49, 52);
        svIcon.iconAnchor = new GPoint(25, 35);  // near base of guy's feet
        svIcon.infoWindowAnchor = new GPoint(25, 5);  // top of guy's head
    
        // Create a HtmlControl to contain a streetview toggle button	
        var svhtml='<div id="streetview-button" class="map-button" onclick="toggleStreetView();"><span>Street View</span></div>';
        //	second create the HtmlControl, no optional arguments passed so default settings will be used for visible(true), selectable(false) and printable(false)
        svButton=new HtmlControl(svhtml);
        //	last we add the new control to the map, overriding HtmlControl's default map position
        //	HtmlControl's default map position is GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7))
        map.addControl(svButton, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(260, 7)));
        
        // Create a HtmlControl to contain a traffic toggle button	
        var thtml='<div id="traffic-button" class="map-button" onclick="toggleTraffic();"><span>Traffic</span></div>';
        //	second create the HtmlControl, no optional arguments passed so default settings will be used for visible(true), selectable(false) and printable(false)
        svButton=new HtmlControl(thtml);
        //	last we add the new control to the map, overriding HtmlControl's default map position
        //	HtmlControl's default map position is GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7))
        map.addControl(svButton, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(357, 7)));
        
        //add geocoder
        geocoder = new GClientGeocoder();
        
        //add directions
        gdir = new GDirections(map, document.getElementById(resultsContent));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);    
    }    
}             

function mapCoords(memberArray) 
{    
    var coordsArray = getMemberCoords(memberArray);
    var latLong = coordsArray;
    var marker;                
    var sidebar = _gel('sidebar-results');
    
    for(var i=0;i<latLong.length;i++){
        var coords = latLong[i].split(",");
        var lat = parseFloat(coords[0]);
        var lng = parseFloat(coords[1]);
        
        var cat = getCategory(memberArray[i]);
        
        var point = new GLatLng(lat,lng);
        marker = createMarker(map,point,i,cat,lat,lng);
        map.addOverlay(marker);                   
        
        var sidebarEntry = createSidebarEntry(marker,point,i,lat,lng);
        memberResults.push(sidebarEntry);
    }
    
    if(map.isLoaded){
        map.removeControl(loadingMessage);
    }
}    

function createMarker(map,point,number,cat,lat,lng){
    var memberInfo = filtMemberList;//filtered member list;
    var member = memberInfo[number];

    // Set up our GMarkerOptions object
    markerOptions = { icon:getIcons(cat) };
    var marker = new GMarker(point, markerOptions);
    
    GEvent.addListener(marker, "click", function() {
        var contentNode = document.createElement('div');
        
        var winHTML = getBubbleInfo(member,true);
        
        var infoArray = member.split(";;");
        
        //latitude and longitude for panorama
        var latlng = point;
        
        //Set the nearest latitude and longitude for the streetview marker
        setNearestLatLng(lat,lng);
        
        var svc = new GStreetviewClient();
        svc.getNearestPanorama(latlng, function(panoData){
            // If no panorama is available, do not add the expand button
            if (panoData.code != 200) {
                marker.openInfoWindowHtml(winHTML);
                _gel("sv-panorama").style.display = "none";
            }
            else {
                marker.openInfoWindowHtml(winHTML, {maxContent: contentNode, maxTitle: "Street View: " + infoArray[memName] + ", " + infoArray[memAddr]});
                //Add panorama to the info window
                setBubblePanorama(latlng,contentNode,"598","320","sv-panorama");
            }
        }
        );
    });

    return marker;     
}

function createSidebarEntry(marker,point,number,lat,lng) {
    var li = document.createElement('li');
    var memberInfo = filtMemberList;//filtered member list;
    var html = getMemberResults(memberInfo[number]);
    
    li.innerHTML = html;
    li.style.cursor = 'pointer';
    li.style.marginBottom = '5px'; 
    
    GEvent.addDomListener(li, 'click', function() {
        GEvent.trigger(marker, 'click');
        //reset the map center and zoom in one more level
        map.setCenter(point);
        
        //Set the nearest latitude and longitude for the streetview marker
        setNearestLatLng(lat,lng);       
    
        location.href = "#map-container";
        
    });
    GEvent.addDomListener(li, 'mouseover', function() {
        li.setAttribute(classAttribute, "selected");
    });
    GEvent.addDomListener(li, 'mouseout', function() {
        li.setAttribute(classAttribute, "");
    });
    return li;
}

function getIcons(cat) {
    var image = null;
    var icon = new GIcon();
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.infoShadowAnchor = new GPoint(18, 25);
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 0);
    icon.iconSize = new GSize(21, 27);
    icon.shadow = "/_layouts/images/cctb/pin_shadow.png"; 
    icon.shadowSize = new GSize(35, 27);
    icon.infoShadowAnchor = new GPoint(22, 25);
    switch(cat){
        case "ATTRACT":
            image = "tour_icon";
            break;
        case "DINING":
            image = "dining_icon";
            break;
        case "HOTEL":
            image = "accommodation_icon";
            break;	
        case "MUSEUM":
            image = "museum_icon";
            break;
        case "NIGHTLIFE":
            image = "nightlife_icon";
            break;
        case "SHOP":
            image = "shopping_icon";
            break;
        case "THEATER":
            image = "theater_icon";
            break;
        case "TRANS":
            image = "transportation_icon";
            break;
        case "CONV_SUPP":
            image = "meeting_icon";
            break;
        case "CONV_SERV":
            image = "convention_icon"; 
            break;
        default:
            image = "generic"; 
            icon.shadow = "http://www.google.com/mapfiles/shadow50.png";        
            icon.iconSize = new GSize(17, 31);
            icon.shadowSize = new GSize(34, 31);
            icon.iconAnchor = new GPoint(9, 31);
            icon.infoWindowAnchor = new GPoint(9, 2);
            icon.infoShadowAnchor = new GPoint(18, 25);
            break;
    }        
    icon.image = "/_layouts/images/cctb/pin_" + image + ".png";
    
    return icon;
}

function showAddress() 
{
    var address = _gel("plotAddress").value;
    
    if (geocoder) 
    {
        geocoder.getLatLng(address,function(point) 
        {
            if (!point) 
            {
                //alert(address + " not found");
            } 
            else 
            {
                map.setCenter(point, 11);
                var marker = createGeoMarker(map,point,address);
                map.addOverlay(marker);
                marker.openInfoWindowHtml(parseStaticAddress(address));
            }
        });
    }
}
function createGeoMarker(map,point,address){   
    // Set up our GMarkerOptions object
    markerOptions = { icon:getIcons('generic') };
    var marker = new GMarker(point, markerOptions);

    GEvent.addListener(marker, "click", function() {
        var winHTML = parseStaticAddress(address);
        marker.openInfoWindowHtml(winHTML);
    });

    return marker;     
}
function handleErrors()
{
    var errorMessage = document.createElement("p");
    errorMessage.setAttribute(classAttribute, "maps-error");
    
    var msg = null;
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    {
        msg = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code;
    }
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    {
        msg = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
    }
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    {
        msg = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;
    }
    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     msg = "The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    {
        msg = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
    }
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    {
        msg = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
    }
    else 
    {
        msg = "An unknown error occurred.";
    }
    //Show error message
    errorMessage.innerHTML = msg;
    _gel(resultsContent).appendChild(errorMessage);
}

function onGDirectionsLoad()
{ 
//        if(gdir.getStatus().code == G_GEO_SUCCESS)
//        {
//            window.setTimeout(function(){_gel(resultsContent).setAttribute("style", "")}, 200);
//        }
}

function setDirections(order) 
{
    //Clear the map of all markers
    map.clearOverlays();
    
    //Reset traffic and streetview
    mapButtonsOff();
    
    //Uncheck all checkboxes
    unCheckAll();
    
    //Remove all child elements from the results container
    clean(resultsContent);
    
    //Show maps-results
    _gel(mapsResults).style.display = "block";
    
    //Show extras content
    _gel(directionsExtras).style.display = "block";
    
    if(_gel(directionsLinks) == null){
        //Add directions header
        var dirHeader = document.createElement("h4");
        dirHeader.setAttribute("id", directionsHeader);
        dirHeader.innerHTML = "<span class=\"float-left\">Driving Directions</span> <span class=\"float-right\">Distance</span>";
        _gel(mapsResults).insertBefore(dirHeader, _gel(resultsContent));
        
        //Add direction links
        var dirLinks = document.createElement("div");
        dirLinks.setAttribute("id", directionsLinks);
        dirLinks.setAttribute(classAttribute,"clearfix");
        dirLinks.innerHTML = "<a href=\"javascript: return false\" onclick=\"return setDirections('reverse');\" class=\"float-left\">Get reverse directions</a>";
        _gel(mapsResults).insertBefore(dirLinks, _gel(resultsContent));
    }
    var fromValue = null;
    var toValue = null;
    var locale = 'en';
    
    if(order == null){
        fromValue = fromAddress.value;
        toValue = toAddress.value;
        reverseFromAddress = toValue;
        reverseToAddress = fromValue;
    }
    else if (order == "reverse"){
        fromValue = reverseFromAddress;
        toValue = reverseToAddress; 
        reverseFromAddress = toValue;
        reverseToAddress = fromValue;   
    }
    
    gdir.load("from: " + fromValue + " to: " + toValue,{ "locale": locale });
}

function setFromAddress(address){
    mapTabClick("",0);	
	removeEvent(fromAddress,"click",clearValue);
	removeEvent(fromAddress,"focus",clearValue);
	
	//Remove the class that also sets the style for the input before the value is cleared.
    var classValue = fromAddress.getAttribute(classAttribute);
    var newClassValue = classValue.replace('clear-value','','gi');
    fromAddress.setAttribute(classAttribute, newClassValue);
    fromAddress.value = address;
    if(toAddress.value != "End Address"){
        toAddress.value = "";
    }
}

function setToAddress(address){
    mapTabClick("",0);	
	removeEvent(toAddress,"click",clearValue);
	removeEvent(toAddress,"focus",clearValue);
	
	//Remove the class that also sets the style for the input before the value is cleared.
    var classValue = toAddress.getAttribute(classAttribute);
    var newClassValue = classValue.replace('clear-value','','gi');
    toAddress.setAttribute(classAttribute, newClassValue);
    toAddress.value = address;
    if(fromAddress.value != "Start Address"){
        fromAddress.value = "";
    }
}

//Streetview functions
function setNearestLatLng(lat,lng){
    nearestLat = lat;
    nearestLng = lng;
}

function toggleStreetView() {
  var nearestlatlng = new GLatLng(nearestLat,nearestLng);
  
  var svc = new GStreetviewClient();
  svc.getNearestPanorama(nearestlatlng, function(panoData){
        // If no panorama is available, set the marker to the default latitude and longitude
        if (panoData.code != 200) {
            var latlng = new GLatLng(defaultLat,defaultLng);
            showPano(latlng);
        }
        else {
            var latlng = new GLatLng(nearestLat,nearestLng);
            showPano(latlng);
        }
    }
  );
}
 
function showPano(latlng){
  var button = _gel("streetview-button").getElementsByTagName("span")[0];
  
  if (!svOverlay) {
    svOverlay = new GStreetviewOverlay();
    map.addOverlay(svOverlay);
    button.style.fontWeight = "bold";
    button.style.borderColor = "rgb(52, 86, 132) rgb(108, 157, 223) rgb(108, 157, 223) rgb(52, 86, 132)";
    
    svMarker = new GMarker(latlng, {icon: svIcon, draggable: true});
    map.addOverlay(svMarker);
    lastMarkerLocation = latlng;
    GEvent.addListener(svMarker, "dragend", onDragEnd);
    GEvent.addListener(svMarker, "click", openPanoramaBubble);  
  } 
  else {
    map.removeOverlay(svOverlay);
    map.removeOverlay(svMarker);
    svOverlay = null;
    button.style.fontWeight = "normal";
    button.style.borderColor = "#fff";
  }
}

function openPanoramaBubble() {    
    var contentNode = document.createElement('div');
    svMarker.openInfoWindow("<div id='sv-panorama' style='width:240px;height:200px;'></div>", {maxContent: contentNode, maxTitle: "Street View"});
    
    var latlng = svMarker.getLatLng();
    
    setBubblePanorama(latlng,contentNode,"598","320","sv-panorama");
}

function setBubblePanorama(latlng,contentNode,width,height,id){
    contentNode.setAttribute("id", "panorama-container");
    contentNode.style.textAlign = "center";
    contentNode.style.width = width + "px";
    contentNode.style.height = height + "px";
    contentNode.innerHTML = "Loading...";
    contentNode.style.marginTop = "10px";
    
    panorama = new GStreetviewPanorama(_gel(id));
    panorama.setLocationAndPOV(latlng, null);
    GEvent.addListener(panorama, "newpano", onNewLocation);
    GEvent.addListener(panorama, "yawchanged", onYawChange); 
    GEvent.addListener(panorama, "error", function(error){
        handlePanoramaErrors(error,id);
    });
    
    //Add a message to indicate how to expand the info bubble
    var expandImg = "http://maps.google.com/intl/en_us/mapfiles/iw_plus.gif";
    var svMsg = document.createElement("p");
    svMsg.setAttribute("id", "expand-message");
    svMsg.innerHTML = "Click the <img src=\"" + expandImg + "\" width=\"12\" height=\"12\" alt=\"Expand icon\" /> icon to see a large Street View map.";
    var parent = _gel(id).parentNode;
    parent.insertBefore(svMsg,_gel(id));
                
    var iw = map.getInfoWindow();
    GEvent.addListener(iw, "maximizeend", function() {        
        panorama.setContainer(contentNode);  
        window.setTimeout("panorama.checkResize()", 5);
    });
}

function onYawChange(newYaw) {
  var GUY_NUM_ICONS = 16;
  var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
  if (newYaw < 0) {
    newYaw += 360;
  }
  guyImageNum = Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS;
  guyImageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + guyImageNum + ".png";
  svMarker.setImage(guyImageUrl);
}

function onNewLocation(lat, lng) {
  var latlng = new GLatLng(lat, lng);
  svMarker.setLatLng(latlng);
}

function onDragEnd() {
  var latlng = svMarker.getLatLng();
  
  if (panorama) {
    svClient.getNearestPanorama(latlng, onResponse);
  }
}

function onResponse(response) {
  if (response.code != 200) {
    svMarker.setLatLng(lastMarkerLocation);
  } else {
    var latlng = new GLatLng(response.Location.lat, response.Location.lng);
    svMarker.setLatLng(latlng);
    lastMarkerLocation = latlng;
    openPanoramaBubble();
  }
}

function handlePanoramaErrors(errorCode,id) {
    var errorMsg = "";
    if (errorCode == 603) {
        errorMsg += "<p class=\"error\">Error: Flash doesn't appear to be installed in your browser. (Code: " + errorCode + ")</p>";
        errorMsg += "<p class=\"error\">To use street view, you need Adobe Flash Player version 9 or newer. <a href='http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash' target='_blank'>Get the latest Flash Player.</a></p>";
    }
    else if(errorCode == 600){
        errorMsg = "<p class=\"error\">Error: There is no nearby streetview panorama available. Code: " + errorCode + "</p>";
    }    
    else{
    }
    _gel(id).style.display = "block";
    _gel(id).style.width = "240px";
    _gel(id).style.height = "60px";
    _gel(id).innerHTML = errorMsg;
    return;
}
//Traffic functions
function toggleTraffic() {
  var button = _gel("traffic-button").getElementsByTagName("span")[0];
  
    if (!tOverlay) {
        //adds traffic overlay
        tOverlay = new GTrafficOverlay();
        map.addOverlay(tOverlay);

        button.style.fontWeight = "bold";
        button.style.borderColor = "rgb(52, 86, 132) rgb(108, 157, 223) rgb(108, 157, 223) rgb(52, 86, 132)";
    } 
    else {
        map.removeOverlay(tOverlay);
        tOverlay = null;

        button.style.fontWeight = "normal";
        button.style.borderColor = "#fff";
    }
}

function mapButtonsOff(){
    var svbutton = _gel("streetview-button").getElementsByTagName("span")[0];
    svbutton.style.fontWeight = "normal";
    svbutton.style.borderColor = "#fff";
    svOverlay = null;
    
    var tbutton = _gel("traffic-button").getElementsByTagName("span")[0];
    tbutton.style.fontWeight = "normal";
    tbutton.style.borderColor = "#fff";
    tOverlay = null;
}
/***** End mapping functions *****/ 

/***** Begin Add to my notebook functions *****/
var loadmessage;// Variable that sets whether to show or not show the loading message
var notebookName;
function addToNotebook(qs,membername) {	// Load the XML data file
	if (qs == ''){
		//DisplayError();
	}
	else {
		var xmlFile = "/_layouts/SetSession.aspx?" + qs;	
		loadmessage = "yes"; // Show the loading message.
		notebookName = membername; //Set member name that has been added to my notebook
		var loadXML = new net.ContentLoader(xmlFile, SetXML, DisplayError,loadmessage);	//Ajax load the XML.
	}
}

function SetXML() {	// Callback function
	var response = this.req.responseText;;
	if (response.indexOf("SET")>-1){
	    alert(notebookName + " has been added to your notebook.");
	}
	else if (response.indexOf("ERROR")>-1){
	    alert("An error has occurred trying to add " + notebookName + " to your notebook. Please try again.");
	
	}
}

function DisplayError() {	// Callback function. This is called in the event the browser doesn't support the calls we're making, or if the content we try to access does not exist. 
	alert("An error has occurred trying to add " + notebookName + " to your notebook. Please try again.");
}
/***** End Add to my notebook functions *****/