//Global timers
var globalTimer1;
var globalTimer2;
var globalTimer3;
var debug_mode = false;
var refresh_count = 0;
    
var Translator = Backbone.Model.extend({
    
    //Change event should be bound to the form elements  
    defaults: {
        'type': 'post',
        'form_name': '',
        'root_id' : '',
        'field_name': '',
        'in_lang': '',
        'out_langs': [],
        'post_id': '',
        'facebook_post_id': '',
        'translations': {}
    },

    initialize: function(params){
        _.bindAll(this, 'getOriginalText', 'getTranslatedText');
        // Need to validate the params to confirm all necessary values
        this.set(params);        
    },

    getOriginalText: function() {
        var text = $("#" + this.get('form_name')).find(".text_in").val();
        return text;
    },

    getTranslatedText: function(lang) {
        var text;
        if (_.include(this.get('out_langs'), lang)) {
            text = $("#" + this.get('form_name')).find(".text_out").val();
        } else {
            var trans = this.get('translations');
            text = trans[lang]['text'];
        }
        return text;
    },
    
    hasImage: function() {
        if ($("#" + this.get('form_name')).find("#image").val()) {
            return true;
        } else {
            return false;
        }
    },
    
    getS3Image: function() {
        // Temp until migration to local storage
        var image_path = wjInterfaceController.s3image;
        console.log("s3 image path: " + image_path);
        return image_path;
    },
    
    getLatLong: function() {
        var latitude = $("#" + this.get('form_name')).find("#mapLat").val();
        var longitude = $("#" + this.get('form_name')).find("#mapLong").val();
        if (!latitude || !longitude) {
            return false;
        }
        return {latitude: latitude, longitude: longitude};
    }

    //define model methods that gets the data from form_name and field_name
});

var TranslatorView = Backbone.View.extend({
   
    events: {
        //"keypress .text_in"    : "submitOnKey",
        //"click .button_submit" : "submitOnClick", Careful! This is out of el scope so need to reimplement
        "focus .text_in"       : "inFieldFocus",
        "blur .text_in"        : "inFieldBlur",
        "keyup .text_in"       : "inFieldKeyup",
        "keyup .text_out"      : "outFieldKeyup"
    },
    
    properties: {        
        class_defaultTextActive: "defaultTextActive",
        class_disabled         : "disabled",
        class_expanded         : "expanded",
        class_transVisible     : "transVisible",
        class_wordCount        : "wordcount",
        class_inLabel          : "label_in",
        class_outLabel         : "label_out",
        class_labelVisible     : "label_visible",
        defaultText            : "Please type here.",
        toolTipText            : "You may modify translated text here.",
        inputTip               : "Tips for input text",
        editTip                : "Tips for translation edit",
        button_lock_duration   : 500,
        wordcount_limit        : 160,
        tooltip_disabled       : false,
        default_lang           : 'en'
    }, 


    initialize: function(params){        
   
       //Usage: transview = new TranslatorView({id: [element id],...});
        _.bindAll(this, 'render', 'setDOMReference', 'submitOnKey', 'submitOnClick', 'inFieldFocus' ,'inFieldBlur', 'inFieldKeyup', 'outFieldKeyup', 'translate', 'submitText', 'setDefaultText');     

        this.model = new Translator();      
        this.model.set({
            "form_name" : params.formName,
            "root_id"   : params.root_id,
            "field_name": params.fieldName,
            "in_lang"   : params.inLang,
            "out_langs" : params.outLangArray
        });
        
        if (params.formName !== 'newPost') {
            this.model.set({'type': 'comment'});
            //temp because the hidden element shouldnt have id
            var post_id = $("#" + params.formName).find("#post_id").val();
            this.model.set({'post_id': post_id});
        }
        
        if (params.options) {
            _(params.options).each(function(value, key){
                this.properties[key] = value;           
            }, this);
        }

        this.setDOMReference(params);

        if (this.properties.wordcount_limit)
        {
            this.wordcount_field.html(this.properties.wordcount_limit);            
        }
        
        this.setDefaultText();
        
        //Make sure to disable submit when in_field is empty or has default text
        if( this.in_field.hasClass(this.properties.class_defaultTextActive) || $.trim(this.in_field.val()) == "" )
        {
            this.button_submit.addClass(this.properties.class_disabled);
        }
        
        // Binding the one final submit button which is out of el scope. To be moved to outer class.
        this.button_submit.bind('click', this, function(e){
             if (e.data.form_name === "groupCreate" || e.data.form_name === "groupEdit") {
                 $("#" + e.data.form_name).submit();
                 return;
             }
             e.data.submitText();
        })
        
    },    
      
    setDOMReference: function(params) {
        //Need to validate params
        this.form_name = params.formName;
        this.root_id = params.root_id;
        this.field_name = params.fieldName;
        this.in_lang = params.inLang;
        this.out_langs = params.outLangArray;
        this.out_fields = [];
        this.out_fields_ref = [];
        this.in_field = $("#" + this.root_id).find("#" + this.field_name + this.in_lang);
        this.button_submit = $("#" + this.form_name).find(".button_submit");
        this.tip_field1 = $("#" + this.root_id).find(".trans-tip1");
        this.wordcount_field = $('#' + this.root_id).find("." + this.properties.class_wordCount);       
        for(var lang in this.out_langs) {
            this.out_fields.push($("#" + this.root_id).find("#" + this.field_name + this.out_langs[lang]));
            this.out_fields_ref.push($("#" + this.root_id).find("#" + this.field_name + this.out_langs[lang] + "_ref"));
        }
    },
    
    submitOnKey: function(e) {
        //Submit with return key
        if (e.which == "13" ) {
            e.preventDefault();
            this.submitText();
        }
    },
    
    submitOnClick: function(e) {
        if (this.form_name === "groupCreate" || this.form_name === "groupEdit") {
            $("#" + this.form_name).submit();
            return;
        }
        this.submitText();       
    },
    
    inFieldFocus: function() {
        
        if (!this.properties.tooltip_disabled) {
            this.showSideTip(this.tip_field1, this.root_id + "-tip1", this.properties.inputTip);        
        }
        
        if (this.in_field.hasClass(this.properties.class_defaultTextActive))
        {
           this.in_field.removeClass(this.properties.class_defaultTextActive);
           this.in_field.val("");
        }

        if(this.field_name === "title_") {
            return;
        }
        
        if(!this.in_field.hasClass(this.properties.class_expanded)) {
            this.in_field.addClass(this.properties.class_expanded);
            //unbind this event here
            this.button_submit.fadeIn("fast");
            this.wordcount_field.fadeIn("fast");
        }
    },
    
    inFieldBlur: function() {
       if (!this.properties.tooltip_disabled) {
           this.hideSideTip(this.tip_field1, this.form_name + "-tip1");
       }
       if (this.in_field.val() === "")
       {
           this.in_field.addClass(this.properties.class_defaultTextActive);
           this.in_field.val(this.properties.defaultText);
       }
    },    
    
    inFieldKeyup: function (e) {
        // get new length of characters
        var max_char = this.properties.wordcount_limit;
        
        var current_char = this.in_field.val().length;
        this.wordcount_field.html(max_char - current_char);

        if (current_char > max_char)
        {
            this.wordcount_field.css("color", "#ff0000");
            if (!this.button_submit.hasClass(this.properties.class_disabled))
            {
                this.button_submit.addClass(this.properties.class_disabled);
                return;
            }
        } else {
            this.wordcount_field.css("color", "#666666");
        }
        
        // If user has monolingual profile.
        if(this.out_langs.length < 1)
        { 
            if (this.in_field.val() !== "" && $("#" + this.root_id).find("." + this.properties.class_wordCount).html() > -1) {
                this.button_submit.removeClass(this.properties.class_disabled);
            }
            // If inField has default text, don't allow submit
            if( this.in_field.hasClass(this.properties.class_defaultTextActive) || $.trim(this.in_field.val()) == "" )
            {
                this.button_submit.addClass(this.properties.class_disabled);
            }
            return;
        }               
        
        // Use separate timers for successive translation fields
        if(!this.button_submit.hasClass(this.properties.class_disabled)) {
            this.button_submit.addClass(this.properties.class_disabled);
        }
        
        var that = this;
        clearTimeout(globalTimer1)
        globalTimer1 = setTimeout( function() {
            // Don't send default text to translator.
            if(that.in_field.hasClass(that.properties.class_defaultTextActive))
            {
                for(var i in that.out_fields)
                {
                    that.out_fields[i].val("");
                }
                return;
            }
            // Send translation request.
            var now = new Date();
            console.log("Translation request sent at " + now.getTime());
            
            that.translate();
        }, this.properties.button_lock_duration);        
        
    },    

    outFieldKeyup: function(e) {

        //Hide submit button while typing.
        this.button_submit.addClass(this.properties.class_disabled);
        clearTimeout(globalTimer2)
        var that = this;
        globalTimer2 = setTimeout( function() {

            //if inField = defaulttext, keep it disabled.
            if(that.in_field.hasClass(that.properties.class_defaultTextActive))
            {
                return;
            }
            //if outField is blank, keep it disabled.
            for(var lang in that.out_fields) {
                if(that.out_fields[lang].val() === "") {
                    return;
                }
            }

            that.button_submit.removeClass(that.properties.class_disabled);
        }, that.properties.button_lock_duration);
        
    },
    
    translate: function (){

        var in_string = encodeURI(this.in_field.val());

        var port = window.location.port;
	if (port != '') {
		port = ':'+port;
	}
        var baseUrl = window.location.protocol+'//'+window.location.hostname+port;

        var requestUrl = baseUrl + "/Rest/translate?q="+in_string+"&source="+this.in_lang+"&target="+this.out_langs.join("+");

        var that = this;

        $.ajax({
            url: requestUrl,
            type: "GET",
            timeout: (60 * 1000),
            success: function(data) {

                var parsedData = JSON.parse(data);

                    var label_field = $("#" + that.root_id).find("." + that.properties.class_outLabel);
                    label_field.addClass(that.properties.class_labelVisible);
                    label_field.fadeIn("fast");

                    for (var i in that.out_langs)
                    {
                        var out_lang = that.out_langs[i];
                        var out_string = parsedData[out_lang];
                        var out_field = that.out_fields[i];
                        out_field.val(out_string);

                        var out_field_ref =  that.out_fields_ref[i];
                        out_field_ref.html(out_string);
                        if (!that.properties.tooltip_disabled) {
                            var tip_field2 = $("#" + that.root_id).find(".trans-tip2");
                        }
                        if(!out_field.hasClass(that.properties.class_transVisible))
                        {
                            out_field_ref.addClass(that.properties.class_transVisible);
                            out_field_ref.parent().css("height", "auto");
                            out_field_ref.animate({
                                opacity: 1
                                }, "fast"
                            );
                            $(out_field).addClass(that.properties.class_transVisible)
                            $(out_field).fadeIn('fast'); 
                            if(!that.properties.tooltip_disabled) {
                                that.showSideTip(tip_field2, that.root_id + "-tip2", that.properties.editTip);
                            }
                            /*
                            $(outFieldRef).bind('click', outField, function(e){
                                e.data.addClass(wjTransFormDecorator.class_transVisible);
                                e.data.slideDown(50);
                            });
                            */
                        }
                    }               
            },
            error: function(XMLHttpRequest, textStatus){
                console.log('Translation failed. Error: ' + textStatus);
            },
            complete: function(){
                //Show submit button after last back-translation. Keep it hidden if field is blank.
                if (in_string !== "" && $("#" + that.root_id).find("." + that.properties.class_wordCount).html() > -1)
                {
                    that.button_submit.removeClass(that.properties.class_disabled);
                }
            }
        });
    },
    
    translateText: function (in_string, in_lang, out_langs, callback){

        in_string = encodeURI(in_string);

        var port = window.location.port;
	if (port != '') {
		port = ':'+port;
	}
        var baseUrl = window.location.protocol+'//'+window.location.hostname+port;

        var requestUrl = baseUrl + "/Rest/translate?q="+in_string+"&source="+in_lang+"&target="+out_langs.join("+");

        $.ajax({
            url: requestUrl,
            type: "GET",
            timeout: (60 * 1000),
            success: function(data) {

                var parsedData = JSON.parse(data);
                callback(parsedData);
            },
            error: function(XMLHttpRequest, textStatus){
                console.log('Translation failed. Error: ' + textStatus);
            }
        });
    },
    
    submitText: function() {
        //translator_collection.properties.supported_langs = ['en', 'ja', 'fr'];        
        var that = this;
        //If disabled, then don't submit.
        if (this.button_submit.hasClass(this.properties.class_disabled)) {
            return;
        }
        this.button_submit.addClass(this.properties.class_disabled);
        
        if (facebook_client.get('isMultipostAllowed')) {
            var source_text = this.in_field.val();
            if (this.in_lang !== this.properties.default_lang) {
                source_text = this.out_fields[0].val();
            }                        
            var current_langs = _.union([this.in_lang], this.out_langs);
            var other_langs = _.difference(translator_collection.properties.supported_langs, current_langs);

            console.log('List of other langs: ' + other_langs);
            console.log('Source text: ' + source_text);

            this.translateText(source_text, this.properties.default_lang, other_langs, function(response){
                console.log(response);
                var data = {};
                _.each(response, function(translation, lang){  
                    if (that.model.get('type') === 'post') {
                        data[lang] = {text: translation};
                    } else {
                        data[lang] = {text: translation};
                    }
                });
                data[that.in_lang] = {text: that.in_field.val()};
                for (var i in that.out_langs) {
                    data[that.out_langs[i]] = {text: that.out_fields[i].val()};
                }
                console.log(data);            
                that.model.set({translations: data});                  

                that.submitText2Facebook(function(){
                    wjInterfaceController.pushContent(that.model, function(){
                        that.resetTranslator(); 
                    });   
                    return;
                });
            });
        } else if (facebook_client.get('isAuthorized')) {
            that.submitText2Facebook(function(){
                wjInterfaceController.pushContent(that.model, function(){
                    that.resetTranslator(); 
                });   
                return;
            });           
        } else {        
            wjInterfaceController.pushContent(this.model, function(){
                that.resetTranslator(); 
            });  
        }
    },
    
    submitText2Facebook: function(callback) {
        var that = this;

        facebook_client.sync(that.model, function(facebook_post_id){
            that.model.set({'facebook_post_id': facebook_post_id});
            if (that.model.get('type') === 'post') {
                $("#" + that.form_name).find('#fbPost_id').val(facebook_post_id);
                if (facebook_client.get('isMultipostAllowed')) {
                    var translations = that.model.get('translations');
                    $("#" + that.form_name).find("#multiplePosts").val(JSON.stringify(translations));
                }
            } else {
                $("#" + that.form_name).find('#fbComment_id').val(facebook_post_id);
            }
            callback();
        });
    },
    
    resetTranslator: function() {

        //Clear inField.
        this.in_field.addClass(this.properties.class_defaultTextActive);
        this.in_field.val(this.properties.defaultText);
        this.in_field.blur();
        this.wordcount_field.html(this.properties.wordcount_limit);
        this.wordcount_field.hide();
        this.button_submit.hide();
        this.button_submit.addClass(this.properties.class_disabled);

        //Reset media elements in post (TEMP)
        if (this.field_name === "postText_") {
            $('.uploader-item').hide();
            $("#image").val("");
            wjInterfaceController.s3image = "";
            $("#videoType").val("");
            $("#video").val("");
            $("#mapLat").val("");
            $("#mapLong").val("");
            $("#uploader-video-source").val("");
            $("#uploader-video-embed").html("");
            $("#uploader-map-address").val("");
            //To be fixed
            $('#post-image-uploader-droparea').children().remove();
            $('#post-image-uploader-droparea').append('<div id="droparea-instructions" class="instructions">Drop an image file here</div>');
        }

        for (var i in this.out_fields) {
            this.out_fields[i].val("");
            this.out_fields_ref[i].html("");
            this.out_fields[i].hide();
            //wjTransForm.outFieldRefArray[i].fadeOut("fast");
            this.out_fields[i].removeClass(this.properties.class_transVisible);
            var label_field = $("#" + this.root_id).find("." + this.properties.class_outLabel);
            label_field.removeClass(this.properties.class_labelVisible);
            this.in_field.removeClass(this.properties.class_expanded);
            this.out_fields_ref[i].animate({
                opacity: 0
                }, "fast"
            );
            if (!this.properties.tooltip_disabled) {
                var tip_field2 = $("#" + this.root_id).find(".trans-tip2");
                this.hideSideTip(tip_field2, this.root_id + "-tip2");
            }
            //labelField.fadeOut("slow");
        }
    },
    
    setDefaultText: function(){
        
        if (this.in_field.val() === "")
        {
            this.in_field.val(this.properties.defaultText);
            //Lets define defaultTextActive class in css.
            this.in_field.addClass(this.properties.class_defaultTextActive);
        } else if (this.in_field.val() == this.properties.defaultText) {
            this.in_field.addClass(this.properties.class_defaultTextActive);
        } else {
            this.in_field.removeClass(this.properties.class_defaultTextActive);
        }
        // hide trans field at first.
        for(var lang in this.out_fields) {
            if(!this.in_field.hasClass(this.properties.class_defaultTextActive))
            {
                this.out_fields[lang].addClass(this.properties.class_transVisible);
            }
        }

        this.in_field.blur();
    },
    
    showSideTip: function (tipField, id, tipText) {        
            tipField.append('<div id="' + id + '" class="side-tip" style="display: none"><div class="tipHeader"></div><div class="tipBody">' + tipText + '</div><div class="tipFooter"></div></div>');        
            //Show the tooltip with faceIn effect           
            $('#' + id).fadeIn('fast');
            $('#' + id).fadeTo('10',0.95);
    },
    
    hideSideTip: function (tipField, id) {
            tipField.children("#" + id).fadeOut("fast", function(){
                tipField.children("#" + id).remove();                
            });
    }
    
});

var TranslatorCollection = Backbone.Collection.extend({
    model: Translator
});

var TranslatorCollectionView = Backbone.View.extend({
    
    properties: {
        supported_langs: ['en', 'ja']
    },

    initialize: function(params) {
        _.bindAll(this, 'createTranslator');
        this.collection = new TranslatorCollection();
    },

    createTranslator: function(params) {
        var translator_view = new TranslatorView(params);
        this.collection.add(translator_view.model);
    }
/*  facebookSync: function() {

        _(this.collection.models).each(function(translator_model){

        }, this);
    }*/
});

var translator_collection = new TranslatorCollectionView();

////////////////////////////////////

var Member = Backbone.Model.extend({
    defaults: {
        user_id: '',
        user_name: '',
        user_image: ''
    }
});

var Group = Backbone.Model.extend({   
    defaults: {
        group_name: '',
        min_post_id: -1,
        max_post_id: -1,
        max_comment_id: -1,
        language: 'en',
        refresh_duration: 5000,
        base_url: '',
        justposted_text: 'Just Posted'
    }
});

var GroupCollection = Backbone.Collection.extend({
    model: Group
})

var GroupCollectionView = Backbone.View.extend({
    
    el: $('#post-container'),
    
    initialize: function(params){
        _.bindAll(this, 'render');       
        
        this.model = new Group();
        this.model.set(params);
        this.collection = new GroupCollection();
        this.collection.add(this.model);

        _(this.collection.models).each(function(item){
            
            //Do whatever initialization for each group model  
            //alert(item.attributes.justposted_text);                                
            
        }, this);
        
        this.render();        
    },
    
    render: function(){        
        _(this.collection.models).each(function(item){

            //Start update for each group            
            
        }, this);                
    }
   
});

////////////////////////////////////

var Facebook = Backbone.Model.extend({

    defaults: {
        user_id: '',
        app_id: '',
        page_id: '',
        page_name: '',
        link: '',
        picture: '',
        scope: '',
        isLiked: false,
        isAuthorized: false,
        isPageOwner: false,
        isMultipostAllowed: false
    },

    initialize: function() {
        _.bindAll(this, 'getAppLoginStatus', 'askForPermission', 'sync', 'like');
    },

    getAppLoginStatus: function() {
        console.log('Page is Liked: ' + this.get('isLiked'));
        var that = this;
        
        if (!this.get('isLiked')) {
            wjInterfaceController.hideLike();
        }
        
        FB.getLoginStatus(function(response) {
            if (response.authResponse) {
                // Need to verify facebook userId vs WJ userId here
                // (ex someone logged out and relogged in with a different fb account)
                that.set({user_id: response.authResponse.userID});
                
                // logged in and connected user, someone you know
                console.log('OAuth response received');                
                that.set({isAuthorized: true});
                
                // Get page info
                FB.api(that.get('page_id'), 'get', function(response){
                    console.log(response); 
                    that.set({name: response.name, link: response.link, picture: response.picture});                
                
                    // If page owner
                    FB.api('me/accounts', 'get', function(response){                    
                        var page = _.detect(response.data, function(pages){
                           return pages.id == that.get('page_id');
                        });

                        if (!page) {
                            return;
                        }                    
                        if (page.hasOwnProperty('access_token')) {
                            that.set({page_token: page.access_token});                       
                            that.set({isPageOwner: true});
                            console.log('Is owner of page: ' + page.name);                        
                            wjInterfaceController.userName = page.name;
                            wjInterfaceController.userImage = that.get('picture');
                            wjInterfaceController.enableMultipost();
                            console.log('User image switched to page: ' + that.get('picture'));   
                        }
                    });
                
                });
                
                // Check whether you have liked a post already
                FB.api(that.get('page_id') + '/feed', 'get', function(response){
                    //console.log(response);
                    _.each(response.data, function(data){
                        if (data.hasOwnProperty('likes')) {                                                       
                            _.each(data.likes.data, function(like){
                                if (like.id == that.get('user_id')) {
                                    wjInterfaceController.liked(data.id);                                    
                                }                                    
                            });
                        }
                    });
                });
                
            } else {
                // Not connected to app
            }
        });
    },
    
    askForPermission: function() {
        var that = this;
        FB.login(function(response){
            if (response.authResponse) {
                console.log('User has just granted permissions.')
                // CALL SERVER TO CREATE WJ ACCOUNT
                var port = window.location.port;
                if (port != '') {
                        port = ':'+port;
                }
                var base_url = window.location.protocol+'//'+window.location.hostname+port;

                var request_url = base_url + "/member/autosignup";
                
                var data = response.authResponse;
                data.pageId = that.get('page_id');
                               
                $.getJSON(request_url, data, function(res){
                    if (res.result) {
                        location.reload();
                    } else {
                        alert("WorldJumper autosignup failed!")
                    }
                });   
            } else {
                console.log("User did not authorize.");
                // Still should be able to view the WJ-Wall
            }
        }, {scope: that.get('scope')}); //manage_pages should be done by page owner only.
    },

    sync: function(trans_model, callback) {
        //Receive Translator model and post it to facebook
        var that = this;
        var publish_data = {};
        var link = this.get('link') + '?sk=app_' + this.get('app_id'); //Not sure how to get link to page tab via API...
 
        var in_lang = trans_model.get('in_lang');
        var lang_list = [in_lang];
        if (this.get('isPageOwner') && this.get('isMultipostAllowed')) {
            lang_list = translator_collection.properties.supported_langs.reverse();           
        }
 
        if (trans_model.get('type') === 'post') {
            
            publish_data.actions = {name: 'View in WorldJumper', link: link};
                        
            if (trans_model.hasImage()) {
                publish_data.picture = trans_model.getS3Image(); //wjInterfaceController.baseUrl + "/media/tmp/" + trans_model.getImageFilename();
            }            
            //Until new media controller  
            if ($("#uploader-video-url").val()) {
                publish_data.link = $("#uploader-video-url").val();
            }
            if (trans_model.getLatLong()) {
                var latlong = trans_model.getLatLong();
                publish_data.link = "https://maps.google.com/maps?q=" + latlong.latitude + ",+" + latlong.longitude;
                //http://maps.google.com/maps?q=37.771008,+-122.41175
            }
            
            //publish_data.targeting = {"locales": "6"};//{"countries":"US","regions":"6,53","locales":"6"};
            var translations = trans_model.get('translations');
                     
            _.each(lang_list, function(lang){
                publish_data.message = that.getTextFromTranslator(trans_model, lang);               
                
                if (that.get('isMultipostAllowed')) {
                    var locale = that.getTargetLocale(lang);
                    publish_data.targeting = {"locales": locale};
                    console.log('Multipost allowed for locales: ' + locale);
                }
                
                console.log('Publishing post to FB for lang: ' + lang + ' body: ' + publish_data.message); 

                if (!that.get('isPageOwner')) {
                    //For general users
                    FB.api('/' + that.get('page_id') + '/feed', 'post', publish_data, function(response) {
                        if (!response || response.error) {
                            alert('Error occured');
                        } else {
                            if (that.get('isMultipostAllowed')) {
                                translations[lang].post_id = response.id;
                            }
                            console.log('Post ID: ' + response.id);
                            if (lang === _.last(lang_list)) {
                                callback(response.id);
                            }
                        }
                    });        
                } else {
                    //For page owner
                    publish_data.access_token = that.get('page_token');
                    FB.api('me/feed', 'post', publish_data, function(response){
                        if (!response || response.error) {
                            alert('Error occured');
                        } else {
                            if (that.get('isMultipostAllowed')) {
                                translations[lang].post_id = response.id;
                            }
                            console.log('Post ID: ' + response.id + '(Posted by page owner)');
                            if (lang === _.last(lang_list)) {
                                callback(response.id);
                            }
                        }
                    });               
                }
            });
            
            trans_model.set({translations: translations});

        } else {
            //Comment   
            publish_data.message = that.getTextFromTranslator(trans_model, in_lang);
            FB.api('/' + trans_model.get('post_id') + '/comments', 'post', publish_data, function(response) {
                if (!response || response.error) {
                    alert('Error occured');
                } else {
                    callback(response.id);
                }
            });           
        }
    },
    
    getTextFromTranslator: function(trans_model, lang) {
        
        var message;

        if (lang === trans_model.get('in_lang')) {
            message = trans_model.getOriginalText() + ' (Original Language)';
        } else {
            message = trans_model.getTranslatedText(lang) + ' (Translated)';
        }
        if (lang !== 'en') {
            message += ' ' + trans_model.getTranslatedText('en') + ' (Translated)';
        }
        return message;
        
    },
    
    getTargetLocale: function(lang) {
        //http://fbdevwiki.com/wiki/Locales
        //en es pt fr sv ja zh ko id th ar
        switch (lang) {
            case 'en':
                return '6,24,51';
            case 'es':
                return '7,23';                
            case 'pt':
                return '16,31';
            case 'fr':
                return '9,44';
            case 'sv':
                return '18';
            case 'ja':
                return '11';
            case 'zh':
                return '20,21';
            case 'ko':
                return '12';
            case 'id':
                return '25';
            case 'th':
                return '35';
            case 'ar':
                return '28';            
            case 'zh_Hant':
                return '22';
            //case 'zh_cn':
            //    return '20';
            //case 'zh_hk':
            //    return '21';  
            default:
                return '';
        }
    },
    
    like: function(post_id, callback) {
        FB.api('/' + post_id + '/likes', 'post', function(response){
            if (response) {
                callback();
            }
        });
    },
    
    deletePost: function(post_id) {
        FB.api('/' + post_id, 'delete', function(response){
            if (response){
                console.log(post_id + ' deleted from facebook');
            } else {
                console.log('Could not delete post_id: ' + post_id);
            }
        })
    },
    
    haveLikedPage: function(page_id) {
        FB.api('me/likes', 'get', function(response){
           console.log(response);
           var id = _.detect(response.data, function(likes){
               return likes.id == that.get('page_id');
           });        
           if (id == page_id) {
               return true;
           } else {
               return false;
           }
        });
    },
    
    checkPermission: function() {
        //var query = FB.Data.query('select publish_stream,read_stream from permissions where uid={0}', session["uid"]);
    }
});

var facebook_client = new Facebook();

//var groupview = new GroupCollectionView();
//
////////////////////////////////////

var wjInterfaceController = {

    groupName: -1,
    groupIcon: "",
    userId: -1,
    userName: "",
    userImage: "",
    minPostId: -1,
    maxPostId: -1,
    maxCommentId: -1,
    autoRefreshDuration: 5000,
    action: 'activities',
    baseUrl: "",
    startTime: 0,
    endTime: 0,
    justPostedText: "Just posted",

    init: function(settings) {
        
        this.startTime = new Date();

        var port = window.location.port;
	if (port != '') {
		port = ':'+port;
	}       
        this.baseUrl = window.location.protocol+'//'+window.location.hostname+port;
        this.groupName = settings.groupName; //["groupName"];
        this.groupIcon = settings.groupIcon;
        this.userId = settings.userId; //json["userId"];
        this.userName = settings.userName; //json["userName"];
        this.userImage = settings.userImage;
        this.minPostId = settings.minPostId; //json["minPostId"];
        this.maxPostId = settings.maxPostId; //json["maxPostId"];
        this.maxCommentId = settings.maxCommentId; //json["maxCommentId"];
        this.languageUrl = '/' + settings.language; //json["language"];
        this.justPostedText = settings.justPostedText;
        if (settings.action) {
            this.action = settings.action;
        }
        if (this.action === "allActivities") {
            this.updateContent("allActivities");
        }
        this.autoRefresh();
        
        console.log('User image: ' + this.userImage);
    },

    autoRefresh: function () {

        globalTimer3 = setTimeout( function() {
            wjInterfaceController.updateContent(wjInterfaceController.action);
        }, wjInterfaceController.autoRefreshDuration);
    },

    pushContent: function(trans_model, resetTranslatorFunc) {
        
        // Reset autofresh timer
        clearTimeout(globalTimer3);
        
        var formField = $("#" + trans_model.get("form_name"));       
        var fieldName = trans_model.get("field_name");
        var text_in = formField.find(".text_in").val();
        var text_out = formField.find(".text_out").val();
        var formActionTarget = formField.attr("action");
        var contentData = formField.serialize();
	var requestUrl = this.baseUrl + formActionTarget;              
        
        //var translations = trans_model.get('translations');       
        //contentData += '&multiplePosts=' + encodeURI(JSON.stringify(translations));

        console.log(trans_model.get('translations'));
        console.log(contentData);
        resetTranslatorFunc();

        $.ajax({
            url: requestUrl,
            type: "POST",
            data: (contentData),
            timeout: (60 * 1000),
            beforeSend: function(){
                
                var content = {
                    user_name: wjInterfaceController.userName,
                    user_image: wjInterfaceController.userImage,
                    text_out: text_in,
                    text_in: text_out,
                    just_posted_text: wjInterfaceController.justPostedText,
                    media: []
                };
                
                if (fieldName === 'commentText_') {                                       
                    var postId = formField.find("#post_id").val();                      
                    $("#comment-template").tmpl(content).appendTo("#post-" + postId);
                  
                } else if (fieldName === 'postText_') {
                    if (formField.find("#image").val().length > 0 || formField.find("#video").val().length > 0 || formField.find("#mapLat").val().length > 0) {                       
                        content.media = true;                    
                    }
                    $("#post-template").tmpl(content).prependTo("#post-container");                    
                }
                $(".post-loading").fadeIn('fast');
                $(".post-loading").animate({
                    backgroundColor: "transparent"
                }, 'slow');
                
            },
            success: function(data) {
                wjInterfaceController.updateContent('activities');
            },
            error: function(XMLHttpRequest, textStatus){
                alert('Post failed. Error: ' + textStatus);
            },
            complete: function(){
            }
        });
    },

    updateContent: function(action) {       

        var requestUrl;

	if (action == 'activities') {
		requestUrl = this.baseUrl + this.languageUrl + '/group/activities/groupName/' + this.groupName + '?minPostId=' + this.minPostId + '&maxPostId=' + this.maxPostId + '&maxCommentId=' + this.maxCommentId;
        } else if (action == 'loadMore') {
		requestUrl = this.baseUrl + this.languageUrl + '/group/loadmore/groupName/' + this.groupName + '/minPostId/' + this.minPostId + '/maxCommentId/' + this.maxCommentId;
        } else if (action === 'allActivities') {
                if (this.minPostId === 0 && this.maxPostId === 0) {
                        requestUrl = this.baseUrl + '/member/activities/recent/10';
                } else {
                        requestUrl = this.baseUrl + '/member/activities/minPostId/' + this.minPostId + '/maxPostId/' + this.maxPostId + '/maxCommentId/' + this.maxCommentId;
                }
        }
        
        $.ajax({
            url: requestUrl,
            type: "GET",
            timeout: (60 * 1000),
            beforeSend: function(){
                //Nothing yet.
            },
            success: function(data) {
                //console.log(data);
                if (action == 'loadMore') {
                    $("#load-more-container").find(".post-loading-media").hide();
                }
                
                var updates = JSON.parse(data);
                console.log(refresh_count + ": PID+ = " + updates.maxPostId + " PID- = " + updates.minPostId + " CID+ = " + updates.maxCommentId);
                console.log(data);
                refresh_count++;

                if (updates['maxPostId'] != undefined)
                        wjInterfaceController.maxPostId = updates['maxPostId'];
                if (updates['minPostId'] != undefined)
                        wjInterfaceController.minPostId = updates['minPostId'];
                if (updates['maxCommentId'] != undefined)
                        wjInterfaceController.maxCommentId = updates['maxCommentId'];

                if(action == 'activities' || action === 'allActivities') {
                        for (var i in updates['posts']) {
                                $("#post-container").prepend(updates['posts'][i]['html']);
                                $(".post-loading").remove();
                        }

                        for (var i in updates['comments']) {
                                $("#post-" + updates['comments'][i]['post_id']).append(updates['comments'][i]['html']);
                                $(".post-loading").remove();
                        }
                } else if (action == 'loadMore') {
                        for (var i in updates['posts']) {
                                $("#post-container").append(updates['posts'][i]['html']);
                        }
                        if (updates.posts) {
                            $("#load-more").show();
                        }                        
                }                
                console.log('Action: ' + action);
                if (action !== 'loadMore') {
                    wjInterfaceController.autoRefresh();
                }
            },
            error: function(XMLHttpRequest, textStatus){
                //alert('Post failed. Error: ' + textStatus);
            },
            complete: function(){
                //$(".post-loading").remove();
            }
        });
    },
    
    loadMoreContent: function () {
        wjInterfaceController.updateContent('loadMore');
        $("#load-more").fadeOut('fast', function(){
            $("#load-more-container").append('<div class="post-loading-media"><img src="' + wjInterfaceController.baseUrl + '/images/default/i_loader.gif" /></div>');
        });
    },

	loadContent: function (url) {
        $.ajax({
            url: url,
            type: "GET",
			dataType: "html",
            timeout: (60 * 1000),
            beforeSend: function(){
				$("#content-container").append('<div class="post-loading-media"><img src="/images/default/i_loader.gif" /></div>');
            },
            success: function(data) {
				$("#content-container").prepend(data);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
            },
            complete: function(){
				$(".post-loading-media").remove();
            }
        });
	},
    
    enableTranslationEdit: function(element) {

        element.mouseover(function(){
            element.find(".feed-content-edittrans").show();
            element.addClass("feed-content-highlighted");
        });

        element.mouseout(function(){
            element.find(".feed-content-edittrans").hide();
            element.removeClass("feed-content-highlighted");
        });
    },    

    editTranslation: function (requestUri,id) {

        var target = $("#" + id + "-edittrans");
        var translation = $("#" + id + "-translation");
        //var content = $("#" + id.replace("-edittrans", ""));

        // Don't load multiple edit trans fields.
        if (target.hasClass("editTransActive")) {
            return;
        }
        target.addClass("editTransActive");
        //if (target.find("#editTranslation").hasClass("editTransActive")) {
        //    return;
        //}

        if (target.find("#editTranslation").length) {
            target.fadeIn("fast");
            return;
        }
        
        requestUri = this.baseUrl + requestUri;

        $.ajax({
            url: requestUri,
            type: "GET",
            dataType: "html",
            timeout: (60 * 1000),
            beforeSend: function(){
                //Nothing yet.
            },
            success: function(data) {
                //var updates = JSON.parse(data);
                target.append(data);
                target.fadeIn('fast');
            },
            error: function(XMLHttpRequest, textStatus){
                //alert('Translation failed. Error: ' + textStatus);
            },
            complete: function(){
                // May add scroll to effect for posts
                var sendButton = target.find(".edittrans");
                var closeButton = target.find(".button-close");
                var formField = target.find("form");
                var formActionTarget = formField.attr("action");
                formActionTarget = wjInterfaceController.baseUrl + formActionTarget;
                sendButton.click(function(){
                   var formData = formField.serialize();
                   var newText = formField.find("#inputText").val();

                   $.post(formActionTarget, formData, function(data) {

                        translation.fadeOut("fast", function(){
                            translation.html("<p class='feed-content-justtranslated'>" + newText + "</p>");
                            translation.fadeIn("fast");
                        });
                        // Clear edittrans field.
                        target.fadeOut("fast");
                        target.removeClass("editTransActive");
                        formField.find("#inputText").val("");
                   });
                });

                closeButton.click(function(){
                    target.fadeOut("fast");
                    target.removeClass("editTransActive");
                });
            }
        });

    },
    
    enableDelete: function (feedContent, target, actionUri, post_id, callback) {
        
        var deleteButton = feedContent.find(".button-delete-container");

        feedContent.mouseover(function(){
            deleteButton.show();
        });
        
        feedContent.mouseout(function(){
            deleteButton.hide();
        });             
        
        deleteButton.click(function(){          
            
            target.fadeOut("fast");
            
            
            if (!facebook_client.get('isAuthorized')) {
                $.get(actionUri);
            //$.get(url, data, callback, type)
            } else {                
                facebook_client.deletePost(post_id);
            }
            callback();
           
        });
    },
    
    like: function (post_id) {
        
        facebook_client.like(post_id, function(){
            var like = $("#post-" + post_id).find(".feed-content-like");
            like.fadeOut('fast', function(){
                like.html('You like this');
                like.fadeIn('fast');
            });           
        });        
    },
    
    liked: function (post_id) {
        $("#post-" + post_id).find(".feed-content-like").html('You like this');
    },
    
    hideLike: function() {
        $(".feed-content-like").hide();
    },
    
    enableMultipost: function() {       
        $("#post-multipost").fadeIn('fast');
        facebook_client.set({isMultipostAllowed: true})
        var check_box = $("#post-multipost").find("input");
        check_box.change(function(){
            if (check_box.attr('checked')) {
                facebook_client.set({isMultipostAllowed: true});              
            } else {
                facebook_client.set({isMultipostAllowed: false});              
            }           
        });
    },
    
    setS3Image: function(form_name) {
        
        //saveimageAction param image
        var that = this;    
        
        var image_filename = $("#" + form_name).find("#image").val();
        var image_path;
        var request_url = that.baseUrl + '/group/saveimage?image=' + image_filename;
        
        $.get(request_url, function(response){
            var json = $.parseJSON(response);
            console.log(json);
            if (json.result) {
                $("#" + form_name).find("#s3image_id").val(json.s3image_id);
                // Temp until migration to local storage
                that.s3image = json.src;
                return true;
            } else {
                return false;
            }
        })
    }    
}

if (typeof console == 'undefined' || debug_mode === false) {
    window.console = {
        log: function () {}
    };
}
