$.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
}

var TwitterTop = {
    updateTweet: true,
    
    updateStatusText: function(keyCode)
    {
        if (keyCode == 32) {
            return false;
        }
        
        if (this.updateTweet == false) {
            return;
        }

        var tweet = 'Hozzáadtam magam a TwitterTophoz (twittertop.hu) a következő kategóriákban:';
        $('input.tag').each(function() {
            if (this.value.length > 0 ) {
                tweet = tweet + ' #' + this.value;
            }
        });

        $('#status_text').text(tweet);
        updateCounter();    
    }    
}

function reply_to(in_reply_to_status_id, in_reply_to)
{
    $('#status-twitty:hidden').slideDown();
    var status_text = $('#status_text').val();
    $('#in_reply_to_status_id').val(in_reply_to_status_id);
    $('#in_reply_to').val(in_reply_to);
    $('#status_text').val('@' + in_reply_to + ' ' + status_text);
    $('#status_text').focus();
    $('#status_text').setCursorPosition($('#status_text').val().length);
    setCharCount('#content #status_text');  
}

function retweet_meme(url, title)
{
    $('#status-twitty:hidden').slideDown();
    var status_text = $('#status_text').val();
    $('#in_reply_to_status_id').val('');
    $('#in_reply_to').val('');
    $('#status_text').val(status_text + ' ' + title + ' ' + url);
    $('#status_text').focus();
    $('#status_text').setCursorPosition($('#status_text').val().length);
    setCharCount('#content #status_text');  
}

function retweet(status_id)
{
    $.ajax({
	    url: '/index/get-status?status_id=' + status_id,
	    type: 'GET',
	    dataType: 'json',
		cache: false,
	    timeout: 20000,
	    error: function(){
	        alert('Ooopsz, hiba történt! Próbáld újra!')
	    },
	    success: function(status){
            $('#status-twitty:hidden').slideDown();
            $('#in_reply_to_status_id').val('');
            $('#in_reply_to').val('');            
            $('#status_text').val(' RT @' + status.user_screen_name + ' ' + status.text);
            $('#status_text').focus();
            $('#status_text').setCursorPosition(0);
            setCharCount('#content #status_text');  
	    }
	});   
}

function hug_reply_to(panel, in_reply_to_status_id, in_reply_to)
{
    $('#' + panel + ' .reply-box').fadeIn();
    var status_text = $('#' + panel + ' #status_text').val();
    $('#' + panel + ' #in_reply_to_status_id').val(in_reply_to_status_id);
    $('#' + panel + ' #in_reply_to').val(in_reply_to);
    $('#' + panel + ' #status_text').val('@' + in_reply_to + ' ' + status_text);
    $('#' + panel + ' #status_text').focus();
    $('#' + panel + ' #status_text').setCursorPosition($('#' + panel + ' #status_text').val().length);
    setCharCount('#' + panel + ' #status_text');
}

function delete_scheduled(status_id)
{
    $.ajax({
	    url: '/scheduled/delete?status_id=' + status_id,
	    type: 'GET',
	    dataType: 'json',
		cache: false,
	    timeout: 20000,
	    error: function(){
	        alert('Ooopsz, hiba történt! Próbáld újra!')
	    },
	    success: function(is_deleted){
	        if (is_deleted) {
	            $('#status_' + status_id).fadeOut('normal');
	        }
	    }
	});   
}

function submit_form(element_id, question)
{
	var question = (question == null) ? 0 : question;
	var cont = false;
	if (question == 0) { cont = true; } else { cont = confirm(question); }
	if ((form = $(element_id).parents("form")) && (cont)) {
		if (form.onsubmit) { 
			if (form.onsubmit() == false) {
				return false;
			}
		}
		form.submit();
		return false;
	}
}

function memberHover()
{
    $(".member_list li:not('.status_item')")
        .bind('mouseover', function(event){$(this).addClass('active')})
        .bind('mouseout', function(event){$(this).removeClass('active')});
}

function updateCounter()
{
    $('#counter').text(140 - $('#status_text').text().length);
}

function slideDown()
{
    $('.expandable').slideDown('fast');
    $('#expand-all').hide();
    $('#compact-all').show();
}

function slideUp()
{
    $('.expandable').slideUp('fast', function() {
        $('#footer').css({'float': 'right'});
        $('#expand-all').show();
        $('#compact-all').hide();        
        $('#footer').css({'float': 'left'});
    });
}

function follow(id, screen_name, follow)
{
    if (follow == undefined) unfollow = false;
    $('#member_' + screen_name + ' > div.member div.name a.follow').hide();
    $('#member_' + screen_name + ' > div.member div.name img.indicator').show();
    var url = '/add/follow/screen_name/' + id;
    if (!follow) {
        url = '/add/unfollow/screen_name/' + id;   
    }
    $.ajax({
	    url: url,
	    type: 'GET',
	    dataType: 'json',
		cache: false,
	    timeout: 20000,
	    error: function(){
	        alert('Ooopsz, hiba történt! Próbáld újra!')
	    },
	    success: function(is_follow){
	        $('#member_' + screen_name + ' > div.member div.name img.indicator').hide();
	        if (!is_follow) {
                $('#member_' + screen_name + ' > div.member div.name a.follow').show();
            }
	    }
	});
}

function flag(status_id)
{
    $('#flag_status_' + status_id + ' img').attr('src', '/images/indicator.gif');
    var url = '/index/flag?status_id=' + status_id;
    $.ajax({
	    url: url,
	    type: 'GET',
	    dataType: 'json',
		cache: false,
	    timeout: 20000,
	    error: function(){
	        alert('Ooopsz, hiba történt! Próbáld újra!')
	    },
	    success: function(status){
	        if (status.id != status_id) {
                $('#flag_status_' + status_id + ' img').attr('src', '/images/icon_star.png');
            } else {
                $('#flag_status_' + status_id + ' img').hide();
            }
	    }
	});
}

function search(term)
{
    if (term.length > 0) {
        var location = '/search/' + term;
        window.location = location;
    }
}

function hideInfo(name, cookiename)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 365);    
    document.cookie = cookiename + '=1;expires=' + exdate.toGMTString() + ';path=/';
    $('.' + name).fadeOut();
}

function mailTo()
{
	var first = 'ma';
	var second = 'il';
	var third = 'to:';
	var address = 'gang';
	var domain = 'twittertop';
	var ext = 'hu'; 
	document.write('<a href="');
	document.write(first+second+third);
	document.write(address);
	document.write('&#64;');
	document.write(domain);
	document.write('.');
	document.write(ext);  
	document.write('">'); 
	document.write('Emailben is</a>');
}

function doStatusUpdate(timeline)
{
    switch (timeline) {
        case 'friends':
            var url = '/timeline/friends?format=html&lastid=' + getLastStatusId();
            break;
        default:
            var url = '/timeline?format=html&lastid=' + getLastStatusId();
            break;
    }
    $.ajax({
	    url: url,
	    type: 'GET',
	    dataType: 'html',
		cache: false,
	    timeout: 3000,
	    error: function(){
	    },
	    success: function(html) {
	        if (html.length) {
                $('#status_list').html(html);
                $('li.status_item:hidden').slideDown();
            }
	    }
	});
	t = setTimeout("doStatusUpdate('" + timeline + "')", 10000);
}

function getLastStatusId()
{
    lastStatusId = $('li.status_item:first').attr('id');
	reg = /status_(\d+)/i;
    return lastStatusId.match(reg)[1];
}

function requestNewHug()
{
    clearTimeout(hugTimeout);
    $('#hugs-widget a#random-refresh img').attr('src', '/images/indicator.gif');
    $('#hugs-widget a#random-refresh img').css({
        'width': '20px',
        'height': '20px',
        'margin': '14px 0 0 14px'
    });    
    var url = '/index/newhug?format=html';
    $.ajax({
	    url: url,
	    type: 'GET',
	    dataType: 'html',
		cache: false,
	    timeout: 3000,
	    error: function() {
	    },
	    success: function(html){
            $('#hugs_content').replaceWith(html);
	    }
	});
	hugTimeout = setTimeout('requestNewHug()', 120000);
}

function requestNewQuestion()
{
    clearTimeout(questionTimeout);
    $('#question-widget a#random-refresh img').attr('src', '/images/indicator.gif');
    $('#question-widget a#random-refresh img').css({
        'width': '20px',
        'height': '20px',
        'margin': '14px 0 0 14px'
    });    
    var url = '/index/newquestion?format=html';
    $.ajax({
	    url: url,
	    type: 'GET',
	    dataType: 'html',
		cache: false,
	    timeout: 3000,
	    error: function() {
	    },
	    success: function(html){
            $('#question_content').replaceWith(html);
	    }
	});
	questionTimeout = setTimeout('requestNewQuestion()', 120000);
}

function setSubmitState(submitObj, is_disabled)
{
    submitObj.attr('disabled', is_disabled);
    if (is_disabled) {
        submitObj.addClass('disabled');    
    } else {
        submitObj.removeClass('disabled');
    }
}

function setCharCount(statusText, enableUpdate)
{
    try {
        var charcount = 140 - $(statusText).val().length;
        var counterObj = $(statusText).parents('form').find('#counter:first');
        var submitObj = $(statusText).parents('form').find('#update-submit:first');
        counterObj.text(charcount);
        if (statusUpdate && charcount == 140) {
            setSubmitState(submitObj, true);
        } else if (charcount < 0) {
            setSubmitState(submitObj, true);
            counterObj.attr('class', 'warn');
        } else if (charcount < 10) {
            setSubmitState(submitObj, false);
            counterObj.attr('class', 'warn');
        } else if (charcount < 20) {
            setSubmitState(submitObj, false);
            counterObj.attr('class', 'info');
        } else {
            setSubmitState(submitObj, false);
            counterObj.attr('class', '');
        }
    } catch (err) {}
}

function bindCounter(statusText)
{
    $(statusText).keyup(function(e) {
        TwitterTop.updateTweet = false; 
        setCharCount(statusText);
    });    
}