/*
    Title:  Nissan Dealer Locator JavaScript
    Description:
        Find the nearest Nissan dealer based on geo-lookup.
        Google Maps API v2 and Postcode Anywhere are used for mapping
        and reverse location lookup.
    Version: 0.1
    Author: Andrew Mason (amason@digitas.com)
    
    Created: 2nd Feb 2010

*/

var DLocator = {
    // Google Map's API for localhost domain, replace with real domain key
    gmap_key: 'ABQIAAAALneoCp1xE_CQf44HhHHPhhR3XJv2DdaUPFhgv6wtBoaGgAejGhTBP6YbEfXlmXOWspuVV_aGf0QcmA',
    map_id: 'dl_google_map',
    results_inner: '#dl_results_inner',
    results_intro: '#dl_results_intro',
    results_controls: '#dl_results_controls',
    search_button: '#dl_search_button',
	//select_button: '#dl_result_select',
    error_box: '#dl_errorbox',
    max_visable: 3,
    min_zoom: 13,
    
    /*  Function: Initiate
    *   Description:
    *       Load the required external files and set-up the page ready for
    *       location searches
    */
    init: function() {
			/*
            // Get Google Maps external JavaScript
            var gmaps_js = 'http://maps.google.com/maps?file=api&v=2&key='+DLocator.gmap_key+'&sensor=false';  
			    
            jQuery.getScript('http://gmaps-utility-library.googlecode.com/svn/trunk/mapiconmaker/1.1/src/mapiconmaker.js');
            jQuery.getScript(gmaps_js);            
            // Hacky timeout because of ALL the flash on the page loading
            //setTimeout("DLocator.setupPage()", 800);
			
*/			
			$(document).ready(function() {
				DLocator.setupPage();
				
			});
			
			

    },
    
    setupPage: function() {
        $(DLocator.search_button).bind('click', function() {
            // Collect the user input value
            var postcode = $('#dl_postcode').val();
            var town = $('#dl_town').val();
            
            // Grab the search values then perform the search
            if (!postcode && !town) {
                // There's no user input so throw error
                DLocator.outputError('nothing to search');
            } else if(postcode) {   
                // Use Postcode
                    DLocator.getNearest(postcode);
            } else {
                // use town name
                DLocator.getNearest(town);
            }
        });
		
		
	
		
		$('#dl_postcode').bind('keydown', function(e){
			if (e.keyCode == 13) {
				var postcode = $('#dl_postcode').val();
				DLocator.getNearest(postcode);
			}
		});
		
		$('#dl_town').bind('keydown', function(e){
			if (e.keyCode == 13) {
				var town = $('#dl_town').val();
				DLocator.getNearest(town);
			}
		});
    },
    
    addMap: function() {
        if (GBrowserIsCompatible()) {
            DLocator.map = new GMap2(document.getElementById(DLocator.map_id));          
            DLocator.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
            DLocator.map.setUIToDefault();
        }
    },
    
    addMarker: function(label, lat, lon) {
        // Reference code:
        // http://gmaps-utility-library.googlecode.com/svn/trunk/mapiconmaker/1.1/examples/markericonoptions-wizard.html
        var iconOptions = {};
        iconOptions.primaryColor = "#9999FF";
        iconOptions.strokeColor = "#000000";
        iconOptions.label = label.toString();
        iconOptions.labelColor = "#000000";
        iconOptions.addStar = false;
        iconOptions.starPrimaryColor = "#FFFF00";
        iconOptions.starStrokeColor = "#0000FF";
        var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        var location = new GLatLng(lat, lon);
        var marker = new GMarker(location, {icon: icon});
        
        // Add the marker to the map
        DLocator.map.addOverlay(marker);
        
    },
    
    buildResultItem: function(count, name, distance, address, tel, fax, postcode) {
        var html = '';
        html += '<div class="dl_result"><div class="dl_result_title">';
        html += '<strong>'+count+'. '+name+'</strong> ';
        html += '<span>(distance '+distance+' miles)</span>';
        html += '</div>';
        html += '<div class="dl_r_col1"><address>'+address+'</address>';
        html += '<div class="dl_result_tel">'+tel+'</div>';
        html += '<div class="dl_result_fax">'+fax+'</div></div>';
        html += '<div class="dl_result_select"><a href="/signup?dealer_postcode=' +escape(postcode) + '">**SELECT DEALER**</a></div>';
        html += '<div class="dl_result_select"><a href="http://maps.google.co.uk/maps?f=d&source=s_d&saddr=&daddr='+escape(postcode)+'&saddr='+escape(DLocator.origin)+'&hl=en" target="_blank">Driving Directions</a></div>';
        html += '</div>';
        
        return $(html);
    },
    
    getNearest: function(origin) {
        // Postcode Anywhere arguments
        var account_code = 'THEGL11121';
        var license_code = 'AU97-TR36-KB96-GN75';
        var items = 9;
        
        //Build the url
        var strUrl = "";
        strUrl = "http://services.postcodeanywhere.co.uk/json.aspx?";
        strUrl += "account_code=" + escape(account_code);
        strUrl += "&license_code=" + escape(license_code);
        strUrl += "&action=stored_nearest";
		strUrl += "&distance=DRIVETIME";
        strUrl += "&origin=" + escape(origin);
        strUrl += "&items=" + escape(items);
        strUrl += "&callback=?";
		
        
        // DEBUG DEMO JSON Service (saves credits :-)
        //strUrl = 'sample_json.php?callback=?';
        //strUrl = 'error_json.php?callback=?';
        
        // Store Origin
        DLocator.origin = origin;
        
        // Make the AJAX request and pass on the returned results
        $.getJSON(strUrl, DLocator.processResults);
    },
    
    processResults: function(data) {
        // If there was an error from the server, output message and end
        if (data[0].error_number) {
            DLocator.outputError(data[0].message);
            return false;
        }
        
        // Hide any errors
        $(DLocator.error_box).hide();
        
        // Check if there's a map. If not then add one
        if (!DLocator.map) {
            DLocator.addMap();
        }
        
        // Loop through each returned result
        // Store each results
		DLocator.results = jQuery.makeArray(data);
		
        
        // Show the first set of results
        DLocator.showResults(0, DLocator.max_visable);
        
    },
    
    showResults: function(first, last) {
        // Clear any markers on the map
        DLocator.map.clearOverlays();
        $(DLocator.results_inner).empty();
        
        // Build up header HTML
        var h_html = 'Showing ' + (first+1) + ' - ' + last;
        h_html += ' of ' + DLocator.results.length;
        h_html += ' results matching the name you entered.';
        // Write the HTML to the DOM
        $(DLocator.results_intro).html(h_html);
        
        // Build up controls HTML
        var c_html = $('<div>Page </div>');
        var count = 1;
        for (var i = 0; i < DLocator.results.length; i++) {
            if (i % DLocator.max_visable == 0) {
                var link = '<a href="#">' + count + '</a>';
                link = $(link);
                link.bind('click', DLocator.paginate);
                c_html.append(link);
                count++;
            }
        }
        c_html.append(' of ' + (count-1));
        // Output the controls HTML to the DOM
        $(DLocator.results_controls).empty();
        $(DLocator.results_controls).append(c_html);

        
        // Create a new Lat, Lng boundary variable
        var bounds = new GLatLngBounds;
        
        for (var i=first; i < last; i++) {
            if (DLocator.results[i] == undefined) {
                break;
            }
            
            // Add Dealer to the map
            DLocator.addMarker(i+1, DLocator.results[i].latitude, DLocator.results[i].longitude);
            
            // Generate the HTML
            var description = $(DLocator.results[i].description);
			
		

            var name = DLocator.results[i].name;
            var distance = DLocator.results[i].distance;
            var address =  $(description[0]).html();
            var tel =  $(description[1]).text();
            var fax =  $(description[2]).text();
            var postcode = DLocator.results[i].destination_postcode;
            var html = DLocator.buildResultItem(i+1, name, distance, address, tel, fax, postcode);
            // Append the result item to the DOM
            $(DLocator.results_inner).append(html);
            
            // Add result location to boundary array
            var location = new GLatLng(DLocator.results[i].latitude, DLocator.results[i].longitude);
            bounds.extend(location);
        }
        
        // Set the zoom level and center map on results
        var zoom = DLocator.map.getBoundsZoomLevel(bounds);
        if (zoom >= DLocator.min_zoom) {
            zoom = DLocator.min_zoom;
        }
        DLocator.map.setZoom(zoom - 1);
        DLocator.map.setCenter(bounds.getCenter());
    
    },
    
    paginate: function(e) {
        // Stop the Browser following the link
        e.preventDefault();
        
        // Remove .active class from <a>'s
        $.each($(DLocator.results_controls + ' a'), function(i, item) {
            $(item).removeClass('active');
        });
        
        // Add active class to clicked link
        $(this).addClass('active');
        
        // Grab the value of the page
        var page = parseInt($(this).text());
        var count = 1;
        // Work out what results to display based on page number
        for (var i=0; i<DLocator.results.length; i++) {
            if (i % DLocator.max_visable == 0) {
                if (count == page) {
                    DLocator.showResults(i, i+DLocator.max_visable);
                }
                count++;
            }        
        }
    },
    
    outputError: function(msg) {
        // Show the error box and output the message
        $(DLocator.error_box).show();
        $(DLocator.error_box).html('<p>Error: ' + msg + '</p>');
        return;
    }

};

// Run the Dealer Locator on DOM ready
DLocator.init();