// JavaScript Document
function initRouter(){
	  function Menu($div){
		var that = this, 
			ts = null;
		
		this.$div = $div;
		this.items = [];
		
		// create an item using a new closure 
		this.create = function(item){
		  var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
		  $item
			// bind click on item
			.click(function(){
			  if (typeof(item.fnc) === 'function'){
				item.fnc.apply($(this), []);
			  }
			})
			// manage mouse over coloration
			.hover(
			  function(){$(this).addClass('hover');},
			  function(){$(this).removeClass('hover');}
			);
		  return $item;
		};
		this.clearTs = function(){
		  if (ts){
			clearTimeout(ts);
			ts = null;
		  }
		};
		this.initTs = function(t){
		  ts = setTimeout(function(){that.close()}, t);
		};
	  }
      
      // add item
      Menu.prototype.add = function(label, cl, fnc){
        this.items.push({
          label:label,
          fnc:fnc,
          cl:cl
        });
      }
      
      // close previous and open a new menu 
      Menu.prototype.open = function(event){
        this.close();
        var k,
            that = this,
            offset = {
              x:0, 
              y:0
            },
            $menu = $('<div id="menu"></div>');
            
        // add items in menu
        for(k in this.items){
          $menu.append(this.create(this.items[k]));
        }
        
        // manage auto-close menu on mouse hover / out
        $menu.hover(
          function(){that.clearTs();},
          function(){that.initTs(3000);}
        );
        
        // change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
        if ( event.pixel.y + $menu.height() > this.$div.height()){
          offset.y = -$menu.height();
        }
        if ( event.pixel.x + $menu.width() > this.$div.width()){
          offset.x = -$menu.width();
        }
        
        // use menu as overlay
        this.$div.gmap3({
          action:'addOverlay',
          latLng: event.latLng,
          content: $menu,
          offset: offset
        });
        
        // start auto-close
        this.initTs(5000);
      }
      
      // close the menu
      Menu.prototype.close = function(){
        this.clearTs();
        this.$div.gmap3({action:'clear', name:'overlay'});
      }

		  
        var $map = $('#googleMap'),
			menu = new Menu($map),
            current,  // current click event (used to save as start / end position)
            m1,       // marker "from"
            m2,       // marker "to"
			center = [42.701614, 23.315735],
			res;
        
        // update marker
        function updateMarker(marker, isM1){
          if (isM1){
            m1 = marker;
          } else {
            m2 = marker;
          }
          updateDirections();
        }
        
        // add marker and manage which one it is (A, B)
        function addMarker(isM1,latLong){
          // clear previous marker if set
          var clear = {action:'clear', name:'marker', tag:''};
          if (isM1 && m1) {
            clear.tag = 'from';
            $map.gmap3(clear);
          } else if (!isM1 && m2){
            clear.tag = 'to';
            $map.gmap3(clear);
          }
          // add marker and store it
		  //alert(isM1);
		  //$map.gmap3('get').setCenter(latLong);
          $map.gmap3({
            action:'addMarker',
            //latLng:current.latLng,
			latLng:latLong,
            options:{
              draggable:true,
              icon:new google.maps.MarkerImage('/assets/templates/euroleasetaxi/images/icon_green' + (isM1 ? 'A' : 'B') + '.png')
            },
            tag: (isM1 ? 'from' : 'to'),
            events: {
              dragend: function(marker){
                updateMarker(marker, isM1);
              }
            },
            callback: function(marker){
              updateMarker(marker, isM1);
            }
          });
        }
        //Price calculation function
		function calcPrice(place,route){
			distance = route.routes[0].legs[0].distance.value;
			duration = route.routes[0].legs[0].duration.value;
			var currentTime = new Date()
			hours = currentTime.getHours();
			callPr = 0.6;
			styPr = 0.18;
			dst = distance/1000;
			if (hours>6 && hours<22) {
				tarifName = 'Т1';
				tarifPrice = 0.59;
				sty = duration/60*0.3;
				prs = dst*tarifPrice;
				
			}
			else {
				tarifName = 'Т2';
				tarifPrice = 0.70;
				sty = duration/60*0.2;
				prs = dst*tarifPrice;	
			}
			styTot=sty*styPr;
			tot = prs+tarifPrice+styTot;
			deviation = tot*0.2;
			deviation = deviation.toFixed(2);
			prs=prs.toFixed(2);
			styPr=styPr.toFixed(2);
			styTot=styTot.toFixed(2);
			tot=tot.toFixed(2);
			callPr=callPr.toFixed(2);
			tarifPrice=tarifPrice.toFixed(2);			
			sty = sty.toFixed(0);			
			dst = dst.toFixed(1);
			dur = duration/60;
			dur = dur.toFixed(0);
			
			receiptHtml='<span class="prleft">Нач. Такса:</span><span class="prright">'+callPr+' лв.</span>';
			receiptHtml+='<span class="prleft">'+tarifName+' цена на км:</span><span class="prright">'+tarifPrice+' лв.</span>';
			receiptHtml+='<span class="prleft">Платени км:</span><span class="prright">'+dst+' км.</span>';
			receiptHtml+='<span class="prleft">&nbsp;</span><span class="prright">'+prs+' лв.</span>';
			receiptHtml+='<span class="prleft">Цена престой:</span><span class="prright">'+styPr+' лв.</span>';
			receiptHtml+='<span class="prleft">Престой:</span><span class="prright">'+sty+' мин.</span>';
			receiptHtml+='<span class="prleft">&nbsp;</span><span class="prright">'+styTot+' лв.</span>';
			receiptHtml+='<span class="prleft">Обща Сума:</span><span class="prright">'+tot+' лв.</span>';
			receiptHtml+='<span class="prleft">&nbsp;</span><span class="prright sml">&plusmn;'+deviation+' лв.</span>';
			receiptHtml+='<span class="rem">Възможни са разлики в показаната и реалната цена.</span>';
			$(place).html(receiptHtml);
			//$(place).html('<span class="left"Нач. Такса:'Разстояние '+dst+' км. <br/>Очакван престой '+sty+' мин.<br>Очаквана цена '+ prs.toFixed(2) + ' лв.');
		}
        // function called to update direction is m1 and m2 are set
        function updateDirections(){
          if (!(m1 && m2)){
            return;
          }
          $map.gmap3({
            action:'getRoute',
            options:{
              origin:m1.getPosition(),
              destination:m2.getPosition(),
              travelMode: google.maps.DirectionsTravelMode.DRIVING
            },
            callback: function(results){
              if (!results) return;
              $map.gmap3({ action: 'setDirections', directions:results});
			  calcPrice('#price',results);
			  $('.adp-summary').css('display', 'none');
            }
          });
		  

        }
	
        
        // MENU : ITEM 1
        menu.add('От Тук', 'itemA', 
          function(){
            menu.close();
            addMarker(true,current.latLng);
          })
        // MENU : ITEM 2
        menu.add('До Тук', 'itemB separator', 
          function(){
            menu.close();
            addMarker(false,current.latLng);
          });
        
        // MENU : ITEM 3
        menu.add('Увеличи', 'zoomIn', 
          function(){
            var map = $map.gmap3('get');
            map.setZoom(map.getZoom() + 1);
            menu.close();
          });
        
        // MENU : ITEM 4
        menu.add('Намали', 'zoomOut',
          function(){
            var map = $map.gmap3('get');
            map.setZoom(map.getZoom() - 1);
            menu.close();
          });
        
        // MENU : ITEM 5
        menu.add('Центрирай', 'centerHere', 
          function(){
              $map.gmap3('get').setCenter(current.latLng);
              menu.close();
          });
          $map.gmap3(
		  {action: 'init',
            options:{
			  center:center,
              zoom: 12
			},
			events:{
              rightclick:function(map, event){
                current = event;
                menu.open(current);
              },
              click: function(){
                menu.close();
              },
              dragstart: function(){
                menu.close();
              },
              zoom_changed: function(){
                menu.close();
              }
			}
		  },
		  // add direction renderer to configure options (else, automatically created with default options)
			{ action:'addDirectionsRenderer',
				preserveViewport: true,
				markerOptions:{
				visible: false
				}
			},
			// add a direction panel
			{ action:'setDirectionsPanel',
				id : 'directions'
			}			
		  );

          $('#address1').autocomplete({
            //This bit uses the geocoder to fetch address values
            source: function(request, response) {
			  addr = '';
			  if (request.term != null) {
				  if (request.term.indexOf('София')==-1){
					addr = request.term+', София, България';
				  }
				  else {
					addr = request.term;
				  }
			  }
              $("#googleMap").gmap3({
                action:'getAddress',
                address: addr,
                callback:function(results){
                  if (!results) return;
                  response($.map(results, function(item) {
                    return {
                      label:  item.formatted_address,
                      value: item.formatted_address,
                      latLng: item.geometry.location
                    }
                  }));
                }
              });
            },
            //This bit is executed upon selection of an address
            select: function(event, ui) {
              
			  addMarker(false,ui.item.latLng);
            }
          });

          $('#address2').autocomplete({
            //This bit uses the geocoder to fetch address values
            source: function(request, response) {
			  addr = '';
			  if (request.term != null) {
				  if (request.term.indexOf('София')==-1){
					addr = request.term+', София, България';
				  }
				  else {
					addr = request.term;
				  }
			  }
              $("#googleMap").gmap3({
                action:'getAddress',
                address: addr,
                callback:function(results){
                  if (!results) return;
                  response($.map(results, function(item) {
                    return {
                      label:  item.formatted_address,
                      value: item.formatted_address,
                      latLng: item.geometry.location
                    }
                  }));
                }
              });
            },
            //This bit is executed upon selection of an address
            select: function(event, ui) {
				addMarker(true,ui.item.latLng);
            }
          });
}		  
