$(document).ready(function() {

    var offsets = [0, 660, 1345, 2110, 2820];
    var hashs = ['philosophy', 'partners', 'about', 'wwd', 'contact'];
    var baloonTop = $(".baloon").css('marginTop');

    // Address Handlers
    $('a[href^=#][href!=#]').click(function() {
        $.address.value($(this).attr('href').replace(/^#/, ''));
        return false;
    })

    $.address.change(function(event) {
        if (event.value == '/')
        {
            event.value = '/about';
        }
        var index = hashs.length;
        for (i = 0; i < index; i++) {
            if (event.value == '/' + hashs[i]) {
                targetOffset = offsets[i];
                index = i;
                break;
            }
        }

        $('html,body').animate({
            'scrollTop': targetOffset + 'px'
        },
        "slow");
    })

    // Get Twitter UpDates and include on site
    $.getJSON('http://twitter.com/status/user_timeline/criaideias.json?count=3&callback=?',
    function(data) {
        $('#loadingT').remove();
        $.each(data,
        function(index, item) {
            $('#tweetSpace').append('<blockquote class="tweet">' + item.text.linkify() + '<em>' + relative_time(item.created_at) + '</em></blockquote>');
        });
    });

    // Format Tweets
    String.prototype.linkify = function() {
        return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/,
        function(m) {
            return m.link(m);
        });
    };

    function relative_time(time_value) {
        var values = time_value.split(" ");
        time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
        var parsed_date = Date.parse(time_value);
        var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
        var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
        delta = delta + (relative_to.getTimezoneOffset() * 60);

        var r = '';
        if (delta < 60) {
            r = 'a minute ago';
        } else if (delta < 120) {
            r = 'couple of minutes ago';
        } else if (delta < (45 * 60)) {
            r = (parseInt(delta / 60)).toString() + ' minutes ago';
        } else if (delta < (90 * 60)) {
            r = 'an hour ago';
        } else if (delta < (24 * 60 * 60)) {
            r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
        } else if (delta < (48 * 60 * 60)) {
            r = '1 day ago';
        } else {
            r = (parseInt(delta / 86400)).toString() + ' days ago';
        }
        return r;
    };

    // Menu animation
    $('#nav>li a').hover(
    function(e) {
        $this = $(this);
        $this.stop().animate({
            paddingTop: '35px'
        },
        {
            queue: false,
            duration: 200
        });
    },
    function() {
        $this = $(this);
        $this.animate({
            paddingTop: '7px'
        },
        {
            queue: false,
            duration: 300
        });
    }
    );

    // Baloons Hover Function
    function baloonUp(baloon) {
        baloon.animate({
            "margin-top": "-=7"
        },
        {
            queue: false,
            duration: 100
        });
        $(".contentBaloon").addClass("scrollY");
        baloon.mouseleave(function() {
            baloonDown(baloon)
        });
    };

    function baloonDown(baloon) {
        baloon.animate({
            "margin-top": baloonTop
        },
        {
            queue: false,
            duration: 100
        });
        $(".contentBaloon").removeClass("scrollY");
        baloon.unbind('mouseleave');

    };

    $(".baloon").mouseenter(
    function() {
        baloonUp($(this))
    }
    );

    // Accordeon
    $("#accordion").tabs("#accordion div.accordionContent", {
        tabs: 'h3',
        effect: 'horizontal'
    });

    // Elastic Form
    $('textarea').elastic();

    // Inlined Label on Form
    function checkForm(input) {
        (input.val() == "") ? input.prev("label.inlined").removeClass("has-text") : input.prev("label.inlined").addClass("has-text");
    };

    $(".inlined").click(function() {
        $(this).next(".input-text").focus();
    });

    $(".input-text").each(function(type) {

        $(this).focus(function() {
            $(this).prev("label.inlined").addClass("focus");
            $(this).addClass("onFocus");
        });

        $(this).keyup(function() {
            checkForm($(this));
        });

        $(this).blur(function() {
            checkForm($(this));
            $(this).prev("label.inlined").removeClass("focus");
            $(this).removeClass("onFocus");
        });
    });

    var input = $(".input-text");
    checkForm(input);

    // Form Valdation
    $('#submit').click(function() {
        var $textarea = $('.input-text');
        var text = $textarea.val();
        if (text != '') {
            var dataString = 'message=' + text;
            $.ajax({
                type: "POST",
                url: "process.php",
                data: dataString,
                success: function() {
                    $('.input-text').val('');
                    var input = $textarea;
                    checkForm(input);
                    $textarea.trigger('live');
                    $('#form').slideUp('slow');
                    $('#contactForm').append("<div id='sucess'></div>");
                    $('#sucess').html("<p><strong>E-mail enviado com sucesso!</strong><a href='#' id='formAgain' class='button'>Mandar outro?</a></p>")
                    .hide().delay(300)
                    .fadeIn();
                    $('#formAgain').click(function() {
                        $('#sucess').fadeOut().remove();
                        $('#form').slideDown('slow');
                        return false;
                    });
                }
            });
        }
        else {
            $('#contactForm').append("<div class='error'></div>");
            $('.error').html("<span>Voc&ecirc; deve digitar alguma mensagem</span>")
            .hide()
            .fadeIn('fast', function() {
                $textarea.focus()})
				.delay(2000).fadeOut('slow',
            function() {
                $(this).remove()
            })
        }
        return false;
    });

});

