var twellow = {};

twellow.init = function() {

// clear/replace the search bar
$('#twellow-search').focus(function() {
    if ($(this).attr('value') == 'Find Twitter users anywhere!') {
        $(this).attr('value', '');
    };
});
$('#twellow-search').blur(function() {
    if ($(this).attr('value') == '' || $(this).attr('value') == ' ') {
        $(this).attr('value', 'Find Twitter users anywhere!');
    }
});

// registration stuff

$('#login_form input').focus(function() {
    $(this).attr('value', '');
})

// get the default iEntry permissions
$.ajax({
    url : '/utils/perms.php'
    ,success : function(response) {
        var reqperms = response;

        // setup FB.login() actions w/ permissions
        $('img.fbconnect').click(function(e) {
            FB.login(function(response) {
                if (response.authResponse) {
                    $.ajax({
                        url : '/utils/ientry.php'
                        ,dataType : 'twellow'
                        ,data : {
                            access_token : response.authResponse.accessToken
                        }
                        ,success : function(response) {
                            if (response) {

                            if (response.login_allowed == false) {
// TODO ID-10T message
                            } else if (response.email_deliverable == false) {
// TODO do we care that we can't send them e-mail?
                            } else if (response._id) {
                                // user already exists, so do logon stuff
                                twellow.logon();
                                $.fancybox.close();
                            } else {
                                // move this doggy along the registration trail
                                twellow.slide(3);
                            }

                            } else {
// TODO throw some error?
                            }
                        }
                        ,async : false
                    });
                }
            }, {scope: reqperms});
        });
    }
});

var T = new BirdHouse({callback_path:'www.twellow.com/utils/', popup: false});
$('img.tconnect').click(function(e) {
    var checked = $('#autotweet').attr('checked'); 
    T.logon(function() {
// TODO confirm registration worked?
        twellow.logon(checked);
        twellow.slide(4);
    }, checked);
});

twellow.reinit();

setTimeout("twellow.welcome()", 5000);

};

twellow.welcome = function() {
   // have we ever shown this person the welcome banner? if not, show it!
   if(!$.readCookie('twellow_welcome')) {
      $.setCookie('twellow_welcome', '1', { 'duration' : 1, 'path' : '/', 'domain' : 'www.twellow.com' });
      twellow.register(0);
   }
}

twellow.register = function(step) {
    this.slide(step);
    $.fancybox({
        type : 'inline'
        ,href : '#register-contain'
        ,titleShow : false
        ,margin : 0
        ,padding : 0
        ,showNavArrows : false
    });
}

twellow.slide = function(step) {
    $('.inner-register').animate({'left':step*-651+'px'});
}

twellow.logon = function(checked) {
    if (checked == undefined) {
        checked = false;
    }
    $.ajax({
        url : '/users/logon'
        ,dataType : 'twellow'
        ,data : { checked : checked }
        ,success : function(response) {
            $('#login').empty();
            $.tmpl(response.template,response.data).appendTo('#login').fadeIn();
            $('.unauthed').removeClass('unauthed').addClass('authed');
            twellow.reinit();
        }
    }); 
}

twellow.logout = function() {
    $.ajax({
        url : '/users/logout'
        ,dataType : 'twellow'
        ,success : function(response) {
            FB.logout();
            $('#login').empty();
            $.tmpl(response.template).appendTo('#login').fadeIn();
            $('.authed').removeClass('authed').addClass('unauthed');
            twellow.reinit();
        }
    });
}

twellow.reinit = function() {
    $('.authed, .unauthed').unbind('click');
    $('.unauthed').click(function() {
        twellow.register(1);
        return false;
    });
    $('.follow[data-action]').each(function(i, el) { twellow.bindFollow(el); });
    $('.following[data-action]').each(function(i, el) { twellow.bindUnfollow(el); });
}

twellow.bindFollow = function(el) {
    $(el).click(function() {
        if ($(this).hasClass('authed')) {

        $(this).html('').unbind('click');
        var loader = $('<img />').attr('src', 'http://images.ientrymail.com/twellow/2011/ajax-loader.gif').appendTo($(this));
        var screen_name = $(this).attr('data-action');
        var button = this;
        $.ajax({
            url : '/users/follow/' + screen_name
            ,dataType : 'twellow'
            ,success : function(response) {
                $(button).unbind();
                $(loader).remove();
                if (response && response.success) {
                    $(button).html('Following').removeClass('follow').addClass('following');
                    // is this matched up with a twellow relationship arrow?
                    var arrows = $(button).parent().find('.search-cat-user-arrows img');
                    if (arrows.length == 1) {
                        // it is!! so update the arrow
                        // TODO implement a sweet HTML5 animation
                        var arrow = $(arrows[0]);
                        switch (arrow.attr('rel')) {
                            case 'friend':
                                var rel = 'mutual';
                                var src = 'http://images.ientrymail.com/twellow/2011/full-arrow.png';
                                var title = 'You follow ' + response.name + ', and they follow you back!';
                                break;
                            default:
                                var rel = 'following';
                                var src = 'http://images.ientrymail.com/twellow/2011/following-arrow.png';
                                var title = 'You are following ' + response.name + ', but they are not following you.';
                                break;
                        }
                        arrow.attr({'rel':rel, 'src':src, 'title':title});
                    }
                    twellow.bindUnfollow(button);
                } else if (response && !response.success) {
                    $(button).html('Follow');
                    twellow.bindFollow(button);
                }
            }
        });

        }
    });
}
twellow.bindUnfollow = function(el) {
    $(el).hover(function() {
        $(this).removeClass('following');
        $(this).addClass('unfollow').html('Unfollow');
        $(this).unbind('click').click(function() {
            $(this).html('').unbind('click').unbind('mouseover').unbind('mouseout');
            var loader = $('<img />').attr('src', 'http://images.ientrymail.com/twellow/2011/ajax-loader.gif').appendTo($(this));
            var button = this;
            var screen_name = $(this).attr('data-action');
            $.ajax({
                url : '/users/unfollow/' + screen_name
                ,dataType : 'twellow'
                ,success : function(response) {
                    if (response && response.success) {
                        $(loader).remove();
                        $(button).html('Follow').removeClass('unfollow').removeClass('following').addClass('follow');
                        var arrows = $(button).parent().find('.search-cat-user-arrows img');
                        if (arrows.length == 1) {
                            var arrow = $(arrows[0]);
                            switch (arrow.attr('rel')) {
                                case 'mutual':
                                    var rel = 'friend';
                                    var src = 'http://images.ientrymail.com/twellow/2011/follower-arrow.png';
                                    var title = response.name + ' follows you, but you do not follow them.';
                                    break;
                                case 'following':
                                default:
                                    var rel = '';
                                    var src = 'http://images.ientrymail.com/twellow/2011/no-followers.png';
                                    var title = 'You do not follow ' + response.name + ', and they do not follow you.';
                                    break;

                            }
                            arrow.attr({'rel':rel, 'src':src, 'title':title});
                        }
                        twellow.bindFollow(button);
                    }
                }
            });
        });
    }, function() {
        $(this).removeClass('unfollow');
        $(this).addClass('following').html('Following');
    });
}

twellow.login = function() {
  var username = $('#login_email')[0].value;
  var password = $('#login_password')[0].value;
  if (username == '' || username == 'Username or Email') {
            $.gritter.add({
                title : 'Login error'
                ,text : 'Invalid username/email.'
                ,image : 'http://images.ientrymail.com/twellow/2011/error-icon.png'
            });
    $('#login_email').focus();
    return false;
  } else if (password == '' || password == 'Password') {
            $.gritter.add({
                title : 'Login error'
                ,text : 'Invalid password.'
                ,image : 'http://images.ientrymail.com/twellow/2011/error-icon.png'
            });
    $('#login_password').focus();
    return false;
  }
  $('#login_password').html('');
  $.ajax({ 
    url : '/users/login'
    ,dataType : 'json'
    ,type : 'POST'
    ,data : { 'username' : username, 'password' : password }
    ,success : function(response) {
      if (response.error) {
            $.gritter.add({
                title : 'Login error'
                ,text : response.error
                ,image : 'http://images.ientrymail.com/twellow/2011/error-icon.png'
            });
      } else {
            $.fancybox.close();
            $('#login').empty();
            $.tmpl(response.template,response.data).appendTo('#login').fadeIn();
            $('.unauthed').removeClass('unauthed').addClass('authed');
            twellow.reinit();
      }
    }
    ,async : false
  });
  return false;
}

$(document).ready(function() { twellow.init(); });

$.ajaxSetup({
    converters: {
        "* twellow": function (value) {
            try {
                var json = $.parseJSON(value);
            } catch (err) {
                // error message!!
                $.gritter.add({
                    title:'Yikes!'
                    ,text:'It appears that something went terribly wrong. Give us a second to get ourselves back in order, and please try again!'
                    ,image:'http://images.ientrymail.com/twellow/2011/error-icon.png'
                });
                return {};
            }
            if (json.message) {
                var image = 'http://images.ientrymail.com/twellow/2011/';
                switch (json.message.type) {
                    case 'error':
                        image += 'error-icon.png';
                        break;
                    case 'announcement':
                        image += 'announcement-icon.png';
                        break;
                    case 'tip':
                        image += 'tip-icon.png';
                        break;
                    case 'warning':
                        image += 'warning-icon.png';
                        break;
                    default:
                        // invalid message type, so let's get outta here
                        return json;
                        break;
                }
                $.gritter.add({
                    title : json.message.title
                    ,text : json.message.text
                    ,image : image
                }); 
                delete json.message;
            }
            return json;
        }
    }
});

