/**
 *Embedded Travelpack
 *Created By: Alan Hietala
 *
 */

var map; //global variable to assign the embedtpkcontroller instance to

/** 
 * the ajax request queue. used to kill off currently running ajax calls when
 * a new one is made
 */
var _requestQueue = new Array();

function cancelRequests(){
    while(_requestQueue.length>0){
        _requestQueue.pop().abort();
    }

}



/**
 * main object that contains the logic for our embedded map
 * most functions are defined within here to keep the global namespace
 * relatively clear
 */
function EmbedTPKController(tpkId,tpkTitle,tpkUserName,tpkUserLink,tpkCoverLink,tpkLink){
      /** Constructor **/
     
     var zoom = 2; //set this to zoomed out nice and far
     //bounding box set to the world by default
     var boundingBox = new GLatLngBounds(new GLatLng(-90,-180),new GLatLng(90,180));
     var title = tpkTitle;
     var username = tpkUserName;
     var userLink = tpkUserLink;
     var packLink = tpkLink;
     var coverLink = tpkCoverLink;
     var googleMap;
     var travelPackId = tpkId ;
     var mapContainer = "map";
      var maxAutoZoom = 14;
      
    $("#tpkfootertitle").html(title);
    $("#tpkheadertitle").html(title);
    if(coverLink!=null && coverLink!=""){
        $("#tpkcover").attr("src",coverLink);
    }else{
    $("#tpkcover").css("display","none");
    }
     $("#tpkfooterlink").attr("href",packLink);
    $("#tpkownerlink").html(username);
    $("#tpkownerlink").attr("href",userLink);
    
	    if (GBrowserIsCompatible()) {
	         googleMap = new GMap2(document.getElementById(mapContainer));
             googleMap.addControl(new GLargeMapControl());
             
             googleMap.enableDoubleClickZoom();
	        if(travelPackId>0){ //we're looking at a travelpack
	            getDotsForOwner(-1,travelPackId,true,"all",renderInitialLoad);
    	        googleMap.setCenter(boundingBox.getCenter(),zoom); 
	        }else{
    	         
               
              }  
                
        		
		        //attach event listeners to the map
		        GEvent.addListener(googleMap,"moveend",mapMoveHandler
									           
						          );
	        
	    
	    }
	
	//set the close buttons up
	clickCloseButton();
	
	/** End Constructor **/
	
	/**
	 * Handler to pass to the first ajax call on load
	 * this should only get called once.
	 */
	function renderInitialLoad(obj){
	    if(obj.grid_data!=null){
	    var clickedDots = obj.grid_data.dot;
        var bounds = new GLatLngBounds();
        if(clickedDots.length==null){
            var p1 = new GLatLng(clickedDots.BoundingBox.North,clickedDots.BoundingBox.East);
            var p2 = new GLatLng(clickedDots.BoundingBox.South,clickedDots.BoundingBox.West);
             
           
            bounds.extend(p1);
            bounds.extend(p2);
        }else{
            for(var x = 0;x<clickedDots.length;x++ ){
                //add a pin on the map
                var p1 = new GLatLng(clickedDots[x].BoundingBox.North,clickedDots[x].BoundingBox.East);
                var p2 = new GLatLng(clickedDots[x].BoundingBox.South,clickedDots[x].BoundingBox.West);
                 
              
                bounds.extend(p1);
                bounds.extend(p2);
               
             }
         }
            boundingBox = bounds;
            zoom = googleMap.getBoundsZoomLevel(bounds);//we want a slightly farther out view
            googleMap.setCenter(bounds.getCenter(),zoom); 
	
	    }else{ // likely an empty travelpack so show the world
	        googleMap.setCenter(boundingBox.getCenter(),zoom);
	    }
	}
	
	
	/**
	 * renderTravelpackItems for the best fit view 
	 */    
	function renderTPKDots(obj){
         if(obj.grid_data!=null){
             var clickedDots = obj.grid_data.dot;
             
             if(clickedDots["@lat"]==null && clickedDots.length!=null){ //check if we've got 1 or an collection
                 for(var x = 0;x<clickedDots.length;x++ ){
                    //add a pin on the map
                    
                    var mark = createMarker(clickedDots[x]);
                    googleMap.addOverlay(mark);
                 }
             }else{
                 var mark = createMarker(clickedDots);
                    googleMap.addOverlay(mark);
             }
         }
	
	
	}
	
	/**
	 * Function to build a marker based on a dot object that is returned from 
	 * the PE webservices
	 */
	function createMarker(clickedDot){
	    var point = new GLatLng(clickedDot["@lat"],clickedDot["@long"]);
        var markerOptions = new Object();
       var itemCount = countDotItems(clickedDot).toString();
       var digitCount = itemCount.toString().length;
       var xoffset = -2*(digitCount-1)-1;
        markerOptions.labelOffset = new GSize(xoffset,-29);
        markerOptions.labelText = countDotItems(clickedDot).toString();
        var icon = new GIcon();
        icon.image = "/i/icons/pinG.png";
        icon.iconAnchor = new GPoint(11, 36);
        icon.iconSize = new GSize(27, 37);
        //icon.shadow = "pin-shadow.png";
        icon.shadowSize = new GSize(27, 37);
        markerOptions.icon = icon;
        var mark = new LabeledMarker(point,markerOptions);
      
        
        
        var showdata = function(){
                                  
                                  getDotsContentForOwner(clickedDot["@lat"],clickedDot["@long"], 50,  -1, travelPackId,  true, "all",showItemListFromDot);
                                        
                               };
        GEvent.addListener(mark,"click",showdata);
	    return mark;
	}
	
	/**
	 *Counts the number of items (media + places) in the list returned from our webservices
	 */
	function countDotItems(items){
	    var count = 0;
	    if(items.places!=null){
	            if(items.places.place.length!=null){
	                for(var x in items.places.place){
	                    count+=parseInt(items.places.place[x]["@count"]);
	                }
	            }else{
	                count +=parseInt(items.places.place["@count"]);
	            }
	          
	    } 
	    
	    if(items.media!=null){
	       count +=parseInt(items.media["@count"]); 
	    }
	    return count;
	
	}
	/**
	 * Gets the travelpack Items for the whole map area that is visible, not just for a single clicked on dot
	 */	
	function getTravelPackItemsForArea( maxToReturn,  pageNum,  ownerId,  travelPackId,handleFunction){
	
	    var southWest = boundingBox.getSouthWest();
		var northEast = boundingBox.getNorthEast();
        var north = northEast.lat();
        var south = southWest.lat();
        var east = northEast.lng();
        var west = southWest.lng();
        cancelRequests();
        _requestQueue.push(
        $.ajax({

        type: "POST",

        url: "/webservice/flashservice.asmx/getTravelPackItemsForAreaJSON",

        data: "{'north':'"+north.toString()+"',"
              +"'south':'"+south.toString()+"',"
              +"'east':'"+east.toString()+"',"
              +"'west':'"+west.toString()+"',"
              +"'maxToReturn':'"+maxToReturn.toString()+"',"
              +"'pageNum':'1',"
              +"'ownerID':'"+ownerId.toString()+"',"
              +"'travelPackId':'"+travelPackId.toString()+"',"
              +"'zoom':'"+zoom.toString()+"'}", 
                

        contentType: "application/json; charset=utf-8", 

        dataType: "json",

        success: function(xhr, status) {
                
                var sb = "";
                //this is on purpose .net webservices
                //return strings of json as a json string
                //hence eval twice. dont ask....
                xhr = xhr.replace("\\\"","\"");
                
                var obj = eval("(" + xhr + ")");
           
                 handleFunction(obj);
                //place the dots on the map 
                 
                
        },

        error: function(xhr, status, error) {

        var err = JSON.parse(xhr.responseText);

        $("#error").html("Error –> " + err.Message);

        }

        }));
	
	
	}
	/**
	 * Get Items that are contained within a given dot. called when dot is clicked
	 */
	function getDotsContentForOwner(lat,lon, maxToReturn,  ownerId,  albumId,  getMedia, catList,handleFunction,boundingbox){
	  
	    var southWest = boundingBox.getSouthWest();
		var northEast = boundingBox.getNorthEast();
        var north = northEast.lat();
        var south = southWest.lat();
        var east = northEast.lng();
        var west = southWest.lng();
        cancelRequests();
        _requestQueue.push(
        $.ajax({

        type: "POST",

        url: "/webservice/flashservice.asmx/GetDotContentsForTravelPackJSON",

        data: "{'lat':'"+lat.toString()+"',"
              +"'lon':'"+lon.toString()+"',"
              +"'maxToReturn':'"+maxToReturn.toString()+"',"
              +"'albumID':'"+albumId.toString()+"',"
              +"'getMedia':'"+getMedia.toString()+"'," 
              +"'commaDelimitedCategoryCodeList':'"+catList.toString()+"',"
              +"'zoomLevel':'"+zoom.toString()+"'}", 
                

        contentType: "application/json; charset=utf-8", 

        dataType: "json",

        success: function(xhr, status) {
                
                var sb = "";
                //this is on purpose .net webservices
                //return strings of json as a json string
                //hence eval twice. dont ask....
                xhr = xhr.replace("\\\"","\"");
                
                var obj = eval("(" + xhr + ")");
                obj.boundingbox = boundingbox;
                 handleFunction(obj);
                //place the dots on the map 
                 
                
        },

        error: function(xhr, status, error) {

        var err = JSON.parse(xhr.responseText);

        $("#error").html("Error –> " + err.Message);

        }

        }));
	}
	
	
	/**
	 * Get the dots for the travel pack
	 */
	 function getDotsForOwner(ownerId,albumId,getMedia,catList,handleFunction){
	     
        var southWest = boundingBox.getSouthWest();
		var northEast = boundingBox.getNorthEast();
        var north = northEast.lat();
        var south = southWest.lat();
        var east = northEast.lng();
        var west = southWest.lng();
        cancelRequests();
        _requestQueue.push(
        $.ajax({

        type: "POST",

        url: "/webservice/flashservice.asmx/GetDotsForTravelPackJSON",
        
        data: "{'latitudeNorth':'"+north.toString()+"',"
              +"'latitudeSouth':'"+south.toString()+"',"
              +"'longitudeEast':'"+east.toString()+"',"
              +"'longitudeWest':'"+west.toString()+"',"
           
              +"'albumID':'"+albumId.toString()+"',"
              +"'getMedia':'"+getMedia.toString()+"'," 
              +"'commaDelimitedCategoryCodeList':'"+catList.toString()+"',"
              +"'zoomLevel':'"+zoom.toString()+"'}", 
                

        contentType: "application/json; charset=utf-8", 

        dataType: "json",

        success: function(xhr, status) {
                
                var sb = "";
                //this is on purpose .net webservices
                //return strings of json as a json string
                //hence eval twice. dont ask....
                xhr = xhr.replace("\\\"","\"");
                
                var obj = eval("(" + xhr + ")");
           
                 handleFunction(obj);
                //place the dots on the map 
                 
                
        },

        error: function(xhr, status, error) {

        var err = JSON.parse(xhr.responseText);

        $("#error").html("Error –> " + err.Message);

        }

        }));

    }
   
    
    
    
    /**
     * Function to call on map move
     *
     */
     function mapMoveHandler(){
        
    
        googleMap.clearOverlays();
		//get the number of dots to draw
		
		//get the dimensions of the map
		
		
		var bounds = googleMap.getBounds();
		
		
        boundingBox = bounds;
        zoom = googleMap.getZoom();
		/*var lngSpan = northEast.lng() - southWest.lng();
		var latSpan = northEast.lat() - southWest.lat();
		for (var i = 0; i < dotNum; i++) {
			var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
				southWest.lng() + lngSpan * Math.random());
			googleMap.addOverlay(new GMarker(point));
		}*/
		
        getDotsForOwner(-1,travelPackId,true,"all",renderTPKDots);
    }
    
    
    
  
    /**
     * Closes the overlay for the item list
     */
    function closeItemList(){
        
        $("#listview").css("display","none");
    }
    /**
     * Opens the overlay for the item list
     */
    function openItemList(){
        var topview = $("#view");
        var view = $("#listview");
        clickOpenButton();
        view.css("display","block");
        topview.css("display","block");
    
    }
    
    /**
     * Handler to pass into the ajax call that retrieves the data
     * from a dot when it is clicked. Populates the list view with 
     * content
     */
    function showItemListFromDot(items){
        //open the detail view
        var topview = $("#view");
        var view = $("#listview");
        var cContainer = view.find("#listviewcontent");
        //set the heading
        $("#tpklisttitle").html("Selected Travel Pack Items");
        //show the zoom button
        showZoomButton();
        //set the zoom button
        var zoombtn = $(".zoombutton").unbind();
        zoombtn.click(function(){
            
            
            
            bbox = new GLatLngBounds;
            //add each point to build the bounds
            if(items.data.mediawall_data["@totalmedia"]>1){
            
                for(var i in items.data.mediawall_data.mediaitem){
                    var mitem = items.data.mediawall_data.mediaitem[i];
                    bbox.extend(new GLatLng(mitem["@lat"],mitem["@long"]));
                }
            }else if(items.data.mediawall_data["@totalmedia"]==1){
                var mitem = items.data.mediawall_data.mediaitem;
                 bbox.extend(new GLatLng(mitem["@lat"],mitem["@long"]));
            }
            if(items.data.places["@totalplaces"]>1){
                for(var j in items.data.places.place){
                    var pitem = items.data.places.place[j];
                     bbox.extend(new GLatLng(pitem["@lat"],pitem["@long"]));
                }
            }else if(items.data.places["@totalplaces"]==1){
                   var pitem = items.data.places.place;
                   bbox.extend(new GLatLng(pitem["@lat"],pitem["@long"]));
            }
           
            boundingBox = bbox;
            zoom = googleMap.getBoundsZoomLevel(bbox);
            if(zoom>maxAutoZoom){
                zoom =maxAutoZoom;
            }
            googleMap.setCenter(bbox.getCenter(),zoom);
            
        });
        
        // set the new variables in the map
        
        
        
        buildListHTML(items,cContainer);
        openItemList();
    }
    
   
    
    
    
     /**
     * Handler to pass into the ajax call that retrieves the data
     * for the current map view. Populates the list view with 
     * that content
     */
    function showItemList(items){
        //open the detail view
        var topview = $("#view");
        var view = $("#listview");
        var cContainer = view.find("#listviewcontent");
        $("#tpklisttitle").html("Travel Pack Items");
        
        buildListHTML(items,cContainer);
        
        openItemList();
	    
       
    }
    /**
     * Creates the HTML to insert in the list view container
     * based on the items retrieved via the ajax call
     */
    function buildListHTML(items,container){
        container.html("");
        var count = parseInt(items.data.mediawall_data["@totalmedia"]) + parseInt(items.data.places["@totalplaces"]);
        if(items.data.mediawall_data["@totalmedia"]>1){
            
            for(var i in items.data.mediawall_data.mediaitem){
                
                container.append(buildPhotoElement(items.data.mediawall_data.mediaitem[i]));
            }
        }else if(items.data.mediawall_data["@totalmedia"]==1){
            container.append(buildPhotoElement(items.data.mediawall_data.mediaitem));
        }
        if(items.data.places["@totalplaces"]>1){
            for(var j in items.data.places.place){
                container.append(buildPlaceHTML(items.data.places.place[j]));
            }
        }else if(items.data.places["@totalplaces"]==1){
            container.append(buildPlaceHTML(items.data.places.place));
        }else if(count==0){
            container.append("<div class='tpkmessage'>There are no travel pack items in this map view.</div>");
        }
        $(".thirdRow").html("<a>"+count.toString()+" ITEMS</a>");
        //return theList;
    }
    /**
     * Creates the HTML for a photo element in the item list
     */
    function buildPhotoElement(photo){
       var maindiv = $(document.createElement("div"));
       maindiv.addClass("secondRowPhoto");
       maindiv.append("<img class='secondRowPhoto_icon' src='/i/category_icons/icn-photos.gif' title='photo' alt='' width='24' height='24'/>");
       var lnk = $(document.createElement("a"));
      
       lnk.click(function(){
        
            showDetailPhoto(photo);
       });
       lnk.attr("href","#");
       lnk.addClass("secondRowPhoto_wthumb_link");
       var img = $(document.createElement("img"));
       img.attr("src","http://"+photo["@pathSlice"]);
       img.attr("alt","");
       img.addClass("secondRowPhoto_wthumb");
       img.attr("width","197");
       img.attr("height","79");
        
        lnk.append(img);
       maindiv.append(lnk);
       
       return maindiv;
       // <div class="secondRowPhoto">
       //             
						
		//				<a href="#"><img src="i/photo1.jpg" alt="" width="197" height="79"/></a>
					
		//		</div>
    }
    
    /**
     * shows the detail view for a photo element that is passed in
     */
    function showDetailPhoto(photo){
        showZoomButton();
       var zoombtn = $(".zoombutton").unbind();
        zoombtn.click(function(){
            zoom = maxAutoZoom;
            googleMap.setCenter(new GLatLng(photo["@lat"],photo["@long"]),maxAutoZoom);
            
        });
        
        showDetailView();
        
        $("#detailviewcontent").html("");
       var cont = $(document.createElement("div"));
       var maindiv = $(document.createElement("div"));
       maindiv.addClass("secondRowMainPhoto");
       maindiv.append("<a href='"+photo["@MediaPageLink"]+"' target='_blank'><img src='http://"+photo["@path"]+"' alt='' width='200' height='150'/></a>");
       var backdiv = $(document.createElement("div"));
       backdiv.addClass("back");
       var backlnk = $(document.createElement("a"));
       
       backlnk.click(function(){
            $("#detailview").css("display","none");
            openItemList();
            
       });
       backlnk.attr("href","#");
       backlnk.html("back to the list");
       backdiv.append(backlnk);
       
       cont.append(maindiv);
       cont.append(backdiv);
       $("#detailviewcontent").html(cont);
        //<div class="secondRowMainPhoto">
        //<img height="150" width="200" alt="" src="/i/photo_main1.jpg"/>
        //</div>
        //<div class="back">
        //<a href="#">back to the list</a>
        //</div>
    
    
    }
    
    /**
     * Displays the detail view for a given place
     */     
      function showDetailPlace(place){
        //set up the zoom button
        showZoomButton();
       var zoombtn = $(".zoombutton").unbind();
        zoombtn.click(function(){
            zoom = maxAutoZoom;
            googleMap.setCenter(new GLatLng(place["@lat"],place["@long"]),maxAutoZoom);
            
        });
        showDetailView();
        $("#detailviewcontent").html("");
       var cont = $(document.createElement("div"));
       var maindiv = $(document.createElement("div"));
       maindiv.addClass("secondRowAddress");
       var addressName = $(document.createElement("div"));
       addressName.addClass("addressName");
       addressName.html("<a href='"+place.GuideLink+"' target='_blank'>"+place.title+"</a>");
       var stars = $(document.createElement("div"));
       stars.addClass("Stars");
       
       stars.html("<img src='/i/screen/w-smallstar"+place.starRating+".gif' />");
       addressName.append(stars);
       maindiv.append(addressName);
       var address= $(document.createElement("div"));
       address.addClass("addressAddress");
       var adr = place.address!=null?place.address:"";
       address.html("<h1>Address:</h1><a>"+adr+"</a>");
       maindiv.append(address);
       var backdiv = $(document.createElement("div"));
       backdiv.addClass("back");
       var backlnk = $(document.createElement("a"));
       
       backlnk.click(function(){
            $("#detailview").css("display","none");
            openItemList();
            
       });
       backlnk.attr("href","#");
       backlnk.html("back to the list");
       backdiv.append(backlnk);
       
       cont.append(maindiv);
       cont.append(backdiv);
       $("#detailviewcontent").html(cont);
        
        
        
    
    
        
    
    }
    /**
     * displays the detail view pane and hides the list view
     */
    function showDetailView(){
       
        $("#view").css("display","block");
        $("#listview").css("display","none");
        $("#detailview").css("display","block");
        
    }
    
     /**
     * Creates the HTML to insert in the list view container
     * for a place item that is passed in
     */
    function buildPlaceHTML(place){
       var maindiv = $(document.createElement("div"));
       maindiv.addClass("secondRowItem");
       
       var contentdiv = $(document.createElement("div"));
       contentdiv.addClass("secondRowItem_content");

       var lnk = $(document.createElement("a"));
       lnk.addClass("secondRowItem_link");
       lnk.click(function(){
            showDetailPlace(place);
       });
       lnk.attr("href","#");
      
       lnk.html(place.title);
       
       var img = $(document.createElement("img"));
       var catImg = "";
       var catAlt = "";
       switch(place.categories["@MainCategoryCode"]){
            case "Attractions":
                catImg = "/i/category_icons/icn-attraction.gif";
                break;
           case "Lodging":
                catImg = "/i/category_icons/icn-hotel.gif";
                break;
           case "Activities":
                catImg = "/i/category_icons/icn-activities.gif";
                break;
                
           case "Dining":
                catImg = "/i/category_icons/icn-dining.gif";
                break;
            case "Restaurants":
            catImg = "/i/category_icons/icn-dining.gif";
            break;
                
           
       }
       img.attr("src",catImg);
       img.addClass("secondRowItem_icon");
       img.attr("alt",place.categories["@MainCategoryCode"]);
       img.attr("title",place.categories["@MainCategoryCode"]);
       img.attr("width","23");
       img.attr("height","23");
       
       var stardiv = $(document.createElement("div"));
       stardiv.addClass("secondRowItem_rating");
       stardiv.html("<img src='/i/screen/w-smallstar"+place.starRating+".gif' />");
       
       contentdiv.append(lnk);
       contentdiv.append(stardiv);
       maindiv.append(img);
       maindiv.append(contentdiv);
       
       
       //var html = "<div class='secondRowItem'>"
       //             +"<img src='i/icon_attraction.gif' alt='' width='24' height='24'/>"
		//			+"<a href='#'>Attraction K</a>"
		//			+"<div class='Stars'>"
		//			+""
		//			+"</div>"
		//		+"</div>";
        return maindiv;
    }
    
     /**
     * Closes the detail view 
     */
    function closeDetail(){
        $("#detailview").css("display","none");
    }
    /**
     * code to attach to the list view expand button when it is closed and you
     * want the next click to open it
     */
    function clickCloseButton(){
        var link = $(".firstRow  .openclosebutton a");
        link.html("<img height='16' width='16' alt='' src='/i/icon_add.gif'/>");
        $("#tpklisttitle").html("Travel Pack Items");
        hideZoomButton();
        link.unbind();
        link.click(function(){
            //var listview = $("#listview");
            var detailview = $("#detailview");
          //  var topview = $("#view");
          // listview.css("display","block");
           detailview.css("display","none");
	     //  topview.css("display","block");
          
            getTravelPackItemsForArea(100,  1,  -1,travelPackId,showItemList); 
	       
	       clickOpenButton();
        });
        
        
    }
    /**
     * code to close the list view expand button 
     * attaches the open events to the button afterwards
     */
    function clickOpenButton(){
         var link = $(".firstRow .openclosebutton a");
        link.html("<img height='16' width='16' alt='' src='/i/icon_less.gif'/>");
        link.unbind();
        link.click(function(){
            var listview = $("#listview");
            var detailview = $("#detailview");
            var topview = $("#view");
            listview.css("display","none");
	       detailview.css("display","none");
	       topview.css("display","none");
	       clickCloseButton();
        });
    
    }    

}
/**
 * Shows the zoom button on the navigation bar
 */
function showZoomButton(){
     $(".zoombutton").css("display","block");

}
/**
 * Hides the zoom button on the navigation bar
 */
function hideZoomButton(){
    $(".zoombutton").css("display","none");

}


/**
 * Custom Overlay for our map
 */


