// functions.js

// =======
// Globals
// =======

var geocoder = new GClientGeocoder();
var myMarker; //marker corresponding to the user's location

var baseIcon, baseSmallIcon;
var redIcon, redSmallIcon;
var blueIcon, blueSmallIcon;
var cyanIcon, cyanSmallIcon;
var greenIcon, greenSmallIcon;
var magentaIcon, magentaSmallIcon;
var blackIcon, blackSmallIcon;

// =========
// Functions
// =========

// Unsorted

function showAll(tab) {
//Expands all menus in a tab.
    
    var divs = tab.getElementsByTagName('div');
    for (c = 0; c < divs.length; c++) {
        if (divs[c].className == "menuBody") {
            divs[c].style.display = "block";
        }
    }
    var images = tab.getElementsByTagName('img');
    for (c = 0; c < images.length; c++) {
        if (images[c].className == "arrow") {
            images[c].src = "/graphics/arrExpanded.gif";
            images[c].removeAttribute('onmouseover');
            images[c].setAttribute('onmouseover', 'src="/graphics/arrExpanded-w.gif"');
            images[c].removeAttribute('onmouseout');
            images[c].setAttribute('onmouseout', 'src="/graphics/arrExpanded.gif"');
            if (images[c].id.substring(5, 8) == "Loc") {
                images[c].title = "Click to hide the list of venues in or near this neighborhood";
            } else {
                images[c].title = "Click to hide the list of venues playing on this day";
            }
        }
    } 
}

function hideAll(tab) {
//Hides all menus in a tab.
    
    var divs = tab.getElementsByTagName('div');
    for (c = 0; c < divs.length; c++) {
        if (divs[c].className == "menuBody") {
            divs[c].style.display = "none";
        }
    }
    var images = tab.getElementsByTagName('img');
    for (c = 0; c < images.length; c++) {
        if (images[c].className == "arrow") {
            images[c].src = "/graphics/arrCollapsed.gif";
            images[c].removeAttribute('onmouseover');
            images[c].setAttribute('onmouseover', 'src="/graphics/arrCollapsed-w.gif"');
            images[c].removeAttribute('onmouseout');
            images[c].setAttribute('onmouseout', 'src="/graphics/arrCollapsed.gif"');
            if (images[c].id.substring(5, 8) == "Loc") {
                images[c].title = "Click to show a list of venues in or near this neighborhood";
            } else {
                images[c].title = "Click to show the list of venues playing on this day";
            }

        }
    } 
}

// -------------
// Map functions
// -------------

function mapIcons() {
//Define all map pins.

    baseIcon = new GIcon();
    baseIcon.shadow = "/icons/tack3d/shadow.png";
    baseIcon.iconSize = new GSize(21, 34);
    baseIcon.shadowSize = new GSize(40, 34);
    baseIcon.iconAnchor = new GPoint(10, 34);
    baseIcon.infoWindowAnchor = new GPoint(10, 1);
    
    redIcon = new GIcon(baseIcon);
    redIcon.image = "/icons/tack3d/red.png";
    blueIcon = new GIcon(baseIcon);
    blueIcon.image = "/icons/tack3d/blue.png";  
    cyanIcon = new GIcon(baseIcon);
    cyanIcon.image = "/icons/tack3d/cyan.png";
    greenIcon = new GIcon(baseIcon);
    greenIcon.image = "/icons/tack3d/green.png";
    blackIcon = new GIcon(baseIcon);
    blackIcon.image = "/icons/tack3d/black.png";
    magentaIcon = new GIcon(baseIcon);
    magentaIcon.image = "/icons/tack3d/magenta.png";

    baseSmallIcon = new GIcon();
    baseSmallIcon.shadow = "/icons/small3d/shadow.png";
    baseSmallIcon.iconSize = new GSize(13, 25);
    baseSmallIcon.shadowSize = new GSize(28, 25);
    baseSmallIcon.iconAnchor = new GPoint(7, 25);
    baseSmallIcon.infoWindowAnchor = new GPoint(7, 1);

    redSmallIcon = new GIcon(baseSmallIcon);
    redSmallIcon.image = "/icons/small3d/red.png";
    blueSmallIcon = new GIcon(baseSmallIcon);
    blueSmallIcon.image = "/icons/small3d/blue.png";
    cyanSmallIcon = new GIcon(baseSmallIcon);
    cyanSmallIcon.image = "/icons/small3d/cyan.png";
    greenSmallIcon = new GIcon(baseSmallIcon);
    greenSmallIcon.image = "/icons/small3d/green.png";
    blackSmallIcon = new GIcon(baseSmallIcon);
    blackSmallIcon.image = "/icons/small3d/black.png";
    magentaSmallIcon = new GIcon(baseSmallIcon);
    magentaSmallIcon.image = "/icons/small3d/magenta.png";  
}

function mapZoom(latLng, zoom) {
//Pans to the new location, if at the same zoom level as current map; otherwise, jumps to it.
    if (map.getZoom() == zoom) {
        map.panTo(latLng);
    } else {
        map.setCenter(latLng, zoom);
    }
}

function createMarker(venue) {
//Creates (but doesn't place) a marker at the supplied coordinates and adds a click event for it.
    var venuePoint = new GLatLng(venue.Lat, venue.Long);
    var icon;
    switch (venue.Day) {
        case 'Sunday':
            var icon = redIcon;
            var small = redSmallIcon;
            break;
        case 'Monday':
            var icon = blueIcon;
            var small = blueSmallIcon;
            break;
        case 'Tuesday':
            var icon = cyanIcon;
            var small = cyanSmallIcon;
            break;
        case 'Wednesday':
            var icon = greenIcon;
            var small = greenSmallIcon;
            break;
        case 'Thursday':
            var icon = magentaIcon;
            var small = magentaSmallIcon;
            break;
        case 'Friday':
            var icon = blackIcon;
            var small = blackSmallIcon;
            break;
        case 'Saturday':
            var icon = blackIcon;
            var small = blackSmallIcon;
            break;
        default:
            var icon = blackIcon;
            var small = blackSmallIcon;
            break;
    }
    var tooltipName = venue.Name.replace(/&amp;/, '&');
    var marker = new GMarker(venuePoint, {icon:icon, title:tooltipName}); 
    var smallMarker = new GMarker(venuePoint, {icon:small, title:tooltipName}); 
    var directionsTo = venue.Address + ', ' + venue.City + ', WA (' + venue.Name + ')';    
    var html = '<h1 style="margin-bottom: 0">' + venue.Name + "</h1>" 
          + '<p style="margin-top: 0">' +writeIf(venue.Name2, venue.Name2 
          + '<br />') + venue.Address + ", " + venue.City + "</p>" 
          + '<p>' + venue.Day + 's, ' + venue.StartTime + writeIf(venue.ScheduleNote, ' <span style="font-size: 8pt">(' + venue.ScheduleNote + ')</span>')
          + '<br />' + writeIf(venue.InfoBoxNote, venue.InfoBoxNote + '<br />') 
          + '<img width="10" height="10" alt="" src="/icons/balloon/info.gif">&nbsp;' 
          + '<a href="/venue/' + venue.VenueID + '"><b>More Info</b></a>&nbsp;|&nbsp;' 
          + '<img width="10" height="10" alt="" src="/icons/balloon/forum.gif">&nbsp;'
          + '<a href="http://www.quiznight.net/bbpress/forum.php?id=2&venue=' + venue.VenueID + '#postform">Discuss</a><br />'
          + drivingDirections(directionsTo, venue.NextDate, venue.StartTime, false) + '</p>';
    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });
    GEvent.addListener(smallMarker, "click", function() { smallMarker.openInfoWindowHtml(html); });
    gMarker["Venue" + venue.VenueID] = marker;
    gSmall["Venue" + venue.VenueID] = smallMarker;
    gInfo["Venue" + venue.VenueID] = html;
    return;
}

function displayInfo (venueID)
{
    gMarker["Venue" + venueID].openInfoWindowHtml(gInfo["Venue" + venueID]);
}

function bigPins() {
//Make all pins big.
    if (pinsAreSmall) 
    {
        for (c in venues) 
        {
            if (venues[c].Small)
            {
                venues[c].Small = 0;
                map.removeOverlay(gSmall["Venue" + venues[c].VenueID]);
                map.addOverlay(gMarker["Venue" + venues[c].VenueID]);
            }
        }
        pinsAreSmall = false;
    }
}

function dayPins(day, venuesDiv) {
//Makes all pins small except for those belonging to the designated day.
    for (c in venues) 
    {
        if (venues[c].Day == day)
        {
            if (venues[c].Small)
            {
                venues[c].Small = 0;
                map.removeOverlay(gSmall["Venue" + venues[c].VenueID]);
                map.addOverlay(gMarker["Venue" + venues[c].VenueID]);
            }
        }
        else
        {
            if (!(venues[c].Small))
            {
                venues[c].Small = 1;
                map.removeOverlay(gMarker["Venue" + venues[c].VenueID]);
                map.addOverlay(gSmall["Venue" + venues[c].VenueID]);
            }
        }
    }
    pinsAreSmall = true;
}

function RecenterControl() {
}

RecenterControl.prototype = new GControl();

RecenterControl.prototype.initialize = function(map) {
    var thisButton = document.createElement("div");
    thisButton.style.display = "block";
    thisButton.style.backgroundColor = "#FFFFFF";
    thisButton.style.backgroundImage = "url('/graphics/mapbutton.gif')";
    thisButton.style.width = "72px";
    thisButton.style.height = "17px";
    thisButton.style.textAlign = "center";
    thisButton.style.border = "1px solid black";
    thisButton.style.cursor = "pointer";
    thisButton.appendChild(document.createTextNode("Recenter"));
    GEvent.addDomListener(thisButton, "mousedown", function() {
        this.style.backgroundImage = "url('/graphics/mapbutton-click.gif')";
    });
    GEvent.addDomListener(thisButton, "mouseout", function() {
        this.style.backgroundImage = "url('/graphics/mapbutton.gif')";
    });
    GEvent.addDomListener(thisButton, "click", function() {
        this.style.backgroundImage = "url('/graphics/mapbutton.gif')";
        mapZoom(startPoint, startZoom);
    });
    map.getContainer().appendChild(thisButton);
    return thisButton;
}

RecenterControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 30));
}

// ----------------
// String functions
// ----------------


function writeIf(field, stringToWrite) {
//Writes the value of a variable (or an optional alternate string), unless the variable is empty.
    if(field) {
        if (stringToWrite) {
            return stringToWrite;
        } else {
            return field;
        }
    } else {
        return '';
    }
}

function toggle(element, arrow, toolTipString) {
//Toggles the display of a block element on or off; optionally flips a navigational arrow.
    if(element.style.display == "block") {
        element.style.display = "none";
        if(arrow) {
            arrow.src = "/graphics/arrCollapsed.gif";
            arrow.alt = "?";
            arrow.removeAttribute('onmouseover');
            arrow.setAttribute('onmouseover', 'src="/graphics/arrCollapsed-w.gif"');
            arrow.removeAttribute('onmouseout');
            arrow.setAttribute('onmouseout', 'src="/graphics/arrCollapsed.gif"');
            arrow.title = "Click to show " + toolTipString;
        }
    } else {
        element.style.display = "block";
        if(arrow) {
            arrow.src = "/graphics/arrExpanded.gif";
            arrow.alt = "?";
            arrow.removeAttribute('onmouseover');
            arrow.setAttribute('onmouseover', 'src="/graphics/arrExpanded-w.gif"');
            arrow.removeAttribute('onmouseout');
            arrow.setAttribute('onmouseout', 'src="/graphics/arrExpanded.gif"');
            arrow.title = "Click to hide " + toolTipString;
        }
    }
}

// =============================================================================
// These functions all have to do with geocoding and saving an address for the 
// user, which can be used to provide driving directions at Google Maps.
// =============================================================================

function geo() {
//This function uses the new Google Maps geocoder to derive a set of coordinates
//for a supplied address, and save the coordinates and structured address as
//cookies.

    var geoAddress=document.geoForm.geoAddress;
    var geoSubmit = document.getElementById('geoSubmit');

    //change text of submit button
    geoSubmit.value = 'Working...';
    geoSubmit.style.color = '#888888';  

    geocoder.getLocations(geoAddress.value, function(response) {
        if (!response || response.Status.code != 200) {
            alert("Couldn't find that address. Please try again.");
            geoAddress.value = 'Enter an address';
            geoAddress.style.color = '#888888';
            geoSubmit.value = 'Save';
            geoSubmit.style.color = '#000000';
        } else {
            var place = response.Placemark[0];
            saveCookie(place);
            geoLocSet(place.address);    
                
            geoMarker(place.address, place.Point.coordinates[1], place.Point.coordinates[0]);
            }
        }
    );
}

function geoMarker(address, lat, lng) {
//Place a marker at the user's location.
    var point = new GLatLng(lat, lng);
    var icon = new GIcon();
    icon.image = '/icons/home.png';
    //icon.shadow = 'icons/cross/shadow.png';
    icon.iconSize = new GSize(27, 27);
    //icon.shadowSize = new GSize(39, 27);
    icon.iconAnchor = new GPoint(17, 14);
    icon.infoWindowAnchor = new GPoint(17, 1);

    myMarker = new GMarker(point, {icon:icon, title:'You Are Here!'});
    map.addOverlay(myMarker);
    GEvent.addListener(myMarker, "click", function() {
        myMarker.openInfoWindowHtml('<h1>You Are Here</h1><p>' + address + '</p>'); 
    });   
}

function geoLocSet(structuredAddress) {
//write structured address to geoLoc div and display it

    var geoEnterAddress=document.getElementById('geoEnterAddress');
    var geoLoc=document.getElementById('geoLoc');
    var currentAddress=document.getElementById('currentAddress');

    currentAddress.innerHTML = structuredAddress;
    geoEnterAddress.style.display = 'none';
    geoLoc.style.display = 'block';
}


function geoClear() {
//Clears the stored address and coords from the page and the cookie.

    var geoAddress=document.geoForm.geoAddress;
    var geoEnterAddress=document.getElementById('geoEnterAddress');
    var geoLoc=document.getElementById('geoLoc');
    var currentAddress=document.getElementById('currentAddress');
    var geoSubmit = document.getElementById('geoSubmit');
    
    //hide structured address; display and format input box
    currentAddress.innerHTML = '';
    geoLoc.style.display = 'none';
    geoEnterAddress.style.display = 'block';

    geoAddress.value = 'Enter an address';
    geoAddress.style.color = '#888888';
    geoSubmit.value = 'Save';
    geoSubmit.style.color = '#000000';
    
    var position = new Cookie(document, 'position', 0, '/');
    position.remove();
    
    map.removeOverlay(myMarker);
}

function saveCookie(place) {
//Saves a placemark to cookies using the Cookie object defined in cookies.js.

    var position = new Cookie(document, 'position', 360, '/', ".quiznight.net");
    position.address = place.address;
    position.latitude = place.Point.coordinates[1];
    position.longitude = place.Point.coordinates[0];
    position.store();
}

function drivingDirections(venueAddress, eventDate, eventTime, isVerbose) {
//If a position cookie is set, retrieves it and returns a link to driving and transit directions on Google Maps.
//encodeURIComponent() requires JavaScript 1.5

    var position = new Cookie(document, 'position', 360, '/');
    var ddLink = '';
    var tdLink = '';
    var directions = '';
    
    if (position.load()) {
        
        //build driving URL string
        ddLink = '<img width="10" height="10" alt="" src="/icons/balloon/driving.gif" />&nbsp;<a href="http://maps.google.com/maps?saddr=';
        ddLink += encodeURIComponent(position.address) + '&daddr=' ;
        ddLink += encodeURIComponent(venueAddress) + '" target="_blank">';
        if (isVerbose) {
            ddLink += 'Get driving directions</a>';
        } else {
            ddLink += 'Directions</a>';
        }
        
        directions = ddLink;
        
        //build and append transit URL string if venue is not in Tacoma or Everett (i.e., outside King County)
        //TODO: make the King County search more elegant and generalizable, if possible
        if (venueAddress.search(/(Tacoma|Everett), WA/) == -1) {
			tdLink = '<img width="10" height="10" alt="" src="/icons/balloon/transit.gif" />&nbsp;';
			tdLink += '<a href="http://www.google.com/transit?saddr=' + encodeURIComponent(position.address);
			tdLink += '&daddr=' + encodeURIComponent(venueAddress);
			tdLink += '&ttype=arr&date=' + eventDate;
			tdLink += '&time=' + encodeURIComponent(eventTime);
			tdLink += '" target="_blank" title="Experimental: Results may not be accurate; check with Metro before leaving">';
			if (isVerbose) {
				tdLink += 'Get transit options <span class="smaller">(Experimental)</span></a>';
			} else {
				tdLink += 'Transit</a><span style="color:#FF0000">*</span></a>';
			}
			directions += '&nbsp;|&nbsp;' + tdLink; 
        }
    }
    return directions;
}

function getLoc() {
//cookie stuff: if available, retrieve it, populate geoLoc, add the marker to the map, and re-store it
    var position = new Cookie(document, 'position', 360, '/');
    if(position.load()) {
      geoLocSet(position.address);
      geoMarker(position.address, position.latitude, position.longitude);
      position.store();
    }
}

function goToMe() {
//Pans the map to the user's saved location.
    var position = new Cookie(document, 'position');
    position.load();
    map.panTo(new GLatLng(position.latitude, position.longitude));
}

function changePhoto(thumb) {
//Changes the primary photo.
    var source = thumb.src;
    var bigSource = source.slice(0, -3) + "380";
    var primary = document.getElementById("primary");
    if(primary.src != bigSource) {
        primary.src = bigSource;
    }
    //Change cursor style on all thumbs to pointer, then change target thumb to auto.
    var j = 1;
    do {
        var imgThumb = document.getElementById('img' + j);
        imgThumb.style.cursor = 'pointer';
        imgThumb.title = 'Click to enlarge';
        j++;
    } while (document.getElementById('img' + j));
    thumb.style.cursor = 'auto';
    thumb.title = '';
}

function switchTab(tab) {
//Switches to the specified tab.

    var loc = document.getElementById('menuLoc');
    var day = document.getElementById('menuDay');
    var all = document.getElementById('menuAll');
    var tabLoc = document.getElementById('tabLoc');
    var tabDay = document.getElementById('tabDay');
    var tabAll = document.getElementById('tabAll');
    var active = '#FFFA73';
    var inactive = '#6DACE8';
    
    if (day.style.display = 'block') {
        bigPins();
    }
 
    switch (tab.id) {
        case 'tabLoc':
            loc.style.display = 'block';
            day.style.display = 'none';
            all.style.display = 'none';
            tabLoc.className = 'tabActive';
            tabDay.className = 'controlTab';
            tabAll.className = 'controlTab';
            break;
        case 'tabDay':
            loc.style.display = 'none';
            day.style.display = 'block';
            all.style.display = 'none';
            tabLoc.className = 'controlTab';
            tabDay.className = 'tabActive';
            tabAll.className = 'controlTab';

            break;
        case 'tabAll':
            loc.style.display = 'none';
            day.style.display = 'none';
            all.style.display = 'block';
            tabLoc.className = 'controlTab';
            tabDay.className = 'controlTab';
            tabAll.className = 'tabActive';

            break;
    }
}