var IFollow = {
    init: function() {
        IFollow.bindButtons();
    },
    unBindButtons: function() {
        $('.a-info').unbind().click(function() {
            return false;
        });
    },
    bindButtons: function() {
	$('a.follow-btn').click(function(){
		var befriend = $(this).attr("rel");
		$("#indi-"+befriend).show();
		$(".result-" ).html("");
		$.post("/follow", {who: befriend}, function(result){
			//console.log( $("#result-"+befriend ).get(), "#result-"+befriend );

			$("#indi-"+befriend).hide();
			if (result.redirect){
				//$("#result-"+befriend ).html(result.redirect);
				document.location.href = result.redirect;
			}
			else if (result.error)
			{
				$("#result-"+befriend ).html(result.error);
			}
			else
			{

				$("#result-"+befriend ).html("ok!");
			}
		}, "json");
	});

        $('.a-info').click(function() {
            IFollow.unBindButtons();
            $('.more-info:not(#info-' + this.id + ')').hide('fast');
            $('#info-' + this.id).toggle('fast', IFollow.bindButtons);
            return false;
        });

        $('.autocomplete').click(function() {
            var id = $(this).siblings('div').attr('id');
            $('.autocomplete').each(function() {
                if ($(this).siblings('div').attr('id') != id) {
                    $(this).siblings('div').hide();
                    $(this).siblings('div').html('');
                }
            });
        });

        $('.autocomplete').keyup(function(e) {
            if (/*e.keyCode != 32 && */ e.keyCode != 8
                && (e.keyCode < 65 || e.keyCode > 90)) {
                return;
            }
            var value = this.value;
            if (value.length < 2) {
                return;
            }

            strict_type = '';

            if ($(this).hasClass('search-only-tags')) {
                strict_type = 'Tags';
            }

            if ($(this).hasClass('search-only-cities')) {
                strict_type = 'Locations';
            }

            var date = new Date();
            var time = date.getSeconds().toString() + date.getMilliseconds().toString();
            IFollow.lastAutoComplete = time;
            setTimeout('IFollow.autoComplete(\'' + this.id + '\', \'' + value + '\', \'' + time + '\', \'' + strict_type + '\')', 150);
        });

        $('.autocomplete').keydown(function(e) {
		/*
            if (this.id != 'tag-1' && this.id != 'big-ass-search' && e.keyCode == 32) {
                return false;
            }
	    */

            switch (e.keyCode) {
                case 9:
                    var li = $(this).siblings('.auto_complete').find('ul li');
                        //console.log (li.text(), li.length);
                    if (li.length == 0) {
                        return;
                    }

                    if (li.length == 1) {
                        this.value = li.children('a').html();
                        $(this).siblings('div').hide();
                        return;
                    }

                    IFollow.autoCompleteScroll(this, true);
                    return false;
                    break;
                case 8:
                case 27: //listen for escape key - added by Jamie 8/16/09
                    $(this).siblings('div').hide();
                    break;
                case 40:
                    IFollow.autoCompleteScroll(this, true);
                    return false;
                    break;
                case 38:
                    IFollow.autoCompleteScroll(this, false);
                    return false;
                    break;
                case 13:
                    if ($('#big-ass-search').val() == '') {
                        return false;
                        break;
                    } else {
                        $(this).siblings('div').children('ul').children('li').each(function() {
                            if ($(this).hasClass('selected')) {
                                IFollow.autoCompleteSelect($(this).children('a'));
                                return;
                            }
                        });

                        if (this.id == 'big-ass-search') {
                            IFollow.autoCompleteSelect(this);
                        } else {
                            var el = $(this).parent('div').siblings('div').get(this.id.charAt(4) - 1);
                            $(el).children('input').focus();
                        }

                        $(this).siblings('div').hide();
                        return false;
                        break;
                    }

            }

        });

        $('#go-big-ass-search').click(function(){
			var bas = $('#big-ass-search');
			if ((bas.hasClass('search-text')) || (bas.val() == '')) {
				bas.val('').removeClass('search-text').focus();
				return false;
			} else {
				IFollow.autoCompleteSelect(document.getElementById('big-ass-search'));
				return false;
			}
			
			
        });

    },
    autoComplete: function(id, value, time, strict_type) {
        if (time != IFollow.lastAutoComplete) {
            return false;
        }

        var el = $('#' + id).siblings('div');
        if ($('#' + id).val().length < 1) {
            el.hide();
            el.html('');
            return;
        }

        if (value != $('#' + id).val()) {
            return;
        }

        var type = 0;
        if (id == 'tag-1') {
            type = 1;
        } else if (id == 'big-ass-search') {
            type = '';
        }

        var url = '/autocomplete.json?term=' + value + '&type=' + type + '&strict_type=' + strict_type;
        $.ajax({
            type: 'GET',
            url:  url,
            dataType: 'JSON',
            success: function(json) {
                json = eval(json);
                if (json.length < 1) {
                    el.hide();
                    return;
                }

                var ul = $('<ul>');
                $.each(json, function(i, value) {
                    var li = $('<li><a href="#" class=' + value.type + ' onclick="IFollow.autoCompleteSelect(this); return false;">' +(value.type==3 ? "@" : "")+ value.name + '</a> ' +( value.users ? '('+ value.users + ')' : '')+'</li>');
                    ul.append(li);
                });

                $(el).html('<ul>' + ul.html() + '</ul>');
                $(el).show();
            }
        });
    },
    autoCompleteSelect: function(el) {
        if (el != null && undefined != el.keyCode) {
            el = this;
        }

        if (IFollow.redirecting)
            return false;

        var type = $(el).attr('class');

        if (type == 1) {
            type = 'city';
        } else if (type==3) {
            type = 'profile';
        } else{
            type = 'twitter';
        }

        if (el.id == 'big-ass-search') {
            window.location = '/'+type+'/' + el.value ;//+ (type!="profile" ? '?decode=utf8' : '');
            IFollow.redirecting = true;
            return false;
        }

        var input = $(el).closest('div').siblings('input');
        input.val($(el).text());

        if (input.attr('id') == 'big-ass-search') {

//            var location = '/' + type + '/' + input.val().replace(/[^A-Za-z0-9_]+/g, '_').toLowerCase();
            var location = '/' + type + '/' + encodeURIComponent(input.val().replace(/@/, "").toLowerCase());// + (type!="profile" ? '?decode=utf8' : '');//'?decode=utf8';
            window.location = location;

            IFollow.redirecting = true;
        } else {
            $('.auto_complete').hide();
            $('.auto_complete').html('');
        }

//	console.log(fillTweet);
	if (fillTweet!==undefined)
		fillTweet();

        return false;
    },
    autoCompleteScroll: function(el, down) {
        var li = $(el).siblings('.auto_complete').find('ul li');
        if (li.hasClass('selected') == false) {
            li.eq(0).addClass('selected');
            return;
        }

        li.each(function() {
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                if (down) {
                    $(this).next().addClass('selected');
                } else {
                    $(this).prev().addClass('selected');
                }

                return false;
            }
        });


    }
};

$(document).ready(function() {
    IFollow.init();

    $('.advsearch .b-btn-signup span').click(function(){
        $this = $(this);
        $form = $this.closest('form');
        $form.find('.form_submit').val('true');

        $tag = $form.find('.search-only-tags');
        if ($tag.hasClass('search-text')) {
            $tag.val('');
            $tag.removeClass('search-text');
        }

        $city = $form.find('.search-only-cities');
        if ($city.hasClass('search-text')) {
            $city.val('');
            $city.removeClass('search-text');
        }

        if ($tag.val() == '' && $city.val() == '') {

        } else {
            $form.submit();
        }
        
    });

/*
    var welcomed = $.cookie('welcomed');
    if (welcomed == null || welcomed == 0) {
        $('#welcome').show();
        $('#welcome-window').show();
    }

    $('.close-window').click(function() {
        $('#welcome').hide();
        $('#welcome-window').hide();
        return false;
    });

    $('#welcome-window > a').click(function() {
        $.cookie('welcomed', 1, { expires: 999 });
    });
*/

});

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }





