(function ($) {
    // This can be used to check if an element exists without
    // having to use .length all the time.
    $.fn.exists = function () {
        return $(this).length > 0;
    };
})(jQuery);

$(document).ready(function () {

    anchor_scroll();

    $('a.anchor-link').click(function (e) {
        anchor_scroll($(this).attr('anchor'));
    });

    $('.thumbnail').css({ 'opacity' : '0' });

    if ($('body').hasClass('home')) {
        Cufon.replace('.slide-text', { textShadow: '2px 2px #CCC' });
        slideSwitch(2000, 4000);
        setInterval( "slideSwitch(2000, 4000)", 5000 );
    }

    if ($('body').hasClass('projects')) { randomize_images(20, 50, $('ul.thumbnails'), $('.thumbnail')); }

    if ($('body').hasClass('project')) { randomize_images(20, 50, $('ul.images'), $('.image')); }

    if ($('#scroll-top').exists()) { scroll_top(100); }

    $('#navigation li').mouseover(function(){
        $(this).addClass('hover');
    });

    $('#navigation li').mouseout(function(){
        $(this).removeClass('hover');
    });

    if ($('#contact-form').exists()) { contact_form(); }
});

function contact_form() {

    $('#contact-form input[type=text]').focus(function() {
        $(this).removeClass('error');
    });

    $('#contact-form textarea').focus(function() {
        $(this).removeClass('error');
    });

    $('#contact-form').submit(function(e){
        e.preventDefault();

        var error = false;
        var email = $('#sender-email');
        var subject = $('#sender-subject');
        var message = $('#sender-message');

        if(email.val().length == 0 || email.val().indexOf('@') == '-1'){
            var error = true;
            email.addClass('error');
        }else{
            email.removeClass('error');
        }
        if(subject.val().length == 0){
            var error = true;
            subject.addClass('error');
        }else{
            subject.removeClass('error');
        }
        if(message.val().length == 0){
            var error = true;
            message.addClass('error');
        }else{
            message.removeClass('error');
        }

        if(error == false){
            $('#sender-submit').attr({'disabled' : 'true', 'value' : 'Sending...' });
            $.post("contact.php", $("#contact-form").serialize(),function(result){
                if(result == 'sent'){
                     $('#cf_submit_p').remove();
                    $('#mail_success').fadeIn(500);
                }else{
                    $('#mail_fail').fadeIn(500);
                    $('#sender_submit').removeAttr('disabled').attr('value', 'Send The Message');
                }
            });
        }
    });
}

function slideSwitch(text_interval, image_interval) {
    var $active = $('#slideshow li.active');

    $active.animate({
        opacity : "0"
    });

    if ( $active.length == 0 ) $active = $('#slideshow li:last');

    //console.log($active_text);

    var $next =  $active.next().length ? $active.next() : $('#slideshow li:first');

    $active.addClass('last-active');

    $next.css({ opacity : 0.0 })
         .addClass('active')
         .animate({ opacity : 1.0 }, {
             duration : image_interval,
             easing : 'easeOutQuart',
             complete : function() {
                 $active.removeClass('active last-active');
             }
         });

    if ($active.hasClass('trigger')) {
        var $text = $('#slideshow-text');
        var $active_text = $('div.slide-text.active', $text);

        $active_text.animate({
            left : "-100%",
            opacity : "0"
        }, {
            duration : text_interval,
            easing : 'easeOutQuart'
        });
        if ( $active_text.length == 0 ) $active_text = $('#slideshow-text div.slide-text:last');
        var $next_text = $active_text.next().length ? $active_text.next() : $('#slideshow-text div.slide-text:first');
        $active_text.addClass('last-active');

        $next_text
             .addClass('active')
             .animate({ left : "0%", opacity : "1" }, {
                 duration : text_interval,
                 easing : 'easeOutQuart',
                 complete : function() {
                     $active_text.removeClass('active last-active');
                 }
             }, {
                 duration : text_interval,
                 easing : 'easeOutQuart'
            });

    }
}

function anchor_scroll(anchor) {
    var elem_loc = 0;
    if (anchor) {
        elem_loc = $('#' + anchor).offset().top - 120;
    } else {
        if(window.location.hash) {
            elem_loc = $(window.location.hash).offset().top - 120;
        }
    }

    $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();
    });

    $('html, body').animate({ scrollTop : elem_loc }, 'slow');
}

function scroll_top(from_top) {
    var scroll = $('#scroll-top');
    $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > from_top) {
            scroll.fadeIn();
        } else {
            scroll.fadeOut();
        }
    });

    $('#scroll-top a').click(function (event) {
        event.preventDefault();
        $('html, body').animate({ scrollTop : 0 }, 'slow');
    });
}

function randomize_images(min_t, max_t, ul_elem, li_elem) {
    var thumbnails = ul_elem;
    var thumbnail = li_elem;
    var array = [];
    var ptr = 0;
    var max = 20;
    var counter = 0;

    thumbnail.each(function () {
        array[ptr] = $(this);
        ptr++;
    });

    function animate_image() {
        var item = pick_random_thumbnail(ptr);
        var $elem = array[item];

        var random_delay = _random(min_t, max_t);

        $elem.animate({ opacity: '1' }, {
            duration : random_delay,
            easing : "easeInQuart",
            complete : function () {
                    if (ptr > 0 && counter < max) { animate_image();
                }
            }
        });
        array.splice(item, 1);

        --ptr;
        counter++;
    }

    animate_image();

}

function pick_random_thumbnail(max) {
    var random_no = Math.floor(Math.random() * max);
    return random_no;
}

function _random(from, to){
    return Math.floor(Math.random() * (to - from + 1) + from);
}

