// TG Activity
// mf2hd
//

   
function activity_delete(link) {
    
    var el = $(link);
    var url = el.attr('href');
    var activity = el.closest('div.row');
    
    el.hide();
    
    $.get(
        url,
        {},
        function(res) {
            el.hide();
        
            if (!res.code) {
                showError(res.message);
            } else {
                activity.hide(300);
                setTimeout(function (){
                    activity.remove();
                }, 350);
            }
        },
        'json'
    );
}
    
(function($) {
	function debugmsg(msg) {	
		 //$('#debug').append('<p>'+msg+'</p>').animate({scrollTop:10000});		
         //console.log(msg);
	}
		  
	$.fn.tgActivity = function(options) {		
		return this.each(function() { tgActivity(this, options); });		
	}	
	
	var tgActivity = function(elem,options) {
		
		if (elem.tgActivityObject) {
            return elem.tgActivityObject;
        } else {
            return new tgActivity.fn.init(elem, options);
        }
	}
	
	var defaultOptions = {
		min_text_chars : 2,
        max_text_chars : 340,
        getUrlImages : 1
	}
	
	tgActivity.fn = tgActivity.prototype = {
		tgActivity: '0.1.0',
        
		init: function(elem,options) {
            debugmsg('Initializing tgActivity version '+this.tgActivity);
			
			var opts = this.opts = $.extend({}, defaultOptions, options);	
            
            var self = this;
            
			elem.tgActivityObject = this;
            
			this.container = $(elem);
            this.form = $('form.new_activity', this.container); //form
            
            this.activeTab = '';
            
            this.photoTab = $('#act_photo', this.container);
            this.linkTab = $('#act_link', this.container);
            this.mediaButtons = $("#mediabtns", this.container);
            this.shareButton = $('#myactivity', this.container);
            this.shareButtonDisabled = $('#myactivity_disabled', this.container);
            
            this.photoTab.hide();
            this.linkTab.hide();
                                    
            //this.form.validate();
            this.form.ajaxForm({
                dataType: 'json',
                success: function (responseText, statusText){
                    
                    self.shareButtonDisabled.hide();
                    self.shareButton.show();
                    
                    $(".loading", self.container).hide();
                    
                    if (!responseText.code) {
                        if (self.activeTab == 'photo') self.photoTab.show();
                        if (self.activeTab == 'link') self.linkTab.show();

                        showError(responseText.message);    
                                                
                    } else {
                        self.activeTab = ''; 
                        
                        $('#text').val('');
                        
                        //clear photo
                        self.photoTab.hide(); 
                        $('#userfile').val('');
                        
                        //clear link
                        $("#linkurl").val('');
                        $("#v2").html('');
                        $("#v1").show();
                        self.linkTab.hide(); 
                        
                        self.mediaButtons.show(200);
                        
                        $('#mb_photo').show();
                        $('#mb_link').show();

                        self.shareButtonDisabled.hide();
                        self.shareButton.show();                
                        
                        //reload act tab
                        $('#activities_holder .no_activity').remove();
                        $('#activities_holder').prepend(responseText.activity);
                        //$('#activities_holder div:first').show(300);
                    }
                },
                beforeSubmit: function (formData, jqForm, options) {
                    if (self.activeTab == '') {

                        var length = $('#text').val().length;
                        
                        if (length < self.opts.min_text_chars) {
                            showError('Status text must be at least ' + self.opts.min_text_chars + ' characters long');
                            return false;
                        }
                        if (length > self.opts.max_text_chars) {
                            showError('Status text should be no more than ' + self.opts.max_text_chars + ' characters long. It is '+length+' characters now.');
                            return false;
                        }
                    } else if (self.activeTab == 'photo') {
                        var fn = $('#userfile').val();
                        
                        var re_text = /\.jpg|\.jpeg|\.png|\.gif|\.bmp/i;
                
                        if (fn.search(re_text) == -1) {
                            showError("File should be either jpg, gif or jpeg");
                            return false;
                        }
                    } else if (self.activeTab == 'link') {
                        postpone = false;
                        t = $("[name='title-editable']");
                        if (t.size() > 0) {
                            //title for link is edited
                            v = t.val();
                            $('#title').val(v);
                            postpone = true;
                        }
                        
                        t = $("[name='desc-editable']");
                        if (t.size() > 0) {
                            //desc for link is edited
                            v = t.val();
                            $('#desc').val(v);
                            postpone = true;
                        }
                        
                        //postpone submit
                        if (postpone) {
                            setTimeout(function (){self.form.submit()}, 200);
                            return false;
                        }
                    }
                    
                    self.shareButtonDisabled.show();
                    self.shareButton.hide();
                    
                    self.linkTab.hide();
                    self.photoTab.hide();
                    
                    $(".loading", self.container).show();
                }
            });
                        
            //
            /*
            $('#text', this.container).bind('input paste', function(e){ 
                
                var el = $(this);
                setTimeout(function() {
                    var text = $(el).val();
                    var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
                    
                    if (regexp.test(text)) {
                        $(el).val('');
                        
                        $("#mb_link").click();
                        $("#linkurl").val(text);
                        
                        setTimeout(function() {
                            //showMessage($("#linkurl").val());
                            $("#rungetlinkparts").click();
                        }, 1000);
                    }
                }, 500);

            });
            */
            
            
            $(elem).tgFromUrl({
                getpartsUrl : "/profile/getlinkparts",
                getImages : self.opts.getUrlImages,
                btnPost : self.shareButton,
                btnPostDisabled : self.shareButtonDisabled,
                callbackPartsGet : function (el){
                    if ($('input[name="hlinkurl"]').size() > 0) {
                        self.shareButtonDisabled.hide();
                        self.shareButton.show();                
                    }
                }
            });
            
            //add link
            /*
            $("#rungetlinkparts", this.container).click(function(){
                $("#v1").hide();
                $("#v2").html('<img src="/images/loading.gif">');
                $.get("/profile/getlinkparts", {url:$("#linkurl").val()}, function(data){ 
                    $("#v2").html(data); 
                    
                    self.shareButtonDisabled.hide();
                    self.shareButton.show();
                    
                    $('#v2 .title-editable').editable(function(value, settings) {
                        $('#v2 #title').val(value);
                        return value;
                    }, 
                    {
                        type      : 'textarea',
                        cancel    : 'Cancel',
                        submit    : 'Save',
                        onblur     : 'submit',
                        indicator : '<img src="/images/loading.gif">',
                        tooltip   : 'Click to edit...',
                        name      : 'content'
                    });
                    
                    $('#v2 .description-editable').editable(function(value, settings) {
                        $('#v2 #desc').val(value);
                        return value;
                    }, 
                    {
                        type      : 'textarea',
                        cancel    : 'Cancel',
                        submit    : 'Save',
                        onblur     : 'submit',
                        indicator : '<img src="/images/loading.gif">',
                        tooltip   : 'Click to edit...',
                        name      : 'content',
                        height    : '200px'
                    });                    
            });
            });
            */
            //end add link 
                
            $('.close', this.photoTab).click(function () {               
                $('#userfile').val('');
                
                self.photoTab.hide(); 
                self.activeTab = ''; 
                
                $('#mb_photo').show();
                $('#mb_link').show();
                
                self.shareButtonDisabled.hide();
                self.shareButton.show();                
            });
            
            $('.close', this.linkTab).click(function () {
                
                $("#v2").html('');
                $("#v1").show();
                $("#linkurl").val('');
                
                self.linkTab.hide(); 
                self.activeTab = ''; 
                
                $('#mb_photo').show();
                $('#mb_link').show();

                self.shareButtonDisabled.hide();
                self.shareButton.show();                
            });
            
            
            $('#userfile', this.container).change(function() {
                var fn = $(this).val()
                
                var re_text = /\.jpg|\.jpeg|\.png|\.gif|\.bmp/i;
                
                if (fn.search(re_text) == -1) {
                    showError("File should be either jpg or gif or jpeg");
                    return false;
                }
                
                self.shareButtonDisabled.hide();
                self.shareButton.show();                 
            });
            
            
            $('#mb_photo', this.container).click(function() {
                $('#mb_photo', self.container).hide();
                $('#mb_link', self.container).hide();
                
                self.linkTab.hide();

                self.shareButton.hide();
                self.shareButtonDisabled.show();
                
                self.activeTab = 'photo';
                //$('#text').val('');
                $('#userfile', self.container).val('');
                self.photoTab.show();
            });

            $('#mb_link', this.container).click(function() {
                $('#mb_photo', self.container).hide();
                $('#mb_link', self.container).hide();
                self.photoTab.hide(); 
              
                self.shareButton.hide();
                self.shareButtonDisabled.show();

                self.activeTab = 'link';
                //$('#text').val('');
                $('#linkurl', self.container).val('');
                self.linkTab.show();
            });

            $('.moreact').click(function () {
                
                var dt = $(this).attr('timestamp');
                url = $(this).attr('href')+'/dt/'+dt;
                             
                $('#activities_holder').append('<p id="loading-more"><br /><br /><img src="/images/loading.gif"></p>');
        
                $.get(url, {}, function(res) {
                        $('#loading-more').remove();   
                        $('#activities_holder').append(res);                             
                    },
                    'html'
                );
                
                return false;
            });
            
		}        
	}
	
	tgActivity.fn.init.prototype = tgActivity.fn;
	
})(jQuery);

