/*var centerLatitude = 40;
var centerLongitude = -95;
var startZoom = 4;
var zmarker;*/

var map;
var dirs;
var map_ready_state; //used to indicate when the map is "working".
var map_driving_dirs_state; //used to indicate when the map is in driving directions mode
var map_pan_state;

var Logo = new GIcon();
Logo.image = 'img/bww_icon.png';
Logo.iconSize = new GSize(32,32);
Logo.iconAnchor = new GPoint(16,16);
Logo.infoWindowAnchor = new GPoint(16,16);

var newLogo = new GIcon();
newLogo.image = 'img/bww_icon_new.png';
newLogo.iconSize = new GSize(32,32);
newLogo.iconAnchor = new GPoint(16,16);
newLogo.infoWindowAnchor = new GPoint(16,16);

var smLogo = new GIcon();
smLogo.image = 'img/bww_icon_sm.png';
smLogo.iconSize = new GSize(24,24);
smLogo.iconAnchor = new GPoint(12,12);
smLogo.infoWindowAnchor = new GPoint(12,12);

var clusterLogo = new GIcon();
clusterLogo.image = 'img/bww_icon_cluster.png';
clusterLogo.iconSize = new GSize(28,25);
clusterLogo.iconAnchor = new GPoint(14,12);
clusterLogo.infoWindowAnchor = new GPoint(14,12);

var arrowMarker = new GIcon();
arrowMarker.image = 'img/arrow.png';
arrowMarker.iconSize = new GSize(39,34);
arrowMarker.iconAnchor = new GPoint(12,34);
arrowMarker.shadow = 'img/arrowshadow.png';
arrowMarker.shadowSize = new GSize(39,34);
arrowMarker.infoWindowAnchor = new GPoint(17,1);

var i=1;
var bww_markers = [];
var bww_descriptions = [];
var to_htmls = [];
var from_htmls = [];
var result_class = 'odd';

function addMarker (latitude, longitude, description, store_id, store_name, address, results_info) {
    var icon = Logo;
    if (new_locations['l'+store_id]) {
        ;//icon = newLogo;
    }
    
    var marker = new GMarker (new GLatLng(latitude, longitude), icon);

    if (results_info) {

        // The info window version with the "to here" form open
        to_htmls[i] = description + 'Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
           '<br>Start address:<br />' +
           '<input type="text" name="saddr" id="saddr" value="" /><br />' +
           '<input value="Get Directions" type="button" onclick="directions('+i+');return false;" />' +
           //'<input type="hidden" name="daddr" id="daddr" value="' + latitude + ',' + longitude+ ' (Address:' + address + ')"/>';
           '<input type="hidden" name="daddr" id="daddr" value="' + latitude + ',' + longitude+ ' (Address:' + address + ')" />';
        // The info window version with the "to here" form open
        from_htmls[i] = description + 'Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
           '<br />End address:<br />' +
           '<input type="text" name="daddr" id="daddr" value="" /><br />' +
           '<input value="Get Directions" type="button" onclick="directions('+i+');return false;" />' +
           //'<input type="hidden" name="saddr" id="saddr" value="' + latitude + ',' + longitude + " (Address:" + address + ")" + 
           '<input type="hidden" name="saddr" id="saddr" value="' + latitude + ',' + longitude+ ' (Address:' + address + ')" />';

        //if point is in the current viewport add an entry to the sidebar panel
        if (map.getBounds().contains(new GLatLng(latitude, longitude))) {
            if (result_class == 'odd') {
                result_class='even';
            }
            else {
                result_class='odd';
            }
            var additional_class = '';
            if (new_locations['l'+store_id]) {
                ;//additional_class += 'new_location';
                results_info += '<strong class="new-location"> <span>&raquo;</span> NEW!</strong>';
            }
            
            document.getElementById('panel').innerHTML += 
                '<div class="panel-result single-item ' + result_class + '"><a href="#" class="' + additional_class + '" onclick="goto_result(' + i + '); return false;">' + store_name + '</a>' + results_info + '</div>';        
        }
    }
    
    description += 'Directions: '
    + '<a href="javascript:tohere('+i+');">To here</a> - '
    + '<a href="javascript:fromhere('+i+');">From here</a><br />';

    bww_markers[i] = marker;
    bww_descriptions[i] = description;

    GEvent.addListener(marker, 'click',
    function() {
        map_ready_state = 0;
        marker.openInfoWindowHtml(description);
        //map_ready_state = 1;
    });
    
    map.addOverlay(marker);
    i++;
}

function goto_result(i) {
    map_ready_state = 0;
    try{
        bww_markers[i].openInfoWindowHtml(bww_descriptions[i]);
    }catch(e){
        
    }
}

function tohere(i) {
    map_ready_state = 0;
    bww_markers[i].openInfoWindowHtml(to_htmls[i]);
}

function fromhere(i) {
    map_ready_state = 0;
    bww_markers[i].openInfoWindowHtml(from_htmls[i]);
}

function addStateMarker (latitude, longitude, abbrev, zoom) {
    var marker = new GMarker (new GLatLng(latitude, longitude), clusterLogo);
    GEvent.addListener(marker, 'click',
        function() {
            change_size();
            
            //document.location = 'index.php?state=' + abbrev + '&zoom=' + zoom;
            search('state',abbrev);
            update_markers();
        }
    );

    map.addOverlay(marker);
}

function addClusterMarker (latitude, longitude, cluster_count) {
    var point  = new GLatLng(latitude,longitude);
    var marker = new GMarker (point, clusterLogo);
        
    //if cluster is in the current viewport add an entry to the sidebar panel
    if (map.getBounds().contains(new GLatLng(latitude, longitude))) {
        if (result_class == 'odd') result_class='even'; else result_class='odd';
        document.getElementById('panel').innerHTML += 
            '<div class="panel-result cluster-item ' + result_class + '"><a href="#" onclick="goto_result(' + i + '); return false;">' + cluster_count + ' Locations</a></div>';
    }

    bww_markers[i] = marker;
    bww_descriptions[i] = cluster_count + ' locations<br />'
        + '<input type="button" value="Expand" onclick="zoom_pan('+latitude+','+longitude+')" />';
    
    GEvent.addListener(marker, 'click',
        function() {
            zoom_pan(latitude, longitude);
        }
    );
    map.addOverlay(marker);
    i++;
}

function zoom_pan(lat, lng) {
    map.closeInfoWindow();
    var point  = new GLatLng(lat,lng);

    //var listener = GEvent.addListener(map, 'moveend', function() {
        //zoom in after the panning is done.
        map.zoomIn();
      //  GEvent.removeListener(listener);
    //});

    map.panTo(point);
    update_markers();
}

function addArrowMarker (point, description) {
    var marker = new GMarker (point, arrowMarker);

    GEvent.addListener(marker, 'click',
        function() {
            map_ready_state = 0;
            marker.openInfoWindowHtml(description);
            map_ready_state = 1;
        }
    );
    
    map.addOverlay(marker);
}

function change_size() {
    if (getInternetExplorerVersion() == 6)
    	document.getElementById('map').style.width     = '554px';
    else
    	document.getElementById('map').style.width     = '554px';
    	
    document.getElementById('panel').style.display = 'block';
    map.checkResize();
}

function update_markers() {
    if (map_ready_state==1) {
        change_size();
    
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var getVars = 'ne=' + northEast.toUrlValue()
        + '&sw=' + southWest.toUrlValue();
        //alert(getVars);
        search('bounds',getVars);
    }
}

function search(mode, search) {
    map.closeInfoWindow();
    map_ready_state = 0;
    switch (mode) {
        case 'zipcode':
            var getVars = "?action=zipcode&zip=" + search + '&r=' + document.getElementById('radius').value;break;
        case 'state':
            var getVars = "?action=state&state=" + search;break;
        case 'bounds':
            var getVars = "?action=bounds&" + search;break;
        case 'lates_locations_n_days':
            var getVars = "?action=lates_locations_n_days";break;
        case 'coming_soon_btn':
            var getVars = "?action=soon_locations";break;
        case 'storeid':
            var getVars = "?action=storeid&storeid=" + search;break;
    }
    
    change_size();

    var request = GXmlHttp.create();

    //request.open('GET', 'get_zip_ll.php' + getVars, true);
    request.open('GET', 'map_data.php' + getVars, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var r = eval('(' + request.responseText + ')');
            
            if (!r.error) {
                document.getElementById('panel').innerHTML = '';

                map.clearOverlays();
                var bounds = new GLatLngBounds();
                if (r.center) {
                    bounds.extend(new GLatLng(r.center.latitude, r.center.longitude));
                }

                if (r.search_results_message) {
                    populate_search_results_message(r.search_results_message, 'normal');
                }
                
                for (id in r.markers) {
                    bounds.extend(new GLatLng(r.markers[id].lat, r.markers[id].lng));
                }
                if (!r.boundsresults) {
                    var point = bounds.getCenter();
                    
                    if (mode != 'lates_locations_n_days') {
                        if (r.center) { 
                            //var point = new GLatLng(r.center.latitude, r.center.longitude);
                            addArrowMarker(new GLatLng(r.center.latitude, r.center.longitude), search);
                        } else {
                            addArrowMarker(point, search);
                        }
                    }

                    map_pan_state = 1;
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                    map_pan_state = 1;
                    //map.panTo(point);
                    map.setCenter(point);
                }

                for (id in r.markers) {
                    if (r.markers[id].store_data) {
                        addMarker(r.markers[id].lat, r.markers[id].lng,
                        r.markers[id].store_data.description, 
                        r.markers[id].store_data.store_id, 
                        r.markers[id].store_data.name, 
                        r.markers[id].store_data.address, 
                        r.markers[id].store_data.results_info);
                    } else {
                        addClusterMarker(r.markers[id].lat, r.markers[id].lng, r.markers[id].cc);
                    }
                }
            } else {
                populate_search_results_message(r.error, 'error');
            }
            map_ready_state = 1;
            
            if(mode == 'storeid'){
                goto_result(1);
            }
        }
    }
    request.send(null);
    return false;
}

function populate_search_results_message(html, classname) {
    document.getElementById('search_results_message').innerHTML = "<p class="+classname+">" + html + "</p>\n";
}

function directions(i, address) {
    from = document.getElementById('saddr').value;
    to   = document.getElementById('daddr').value;
    map_driving_dirs_mode = 1;

    dirs = new GDirections(map, document.getElementById("panel"));
    GEvent.addListener(dirs, "error", handleErrors);

    display_directions(i, from, to);
}

function display_directions(i, from, to) {
    bww_markers[i].closeInfoWindow();
    map_ready_state = 0;

    var trackingImage = '<img src="' + window.location.protocol + '//idcs.interclick.com/Segment.aspx?sid=34813f45-56d2-485d-b5cc-2008a87abeec"/>';
    objPanel = document.getElementById('panel');
    objPanel.innerHTML = '<h3>Driving Directions</h3>'
        + '<div class="print-button"><input type="button" value="Print" onclick="pageTracker._trackEvent(\'Locator\', \'Directions\', \'Print\');print_directions();" />'+trackingImage+'</div>';

    dirs.load("from: " + from + " to: " + to);
}

function print_directions(){
    var tagId = 'doubleclickSpotlightTag';
    if(!document.getElementById(tagId)){
        /*
        document.write('
<!-- Tag for Activity Group: Actions, Activity: Print directions -->

<!-- Start of DoubleClick Spotlight Tag: Please do not remove-->
<!-- Activity Name for this tag is:Print directions -->
<!-- Web site URL where tag should be placed: http://www.buffalowildwings.com/ -->
<!-- Creation Date:5/20/2009 -->
<SCRIPT language="JavaScript">
var axel = Math.random()+"";
var a = axel * 10000000000000;
document.write(\'<IFRAME SRC="http://fls.doubleclick.net/activityi;src=2309546;type=actio549;cat=print196;ord=\'+ a + \'?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>\');
</SCRIPT>
<NOSCRIPT>
<IFRAME SRC="http://fls.doubleclick.net/activityi;src=2309546;type=actio549;cat=print196;ord=1?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>
</NOSCRIPT>
');
        */
        //recoding the necessary bits
        var axel = Math.random()+"";
        var a = axel * 10000000000000;
        var newNode = document.createElement('div');
        newNode.id = tagId;
        newNode.innerHTML = '<IFRAME SRC="http://fls.doubleclick.net/activityi;src=2309546;type=actio549;cat=print196;ord='+ a + '?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>';
        document.body.appendChild(newNode);
        printedOnce = true;
    }
    window.print();
    return false;
}

function handleErrors(){
   if (dirs.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alerf("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: " + dirs.getStatus().code);
   else if (dirs.getStatus().code == G_GEO_SERVER_ERROR)
     alerf("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + dirs.getStatus().code);
   
   else if (dirs.getStatus().code == G_GEO_MISSING_QUERY)
     alerf("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: " + dirs.getStatus().code);

   else if (dirs.getStatus().code == G_GEO_BAD_KEY)
     alerf("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + dirs.getStatus().code);

   else if (dirs.getStatus().code == G_GEO_BAD_REQUEST)
     alerf("A directions request could not be successfully parsed.\n Error code: " + dirs.getStatus().code);
    
   else alerf("An unknown error occurred.");
}

function alerf(message) {
    if (message) {
        objPanel = document.getElementById('panel');
        objPanel.innerHTML += '<div class="error"><div><strong>Error</strong></div>' + message + '</div>';
    }
}

function init(centerLatitude, centerLongitude, startZoom) {
    create_map(centerLatitude, centerLongitude, startZoom);

    for (id in markers) {
        if (markers[id].zoom) {
            addStateMarker(markers[id].latitude, markers[id].longitude,
            markers[id].abbrev, markers[id].zoom);
        } else {
            addMarker(markers[id].latitude, markers[id].longitude,
            markers[id].description, markers[id].store_id, markers[id].name, markers[id].store_name, markers[id].address, '');
        }
    }
    map_ready_state=1;
    map_driving_dirs_state=0;
}

function create_map(centerLatitude, centerLongitude, startZoom) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addMapType(G_PHYSICAL_MAP);
    map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();

    GEvent.addListener(map,'moveend',function(){
        if (map_pan_state == 1) {
		    map_pan_state = 0;
		}
		else {
		    update_markers();
		}
    });
    GEvent.addListener(map,'dragstart',function(){
        if(map_ready_state == 0) {
            map.closeInfoWindow();
        }
    });
    GEvent.addListener(map, 'infowindowclose',function() {
        if (map_driving_dirs_state==0) {
            map_ready_state = 1;
        }
    });
    GEvent.addListener(map, 'infowindowopen',function() {
        map_ready_state = 0;
    });
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

jQuery(function($) {
    $('input.prompted').
        focus(function() {
            if($(this).val() == this.defaultValue) {
                $(this).val('');
            }
        }).blur(function() {
            if($(this).val() == '') {
                $(this).val(this.defaultValue);
            }
        });
    
    $('#zipcode_search_submit').click(function() {
        var v = $('#zipcode').val();
        
        if (v == '' || v == $('#zipcode')[0].defaultValue) {
            return false;
        }
    
        search('zipcode', v);
        return false;
    });

    $('#state_search_submit').click(function() {
        if ($('#state_select')[0].selectedIndex == 0) {
            return false;
        }
        
        var v = $('#state_select').val();
        
        search('state', v);
        return false;
    });

    $('#lates_locations_n_days').click(function() {
        search('lates_locations_n_days', 'USA');
        return false;
    });
    $('#coming_soon_btn').click(function() {
        search('coming_soon_btn', 'USA');
        return false;
    });
});







