/*----------------------------------------------------------
 * map_data_load.js
 *
 * This file contains all sorts of useful helper functions
 * for using Google Maps API V3 
 *--------------------------------------------------------*/

var gEditMarkerList = new Array();
var gEditFormList = new Object();
var gPhotoFormList = new Object();
var gPlaceInfoList = new Object();
var gSuggestionInfoList = new Object();
var gPointTypeList = new Array();
var gPointTypeArray = new Object();
var gPointCategories = [];
var gMarkerChain = new Object();
var gSelectedPlaceNumber = 0;
var gSelectedPhotoNumber = 0;
var gSelectedSuggestionNumber = 0;
var gNavPointList = new NavigablePointList('place');
var gNavSuggestionList = new NavigablePointList('suggestion');
var gNavPhotoList = new NavigablePointList('photo');
var gEditSelectorDrawn = false;
var gAddSelectorDrawn = false;

function clickNextGlobalPoint(){
	gNavPointList.ClickNextPoint(gSelectedPlaceNumber, gMap);
}
function clickPrevGlobalPoint(){
	gNavPointList.ClickPrevPoint(gSelectedPlaceNumber, gMap);
}
function clickNextGlobalPhoto(){
	gNavPhotoList.ClickNextPoint(gSelectedPhotoNumber, gMap);
}
function clickPrevGlobalPhoto(){
	gNavPhotoList.ClickPrevPoint(gSelectedPhotoNumber, gMap);
}
function clickNextGlobalSuggestion(){
	gNavSuggestionList.ClickNextPoint(gSelectedSuggestionNumber, gMap);
}
function clickPrevGlobalSuggestion(){
	gNavSuggestionList.ClickPrevPoint(gSelectedSuggestionNumber, gMap);
}

function loadPointsTypesFromDatabase(){
  $.post("/trips/getPointTypes.php", { },
   function(data){
     gPointTypeList = data;
   }
   , "json");
}

function openInfoWindowWithPointNum( markerNumber ){
	var markerData = gPlaceInfoList[markerNumber];
	gSelectedPlaceNumber = markerNumber;
	var typeName = markerData.type;
	var newInfoBoxTitle = "<span><img src='"+ gPointTypeList[typeName].iconPath +"' /> " + typeName +  "</span>";
	setInfoBoxTitle(newInfoBoxTitle);
	 fillInInfoBox(markerData.point_id,
	 					markerData.name, markerData.street_address_1,
	 					markerData.city, markerData.state, markerData.country, 
	 					markerData.phoneNumber, markerData.lng, markerData.lng, 
	 					markerData.description, markerData.type);
	 $("#placeinfobox").dialog('open');
}
function openSuggestionWindowWithPointNum( markerNumber ){
	var markerData = gSuggestionInfoList[markerNumber];
	gSelectedSuggestionNumber = markerNumber;
	
	var typeName = 'suggestion';
	var newInfoBoxTitle = "<span><img src='"+ gPointTypeList[typeName].iconPath +"' /> " + typeName +  "</span>";
	setInfoBoxTitle(newInfoBoxTitle);
	 fillInSuggestionInfoBox(markerData.point_id,
	 					markerData.name, markerData.street_address,
	 					markerData.city, markerData.state, markerData.country, 
	 					markerData.phoneNumber, markerData.latitude, markerData.longitude, 
	 					markerData.description, markerData.type, markerData.suggestor_name, markerData.suggestor_website, markerData.suggestor_twitter);
	 $("#placeinfobox").dialog('open');
}
function openPhotoWindowWithPointNum( markerNumber ){
	var markerData = gSuggestionInfoList[markerNumber];
	gSelectedPhotoNumber = markerNumber;
	
	var markerData = gPhotoFormList[gSelectedPhotoNumber];
	setInfoBoxTitle(markerData.title);
	fillInPhotoBox(markerData.point_id,
		markerData.title,
	 markerData.ownername,
		markerData.linkToImage,
		markerData.imageUrl
	);
	 $("#photobox").dialog('open');
}


function loadPointsFromDatabase( mapId, map ){
//load point types, then once those have loaded, get all the points
$.post("/trips/getPointTypes.php", { },
 function(data){
   gPointTypeList = data;
   $.post("/trips/getMapPoints.php", { map_id: mapId },
    function(data){
      var markerList = data.markers;
      //Create points for all markers in the results
      for( iMarker = 0; iMarker < markerList.length; iMarker++){
        var typeName = markerList[iMarker].type;
        var marker = makeNewMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, gPointTypeList[typeName].iconPath, markerList[iMarker].name);
        var newPointHtml = "<div class='pointTextEntry' pointNum='"+iMarker+"'>";
        newPointHtml += "<span class='pointTextTitle'><img src='"+ gPointTypeList[typeName].iconPath +"'/>"+ markerList[iMarker].name + "</span>";
        newPointHtml += "</div>";
        $("#pointlistdash").append(newPointHtml);
        marker.set("marker_num", iMarker);
        gNavPointList.AddPoint(marker,iMarker);
        gPlaceInfoList[iMarker] =  markerList[iMarker];
        google.maps.event.addListener(marker, 'click', function() {
        	selectPlace(this.get("marker_num"));
        	/*openInfoWindowWithPointNum(this.get("marker_num"));
        	//select text entry
        	$(".pointTextEntry").removeClass('selectedPlaceLine');
        	$(".pointTextEntry[pointnum="+this.get("marker_num")+"]").addClass('selectedPlaceLine');*/
         });
        
        var category = gPointTypeList[typeName].category;
        
        if(!gMarkerList[category]){
          gMarkerList[category] = new Array();
        }
        if(!gMarkerList[typeName]){
          gMarkerList[typeName] = new Array();
        }
        
        gMarkerList[category].push(marker);
        gMarkerList[typeName].push(marker);
      }
      $(".pointTextEntry").click(function(){
      	selectPlace($(this).attr('pointNum'));
      	/*$(".pointTextEntry").removeClass('selectedPlaceLine');
      	$(this).addClass('selectedPlaceLine');
      	var markerData = gPlaceInfoList[$(this).attr('pointNum')];
      	gMap.setCenter(new google.maps.LatLng( markerData.lat, markerData.lng));
      	gMap.setZoom(12);
      	openInfoWindowWithPointNum($(this).attr('pointNum'));  */    
      	});
    }, "json");
   }
 , "json");
  
}

function selectPlace(placeNumber){
	openInfoWindowWithPointNum(placeNumber);
	$(".pointTextEntry").removeClass('selectedPlaceLine');
	$(".pointTextEntry[pointnum="+placeNumber+"]").addClass('selectedPlaceLine');
	var markerData = gPlaceInfoList[placeNumber];
	gMap.setCenter(new google.maps.LatLng( markerData.lat, markerData.lng));
	gMap.setZoom(12);
	$("#pointlistdash").scrollTo( $(".pointTextEntry[pointnum="+placeNumber+"]") );
	
	
}
function deselectPlaces(){
	$(".pointTextEntry").removeClass('selectedPlaceLine');
}
function selectEditPlace(placeNumber){
	var markerData = gEditFormList[placeNumber];
	 fillInEditForm(markerData.point_id,
	 					markerData.name, markerData.street_address_1,
	 					markerData.city, markerData.state, markerData.country, 
	 					markerData.phoneNumber, markerData.lat, markerData.lng, 
	 					markerData.description, markerData.type);
	 $("#placeinfobox").dialog('open');
	 $('#placeinfobox').bind('dialogclose', function(event, ui) {
	 		//clear out form
	   	clearEditForm();
	 });
	 
	 
	 $(".pointTextEntry").removeClass('selectedPlaceLine');
	 $(".pointTextEntry[pointnum="+placeNumber+"]").addClass('selectedPlaceLine');
	 $("#pointlistdash").scrollTo( $(".pointTextEntry[pointnum="+placeNumber+"]") );
	 gMap.setCenter(new google.maps.LatLng( markerData.lat, markerData.lng));
	 gMap.setZoom(12);
}

function loadPointsFromDatabaseForEdit( mapId, map ){
var baseUrl = "/trips/getPointCategories.php";
$.getJSON( baseUrl,{}, function(data){
	$.each(data, function( element, value ){
	//for(var iCat = 0; iCat < data.length; iCat++){
		var iOrder = Number(value.order);
		gPointCategories[iOrder] = new Object();
		gPointCategories[iOrder]['class'] = value.class;
		gPointCategories[iOrder]['title'] = value.title;
		gPointTypeArray[value.title] = [];
	});
 

	$.post("/trips/getPointTypes.php", { }, function(data){
	  gPointTypeList = data;
	  $.each(data, function( element, value ){
	  	var type = element;
	  	var order = Number(value.order);
	  	var category = value.category;
	  	if(typeof(gPointTypeArray[category]) != "undefined"){
	  		gPointTypeArray[category][order] = new Object();
	  		gPointTypeArray[category][order]['type'] = type;
	  		gPointTypeArray[category][order]['iconPath'] = value.iconPath;
	  	}
	  	
	  });
	  if(gEditSelectorDrawn != true){
	  	drawEditPointSelector();
	  }	
	  if(gAddSelectorDrawn != true){
	  	drawAddPointSelector();
	  }
	  //draw point type selector
	  $.post("/trips/getMapPoints.php", { map_id: mapId },
	   function(data){
	     var markerList = data.markers;
	     
	     //Create points for all markers in the results
	     for( iMarker = 0; iMarker < markerList.length; iMarker++){
	       var typeName = markerList[iMarker].type;
	       var marker = makeNewMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, gPointTypeList[typeName].iconPath, markerList[iMarker].name);
	       var newPointHtml = "<div class='pointTextEntry' pointNum='"+iMarker+"'>";
	       newPointHtml += "<span class='pointTextTitle'><img src='"+ gPointTypeList[typeName].iconPath +"'/>"+ markerList[iMarker].name + "</span>";
	       newPointHtml += "</div>";
	       $("#pointlistdash").append(newPointHtml);
	       marker.set("marker_num", iMarker);
	       gEditFormList[iMarker] =  markerList[iMarker];
	       google.maps.event.addListener(marker, 'click', function() {
	         var markerData = gEditFormList[this.get("marker_num")];
	          fillInEditForm(markerData.point_id,
	          					markerData.name, markerData.street_address_1,
	          					markerData.city, markerData.state, markerData.country, 
	          					markerData.phoneNumber, markerData.lat, markerData.lng, 
	          					markerData.description, markerData.type);
	          $("#placeinfobox").dialog('open');
	          $('#placeinfobox').bind('dialogclose', function(event, ui) {
	          		//clear out form
	            	clearEditForm();
	          });
	        });
		   var category = gPointTypeList[typeName].category;
		   if(!gMarkerList[category]){
		     gMarkerList[category] = new Array();
		   }
		   if(!gMarkerList[typeName]){
		     gMarkerList[typeName] = new Array();
		   }
		   
	       gMarkerList[category].push(marker);
	       gMarkerList[typeName].push(marker);
	       gMarkerList['master'].push(marker);
	     }
	     $(".pointTextEntry").click(function(){
	     	$(".pointTextEntry").removeClass('selectedPlaceLine');
	     	$(this).addClass('selectedPlaceLine');
	     	
	     	var markerData = gEditFormList[$(this).attr('pointNum')];
	     	gMap.setCenter(new google.maps.LatLng( markerData.lat, markerData.lng));
	     	gMap.setZoom(12);
	     	 fillInEditForm(markerData.point_id,
	     	 					markerData.name, markerData.street_address_1,
	     	 					markerData.city, markerData.state, markerData.country, 
	     	 					markerData.phoneNumber, markerData.lat, markerData.lng, 
	     	 					markerData.description, markerData.type);
	     	 $("#placeinfobox").dialog('open');
	     	 $('#placeinfobox').bind('dialogclose', function(event, ui) {
	     	 		//clear out form
	     	   	clearEditForm();
	     	 });
	     });
	    // if(gMarkerGrouper){
	    //   gMarkerGrouper.addMarkers(gMarkerList['master']);
	    // }
	   }, "json");
	}
	, "json");
  });
}

//------------------------------------------------------------

function loadPhotosFromDatabase( mapId, map ){
  $.post("/flickr/getPhotos.php", { mapId: mapId },
   function(data){
     var markerList = data;
     //Create points for all markers in the results
     for( iMarker = 0; iMarker < markerList.length; iMarker++){
       var marker = makePhotoMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, markerList[iMarker].title);
       marker.set("marker_num", iMarker);
       gNavPhotoList.AddPoint(marker,iMarker);
       
       //put marker info in global list, ordered by marker_num
       gPhotoFormList[iMarker] = markerList[iMarker];
       //attach marker num to icon
       
       google.maps.event.addListener(marker, 'click', function() {
       
           var markerData = gPhotoFormList[this.get("marker_num")];
           setInfoBoxTitle(markerData.title);
           fillInPhotoBox(markerData.point_id,
           	markerData.title,
            markerData.ownername,
           	markerData.linkToImage,
           	markerData.imageUrl
           );
            
            $("#photobox").dialog('open');
          });
         
       gMarkerList['photo'].push(marker);       
     }
   }, "json");
}

//------------------------------------------------------------

function loadPhotosFromDatabaseDialog( mapId, map ){
  $.post("/flickr/getPhotos.php", { mapId: mapId },
   function(data){
     var markerList = data;
     //Create points for all markers in the results
     for( iMarker = 0; iMarker < markerList.length; iMarker++){
       var marker = makePhotoMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, markerList[iMarker].title);
       var infoHtml =  makePhotoInfoWindow( markerList[iMarker].title,
						markerList[iMarker].ownername,
						markerList[iMarker].linkToImage,
						markerList[iMarker].imageUrl);
       addInfoWindow( gMap, infoHtml, marker, 'photo' );
       gMarkerList['photo'].push(marker);
     }
   }, "json");
}

//------------------------------------------------------------

function loadVideosFromDatabase( mapId, map ){
  $.post("getYoutubeMarkers.php", { map_id: mapId },
   function(data){
     var markerList = data.markers;
     //Create points for all markers in the results
     for( iMarker = 0; iMarker < markerList.length; iMarker++){
       var marker = makeVideoMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, markerList[iMarker].title);
        marker.set("marker_num", iMarker);
       var infoHtml =  makeVideoInfoWindow( markerList[iMarker].title,
						markerList[iMarker].length,
						markerList[iMarker].video_id);
       gMarkerList['videoInfoWindow'][iMarker] = infoHtml;
      google.maps.event.addListener(marker, 'click', function() {
        gMap.setCenter(this.getPosition());
        $("#video_form_contents").html(gMarkerList['videoInfoWindow'][this.get("marker_num")]);
        var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
        gMap.panBy(0, (((windowHeight)/2)-435) );
        $("#video_form_container").show();
      });

     gMarkerList['video'].push(marker);
     }
   }, "json");
}

//------------------------------------------------------------

function loadSuggestionsFromDatabase( mapId, map, infoWindowType ){
  $.post("/trips/getSuggestions.php", { map_id: mapId },
   function(data){
     var markerList = data.markers;
     //Create points for all markers in the results
     for( iMarker = 0; iMarker < markerList.length; iMarker++){
       var marker = makeSuggestionMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, markerList[iMarker].name);
       
       var infoHtml;
       if(infoWindowType == "full"){
         infoHtml =  makeFullSuggestionInfoWindow( markerList[iMarker].name,
						markerList[iMarker].description,
						markerList[iMarker].street_address_1,
						markerList[iMarker].city,
						markerList[iMarker].state,
						markerList[iMarker].phoneNumber,
						markerList[iMarker].country,
        					markerList[iMarker].suggestor_name,
        					markerList[iMarker].suggestor_twitter,
        					markerList[iMarker].suggestor_uri);
       }
       else{
         infoHtml =  makeSuggestionInfoWindow( markerList[iMarker].name,
						markerList[iMarker].description,
						markerList[iMarker].street_address_1,
						markerList[iMarker].city,
						markerList[iMarker].state,
						markerList[iMarker].phoneNumber,
						markerList[iMarker].country,
        					markerList[iMarker].suggestor_name,
        					markerList[iMarker].suggestor_twitter,
        					markerList[iMarker].suggestor_uri);

       }
       addInfoWindow( gMap, infoHtml, marker , 'suggestion');
       gMarkerList['suggestion'].push(marker);
     }
   }, "json");
}


function loadGeoRSS( mapId){
  $.post("getBlogPosts.php", { map_id: mapId },
   function(data){
     var markerList = data.blogPosts;
     //Create points for all markers in the results
     for( iMarker = 0; iMarker < markerList.length; iMarker++){
        var marker = makeBlogpostMarker( gMap, markerList[iMarker].lat, markerList[iMarker].lng, markerList[iMarker].title );
        var windowHtml = makeBlogpostInfoWindow ( markerList[iMarker].title, 
						markerList[iMarker].link, 
						markerList[iMarker].pubDate );
        addInfoWindow( gMap, windowHtml, marker , 'blogpost');
        gMarkerList['blogpost'].push(marker);
     }
   }, "json");
}

