/**
 * Auto Car Browser
 * 
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 * 
 */
 
 
/**
 * Put the Google local search in the global scope
 * 
 * @type GlocalSearch
 */
var localSearch;
    
var AutoBrowser = new Class(
{
	/**
	 * Implement Options and ByngView
	 *  
	 */
	Implements: [Options, ByngView],
	
	/**
	 * Holds meta data for ByngView
	 * 
	 */
	meta: {
		file    : 'auto.browser.js',
		version : '0.1',
		gateway : {'package' : 'site', 'module' : 'browser'}
	},
	
	/**
	 * Default options
	 * 
	 */
    options: {
       	gmap : {
       		icons  : { 'dealer' : '/html/images/newpin.png' },
       		zoom   : 13,
       		centre : { 'lat' : -2, 'lng' : 51 },
       		directions : {'width' : 700, 'height' : 500}
       	}
    },
    
    /**
     * Initialize the browser
     * 
     * @param String screen
     */
    initialize : function ( )
    {
    	this.view  = this.getProperty('view');
    	this.carId = this.getProperty('carId');
    	switch (this.view) {
    		case "single":
    			this.gmap = $('map_canvas');	
    			if (this.gmap) this.drawMap( [this.gmap.getProperty('title')] );
    			if ($('savetofaves')) {
    				$('savetofaves').getElement('a').addEvent('click', this.saveFavourite.bind(this));
    			}
   		break;
    		case "list":
    			this.loadList($$('#yoursearchresults li.item'));
    		break;
    	}
    },
    
    /**
     * Handle the list of results
     * 
     * @param DomElements[] items
     */
    loadList : function ( items )
    {
    	// no results
    	if (items.length == 0) return;
    	
    	// attach favorites behaviour
    	items.getElement('.actions .ql-short').addEvent('click', this.saveFavourite.bind(this));
    },
    
    /**
     * Save favorite
     * 
     * @param Mixed arg
     */
    saveFavourite : function ( arg )
    {
    	var carId = this.normalise(arg);
    	Byng.transit.post({ 'request' 	 : this.getRequest().setAction('add_favourite'),
    						'onComplete' : this.favouriteSaved.bind(this)},
    						{'carId' : carId});   	
    },
    
    /**
     * Handle favorite saved
     * 
     * @param DomElement xml
     */
    favouriteSaved : function ( xml )
    {
    	var resp = new ByngXml(xml);
    	if (resp.getCode() == 0) {
    		var ans = confirm('Please register to save favorites. Would you like to register now?');
    		if ( ans == true) window.location = '/register';
    		return;
    	} else {
    		var carId = resp.getParam('carId');
    		var list = Byng.ui.ge({'carId' : carId});
			if (resp.getParam('status') == true) {
				list.addClass('favourite');
			} else {
				list.removeClass('favourite');
			}
    	}
    },
    
    /**
     * Draw a map with postcode
     * 
     * @param Array postcodes
     */
    drawMap : function (postcodes)
    {	
		var map;
		var gdir;
		var geocoder = null;
		var addressMarker;
		
		if (!postcodes) return;


    	localSearch = new GlocalSearch();
    	
		if (GBrowserIsCompatible()) {      
			
			this.map = new GMap2(this.gmap);
			//this.map.enableScrollWheelZoom();
			this.map.disableDragging();
			postcodes.each(this.lookupPostcode.bind(this));
		}
    	
    	// attach the directions link
    	if ($('directionsoverlay')) {
			$('directionsoverlay').addEvent('click', this.showDirections.bind(this));
    	}
								    	
    	// unload to prevent memory leaks
    	document.getElement('body').addEvent('unload', function () { GUnload(); });		
    },
    
    /**
     * Place a market on the map
     * 
     * @param point GPoint
     */
    placeMarker : function (point)
    {    	
		var marker0 = new GMarker(point, {'icon' : this.createIcon()});
		this.map.setCenter(new GLatLng(point.lat(), point.lng()), this.options.gmap.zoom);
		this.map.addControl(new GSmallMapControl());		
		this.map.addOverlay(marker0);		
    },
    
    /**
     * Create a new map icon
     * 
     * @return GIcon
     */
    createIcon : function ()
    {
    	var icon 			= new GIcon();
			icon.iconSize   = new GSize(40, 59);
			icon.iconAnchor = new GPoint(20, 59);
			icon.image      = this.options.gmap.icons.dealer;
		return icon;
    },
    
    /**
     * Look-up a postcode string
     * 
     * @param String postcode
     */
	lookupPostcode : function (postcode) 
	{
		localSearch.setSearchCompleteCallback(null, 
			function() {
				// handle the query result
				if (localSearch.results[0]) {		
					var resultLat = localSearch.results[0].lat;
					var resultLng = localSearch.results[0].lng;
					var point = new GLatLng(resultLat,resultLng);
					this.placeMarker(point);
				}else{
					throw ("Postcode not found!");
				}
			}.bind(this));	
		localSearch.execute(postcode + ", UK");
	},
	
	/**
	 * Show directions
	 * 
	 * @param Event e
	 */
	showDirections : function (e)
	{
		var destination = this.getProperty('destination');
		if (destination != '') {	
			e.stop();
			window.open( (e.target.get('tag') == 'span' ? e.target.getParent() : e.target).getProperty('href')+'&s',
						'_blank','toolbar=no' +
						',width='  + this.options.gmap.directions.width +
						',height=' + this.options.gmap.directions.height + 
						',resizable=yes,menubar=yes,location=no');	
			return;
			
			// doesn't work with UK postcodes 
			var canvas = $('directions_canvas').set('opacity',0).setStyle('display','block');
			this.directions = {'from' : postcode, 'to' : destination};
			var show = new Fx.Morph(canvas, {
				     duration: 300, 
				     transition: Fx.Transitions.Quad.easeInOut
			}).addEvent('complete', function(el) {
				var map = new GMap2(el);
					map.enableScrollWheelZoom();
				var directions = new GDirections(map);
					directions.load("from: " + 12304 + " to: 49 W Maryland St, Indianapolis, IN 46204", "en_US");
//					directions.load("from: {from} to: {to}".substitute(this.directions), "en_UK");
					console.log(directions.getNumRoutes()); 
			}.bind(this)).start({
				'opacity':[0,1]
			});
		}
	}
    
    
});

window.addEvent('domready', function() 
{	
	Byng.app.browser = new AutoBrowser();
});