var map;
var upc_centerlat = 34.02202;
var upc_centerlng = -118.286;
var upc_centerpoint = new GLatLng(upc_centerlat,upc_centerlng);
var hsc_centerlat = 34.061619;
var hsc_centerlng = -118.204436;
var hsc_centerpoint = new GLatLng(hsc_centerlat,hsc_centerlng);
var startZoom = 16;
var deselectCurrent = function() {};
var smarkers = new Array();
var photosrc = new Array();
var locname = new Array();
var currentmap = 'upc';
var currentmapid = 1;
var d = 0;
var threedee_layer = [new GTileLayer(new GCopyrightCollection(''), 10, 17)];
threedee_layer[0].getTileUrl = function(tile,zoom) {
    var z = 17 - zoom;
    return "./images_3d/index.php?x=" + tile.x + "&y=" + tile.y + "&zoom=" + z;
}
threedee_layer[0].getOpacity = function() { return 1.0; }
var threedee_tiles = [
        G_NORMAL_MAP.getTileLayers()[0],
        threedee_layer[0]
];
var threedee_map = new GMapType(threedee_tiles, G_NORMAL_MAP.getProjection(), 'USC');


function urldata() {

    // get url data
    var ss = location.search.substring(1);
    if(ss) {
        c = ss.indexOf('cat=');
        if(c != -1) {
	    cat = ss.substring(c+4);
            if(cat.indexOf('&') != -1) {
		cat = cat.substring(0,cat.indexOf('&'));
	    }
	    var cat_id = '';
	    if(cat=='Galleries/Auditoria') { cat_id = 'galleries'; } else { if(cat=='Parks and Plazas') { cat_id = 'park'; } else if(cat=='History Stations') { cat_id = 'history'; } else { cat_id = cat.toLowerCase(); }}
	    showCat(cat,cat_id)
        } else if(ss.indexOf('q=') != -1) {
	    var que = ss.substring(ss.indexOf('q=')+2);
	    if(que.indexOf('&') != -1) {
                que = que.substring(0,que.indexOf('&'));
            }
	    document.queryform.query.value = que;
	    searchLoc(que);
	} else if(ss.indexOf('b=') != -1) {
            var bldg = ss.substring(ss.indexOf('b=')+2);
            if(bldg.indexOf('&') != -1) {
                bldg = bldg.substring(0,bldg.indexOf('&'));
            }
            document.queryform.query.value = bldg;
            searchLoc(bldg,1);
	}

	maptype = ss.indexOf('type=');
	if(maptype != -1) {
	    showmaptype = ss.substring(maptype+5);
	    if(showmaptype.indexOf('&') != -1) {
                showmaptype = showmaptype.substring(0,showmaptype.indexOf('&'));
            }
	    if(showmaptype) {
		if(showmaptype=='satellite') { map.setMapType(G_SATELLITE_MAP); } 
		if(showmaptype=='google') { map.setMapType(G_NORMAL_MAP); }
		if(showmaptype=='hybrid') { map.setMapType(G_HYBRID_MAP); }   
	    }
	}

        zoomlevel = ss.indexOf('z=');
        if(zoomlevel != -1) {
            showzoom = ss.substring(zoomlevel+2);
            if(showzoom.indexOf('&') != -1) {
                showzoom = showzoom.substring(0,showzoom.indexOf('&'));
            }
            if(showzoom) {
                if(showzoom=='in') { map.setZoom(17); }
		if(showzoom=='out') { map.setZoom(15); }
            }
        }

	markid = ss.indexOf('id=');
	if(markid != -1) {
	    mark = ss.substring(markid+3);
	    if(mark.indexOf('&') != -1) {
		mark = mark.substring(0,mark.indexOf('&'));
	    }
	    if(mark) {
                if(mark.indexOf('\,') != -1) {
                    marklist = mark.split('\,');
		    for(j=0; j<marklist.length; j++) {
        	        for(i=0; i<markers.length; i++) {
	                    showid = markers[i].showid();
                    	    if(showid == marklist[j]) {
            	                markers[i].showmarker(); 
    	                    }
	                }
		    }
                }

		for(i=0; i<markers.length; i++) {
		    showid = markers[i].showid();
		    if(showid == mark) {
			markers[i].showmarker(); markers[i].getinfo(); markphoto = markers[i].showphoto(); 
		    }
		}
	    }
	}
    }
    utility_links();
}

// pin marker icon
var icon = new GIcon();
icon.image = "gui/pin_marker.png";
icon.shadow = "gui/pin_shadow.png";
icon.iconSize = new GSize(16, 38);
icon.shadowSize = new GSize(31, 38);
icon.iconAnchor = new GPoint(9, 37);
icon.infoWindowAnchor = new GPoint(6, 4);

// parking marker icon
var parking = new GIcon();
parking.image = "gui/parking_marker.png";                                       
parking.iconSize = new GSize(17, 17);
parking.shadowSize = new GSize(26, 17);
parking.iconAnchor = new GPoint(9, 9);
parking.infoWindowAnchor = new GPoint(7, 5);
 
// entrance marker icons
var entrance1 = new GIcon();
entrance1.image = "gui/entrance1.png";
entrance1.iconSize = new GSize(73, 42);
entrance1.iconAnchor = new GPoint(10, 1);
entrance1.infoWindowAnchor = new GPoint(10, 1);

var entrance2 = new GIcon();
entrance2.image = "gui/entrance2.png";
entrance2.iconSize = new GSize(73, 42);
entrance2.iconAnchor = new GPoint(10, 1);
entrance2.infoWindowAnchor = new GPoint(10, 1);

var entrance3 = new GIcon();
entrance3.image = "gui/entrance3.png";
entrance3.iconSize = new GSize(87, 28);   
entrance3.iconAnchor = new GPoint(1, 10);
entrance3.infoWindowAnchor = new GPoint(1, 10);

var entrance4 = new GIcon();
entrance4.image = "gui/entrance4.png";
entrance4.iconSize = new GSize(73, 42);
entrance4.iconAnchor = new GPoint(9, 42);
entrance4.infoWindowAnchor = new GPoint(9, 42);

var entrance5 = new GIcon(); 
entrance5.image = "gui/entrance5.png";
entrance5.iconSize = new GSize(73, 42);
entrance5.iconAnchor = new GPoint(9, 42);
entrance5.infoWindowAnchor = new GPoint(9, 42);

var entrance6 = new GIcon();
entrance6.image = "gui/entrance6.png"; 
entrance6.iconSize = new GSize(87, 28);
entrance6.iconAnchor = new GPoint(87, 19);
entrance6.infoWindowAnchor = new GPoint(87, 19);

var entrance7 = new GIcon();
entrance7.image = "gui/entrance7.png";
entrance7.iconSize = new GSize(87, 28);
entrance7.iconAnchor = new GPoint(87, 19);
entrance7.infoWindowAnchor = new GPoint(87, 19);

var entrance8 = new GIcon();
entrance8.image = "gui/entrance8.png";
entrance8.iconSize = new GSize(73, 42);
entrance8.iconAnchor = new GPoint(9, 42);
entrance8.infoWindowAnchor = new GPoint(9, 42);

var campi = new Array();
campi[1] = 'University Park Campus';
campi[2] = 'Health Sciences Campus';
campi[3] = 'Marina Del Rey';
campi[4] = 'Catalina';
campi[5] = 'Downtown Los Angeles';
campi[6] = 'Children\'s Hospital';
campi[7] = 'Alhambra';
campi[8] = 'Orange County Center';
campi[9] = 'State Capital Center \(Sacramento\)';
campi[10] = 'Washington, DC, Center';
campi[11] = 'Pasadena';
campi[12] = 'Hong Kong';
campi[13] = 'Mexico City';
campi[14] = 'Taipei';
campi[15] = 'Tokyo';
campi[16] = 'Downtown Arts District';

function initializePoint(pointData) {
    var point = new GLatLng(pointData.latitude, pointData.longitude);
    pointData.campusname = campi[pointData.campus];
    if(pointData.type == 'Entrance') {
        var entrance_number = pointData.name.substr(9);
        switch(entrance_number) {
        case '1': var marker = new GMarker(point, {icon:entrance1}); break;
        case '2': var marker = new GMarker(point, {icon:entrance2}); break;
	case '3': var marker = new GMarker(point, {icon:entrance3}); break;
	case '4': var marker = new GMarker(point, {icon:entrance4}); break;
	case '5': var marker = new GMarker(point, {icon:entrance5}); break;
	case '6': var marker = new GMarker(point, {icon:entrance6}); break;
	case '7': var marker = new GMarker(point, {icon:entrance7}); break;
	case '8': var marker = new GMarker(point, {icon:entrance8}); break;
	default: var marker = new GMarker(point, {icon:icon,title:pointData.name});
	}
    } else {
	if(pointData.type == 'Parking') {
            var marker = new GMarker(point, {icon:parking,title:pointData.name});
	} else {
	    var marker = new GMarker(point, {icon:icon,title:pointData.name});
	}
    }
	
    var listItem = document.createElement('li');
    listItem.setAttribute("id",pointData.id);
    var listItemLink = listItem.appendChild(document.createElement('a'));
    listItemLink.href = "#";
    listItemLink.innerHTML = pointData.name;
if(pointData.code) {
    listItemLink.innerHTML += ' ('+pointData.code+')'; 
}	

    var inputForm = document.createElement("form");
    inputForm.setAttribute("id","info");
    inputForm.setAttribute("action","");
    inputForm.onsubmit = function() { storeMarker(); return false; };

    blankRE=/^[\s]*$/;
	
    var detail = '<div class="point_detail">' + '<h4>' + pointData.name; 
    if(pointData.code != "") { 
	detail = detail.concat(' <abbr>(' + pointData.code + ')</abbr>');
    }
    detail = detail.concat('</h4>');

    if(pointData.photo != "") {
	detail = detail.concat('<img id="location_photo" class="locphoto" src="gui/spacer.gif" width="220" height="100" alt="'+pointData.name+'" />');
	photosrc[pointData.id] = '/venues/' + pointData.photo;
	locname[pointData.id] = pointData.name;
    } 

    detail = detail.concat('<p class="short_description">',pointData.short,'</p>');
    if(pointData.address) {
	detail = detail.concat('<p class="address">',pointData.address,'</p>');
    }

    if(pointData.url != "") {
        detail = detail.concat('<a class="website" href="',pointData.url,'">Website</a>');
    }
    if(pointData.code != "") {
	detail = detail.concat('<a class="accessibility" href="http://fmsmaps.usc.edu/gpix/bldgdetailsA_Z/ADA_Detail_',pointData.code,'.pdf">Accessibility</a>');
    }
//    detail = detail.concat('<span class="events"></span><br clear="left" /></div>');
    detail = detail.concat('</div>');

if((pointData.code != "")||(pointData.url != "")) { detail = detail.concat('<br clear="left" />'); }
    detail = detail.concat('</div>');
    pointData.detail = detail;
    inputForm.innerHTML = detail;

    var focusPoint = function() {
	deselectCurrent(); 
	listItem.className = 'current';
	deselectCurrent = function() { listItem.className = ''; }
	marker.openInfoWindow(inputForm);
	if(photosrc[listItem.id]) {
 	    if(!document.getElementById("location_photo")) {
		timerload(photosrc[listItem.id]);
	    } else {
		$('#location_photo').attr("src",photosrc[listItem.id]);
	    }
	}
//	loadevents(locname[listItem.id]);
	return false;
    }
 
    GEvent.addListener(marker, 'click', focusPoint);
    listItemLink.onclick = focusPoint;
	
    pointData.showmarker = function() {
	if (!pointData.visible && !pointData.def) {
	    document.getElementById('sidebar-list').appendChild(listItem);
	    pointData.visible = 1;
	    map.addOverlay(marker);
	} else {
	    if(document.getElementById('locations').checked = true) {
		document.getElementById('sidebar-list').appendChild(listItem);
	    }
	}
    }

    pointData.hidemarker = function() {
	if (pointData.visible && !pointData.def) {
	    $('#sidebar-list #marker'+pointData.id).remove();
	    map.removeOverlay(marker);
	    pointData.visible = 0;
	}
    }

    pointData.showdef = function() {
        if (!pointData.visible) {
	    map.addOverlay(marker);
	    pointData.visible = 1;
	}
	pointData.def = 1;
    }

    pointData.hidedef = function() {
        if (pointData.visible) {
            map.removeOverlay(marker);
	    pointData.visible = 0;
        }
	pointData.def = 0;
    }

    pointData.showid = function() {
        return pointData.id;
    }

    pointData.showname = function() {
	return pointData.name;
    }

    pointData.showphoto = function() {
	return pointData.photo;
    }

    pointData.showlat = function() {
	return pointData.latitude;
    }

    pointData.showlong = function() {
        return pointData.longitude;
    }

    pointData.showcode = function() {
        if(pointData.code) {
            return pointData.code;
        } else {
            return false;
        }
    }

    pointData.showvis = function() {
	if(pointData.visible) {
	    return true; 
	} else {
	    return false;
	}
    }

    pointData.getinfo = function() {
	marker.openInfoWindow(inputForm);
        if(pointData.photo) {
            if(!document.getElementById("location_photo")) {
        	timerload('/venues/'+pointData.photo);
            } else {
		$('#location_photo').attr("src",'/venues/'+pointData.photo);
	    }
        }
    }

    pointData.hidemarker();
}

function timerload(which) {  
    window.setTimeout(function() {
        $('#location_photo').attr("src",which);
    }, 1250);
}

// search function

function searchLoc(which,bldg) {
    if(bldg) {
	var searchscript = 'search_bldg.php';
    } else {
	var searchscript = 'search.php';
    }

if(smarkers) {
    for (id in smarkers) {
        is_visible = smarkers[id].visible;
        if(is_visible) {
            smarkers[id].hidemarker();
        }
    }
}

    // if all locations are currently checked by default
    allchecked = document.getElementById('locations').checked;
    if(allchecked) {
	document.getElementById('locations').checked = false;
	hideDefaults();
    }

    // hide buildings and close categories if open
    hideMarked(); $("h4.on").removeClass("on").addClass("off"); $('#events').hide();

    for (id in markers) {
	is_visible = markers[id].showvis();
	if(is_visible) {
	    markers[id].hidemarker();
	}
    }


    $('.expanded ul:visible').slideUp();
    $('#sidebar-list').remove();
    $('.expanded').removeClass('expanded').addClass('expandable');


    // show search results
    $('#search_results:hidden').show();
    $('#search_results').addClass('expanded');
    $('#search_results').append('<ul id="sidebar-list"></ul>');

    if(!which) {
	var query = document.getElementById('query').value;
    } else {
	var query = which;
    }

    if(query.length > 1) {
    var getVars = "?query=" + query.replace(/&/g, ".ampersand.");

    GDownloadUrl(searchscript + getVars, function(data,responseCode) {	
	eval(data);
	if(smarkers.length) {
	    var bc_lat = 0;
	    var bc_long = 0;
	    var i = j = k = 0;
        var otherc = mapindex = lastmap = '';
	    var offmap = new Array;
	    for(id in smarkers) {
		i++;
		if(smarkers[id].campus == currentmapid) {
		    initializePoint(smarkers[id]);
		    smarkers[id].showmarker();
		    bc_lat = bc_lat + smarkers[id].showlat();
		    bc_long = bc_long + smarkers[id].showlong(); k++
		} else {
		    if(smarkers[id].campus) {
			otherc = smarkers[id].campus;
			offmap[j] = otherc+'|'+id;
			j++;
		    }
		}
	    }

            if(currentmapid == 2) { var zip = 90033; } else { var zip = 90089; }
//            $('#sidebar-list').append('<li class="other"><a href="http://maps.google.com/maps?q='+query+'+near+'+zip+'">Search Google Maps for more results</a></li>');


	    bc_lat = (bc_lat / i);
	    bc_long = bc_long / i;
	    var bc = new GLatLng(bc_lat,bc_long);
//var cmap = currentmap.toUpperCase();
if(!k) { $('#sidebar-list').append('<li class="other">Sorry, there are no matching locations on the '+currentmap.toUpperCase()+' map.</li>'); }

	    if(j) {
		$('#sidebar-list').append('<li class="other">There are <strong>'+j+'</strong> search results within other campuses and maps. <a href="#" id="showallresults">Show all results</a></li>');
		$('#showallresults').click(function() { 
            if($('#showallresults').html() == 'Show all results') {
            $('#showallresults').html('Hide other results'); 
            offmap.sort();
		    for (k=0; k<offmap.length; k++) { 
                locationindex = offmap[k].substr(offmap[k].indexOf('|')+1);
                mapindex = offmap[k].substr(0,offmap[k].indexOf('|'));

                if(!lastmap || (mapindex != lastmap)) { 
                    $('#sidebar-list').append('<li class="offcamp"><h4>'+campi[mapindex]+'</h4></li>'); lastmap = mapindex;
                }
                initializePoint(smarkers[locationindex]);
                smarkers[locationindex].showmarker(); 
                $('#sidebar-list li#'+smarkers[locationindex].id).click(function() { 
// switch campus 
if(smarkers[locationindex].campus == 2) { 
    currentmap = 'hsc'; currentmapid=2;
    $('li#patient_care:hidden').show(); $('li#athletics:visible').hide();
    $('li#upc a').removeClass('on'); 
    $('li#hsc a').addClass('on'); 
    map.setCenter(hsc_centerpoint, startZoom, G_HYBRID_MAP); utility_links();
} else if(smarkers[locationindex].campus == 1) {
    currentmap = 'upc'; currentmapid=1;
    $('li#patient_care:visible').hide(); $('li#athletics:hidden').show();
    $('li#hsc a').removeClass('on');
    $('li#upc a').addClass('on');
    map.setCenter(upc_centerpoint, startZoom, threedee_map); utility_links();
}
});
            } } else {
            $('#showallresults').html('Show all results');
            for (k=0; k<offmap.length; k++) { 
                locationindex = offmap[k].substr(offmap[k].indexOf('|')+1);
                $('.offcamp').remove(); $('#'+smarkers[locationindex].id).remove();
            }

            }
            return false; 
		});
	    }

	    if((smarkers.length==1) && (smarkers[0].campus == currentmapid)) {
		smarkers[0].getinfo(); 
	    } else {
//		map.panTo(bc);
	    }
	} else {
	    if(currentmapid == 2) { var zip = 90033; } else { var zip = 90089; }
	    $('#search_results #sidebar-list').append('<li>Sorry, there were no results for your search. <a href="http://maps.google.com/maps?q='+query+'+near+'+zip+'">Search Google Maps for more results.</a></li>');
	} 

	utility_links();
    }); } else {
            $('#search_results #sidebar-list').append("<li>Please try entering a longer search term.</li>");
        }

}

function urlencode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
        output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + hexVal.toUpperCase();
      }
      x++;
    }
  }  
  return output;
}

function hideSearched() {
    $("#search_results:visible").slideUp();
    for (id in smarkers) {
	is_visible = smarkers[id].visible;
	if(is_visible) {
	    smarkers[id].hidemarker();
	}
    }
}

function hideMarked() {
    for (id in markers) {
	is_visible = markers[id].showvis();
	if(is_visible) {
	    markers[id].hidemarker();
	}
    }  
}

function showCat(type,type_id) {
    $('#sidebar-list').remove();
    hideSearched(); hideMarked();
    document.getElementById('locations').checked = false;
    if(type_id) {
	$('#'+type_id).append('<ul id="sidebar-list"></ul>');
    } else {
	$('#categories').append('<ul id="sidebar-list"></ul>');
    }
    var mc = 0;
    for (id in markers) {
	if((markers[id].type == type)&&(markers[id].campus==currentmapid)) {
	    markers[id].showmarker(); mc++;
	}
    }
    if(!mc) { $('#sidebar-list').html('<li>Sorry, there are no locations of this type on this campus.</li>'); }
    utility_links();
}

function hideCat(type) {
    hideSearched();
    hideMarked();
    $('#sidebar-list').remove();
    for (id in markers) {
	if(markers[id].type == type) {
	    markers[id].hidemarker();
	}
    }
    utility_links();
}


function showAllNames() {
    // remove any sidebar lists
    $('#sidebar-list').remove();

    // uncheck default checkboxes except for 'all locations'
 //   $('#defaults input').each(function() { this.checked = false; });
    document.getElementById('locations').checked = true;

    // hide search results
    hideSearched();

    // unselect building types
    $("#building_types li h4.on").removeClass("on").addClass("off");

    $('#building_names').append('<ul id="sidebar-list"></ul>');
    var lastmarker = '';
    for (id in markers) { 
	markername = markers[id].showname();
	if(markername != lastmarker) {
	lastmarker = markername;
	if(markers[id].campus==currentmapid) {
	    markers[id].showmarker(); 
	}
	}
    }
}

function hideAll() {
    $('#sidebar-list').remove();
    for (id in markers) {
        markers[id].hidemarker();
    }
}

function showDefault(type) {
    for (id in markers) {
	if (markers[id].type == type) {
	    markers[id].showdef();
	    markers[id].def = 1;
	}
    }
}

function hideDefault(type) {
    for (id in markers) {
	if (markers[id].type == type) {
	    markers[id].hidedef();
	    markers[id].def = 0;
	}
    }
}

function hideDefaults() {
    for (id in markers) {
	markers[id].hidedef();
	markers[id].def = 0;
    }
}

function get_window_size(which) {
    var window_width = window_height = 0;
    if( typeof(window.innerWidth) == 'number' ) {//Non-IE
	window_width = window.innerWidth;
	window_height = window.innerHeight;
    } else if(document.documentElement && (document.documentElement.clientWidth)) {//IE 6+ in 'standards compliant mode'
	window_width = document.documentElement.clientWidth;
	window_height = document.documentElement.clientHeight;
    } else if(document.body && (document.body.clientWidth)) {//IE 4 compatible
	window_width = document.body.clientWidth;
	window_height = document.body.clientHeight;
    }
    if(which=='width') { return window_width; } else { return window_height; }
}

function init() {
    var windowheight = (get_window_size("height") - 172);
    document.getElementById('map').style.height = windowheight + "px";
    document.getElementById('sidebar').style.height = (windowheight+27) + "px";
    var type;
    var allTypes = { 'All':[] };
	
    map = new GMap2(document.getElementById("map"));
    geocoder = new GClientGeocoder();
    map.removeMapType(G_NORMAL_MAP);
    map.addMapType(threedee_map);

    // restrict the range of zoom levels
    var mt = map.getMapTypes();
    for (var i=0; i<mt.length; i++) {
	mt[i].getMinimumResolution = function() {return 10;}
	mt[i].getMaximumResolution = function() {return 17;}
    }
	
    // monitor the window resize event and let the map know when it occurs
    if (window.attachEvent) {
	window.attachEvent("onresize", function() {
	    windowheight = (get_window_size("height") - 172);
	    document.getElementById('map').style.height = windowheight + "px";
	    document.getElementById('sidebar').style.height = (windowheight+27) + "px";
	});
    } else {
	window.addEventListener("resize", function() {
	    windowheight = (get_window_size("height") - 172);
	    document.getElementById('map').style.height = windowheight + "px";
	    document.getElementById('sidebar').style.height = (windowheight+27) + "px";
	} , false);
    }

    map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(3,16)));

// hash?
if(window.location.hash && (window.location.hash.indexOf('hsc') != -1)) {
	currentmapid=2; currentmap = 'hsc';
	map.setCenter(hsc_centerpoint,startZoom,G_HYBRID_MAP);
    $('li#upc a').removeClass('on'); 
    $('li#hsc a').addClass('on');
    $('li#patient_care:hidden').show(); $('li#athletics:visible').hide();
} else {
    map.setCenter(upc_centerpoint, startZoom, threedee_map);
    $('li#patient_care:visible').hide(); $('li#athletics:hidden').show();
}

    GEvent.addListener(map, "dragend", function() {
        utility_links();
    });

    hscpoly = new GPolygon([
        new GLatLng(34.060633,-118.214403),
        new GLatLng(34.061081,-118.213797),
        new GLatLng(34.061137,-118.213679),
        new GLatLng(34.062286,-118.211871),
        new GLatLng(34.064872,-118.208234),
        new GLatLng(34.065014,-118.207998),
        new GLatLng(34.065085,-118.207676),
        new GLatLng(34.065277,-118.206298),
        new GLatLng(34.065321,-118.206158),
        new GLatLng(34.065503,-118.205037),
        new GLatLng(34.065543,-118.203894),
        new GLatLng(34.065628,-118.203776),
        new GLatLng(34.06561,-118.202983),
        new GLatLng(34.064877,-118.19868),
        new GLatLng(34.064792,-118.198621),
        new GLatLng(34.064521,-118.197044),
        new GLatLng(34.062708,-118.197902),
        new GLatLng(34.062606,-118.197876),
        new GLatLng(34.062072,-118.198208),
        new GLatLng(34.06197,-118.198246),
        new GLatLng(34.060695,-118.199029),
        new GLatLng(34.057704,-118.200912),
        new GLatLng(34.055988,-118.202006),
        new GLatLng(34.055953,-118.202108),
        new GLatLng(34.054691,-118.20294),
        new GLatLng(34.054979,-118.203653),
        new GLatLng(34.058197,-118.210997),
        new GLatLng(34.05889,-118.212665),
        new GLatLng(34.058993,-118.212837),
        new GLatLng(34.05905,-118.212934),
        new GLatLng(34.060135,-118.213969),
        new GLatLng(34.06041,-118.214237),
	new GLatLng(34.060633,-118.214403)
    ], '#900', 2, 0.8, '#900', 0.1);
    map.addOverlay(hscpoly);

    var mark;
    var ss = location.search.substring(1);
	markid = ss.indexOf('id=');
	if(markid != -1) {
	    mark = ss.substring(markid+3);
	    if(mark.indexOf('&') != -1) {
            mark = mark.substring(0,mark.indexOf('&'));
	    }
    }
    markers.sort(sortbytitle);

    for(id in markers) {
	initializePoint(markers[id]);
	allTypes[markers[id].type] = true;
    }

// map navigation functions

    // default checkboxes
    $('input.default').each(function() { 
	showDefault(this.value); 
	this.checked = true; 
    });

    // search field
    $('#queryform').submit(function() { searchLoc(); return false; });

    var str = "Search the map";
    var q = document.getElementById('query');
    q.value = str;
    q.onfocus = function() {
        if(q.value == str) {
            q.value='';
            q.style.color="#000";
        }
    }
    q.onblur = function() {
        if(q.value == '') {
            q.value=str;
            q.style.color="#aaa";
        } else {
            q.style.color="#000";
        }
    }

    // map switcher 
    $('#maps_menu li.c a').click(function() {
	var switchmap = (this.parentNode).id;

	// URL hash
	window.location.hash = switchmap;

	// tabs
	$('#'+currentmap+' a').removeClass('on');
	$('#'+switchmap+' a').addClass('on');

	currentmap = switchmap;
	$('#sidebar-list').remove();
	hideSearched(); hideMarked();
	$("h4.on").removeClass("on").addClass("off"); 
	$('#events').hide();

	// hide any marked buildings
	hideAll();

        // close 'Locations By Name' if open
        $('.expanded#building_names').removeClass("expanded").addClass("expandable");

        // open categories if closed
        $('.expandable#building_types').removeClass("expandable").addClass("expanded");
        $('#categories #building_types ul:hidden').slideDown();

        // uncheck any selected categories
        $("#building_types li h4.on").removeClass("on").addClass("off");


	// for HSC,
	if(switchmap == 'hsc') {
	    // set map id to 2
	    currentmapid=2;

	    // set center, zoom level, overlay
	    map.setCenter(hsc_centerpoint,startZoom,G_HYBRID_MAP);
	    $('li#patient_care:hidden').show(); $('li#athletics:visible').hide();
	} else
	// for UPC
	if(switchmap=='upc') {
	    // set map id to 1
	    currentmapid = 1;

	    // set center, zoom level, overlay
	    map.setCenter(upc_centerpoint, startZoom, threedee_map);
	    $('li#patient_care:visible').hide(); $('li#athletics:hidden').show();
	}
	utility_links();
	return false;
    });

    // location list behavior  
    $("#categories li#building_names h3").mouseup(function() {
	t = this.parentNode.className; 
	if(t=='expandable') {
	    showAllNames();
        }
    });  

    // expandable menu behavior
    $("#categories li h3").mouseup(function(){
	t = this.parentNode.className;
	if(t.indexOf('expandable') != -1) {
	    $('#categories .expanded ul').slideUp("normal"); $('#categories .expanded').removeClass("expanded").addClass("expandable");
	    $(this.parentNode).removeClass("expandable").addClass("expanded");
	    $(this.nextSibling).slideDown("normal");
	    return false;
	} else { 
	    if(t.indexOf('expanded') != -1) { 
		$(this.parentNode).removeClass("expanded").addClass("expandable");
		$(this.nextSibling).slideUp("normal");
	    }
	}
    });

    // search results, events initially hidden
    $('#search_results').hide(); $('#events').hide();

    // building category behavior
    $("#building_types li h4").mouseup(function() {   
	$('#events:visible').hide();
	t = this.className; if(t=='off') {
	$("#building_types li h4.on").removeClass("on").addClass("off");
	$(this).removeClass("off").addClass("on");
	deselectCurrent();
	if(this.innerHTML=='Parks and Plazas') {
	    var category = 'Park/Plaza';
	} else if(this.innerHTML=='History Stations') {
	    var category = 'History Station';
	} else {
	    var category = this.innerHTML;
	}
	showCat(category,this.parentNode.id);
    } else {
	if(t=='def_on') {
	    $(this).removeClass("def_on").addClass("off");
	    hideDefault(this.innerHTML);
	} else {
	    $(this).removeClass("on").addClass("off");
	    $('.expanded#building_names ul').slideUp(); $('.expanded#building_names').removeClass('expanded').addClass('expandable');
	    hideCat(this.innerHTML);
	}
    }
    });

    // display markers behavior (checkboxes)
    $("#defaults input").mouseup(function() {
	t = this.checked;
	if(!t) {
	    if(this.value=='Locations') { 
                $("#defaults input").each(function() { this.checked = false; });
		for(id in markers) {
		    if(markers[id].campus == currentmapid) {
			markers[id].showdef();
		    }
		}
	    } else {
		allchecked = document.getElementById('locations').checked;
		if(allchecked) {
		    document.getElementById('locations').checked = false;
		    hideDefaults();
		}
		showDefault(this.value);
	    }
	} else {
            if(this.value=='Locations') { 
                for(id in markers) {
                    markers[id].hidedef();
                }
           } else {
                hideDefault(this.value);
            }   
	}
    });

    $('#print').click(function() {
        utility_links();
    });

    if(ss) { urldata(); }
    utility_links();
}

function createMarker(latlng, html) {
	var marker = new GMarker(latlng);
	GEvent.addListener(marker, 'click', function() {
		var markerHTML = html;
		marker.openInfoWindowHtml(markerHTML);
	});
	return marker;
}

function mapzoom(dir) {
    if(dir == 'in') {
        map.zoomOut();
    } else if(dir == 'out') {
        map.zoomIn();
    } else { 
	return false; 
    }
}

// location event loader
function loadevents(location) { 
    var path =  "ws/eo2/feeds/event_list/32/location/"+location;
    proxy = "proxy.php?path=" + encodeURIComponent(path);
    $.get(proxy, function(data){
        if(data.indexOf('No upcoming events') == -1) {
            $('.events').html('Events').click(function() { $('#categories .expanded ul').slideUp("normal"); $('#events h3 span').html(location); $('#events .event_list').html(data); $('#events').slideDown(); return false; });
        } else {
            $('.events').hide();
        }
    });
}


// print, email functions
function utility_links() {
    var utility = '?d=';
    $('#defaults input').each(function() {
        if(this.checked) {
            utility += this.value + '+';
        }
    });
           
    $('#building_types li h4.on').each(function() {
        if(this.innerHTML=='Parks and Plazas') {
            var category = 'Park/Plaza';
        } else {
            var category = this.innerHTML;
        }
    
        utility += '&c=' + category;
    });
        
    if(document.getElementById('query').value != 'Search the map') {
	utility += '&q=' + document.getElementById('query').value;
    }

    utility += '&x=' + map.getCenter().lat();
    utility += '&y=' + map.getCenter().lng();
    utility += '&z=' + (17 - map.getZoom());

    if(document.getElementById('print')) {

if(currentmapid==2) {
//	document.getElementById('print').href = 'print.php' + utility;
document.getElementById('print').href = 'http://www.usc.edu/assets/maps/hsc_map.pdf';
document.getElementById('directions').href = 'http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1975+zonal+ave+los+angeles&sll=34.097875,-118.234863&sspn=0.141296,0.244789&ie=UTF8&ll=34.06345,-118.205767&spn=0.008195,0.013669&z=16&iwloc=A&iwstate1=dir';
} else {
document.getElementById('print').href = 'http://www.usc.edu/private/about/visit_usc/USC_UPC_map_color.pdf'
document.getElementById('directions').href = 'http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=3551+trousdale+pkwy+los+angeles&sll=37.0625,-95.677068&sspn=34.587666,62.666016&ie=UTF8&ll=34.021684,-118.285246&spn=0.017678,0.030599&z=16&iwloc=near&iwstate1=dir';
}

//document.getElementById('print').href = 'print.php' + utility;

    }
}

// title sort
function sortbytitle(a, b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

