﻿// JScript File

var YWSID = "LN2216w0mW-5W-9npbTmpg";
var CategoryName = "restaurants";
var YelpData = "";
var yelpMarkers = new Array();

yelpIcon = new GIcon();
yelpIcon.image = defaultAttIcon;
yelpIcon.shadow = defaultAttIconShadow;
yelpIcon.iconSize = new GSize(defaultAttIconWidth, defaultAttIconHeight);
yelpIcon.shadowSize = new GSize(defaultAttIconShadowWidth, defaultAttIconShadowHeight);
yelpIcon.iconAnchor = new GPoint(15, 29);
yelpIcon.infoWindowAnchor = new GPoint(15, 3);

/*
 * Construct the URL to call for the API request
 */
function constructYelpURL() {    
    for (i = 1; i <= document.m_FrmMain.m_AttCatID.length; i++) 
    {
        if (document.getElementById("m_AttCat" + i).checked == true) 
        {
            CategoryName = document.getElementById("m_AttCat" + i).value;
            if(CategoryName=="restaurants")
            {            
                CategoryName = document.getElementById("m_AttCat").value;
            }
            break;
        }
    }
    var mapBounds = map.getBounds();
    var URL = "http://api.yelp.com/" +
        "business_review_search?"+
        "callback=" + "handleResults" +
        "&category=" + CategoryName + 
        "&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);
}

/*
 * Called on the form submission: updates the map by
 * placing markers on it at the appropriate places
 */
function updateMap() {
    // turn on spinner animation
    // document.getElementById("spinner").style.visibility = 'visible';
    
    YelpData = "";
    YelpData += "<div align=\"center\">";
//    YelpData += "   <br /><br /><br /><br />";
    YelpData += "   <br />";
    YelpData += "   &nbsp;&nbsp;<img id=\"Img1\" src=\"images/spinner.gif\" />&nbsp;&nbsp;";
//    YelpData += "   <br /><br />";
    YelpData += "   <strong>Please Wait while Loading....<br /></strong>";                            
    YelpData += "</div>";
    
    if(CategoryName=="restaurants"){
        YelpData += "<img src=\"http://s0b.bluestreak.com/ix.e?bb&amp;t=27729\" width=\"1\" height=\"1\" border=\"0\">";
    }else if(CategoryName=="amusementparks"){
        YelpData += "<img src=\"http://s0b.bluestreak.com/ix.e?bb&amp;t=27731\" width=\"1\" height=\"1\" border=\"0\">";
    }else if(CategoryName=="shopping"){
        YelpData += "<img src=\"http://s0b.bluestreak.com/ix.e?bb&amp;t=27732\" width=\"1\" height=\"1\" border=\"0\">";
    }else if(CategoryName=="arts"){
        YelpData += "<img src=\"http://s0b.bluestreak.com/ix.e?bb&amp;t=27733\" width=\"1\" height=\"1\" border=\"0\">";
    }else{ 
        YelpData += "<img src=\"http://s0b.bluestreak.com/ix.e?bb&amp;t=27730\" width=\"1\" height=\"1\" border=\"0\">";
    }
    
    document.getElementById("m_AttDiv").innerHTML = YelpData;

    var yelpRequestURL = constructYelpURL();

    /* clear existing markers */
    //map.clearOverlays();   
    clearYelpMarkers();
    clearM6PicksMarkers();
    map.setCenter(currentPoint, currentZoom);  
    
    /* 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;
}

/*
 * If a sucessful API response is received, place
 * markers on the map.  If not, display an error.
 */
function handleResults(data) {
    // turn off spinner animation
    // document.getElementById("spinner").style.visibility = 'hidden';
    if(data.message.text == "OK") {
        YelpData = "";
        YelpData += "   <table cellspacing=\"0\" cellpadding=\"0\" style=\"width:460px;\">";

        for(var i=0; i<data.businesses.length; i++) {
            biz = data.businesses[i];
            createMarker(biz, new GLatLng(biz.latitude, biz.longitude), i);            

            YelpData += " <tr onmouseover=\"this.style.backgroundColor='#e8e8e8';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='';\" onclick=\"attractionClick(" + i + ");\">";
            YelpData += "     <td class=\"m_attList\">";
            YelpData += "         <table width=\"100%\">";
            YelpData += "             <tr>";
            YelpData += "                 <td width=\"125\" valign=\"top\">";
            YelpData += "                     <img class='businessimage' src='" + biz.photo_url + "'/>";
            YelpData += "                 </td>";
            YelpData += "                 <td valign=\"top\">";
            YelpData += "                     <b>" + biz.name + "</b><br>";
            YelpData += "                     <img class='ratingsimage' src='" +biz.rating_img_url_small+ "'/> based on " + biz.review_count + " reviews";
            YelpData += "                     <br /><br>";
            YelpData +=                       biz.address1 + "<br/>";
            if(biz.address2.length) 
            YelpData +=                       biz.address2+ "<br/>";
            YelpData +=                       biz.city + ",&nbsp;" + biz.state + "&nbsp;" + biz.zip + "<br/>";
            if(biz.phone.length)
            YelpData +=                       formatPhoneNumber(biz.phone);
            YelpData += "                 </td>";
            YelpData += "             </tr>";
            YelpData += "         </table>";
            YelpData += "     </td>";
            YelpData += " </tr>";
        }
        YelpData += "   </table>";
        document.getElementById("m_AttDiv").innerHTML = YelpData;
    }
    else {
        //alert("Error: " + data.message.text);
    }
}

/*
 * Formats and returns the Info Window HTML 
 * (displayed in a balloon when a marker is clicked)
 */
function generateInfoWindowHtml(biz) {
    var text = '<div class="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" class="popAnchor"><strong>'+biz.name+'</strong></a><br/>';
    // stars
    text += '<img class="ratingsimage" src="'+biz.rating_img_url_small+'"/> based on ';
    // reviews
    text += biz.review_count + ' reviews<br/><br />';
    // categories
//    text += formatCategories(biz.categories);
    // neighborhoods
//    if(biz.neighborhoods.length)
//        text += formatNeighborhoods(biz.neighborhoods);
    // address
    text += biz.address1 + '<br/>';
    // address2
    if(biz.address2.length) 
        text += biz.address2+ '<br/>';
    // city, state and zip
    text += biz.city + ', ' + biz.state + ' ' + biz.zip + '<br/>';
    // phone number
    if(biz.phone.length)
        text += formatPhoneNumber(biz.phone);
    // Read the reviews
//    text += '<br/><a href="'+biz.url+'" target="_blank" class="popAnchor">Read the reviews »</a><br/>';
    // div end
    text += '</div></div>'
    text += "<br />";
    text += '<div id="divAttractionInfoWindow">';
    text +=   'Get Directions:&nbsp;&nbsp;';
    text +=   '<a href="javascript:showDirectionsFrom()" class="popAnchor">To Here</a> | ';   
    text +=   '<a href="javascript:showDirectionsTo()" class="popAnchor">From Here</a>';
    var markerAddy =  biz.address1 + ', ' + biz.city + ', ' + biz.state + ' ' + biz.zip;
    text +=   '<div id="m_divBubbleForm" class="m_divBubbleForm">';
    text +=       '<div id="m_divBubbleFormStart" style="display:none;vertical-align:middle;">From:&nbsp;&nbsp;<input name="m_DirBubbleStart" id="m_DirBubbleStart" type="text" class="m_bubbleSearchCell" value="" onkeydown="if(event.keyCode==13)directionsBubbleClick(\'from\',\'' + markerAddy + '\');"> <input type="button" id="m_BtnBubbleDirections" value="GO" class="m_bubbleButton" onclick="directionsBubbleClick(\'from\',\'' + markerAddy + '\');" /></div>';
    text +=       '<div id="m_divBubbleFormEnd" style="display:none;vertical-align:middle;">To:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="m_DirBubbleEnd" id="m_DirBubbleEnd" type="text" class="m_bubbleSearchCell" value="" onkeydown="if(event.keyCode==13)directionsBubbleClick(\'to\',\'' + markerAddy + '\');"> <input type="button" id="m_BtnBubbleDirections" value="GO" class="m_bubbleButton" onclick="directionsBubbleClick(\'to\',\'' + markerAddy + '\');" /></div>';
    text +=   '</div>';
    text += '</div><br />';
    return text;
}

/*
 * 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 neighborhoods HTML
 */
function formatNeighborhoods(neighborhoods) {
    s = 'Neighborhoods: ';
    for(var i=0; i<neighborhoods.length; i++) {
        s += '<a href="' + neighborhoods[i].url + '" target="_blank">' + neighborhoods[i].name + '</a>';
        if (i != neighborhoods.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/>';
}

/*
 * Creates a marker for the given business and point
 */
function createMarker(biz, point, markerNum) {
    var infoWindowHtml = generateInfoWindowHtml(biz)
    var yelpMarker = new GMarker(point, yelpIcon);
    map.addOverlay(yelpMarker);
    GEvent.addListener(yelpMarker, "click", function() {
        yelpMarker.openInfoWindowHtml(infoWindowHtml, {maxWidth:400});
    });
    
    yelpMarkers.push(yelpMarker);
}

function clearYelpMarkers() {
    for (var i=0;i<yelpMarkers.length;i++) 
    {
        map.removeOverlay(yelpMarkers[i]);
    }
    yelpMarkers = [];
}
    
function attractionClick(i){
    try{
        //var zoomLvl = map.getZoom();
        var zoomLvl = 10;
        map.setCenter(new GLatLng(yelpMarkers[i].getPoint().lat(), yelpMarkers[i].getPoint().lng()), zoomLvl);
        setTimeout("GEvent.trigger(yelpMarkers["+i+"],'click');",100);        
    }catch(err){
        alert("The attraction you have selected cannot be mapped.  Please select another attraction.");
    }
} 