// JavaScript Document

//http://gmaps-samples-v3.googlecode.com/svn/trunk/toomanymarkers/toomanymarkers.html
//http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/docs/reference.html
//// http://itouchmap.com/latlong.html*/	

//Debugger function wrappers - remove these before deployment

function flog( msg ) {
	if ( window.console && console.debug ) {
		console.log(msg);	
	}
}
function fdir( msg ) {
	if ( window.console && console.debug ) {
		console.dir(msg);	
	}
}


(function() {
	
	var _map; /*the map*/
	var mapInitialized = false;
	var markerImages = [];
	var geocoder;	
	var markerCluster; 
	var startLatlng;
	var endLatlng;
	var currentAdress;
	var endLocation;  
	var selectedMarkerID;
	var markers = [];
	var infoWindows = [];
   
	var iconImages = {};
	iconImages["14"] = "/mobileweb/img/ladestik.png",
	iconImages["31"] = "/mobileweb/img/ladestik.png",
	iconImages["29"] = "/mobileweb/img/ladestander_gray.png",
	iconImages["30"] = "/mobileweb/img/ladestander.png",
	iconImages["32"] = "/mobileweb/img/ladestik.png"
	
	var filterType;
	var xmlLoaded = false;
	var pages = ["mapPage",  "listView", "about"];
	var standerlist;
	var standerxml;
	var pageIndex = 0;
	var galleryLength = 3;
	var jsonMarkers = [];
	var zoomLevel = 12; 

	var directionsService = new google.maps.DirectionsService();
	
	google.maps.event.addDomListener(window, 'load', function() {            
		initialize();  		
		
    });	
	
	//orientationchange resize	
	$(window).bind("pageshow", function(){
		//reorient();
		if(_map) fullScreenMap();
		
	 });
	$(window).bind("orientationchange resize", function(){
		//reorient();
		if(_map) fullScreenMap();
		
		/*var orientation = window.orientation;
		var new_orientation = 0/*(orientation) ? 0 : 180 + orientation*/;
		/*$('body').css({
			"-webkit-transform": "rotate(" + new_orientation + "deg)"
		});*/
		
	 });
	function fullScreenMap(){

		
		google.maps.event.trigger(_map, "resize");
		_map.setCenter(startLatlng);
		
	}
	
    function initialize() {
		
		createMap();	
		
	}
		
		 
		$(document).ready(function() {
		
			standerlist = $("#standerliste");			
									
			$('img').mousedown(function(e) { e.preventDefault(); });			
			
			$("#filterBtn").bind('click', function(){
				showFilter();
			 });
			$("#showMap").bind('click', function(){
				 $.mobile.changePage($("#mapPage"), "slide", true, true);
			 });
			$("#showList").bind('click', function(){
				 $.mobile.changePage($("#listView"), "slide", true, true);
			 });
			$("#about").bind('click', function(){
				 $.mobile.changePage($("#testenelbil"), "slide", true, true);
			 });	
			
			$("#mapVievLi").bind('click', function(){
				 $('#slideShow').cycle(0);				 
			 });
			$("#listViewLi").bind('click', function(){				
				 $('#slideShow').cycle(1);
			 });
			$("#about_li").bind('click', function(){
				$('#slideShow').cycle(2);				
			 });
			
			 $("#slideShow").live("swipeleft", function (e) {
				e.preventDefault();
				e.stopPropagation();				
				if(pageIndex <galleryLength-1){				
					pageIndex++;
					$('#slideShow').cycle(pageIndex);					
				}
			});
			 $("#slideShow").live("swiperight", function (e) {
					e.preventDefault();
					e.stopPropagation();					
					if(pageIndex != 0){
						pageIndex --;
						$('#slideShow').cycle(pageIndex);
					}	
			});
			

			function deselectAllBullets(){
				
				$("#mapVievLi img").attr("src","img/swipeDeselected.jpg");
				$("#listViewLi img").attr("src","img/swipeDeselected.jpg");
				$("#about_li img").attr("src","img/swipeDeselected.jpg");				
			}
			
			function onAfter(curr, next) {
				
				$(".customBackButton").bind('click',function(){
					window.history.back();									 
				});
				deselectAllBullets();
				var curr = $(this).attr('id');
				if(curr == "showMap"){
					$("#mapVievLi img").attr("src","img/swipeSelected.jpg");					
				}
				else if(curr == "showList"){
					$("#listViewLi img").attr("src","img/swipeSelected.jpg");					
				}
				else{
					$("#about_li img").attr("src","img/swipeSelected.jpg");
				}
			}
			$('.ui-btn-back').live('tap',function() {
				  history.back(); return false;
				}).live('click',function() {
				  return false;
			});
			
			$('#home').live('pageshow',function(event, ui){
				$('a[href*="#listView"]').removeClass("ui-btn-active"); 				 
			});
			$('#mapPage').live('pageshow',function(event, ui){
				$('a[href*="#mapPage"]').addClass("ui-btn-active"); 
				$('a[href*="#listView"]').removeClass("ui-btn-active"); 
			});
			
			$('#standerinfo').live('pageshow',function(event, ui){
					$('a[href*="#listView"]').addClass("ui-btn-active"); 
					$('a[href*="#mapPage"]').removeClass("ui-btn-active"); 
					var hasIndex = false;
					disposeStanderView();
					$(standerxml).find("location").each(function (i) {
						if(selectedMarkerID == i){
							
							var that = $(this);
							$('#standerLogoIcon').attr("src",iconImages[that.find("connector_type1").text()]); 
							
							$('.standerHeader').html(that.find("street_name").text()+" "+that.find("house_number").text()+"," + " <br />"+that.find("city").text()+" " + that.find("postal_code").text());							
							var cType = "Jordstik";
							if(that.find("connector_type1").text() == 30 || that.find("connector_type1").text() == 29){
								cType = "CHAdeMO Quickcharge";
							}
							else if(that.find("connector_type1").text() == 31){
								cType = "SAE1772";
							}
							else if(that.find("connector_type1").text() == 32){
								cType = "Mennekes";
							}
							var capacity;
							
							if(that.find("charge_capacity").text() == 5){
								capacity = "10A";
							}
							else if(that.find("charge_capacity").text() == 7){
								capacity = "16A";
							}
							else if(that.find("charge_capacity").text() == 13){
								capacity = "<200A (jævnstrøm)";
							}
							
							$('#infoList').append('<li>Operatør: ' + that.find("operator").text()+'</li>');
							$('#infoList').append('<li>Stiktype: ' + cType+'</li>');
							$('#infoList').append('<li>Lade kapacitet: ' + capacity+'</li>');														
							
							var addr = that.find("street_name").text()+" "+that.find("house_number").text()+" " + that.find("city").text() +" " + that.find("postal_code").text();
							hasIndex = true;						
							$('#driveDrirectionLink').attr("href", "http://maps.google.dk/maps?cid=16165705821841939690&daddr="+addr);
							
							return;
						
						}
						
					});
					
					// Her redirecter vi
					if(!hasIndex) $.mobile.changePage($("#mapPage"), "slide", true, true);
					
					
			});
			
			$('#listView').live('pageshow',function(event, ui){			
			  	$('a[href*="#listView"]').addClass("ui-btn-active"); 
				$('a[href*="#mapPage"]').removeClass("ui-btn-active"); 			
				disposeElements();				
				
				$(standerxml).find("location").each(function (i) {
					
					var item = '<li class="standerItem" id="'+ i+'"><a href="#standerinfo">'+$(this).find("poi_name").text()+'</a></li>';					
					standerlist.append(item);
					
				});
				$('.standerItem').bind('click',function(ev) {								
						selectedMarkerID = $(this).attr("id");
				});
				standerlist.listview('refresh');				
				
			});
			
			$('#filter').live('pageshow',function(event, ui){			
			  	$('a[href*="#listView"]').addClass("ui-btn-active"); 
				$('a[href*="#mapPage"]').removeClass("ui-btn-active"); 			
				
				disposeFilterlist();
				
				
				$(standerxml).find("location").each(function (i) {	
					
					var that = $(this);
					if(filterType==1 || filterType==2 ){
						var item = '<li class="standerItem" id="'+ i+'"><a href="#standerinfo">'+$(this).find("poi_name").text()+'</a></li>';					
						
						$('#standerlisteFilter').append(item);
					}
					else{
						var localType = $(this).find("connector_type1").text()
						 
						 if( localType == filterType ){
							 
							var item = '<li class="standerItem" id="'+ i+'"><a href="#standerinfo">'+$(this).find("poi_name").text()+'</a></li>';					
						
							$('#standerlisteFilter').append(item);
						}
						
					}
					
				});
				$('.standerItem').bind('click',function(ev) {								
						selectedMarkerID = $(this).attr("id");
				});
				$('#standerlisteFilter').listview('refresh');				
				
			});
			
		 });	
	function disposeFilterlist(){
		
		$('#standerlisteFilter').children().remove();
	}
	function showFilter(){
		disposeElements();	
		
		var arr = [{id:1, text:"Kun ChooseEV"},{id:2, text:"Alle standere"},{id:14, text:"Type: Jordstik"},
				   {id:30, text:"Type: CHAdeMO Quickcharge"}, {id:31, text:"Type: SAE1772"},
				   {id:32, text:"Type: Mennekes"}];
				
		for(var i=0; i<arr.length;i++){
			var obj= arr[i];
			var item = '<li class="standerItem" id="'+ obj.id+'"><a href="#filter">'+obj.text+'</a></li>';					
			standerlist.append(item);
		}		

		$('.standerItem').bind('click',function(ev) {	
			filterType = $(this).attr("id");		
			
		});
		standerlist.listview('refresh');			
	}
	function disposeStanderView(){
		$('#infoList').children().remove();
	}
	function disposeElements(){
		$('#standerliste').children().remove();
		//$('#standerliste').children().remove();
	}						   
	function showSingleStanderPage(){
		//standerinfo
	}
	
	function parseXml(xml){
		
		standerxml = xml;
		$(xml).find("location").each(function (i) {
			var p = new Object();
			p.latlng = {lat:$(this).find("latitude").text(), lng:$(this).find("longitude").text()};			
			p.info = {id:"stander_"+i,connector_type1:$(this).find("connector_type1").text()};				
			jsonMarkers.push(p);			
		});
		
	}
	
	function createMap() {
		  

				startLatlng =  new google.maps.LatLng(56.25064987433714,10.84375);
				zoomLevel = 6; 
				initMap();
				mapInitialized = true;
				
		
		
    }
	
	function initMap(){
		
		flog("map initialized");
		// måske vi skulle have en loader bar		
		var myOptions = {
					zoom: zoomLevel,
					center: startLatlng,
					disableDefaultUI: true,					
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					mapTypeControl: true,
					navigationControl: true          
				};
			_map = new google.maps.Map(document.getElementById("map"), myOptions);	
			/*var marker = new google.maps.Marker({
            position: startLatlng,
            map: _map,
			clickable:false,
            draggable: false,			
            icon: "/mobileweb/img/iamherenow-dot.png",
            visible: true
       	 });*/
		fullScreenMap();
		placeMarkers();
	}
	// LOADING MARKRES	
	$.ajax({
		type: "GET",
		cache: false,
		url:poiPath,
		dataType: "xml",
		success: parseXml
	});
	
	function addMarker(mObject/*LatLng*/,index){
		
		var m_icon = iconImages[mObject.info.connector_type1];	
	
		var latlng = new google.maps.LatLng(mObject.latlng.lat, mObject.latlng.lng);		
		var marker = new google.maps.Marker({
            position: latlng,
            map: _map,
            draggable: false,			
            icon: m_icon,
            visible: true
        });		
		marker.index = index;
		marker.id = mObject.info.id;			   
        google.maps.event.addListener(marker, 'click', function() { 
		   selectedMarkerID = index;
		   for(var i = 0; i<infoWindows.length; i++)
           {
                infoWindows[i].close();
           }
           var poi = $(standerxml).find("location").eq(index);
           var name = poi.find("poi_name").text();
           var address = poi.find("street_name").text()+" "+poi.find("house_number").text(); 
           var city = poi.find("postal_code").text()+" "+poi.find("city").text(); 
           var phone =  poi.find("phone").text();
		   var infoHtml = "<div class='info-text'><p><strong>"+name+"</strong></p><p>"+address+"</p><p>"+city+"</p><p>"+phone+"</p></div>";
           var infowindow = new google.maps.InfoWindow({
                content: infoHtml
           });
           infoWindows.push(infowindow);
           infowindow.open(_map, marker);
		   $.mobile.changePage($("#standerinfo"), "slide", true, true);
		 
        });
        markers.push(marker);
		
	}
	function placeMarkers(){
		var arr = jsonMarkers;
        var l = arr.length;		
        for (var i = 0; i < l; i++) {			
			addMarker(arr[i],i);          		
        }	
		var styles = [[{
			url: '/mobileweb/img/m1.png',
			width: 40, height: 45,
			opt_anchor: [0, 0],
			opt_textColor: '#FFFFFF',
			opt_textSize: 12
			
		  }, {
			url: '/mobileweb/img/m1.png',
			width: 40, height: 45,
			opt_anchor: [0, 0],
			opt_textColor: '#FFFFFF',
			opt_textSize: 13			
		  }	, {
			url: '/mobileweb/img/m1.png',
			width: 40, height: 45,
			opt_anchor: [0, 0],
			opt_textColor: '#FFFFFF',
			opt_textSize: 12
		  }, {
			url: '/mobileweb/img/m1.png',
			width: 40, height: 45,
			opt_anchor: [0, 0],
			opt_textColor: '#FFFFFF',
			opt_textSize: 12
		  }]];
		var clusterOpts = {'minimumClusterSize':10, styles:styles[0]};
		markerCluster = new MarkerClusterer(_map, markers, clusterOpts);
		
		
	}


})();
