/* Code *mostly* from yelp.com's api example. */
var map = null;
var icon = null;
var business_markers = new Array(20);

function constructYelpURL() {
    var mapBounds = map.getBounds();

    var URL = "http://api.yelp.com/" +
        "business_review_search?"+
        "callback=" + "handleResults" +
        "&term=" + document.getElementById("business_cat").value + 
        "&num_biz_requested=20" +
        "&tl_lat=" + mapBounds.getSouthWest().lat() +
        "&tl_long=" + mapBounds.getSouthWest().lng() + 
        "&br_lat=" + mapBounds.getNorthEast().lat() + 
        "&br_long=" + mapBounds.getNorthEast().lng() +
        "&ywsid=" + YWSID;
    return encodeURI(URL);
}

function updateMap() {
    // turn on spinner animation
    document.getElementById("spinner").style.visibility = 'visible';
    var yelpRequestURL = constructYelpURL();
    /* clear existing markers */
    //map.clearOverlays();
    for (i = 0; i<20; i++)  {
        if (business_markers[i] != null) {
            map.removeOverlay(business_markers[i]);
            business_markers[i] = null;
        }
    }
    /* do the api request */
    var script = document.createElement('script');
    script.src = yelpRequestURL;
    script.type = 'text/javascript';
    var head = document.getElementsByTagName('head').item(0);
    head.appendChild(script);
    return false;
}

function handleResults(data) {
    // turn off spinner animation
    document.getElementById("spinner").style.visibility = 'hidden';
    if(data.message.text == "OK") {
        if (data.businesses.length == 0) {
            $("#map_no_results").show();
            return;
        }
        $("#map_no_results").hide();
        for(var i=0; i<data.businesses.length; i++) {
            biz = data.businesses[i];
            createMarker(biz, new GLatLng(biz.latitude, biz.longitude), i);
        }
    }
    else {
        alert("Error: " + data.message.text);
        $("#map_no_results").hide();
    }
}

/*
 * Formats the categories HTML
 */
function formatCategories(cats) {
    var s = 'Categories: ';
    for(var i=0; i<cats.length; i++) {
        s+= cats[i].name;
        if(i != cats.length-1) s += ', ';
    }
    s += '<br/>';
    return s;
}

/*
 * Formats the phone number HTML
 */
function formatPhoneNumber(num) {
    if(num.length != 10) return '';
    return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10) + '<br/>';
}

function createMarker(biz, point, markerNum) {
    var infoWindowHtml = generateInfoWindowHtml(biz)
    var marker = new GMarker(point, icon);
    business_markers[markerNum] = new GMarker(point, icon);
    map.addOverlay(business_markers[markerNum]);
    GEvent.addListener(business_markers[markerNum], "click", function() {
        business_markers[markerNum].openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
    });
    // automatically open first marker
/*
    if (markerNum == 0)
        business_markers[markerNum].openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
*/
}

function generateInfoWindowHtml(biz) {
    var text = '<div class="yelp_marker">';
    // image and rating
    text += '<img class="businessimage" src="'+biz.photo_url+'"/>';
    // div start
    text += '<div class="businessinfo">';
    // name/url
    text += '<a href="'+biz.url+'" target="_blank">'+biz.name+'</a><br/>';
    // stars
    text += '<img class="ratingsimage" src="'+biz.rating_img_url_small+'"/>&nbsp;based&nbsp;on&nbsp;';
    // reviews
    text += biz.review_count + '&nbsp;reviews<br/><br />';
    // categories
    text += formatCategories(biz.categories);
    // address
    text += biz.address1 + '<br/>';
    // address2
    if(biz.address2.length) 
        text += biz.address2+ '<br/>';
    // city, state and zip
    text += biz.city + ',&nbsp;' + biz.state + '&nbsp;' + biz.zip + '<br/>';
    // phone number
    if(biz.phone.length)
        text += formatPhoneNumber(biz.phone);
    // Read the reviews
    text += '<br/><a href="'+biz.url+'" target="_blank">Read the reviews »</a><br/>';
    // div end
    text += '</div></div>';
    return text;
}
