// TG Activity
// mf2hd
//

function comment_show(elem) {
   var el = $(elem).parent().next('.comment_box');
   el.toggle();
   el.find('.new_comment_text').focus();
   return false;
}

function comments_show(link) {
    
    var el = $(link);
    var url = el.attr('href');
    
    var box = el.parent().next('.comment_box');
    var list = box.find('.comments_list');
    
    el.prev().hide();
    el.hide();
    list.html('<img src="/images/loading.gif">');
    
    $.get(
        url,
        {},
        function(res) {
            list.html(res);
            box.show();
        },
        'html'
    );
    
   return false;
}


function comment_submit(sub) {
    
    sub = $(sub);
    sub.hide();
    
    dsub = sub.parent().find('a.ui-state-disabled');
    dsub.show();
    
    var form = sub.closest('form');
    
    var text = form.find('.new_comment_text');
    text.attr('readonly', true);
    
    if (text.val().length < 1) {
        showMessage('Comment is empty.');
        return false;
    }
        
    //sub.attr('disabled', true);
    $(form).ajaxSubmit({
        dataType: 'json',
        success: function (responseText, statusText){            
            if (!responseText.code) {
                showError(responseText.message);    
            } else {
                text.val('');
                form.find('.comments_list').append(responseText.html);
                form.find('.activity_comment:last').show(300);
            }
            text.attr('readonly', false);
            dsub.hide();
            sub.show();
        }
    });
}
   
function comment_delete(link) {
    
    var el = $(link);
    var url = el.attr('href');
    var comment = el.closest('div.activity_comment');
    
    el.hide();
    
    $.get(
        url,
        {},
        function(res) {
            el.hide();
        
            if (!res.code) {
            showError(res.message);
            } else {
            comment.hide(300);
            setTimeout(function (){
                comment.remove();
            }, 350);
            }
        },
        'json'
    );
}
   
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});		
	}
		  
	$.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
	}
	
	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").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').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").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",
                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').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').click(function() {
                $('#mb_photo').hide();
                $('#mb_link').hide();
                
                self.linkTab.hide();

                self.shareButton.hide();
                self.shareButtonDisabled.show();
                
                self.activeTab = 'photo';
                //$('#text').val('');
                $('#userfile').val('');
                self.photoTab.show();
            });

            $('#mb_link').click(function() {
                $('#mb_photo').hide();
                $('#mb_link').hide();
                self.photoTab.hide(); 
              
                self.shareButton.hide();
                self.shareButtonDisabled.show();

                self.activeTab = 'link';
                //$('#text').val('');
                $('#linkurl').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);
