/**
 * @fileoverview Gulu "public page" JS module for some common features
 *                    in different public pages. 
 * @author Eric Lee <eric.lee@geniecapital.com.tw>
 */
 
var Gulu = Gulu || {};
Gulu.PublicPage = Gulu.PublicPage || {};

/**
 * initialize the comment(chat) including height resize.
 * @extends Backbone.View
 */
Gulu.PublicPage.CommentImView = Backbone.View.extend({
    el: ".col_right_public",
    initialize: function(){
        _.bindAll(this, 'render', 'resizeHeight', 'getCommentListHeight', 'bindEvent');
        this.offsetTop = $($(this.el)).offset().top;
        this.render();
    },
    render: function(){
        if(this.options.chatType != 'events'){
	        new GComments.Commenter({ container  : $($(this.el)).find('#comment_container'), 
	                                  im_style   : true,
	                                  placeholder: this.options.senderName + ':'});
	        $(".glchat_rt_object").globjectnotify();
	    };
        this.resizeHeight();
        this.bindEvent();
    }, 
    
    //helper functions:
    /**
	 * Adjust the height of comment section according to the window size.
	 */
    resizeHeight: function(){
        var footerHeight = $('#footer').height();
        var winHeight = 0;
        var body = window.document.body;
        if (window.innerHeight) {
            winHeight = window.innerHeight;
        } else if (body.parentElement.clientHeight) {
            winHeight = body.parentElement.clientHeight;
        } else if (body && body.clientHeight) {
            winHeight = body.clientHeight;
        };
        var newHeight = winHeight - footerHeight - this.offsetTop;
        if (this.options.fixHeight) {
            if(this.options.fixHeightVal > this.options.minHeight){
                $(this.el).height(this.options.fixHeightVal);
            }else{
                $(this.el).height(this.options.minHeight);
            }
            //if($('.event_container').length>0){
                $('.event_container').width(970);
                //$('.dare_container').width(970);
                $('.wantto_container').width(970);
            //}
        }else if(newHeight<this.options.minHeight){
            $($(this.el)).height(this.options.minHeight);
        }else{
            $($(this.el)).height(newHeight);
        };
        $(this.el).find('.comment_list').css('max-height', this.getCommentListHeight());
        $(this.el).find('.nothing_data').css('margin-bottom', $(this.el).height() - this.options.minHeight + 100);
        //$(this.el).find(".comment_list").prop({scrollTop: $(this.el).find(".comment_list")
        //                             .prop("scrollHeight")});
        
    },
    
    /**
     * Get the height of ".comment_list".
     * @return {int} the height of ".comment_list" 
     */
    getCommentListHeight: function(){
        var offset = 8;
        return $(this.el).height() 
                - $(this.el).find('.box_title').outerHeight(true) 
                - $(this.el).find('#comment_container .separator_dashed').outerHeight(true) 
                - $(this.el).find('#comment_container .text_field.cf').outerHeight(true)-offset;
    },
    
    /**
     * Bind the mousewhell event (only allow comment list to scroll) 
     * and window resize event (adjust comment list height).
     */
    bindEvent: function(){
       var _this = this;
       $('body').bind('mousewheel DOMMouseScroll', function(e) { // on scroll
           var $div = $(_this.el).find('.comment_list');
           var delta = e.wheelDelta || e.detail;
           $div.scrollTop($div.scrollTop() 
                           + ( delta < 0 ? 1 : -1 ) * 30);
           return false; 
       });
       $('body').attr('ontouchmove',"touchMove(event);");
       $(window).resize(function() {
           _this.resizeHeight();
       });
       
    }
});

/**
 * Public page footer
 * @extends Backbone.View
 */
Gulu.PublicPage.PublicPageFooterView = Backbone.View.extend({
    el: '#footer',
    initialize: function(){
        _.bindAll(this, 'render', 'correctPosition', 'bindEvent');
        this.offsetTop = $(this.el).offset().top;
        this.render();
        
    },
    render: function(){
        $(this.el).find('.bd').hide();
        $(this.el).css({
            'margin-top':'0',
            'height':'39px',
            'position':'fixed',
            'bottom':'0px'
        });
        $(this.el).find('.info').css('padding','5px');
        $(this.el).find('.ft').css('margin-top','7px');
        $(this.el).find('.ft .info ul').css('padding-top','7px');
        $('.category_sec .title').hide();
        
        this.correctPosition();
        this.bindEvent();
    },
    
    //helper functions:
    /**
	 * adjsut the position of the footer according to window size.
	 */
    correctPosition: function(){
        
        var winHeight = 0;
        var body = window.document.body;
        if (window.innerHeight) {
            winHeight = window.innerHeight;
        } else if (body.parentElement.clientHeight) {
            winHeight = body.parentElement.clientHeight;
        } else if (body && body.clientHeight) {
            winHeight = body.clientHeight;
        };
        if(winHeight < $('.col_right_public').offset().top + $('.col_right_public').height()-5+39 
            || winHeight < this.options.minCommentHeight + 500){
            
            $('#footer').css({'position':'relative',
                              'bottom'  :'auto'});
        }else{
            $('#footer').css({'position':'fixed',
                              'bottom'  :'2px'});
        }
    },
    
    /**
     * bind resize window event.
     */
    bindEvent: function(){
       var _this = this;
       $(window).resize(function() {
           _this.correctPosition();
       });
    }
});

/**
 * Main Public page view
 * @extends Backbone.View
 */
Gulu.PublicPage.PublicPageBaseView = Backbone.View.extend({
    el: '#main_body',
    initialize: function(){
        //context binding
        _.bindAll(this, 'render','lockPage','unlockPage','checkAuth');
        $.ajaxSetup({ cache: false });
        //page initialization
        
        if (this.options.pageType == "events"){
            $(".event_public .glchat_rt_object").globjectnotify();
            $(".event_public .glchat").glchat();
            $(".event_public .glpresence").glpresence();
            $(".event_public .rsvp").glbcast();
        }
        if(!this.options.lightBoxMode){
            gCometURL = "/runtime";
            $.fn.glchat.startComet();
        }else if (this.options.pageType == "events"){
            $.fn.glchat.subscribe_chat(this.options.chatUUID);
        };
        
        //nothing-text
        this.options.connectText = "";
        if (this.options.pageType == "wantto"){
            this.options.connectText = gettext("Log in to find out where your friends want to go");
        }else if(this.options.pageType == "dare"){
            this.options.connectText = gettext("Log in to find out what's going on");
        } 
        if(!this.options.minCommentHeight){
            this.options.minCommentHeight = 402;
        }
        
        this.render();
        
    },
    render: function(){
        this.checkAuth();
        if(!this.options.lightBoxMode){
            this.publicPageFooterView = new Gulu.PublicPage.PublicPageFooterView({minCommentHeight:this.options.minCommentHeight});
        }
        this.commentImView = new Gulu.PublicPage.CommentImView({
           minHeight: this.options.minCommentHeight,
           senderName: this.options.veiwerUserName,
           fixHeight: this.options.lightBoxMode,
           fixHeightVal: this.options.fixHeightVal,
           chatType: this.options.pageType

        });
        
        if($('.pupup_content').length>0){
            $('.pupup_content').width(970);
        };
        $('.ui_dialog').width(970);
    },
    
    //helper functions:
    /**
	 * lock page functions when user is not allow to view/comment on the page
	 */
    lockPage: function(){
        $('.nothing_data').css('display','block');
        $('.comment_list.talk_box_group').css('display','none');
        $('.comment_form input').attr("disabled", true);
    },
    
    /**
     * unlock page functions
     */
    unlockPage: function(){
        if($('.comment_list.talk_box_group').find('li').length > 0){
            $('.nothing_data').css('display','none');
        } 
        $('.comment_list.talk_box_group').css('display','block');
        $('.comment_form input').attr("disabled", true);
    },
    
    /**
     * display proper auth option according to the auth state of the page
     */
    checkAuth: function(){
       if (this.options.authState == 1){
           $('.nothing_data .text').text(gettext("facebook connect and start chatting!"));
           this.lockPage();
           systemTxt(this.options.connectText + '<br><br><br><input type="button" class="btn_fb_l pupup_fb">',{'hasbtn':false});
           var gulu_fb = new Facebook();
           $('.btn_fb_l.pupup_fb').click(function(){
               gulu_fb.doLogin("/facebook/connect/?next=/"+this.options.pageType+"/p/"+this.options.targetId);
           });
           $('.comment_form').hide();
       }else if(this.options.authState == 2){
           $('.nothing_data .text').text(gettext("facebook connect or sign up to start chatting!"));
           this.lockPage();
           $('#signup_popup_anchor').click();
           $('.comment_form').hide();
       }else if(this.options.authState == 3){
           $('.nothing_data .text').text(gettext("weibo connect and start chatting!"));
           this.lockPage();
           var state = encodeURIComponent('next=/'+this.options.pageType+'/p/'+this.options.targetId);
           systemTxt(this.options.connectText+'<br><br><br><a href="/weibo/connect/?state='+state+'" class="btn_weibo_l pupup_weibo"></a>',{'hasbtn':false});
           $('.comment_form').hide();
       }
    }
});


/**
 * Public page media model
 * @extends Backbone.Model
 */
Gulu.PublicPage.MediaModel = Backbone.Model.extend({});

/**
 * Public page media model
 * @extends Backbone.Collection
 */
Gulu.PublicPage.MediaSet = Backbone.Collection.extend({
    /*
     * data {'type', 'id', 'url_large', 'url', 'has_social' }
     */
    model: Gulu.PublicPage.MediaModel,
    
    initialize: function(options){
        _.bindAll(this, 'url');
        this.target_id = options.target_id;
        this.target_type = options.target_type;
        this.user_id = options.user_id;
    },

    url: function(){
        return "/"+ this.target_type +"/ajax/get_media/?tid="+ this.target_id + "&uid=" + this.user_id;
    }
});

/**
 * view for each photo or video li in gallery
 * @extends Backbone.View
 */
Gulu.PublicPage.MediaView = Backbone.View.extend({
    tagName: 'li',
    
    initialize: function(){
        _.bindAll(this, 'render','bindShowDetail');
        this.bindShowDetail();
        
    },
    
    render: function(){
        var compiled = _.template($("#template_media_li").html());
        var context = {media: this.model};
        $(this.el).html(compiled(context));
        return this;
    },
    
    //helper functions
    /**
     * bind event for clicking the thumnial
     */
    bindShowDetail: function(){
        var $this = this;
        var compiled = _.template($("#media_lightbox_content").html());
        var context = {media: this.model};
        var html = compiled(context);
        var settings = null;
        
        if (this.model.get('has_sns')){
            settings = {'title':'Video', 'hasbtn':false, 'callback_close':$this.share_social, 'callback':$this.convertUI};
        }
        if(this.model.get('type') == 'video'){
            thisObj.bind_player({
                video_id: thisObj.attr('class').split(' ')[3],
                url: "/videostream/ajax/show_video_player/",
                append_html: html,
                settings: settings
            });
        }else if(this.model.get('type') == 'photo'){
            $(this.el).click(function(){
	            if ($this.model.get('has_sns')){
	                systemTxt(html, {'title':'Photo',
	                                 'hasbtn':false, 
	                                 'callback_close':$this.share_social,
	                                 'callback':$this.convertUI});
	            }else{
	                systemTxt(html, {'title':'Photo'});
	            }
	            return false;
            });
        }
    },
    
    /**
     * function for sharing photo or video to sns
     */
    share_social: function(){
        var share_to_fb = $('input[name="post_to_facebook"]').is(':checked');
        var share_to_wb = $('input[name="post_to_weibo"]').is(':checked');
        if (share_to_wb || share_to_fb){
            /*
             * TODO: share event photo to SNS
             */
             /*
            $.ajax({
                url: "/dare/ajax/share_media/" ,
                type: 'POST',
                data: {'dare_id':dareId, 'media_id':thisObj.data('mediaId'), 'media_type':'video', 
                       'share_to_fb':share_to_fb, 'share_to_wb':share_to_wb},
                dataType:'json',                    
                success: function(response){
                    systemTxt(gettext('Successfully Shared!'));
                },
                error: function( xhr ){
                    console.log(xhr.responseText);
                }
            });
            */
        }
    },
    
    convertUI: function(){
        $(".ui_popup").find("input:checkbox").autoConvertUI({
            type: "checkbox",
            hook_event_1: function() {
                // callback function write here
            }
        });
    }
    


});


/**
 * Public page gallery view
 * @extends Backbone.View
 */
Gulu.PublicPage.GalleryView = Backbone.View.extend({
    el: '.media_gallery',
    initialize: function(options){
        //context binding
        var $this = this;
        _.bindAll(this, 'render', 'setPageNum', 'appendItem', 'prependItem', 'showPage' );
        //page initialization
        this.collection.bind('reset', this.render);
        this.collection.bind('add', this.prependItem);
        this.collection.fetch();
        this.event_id = this.options.event_id;
        this.uid = this.options.uid;
        this.numPerPage = options.numPerPage;
        this.galleryPage = 1;
        this.numOfRow = 0;
        this.photoHeight = $(this.el).find('li:nth-child(1)').height();
        this.paddingHight = parseInt($(this.el).find('li:nth-child(1)').css("margin-top").replace("px", ""));
        
        this.bindEvent();        
        //init video uploader
        $('.upload_media').PhotoVideoUploader({
            object_id: this.event_id,
            user_id: $('.upload_media').data('userId'),
            url: '/events/ajax/file_uploader/?event_id=' + this.event_id,
            add_media_url: '/events/ajax/add_media/?uid='+this.uid,
            success_call_back: function(data){
                $('.no_content').hide();
                $('.public_page_gallery').show();
                $this.collection.fetch();     
            }
        });
        
    },
    
    render: function(){
        var $this = this;
        var $target = $(this.el);
        $target.find('li:gt(0)').remove();
        _(this.collection.models).each(function(item){
            $this.appendItem(item);
        });
        
        this.resizeHeight();                                                    
        return this;
    },
    //helper functions
    
    /**
     * adjust the height of the gallery
     */
    resizeHeight: function(){
        var newHeight = $('.col_right_public').height() - 374;
        
        if (newHeight > this.photoHeight + this.paddingHight){
	        $(this.el).parent().height(newHeight);
        }else{
            $(this.el).parent().height(this.photoHeight + this.paddingHight);
        };
        
        $('.no_content').height($('.col_right_public').height() - 348);
        
        this.showPage();
        $('.page_nums .num:eq('+ (this.galleryPage-1) +')').click();
    },
    
    /**
     * bind resize window event.
     */
    bindEvent: function(){
       var _this = this;
       $(window).resize(function() {
           _this.resizeHeight();
       });
    },
    
    /**
     * setup page numbers
     */
    setPageNum: function(){
        var $this = this;
        
        //init numbers
        var maxPage = Math.ceil(this.collection.length/this.numPerPage);
        $('.page_nums ul').html('');
        for(var i=1; i<=maxPage; i++){
            $('.page_nums ul').append('<li><a href="#" class="num">'+i+'</a></li> ');
        };
        $('.page_nums ul li:nth-child('+$this.galleryPage+')').addClass('on');
        
        //bind click events
        $(".page_nums .next").unbind();
        $(".page_nums .priv").unbind();
        $('.page_nums .num').unbind();
        
        $('.page_nums .num').click(function(){
            $('.page_nums ul li:nth-child('+$this.galleryPage+')').removeClass('on');
            $this.galleryPage = parseInt($(this).text());
            $('.page_nums ul li:nth-child('+$this.galleryPage+')').addClass('on');
            $this.showPage(true);
            return false;
        });
        $(".page_nums .next").click(function(){
            if($this.galleryPage < maxPage){
                $('.page_nums ul li:nth-child('+$this.galleryPage+')').removeClass('on');
                $this.galleryPage += 1;
                $('.page_nums ul li:nth-child('+$this.galleryPage+')').addClass('on');
                $this.showPage(true);
            }
            return false;
        });
        $(".page_nums .priv").click(function(){
            if($this.galleryPage >1){
                $('.page_nums ul li:nth-child('+$this.galleryPage+')').removeClass('on');
                $this.galleryPage -= 1;
                $('.page_nums ul li:nth-child('+$this.galleryPage+')').addClass('on');
                $this.showPage(true);
            }
            return false;
        });
        
    },
    
    /**
     * display current page
     */
    showPage: function(force){
        var newNumOfRow = Math.floor($(this.el).parent().height()/(this.photoHeight + this.paddingHight));
        if ((newNumOfRow != this.numOfRow || force == true ) && $(this.el).find('li').length > 1){
            this.numOfRow = newNumOfRow;
            this.numPerPage = this.numOfRow*4-1; 
            if(force != true){ 
                this.galleryPage = 1;
            }
            
	        $(this.el).children().filter(':gt(0)').hide();
	        for(var ind=1; ind<=this.numPerPage; ind++){
	            $(this.el).find(' li:nth-child('+ ((this.galleryPage-1)*this.numPerPage+ind+1)  +')').show();
	        }
	        this.setPageNum();
        }
    },
    
    /**
     * append photo or video 
     */
    appendItem: function(item){
        var $target = $(this.el);
        var media = new Gulu.PublicPage.MediaView({model:item});
        $(media.render().el).hide().appendTo($target);
    },
    
    /**
     * prepend photo or video 
     */
    prependItem: function(item){
        var $target = $(this.el).find('li:first-child');
        var media = new Gulu.PublicPage.MediaView({model:item});
        $(media.render().el).hide().insertAfter($target).fadeIn();
    }
});
























