/**
 * @fileoverview Gulu "wantto public page" JS module
 * @author Eric Lee <eric.lee@geniecapital.com.tw>
 */

var Gulu = Gulu || {};
Gulu.WantToPublic = Gulu.WantToPublic || {};

/**
 * Public page friend feed view
 * @extends Backbone.View
 */
Gulu.WantToPublic.PublicFriendFeedView = Backbone.View.extend({
    el: ".wantto_friend",
    initialize: function(){
        _.bindAll(this, 'render', 'resizeHeight', 'bindEvent');
        this.render();
    },
    render: function() {
        this.offsetTop = $(this.el).offset().top;
        this.resizeHeight();
        this.bindEvent();
        showDialogAjax({
           selector:$(".new_post_link a"),
           url: "/wantto/ajax/render_wantto_form/",
           type: "GET",
           callback: function(){
               $('.ui_dialog.all_center').css('width', '490px');  //For IE7
               $('.ui_dialog.all_center').css('margin-left', '-256px');  //For IE7
               //$('.popup_q_invite form.quick_invite .input_invite_location').trigger('remove_last');
           },
           callback_close: function(self){
               popup_invite = false;
           },
           nail: "nail_win_middle"
       });
    },
    
    //helper functions:
    /**
     * Adjust the height of friendfeed section according to the window size.
     */
    resizeHeight: function(){
        $(this.el).height($('.col_right_public').height() - 248);
        var feedHeight = 30;
        var lastFeedIndex = Math.floor(($('.wantto_friend').height()-$('.wantto_friend .box_title').height()-8)/feedHeight)-2;
        $('.friend_feed_container li:gt('+lastFeedIndex+')').hide();
        $('.friend_feed_container li:lt('+lastFeedIndex+')').show();
        $('.friend_feed_container li:eq('+lastFeedIndex+')').show();
    },
    /**
     * bind resize window event.
     */
    bindEvent: function(){
       var _this = this;
       $(window).resize(function() {
           _this.resizeHeight();
       });
    }
});

/**
 * Main public page view
 * @extends Backbone.View
 * TODO: refactor friendfeed, Gmap 
 */
Gulu.WantToPublic.WtPublicView = Backbone.View.extend({
    el: '#main_body',
    initialize: function(){
        _.bindAll(this, 'render', 'initFriendFeed', 'initGmap', 'appendFriendFeed');
        this.render();
    },
    render: function(){
        this.num_per_page = 20;
        this.feed_index = 0;
        this.initFriendFeed();
        this.publicFriendFeedView = "";
        if(this.options.viewerUserEmail){
            this.publicFriendFeedView = new Gulu.WantToPublic.PublicFriendFeedView({minHeight:125});
        };
        this.initGmap();
    },
    //helper functions:
    /**
	 * initialize friendfeed section
	 * TODO: use backbone model 
	 */
    initFriendFeed: function(){
       var _this = this;
       $('.friend_feed_more').click(function(){
           $.ajax({
               url: "/wantto/ajax/more_feed_public/" ,
               type: 'POST',
               data: {'num_per_page':_this.num_per_page, 'feed_index':_this.feed_index,'viewer_user_id':_this.options.viewerUserId,'viewer_email':_this.options.viewerUserEmail},
               dataType:'json',                    
               success: _this.appendFriendFeed, 
               error: function( xhr ){
                   console.log(xhr.responseText);
               }
           });
           return false;
       });
       $(".friend_feed_more").click();    
    },
    
    /**
     * Append Friendfeed
     * TODO: use underscore template 
     */
    appendFriendFeed: function(result){
        if (result.ok == 1){
            var feeds = result.data;
            for (var i=0; i < feeds.length; i++){
                
                //assign info
                var friend_info = guluglobal.ctlist[feeds[i].user_id];
                var $template = $('.feed_tpm').clone();
                $template.removeClass('feed_tpm');
                $template.find('.feed_msg').attr("href", feeds[i].wantto_url) ;
                $template.find('.user_name').html(feeds[i].wantto_display );
                
                if(this.options.viewerUserId){
                    if(friend_info){
                        $template.find('.pic img').attr("src", friend_info['photo_url']);
                    }else{
                        $template.find('.pic img').attr("src", feeds[i].user_photo_url) ;
                    }
                }else{
                    $template.find('.pic img').attr("src", feeds[i].user_photo_url) ;
                }
                
                //append to ul
                $template.css('display','block');
                $template.appendTo($(".feed_list" ));
                $(".category_sec."+feeds[i].category).css('display','block');
                
                //resize divs
                if(this.options.viewerUserEmail){
                    this.publicFriendFeedView.resizeHeight();
                };
                if (!this.options.pageView.options.lightBoxMode){
                    this.options.pageView.publicPageFooterView.correctPosition();
                }
            }
            this.feed_index += this.num_per_page;
            if (result.no_more){
                $('.more_btn').hide();
                $('.wantto_friend').find('.separator_dashed').hide()
            }                
        }  
    },
    
    /**
     * initialize Gmap
     */
    initGmap: function(){
        $('.place_map .map_group').css({'width':'246px', 'height':'150px'});
        var latitude = this.options.placeLatitude;
        var longitude = this.options.placeLongitude;
        var RMap;
        var zoom = 13;
        var type = google.maps.MapTypeId.ROADMAP;
        var flag = flag;
        
        //declare image
        var genieImage = new google.maps.MarkerImage('http://media01.linkedin.com/media/p/2/000/050/211/28f3ecc.png',
                    new google.maps.Size(62, 72));
            var placeImage = new google.maps.MarkerImage(this.options.staticUrl+'images/place.png',
                    new google.maps.Size(30, 30));
            var userImage = new google.maps.MarkerImage(this.options.staticUrl+'images/user.png',
                    new google.maps.Size(30, 30));
            var routeImage = this.options.staticUrl+'images/location.png';
            
              var customMarkers = [];
              customMarkers["genie"] = genieImage;
              customMarkers["place"] = placeImage;
              customMarkers["user"] = userImage;
              customMarkers["route"] = routeImage;
        
        //query geographic coordinate first
        if( ( Math.abs(longitude) <= 180 && Math.abs(latitude) <= 90) &&
            ( longitude != 0 && latitude != 0 ) 
          ){
            latlng = new google.maps.LatLng(latitude, longitude);
            RMap = new MapManager('place_map');
            RMap.init();
            RMap.setCustomMarkers(customMarkers);
            RMap.setMapOptions({'draggable':true});
            RMap.initDirectionService();
            RMap.toPositionByLatlng(latlng);
            google.maps.event.addListenerOnce(RMap.map, 'idle', function(){
                RMap.setMarker(RMap.map.getCenter());
            });
            google.maps.event.addListener(RMap.map, 'dblclick', function(event){RMap.setUserLocation(event.latLng)});
        }
        //otherwise query address
        else{
            RMap = new MapManager('place_map');
            RMap.init();
            RMap.setCustomMarkers(customMarkers);
            RMap.setMapOptions({'draggable':true});
            RMap.initDirectionService();
            RMap.toPositionByAddress(this.options.placeAddr);
            google.maps.event.addListenerOnce(RMap.map, 'idle', function(){
                RMap.setMarker(RMap.map.getCenter());
            });
            google.maps.event.addListener(RMap.map, 'dblclick', function(event){RMap.setUserLocation(event.latLng)});
        }
    }
});

