jQuery(document).ready(function($) {
    
    var mouseX, windowWidth;
    
    var $head_selected = false;
    var $body_selected = false;
    var $leg_selected  = false;
    var $box_showing   = false;
    
    var $head_id = 0;
    var $body_id = 0;
    var $leg_id  = 0;
    
    var $people_items = $("#people_items_inner");
    var $people_count = $('.person', $people_items).length;
    
/*    var $scroller = $('#page-content, .coaching_block, .popup_bubble, #profile_container');
    
    if ( $scroller.length ) {
        $scroller.jScrollPane();
    }  */
    
    var $coachingRight = $(".coaching #page-right");
    var $body          = $("body");
    var $coachingBlock = $(".coaching_block");
    var $pagecontent   = $("#page-content");
    var $courseBlock   = $(".course_block");
    var $coachingBody  = $("body.coaching");
    
    var topColumn = $("#top-columns");
    
    if ( $body.length ) {
        
        $body.jScrollPane({
            autoReinitialise: true
        });
        
        var $bodyApi = $body.data('jsp');
        $bodyApi.reinitialise(); 
        
    }
    
    $("#indigenous-columns .coaching_block:eq(1)").addClass('first_coaching_block');
    
    if ( topColumn.length ) {
        
        topColumn.columnize({width: 400, height: 440, lastNeverTallest: true });
        
    }
    
    setTimeout(hideWelcome, 3000);
    
    function hideWelcome() {
        
        $("#welcome-message").fadeOut();
        
        resizeEvents();
        
    }
    
    $("#overlay").bind("click", function() {
        
        $('.popup_bubble').fadeOut();
        $(this).fadeOut();
        $(this).empty();
         
    });
    
    $("#make_character img").hover(function() {
        
        $(this).css({
            border: '3px solid #8CB630',
            padding: '20px 0'
        });
        
    }, function() {
        $(this).css({
            border: 'none',
            padding: '0'
        });
    });
    
    $("#facebook").hover(function(){
        
        var $image  = $(this).children('img');
        var $newSrc = $image.attr('src').replace('.png', '');
            $newSrc = $newSrc + '_hover.png';
            
        $image.attr('src', $newSrc);
        
    }, function() {

        var $image  = $(this).children('img');
        var $newSrc = $image.attr('src').replace('_hover', '');
            $newSrc = $newSrc;
            
        $image.attr('src', $newSrc);
        
    });
    
    $("#twitter").hover(function(){
        
        var $image  = $(this).children('img');
        var $newSrc = $image.attr('src').replace('.png', '');
            $newSrc = $newSrc + '_hover.png';
            
        $image.attr('src', $newSrc);
        
    }, function() {

        var $image  = $(this).children('img');
        var $newSrc = $image.attr('src').replace('_hover', '');
            $newSrc = $newSrc;
            
        $image.attr('src', $newSrc);
        
    });
    
    resizeEvents();
    
    $('.builder-items a').hover(function(){
        
        $(this).fadeTo("fast", 0.6);
        
    }, function() {
        
        $(this).fadeTo("fast", 1);
        
    });
    
    $("#left_side .course_content a").remove();
    
    var $indigenousPage = $('.indigenous');
    
    $people_items.wrapInner("<table cellspacing='30'><tr>");
    $("#courses_content").wrapInner("<table cellspacing='30'><tr>");
    $(".person", $people_items).wrap("<td>");
    $(".course_block").wrap("<td>");
    
    $('#coach-columns-inner').wrapInner("<table cellspacing='30'><tr>");
    $(".coaching_block").wrap("<td>");
    
    var $coachColumns = $('#coach-columns');
    
    if ( $coachColumns.length )
    {
        console.log('Has coach columns');
        
        var $pageContent  = $('#page-content');
        var $theColumns   = $('td', $coachColumns);
        
        var extraWidth = 0;
        
        $theColumns.each(function(){
            extraWidth += $(this).outerWidth(true);
        });
        
        if ( extraWidth !== 0 )
        {
            var $pageContentWidth = $pageContent.outerWidth(true);
            var $addedWidth = $pageContentWidth + extraWidth /2 - 400;
            
            $pageContent.width($addedWidth);
        }
    }
    
    
    $(".person", $people_items).click(function(){
        
        var $inner = $(this).find('.popup_bubble');
        
        $inner.clone().fadeIn().appendTo("#overlay");
        $("#overlay").fadeIn();
         
    });
    
    $(".person .person-avatar-image a").click(function(e){
        
        e.preventDefault();
        
    });
    
    $("'[placeholder]'").focus(function() {
        var input = $(this);
        if (input.val() == input.attr("'placeholder'")) {
            input.val("''");
            input.removeClass("'placeholder'");
        }
    }).blur(function() {
        var input = $(this);
        if (input.val() == "''" || input.val() == input.attr("'placeholder'")) {
            input.addClass("'placeholder'");
            input.val(input.attr("'placeholder'"));
        }
    }).blur();
    
/*    $("'[placeholder]'").parents("'form'").submit(function() {
      $(this).find("'[placeholder]'").each(function() {
        var input = $(this);
        if (input.val() == input.attr("'placeholder'")) {
          input.val("''");
        }
      })
    });*/
    
    
    
    var $radioInputs = $('input:radio'); 
    
    if ( $radioInputs.length )
    {
        $radioInputs.wrap('<div class="radio-wrapper" />');
        
        $('input:radio:checked').each(function(){
            $(this).parent().addClass('selected-radio'); 
        });
        
        $radioInputs.bind('click', function(e){
            
            e.stopPropagation();
             
        });
    }
    
    var $radioWrapper = $('.radio-wrapper');
    
    if ( $radioWrapper.length )
    {    
        $radioWrapper.bind('click', function(e) {
            
            e.stopPropagation();
            
            var $this = $(this);
            
            var $this  = $(this);
            var $child = $(this).children('input');
            
            if ( !$child.is(':checked') )
            {
                $radioWrapper.removeClass('selected-radio');
                $radioWrapper.find('input').attr('checked', false);
                
                $this.addClass('selected-radio');
                $child.attr('checked', true);
            }
            
            e.stopPropagation();
             
        });
    }
    
    var $modalBg  = $('#modal-bg');
    var $modalBox = $('.modal-box');
    
    if ( $modalBg.length )
    {
        $modalBg.bind("click", function(e) {
            
            e.stopPropagation();
            
            if ( $modalBox.length )
            {
                $modalBox.fadeOut();    
            }
            
            $(this).fadeOut();
             
        });
    }
    
    var $changeClick = $('.change-link');
    
    $('#trigger_contact').click(function(e){
        
        e.preventDefault();
        
        $modalBg.fadeIn();
        $("#contact-box").fadeIn();
        
    });
    
    if ( $changeClick.length )
    {
        $changeClick.bind("click", function(e){
            
            e.preventDefault();
        
            $modalBg.fadeIn();
            
            var $thisId = $(this).attr('id');
            
            if ( $thisId == 'change-head' )
            {
                $modalBox.fadeOut();
                $('#head-modal').fadeIn();
            }
            else if ( $thisId == 'change-body' )
            {
                $modalBox.fadeOut();
                $('#body-modal').fadeIn();
            }
            else if ( $thisId == 'change-legs' )
            {
                $modalBox.fadeOut();
                $('#leg-modal').fadeIn();
            }
             
        });
    }
    
    var $saveClick = $('.save-type');
    
    if ( $saveClick.length )
    {
        $saveClick.bind("click", function(e){
            
            e.preventDefault();
            
            // Hide all modals and the modal BG
            $modalBg.fadeOut();
            $modalBox.fadeOut();
            
            // Get which save link was clicked
            var $thisId     = $(this).attr('id');
            
            var $trueParent, $trueRel;
            
            if ( $thisId == 'save-head-type' )
            {
                $trueParent = $('.selected_head');
                $trueRel    = $trueParent.attr('rel');
                
                var $builderHeads = $('#builder-heads');
                
                 $('ul', $builderHeads).hide().removeClass('selected-head-section');
                 $('#heads-'+$trueRel, $builderHeads).fadeIn().addClass('selected-head-section');
            }
            else if ( $thisId == 'save-body-type' )
            {
                $trueParent = $('.selected_body');
                $trueRel    = $trueParent.attr('rel');
                
                var $builderBodies = $('#builder-bodies');
                
                 $('ul', $builderBodies).hide().removeClass('selected-body-section');
                 $('#body-'+$trueRel, $builderBodies).fadeIn().addClass('selected-body-section');
            }
            else if ( $thisId == 'save-leg-type' )
            {
                $trueParent = $('.selected_leg');
                $trueRel    = $trueParent.attr('rel');
                
                var $builderLegs = $('#builder-legs');
                
                 $('ul', $builderLegs).hide().removeClass('selected-leg-section');
                 $('#leg-'+$trueRel, $builderLegs).fadeIn().addClass('selected-leg-section');
            }
                       
            
             
        });
    }
    
    
    
    $('.builder-items li a').click(function(event) {
        
        var $id = $(this).attr('id');
        var $exploded = $id.split('-');
        
        var $type = $exploded[0];
        var $numb = $exploded[1];
        
        if ( $type === 'head' )
        {
            $('#head_id').val($numb);
        }
        else if ( $type === 'body' )
        {
            $('#body_id').val($numb);
        }
        else if ( $type === 'leg' )
        {
            $('#legs_id').val($numb);
        }
        
        builderUpdate();
        
        event.preventDefault();
         
    });    
    
    $(window).resize(resizeEvents);
    
    $('.validate-form').submit(function(event) {
        
        var err = '';
        
        $('input, textarea', $(this)).each(function() {
            
            if ( $.trim($(this).val()).length == 0 && $(this).hasClass('required') )
            {
                var $closest = $(this).parent().find('label').text();
                
                err += ""+$closest+" is s a required field\r\n";
            }
            
        });
        
        var $compare1 = $('.compare:eq(0)');
        var $compare2 = $('.compare:eq(1)');
        
        if ( $compare1.length && $compare2.length )
        {
            if ( $compare1.val() !== $compare2.val() )
            {
                err += "The passwords you entered do not match\r\n";
            }
        }
        
        if ( err !== '' )
        {
            alert(err);
            event.preventDefault();
        }
        
    });
    
    jQuery('.head').click(function(e) {
        
        if ( $box_showing )
        {
            hidePopup();
        }
        
        var $this = jQuery(this);
        var $id   = $this.attr('rel');
        jQuery('.selected_head').removeClass('selected_head');
        $(this).addClass('selected_head');
        
        greyThemOut('heads');
        
        $head_id = $id;
        $head_selected = true;
        
        namePopup();
        
    });
    
    jQuery('.body').click(function(e) {
        
        if ( $box_showing )
        {
            hidePopup();
        }
        
        var $this = jQuery(this);
        var $id   = $this.attr('rel');
        jQuery('.selected_body').removeClass('selected_body');
        $(this).addClass('selected_body');
        
        greyThemOut('bodies');
        
        $body_id = $id;
        $body_selected = true;
        
        namePopup();
        
    });
    
    jQuery('.leg').click(function(e) {
        
        if ( $box_showing )
        {
            hidePopup();
        }
        
        var $this = jQuery(this);
        var $id   = $this.attr('rel');
        jQuery('.selected_leg').removeClass('selected_leg');
        $(this).addClass('selected_leg');
        
        greyThemOut('legs');
        
        $leg_id = $id;
        $leg_selected = true;
        
        namePopup();
        
    });
    
    $("#filter a").click(function(e) {
        
        var filterId      = $(this).attr('id');
        var parentLi      = $(this).parent();
        
        var $emerging     = $(".person-emerging", $people_items);
        var $growing      = $(".person-growing", $people_items);
        var $established  = $(".person-established", $people_items);
        var $changing     = $(".person-changing", $people_items);
        
        if ( $people_items.length )
        {
            if ( filterId == "filter-all" )
            {
                remove_select_state();
                parentLi.addClass('selected');
                $('.person', $people_items).fadeIn();
                $bodyApi.scrollTo(0, 0, true);
            }
            
            if ( filterId == "filter-emerging" && $emerging.length >= 1 )
            {
                remove_select_state();
                parentLi.addClass('selected');
                hide_people();
                $(".person-emerging").fadeIn();
            }
            
            if ( filterId == "filter-growing" && $growing.length >= 1 )
            {
                remove_select_state();
                parentLi.addClass('selected');
                hide_people();
                $(".person-growing").fadeIn();
            }
            
            if ( filterId == "filter-established" && $established.length >= 1 )
            {
                remove_select_state();
                parentLi.addClass('selected');
                hide_people();
                $(".person-established").fadeIn();
            }
            
            if ( filterId == "filter-changing" && $changing.length >= 1 )
            {
                remove_select_state();
                parentLi.addClass('selected');
                hide_people();
                $(".person-changing").fadeIn();
            }
        }
        
        e.preventDefault();
    });
    
    $('#name_form').submit(function(e){
        
        $('#head_id').val($head_id);
        $('#body_id').val($body_id);
        $('#leg_id').val($leg_id);
        
        if ( $("#name").val() !== "Name" )
        {         
            $.post(base_url + '/session.php', $(this).serialize(), function(data) {
                if ( data == 'success' )
                {
                    window.location.reload();
                }
            });
        }
        else
        {
            alert('Enter your name');
        }
        
        e.preventDefault();
        
    });
    
    $('#name').focus(function(e){
        
        if ( $(this).val() == "Name" )
        {
            $(this).val('');   
        }
         
    });
    
    $('#name').blur(function(e){
        
        if ( $(this).val() == "" )
        {
            $(this).val('Name');   
        }
         
    });
    
    $('#email_address').click(function(){
        
        if ($(this).val() == "Email")
        {
            $(this).val('');
        }
         
    });
    
    $('#email_address').blur(function() {
        
        if ($(this).val().trim() == "") {
            $(this).val("Email");
        }
    });
    
    $('#subscribe_form').submit(function(e){
        
        $.post($(this).attr('action'), { email_address: $('#email_address').val() },
            function(data) {
            
            if ( data == "Success" ) {
                alert('You have successfully subscribed');
            } else {
                alert('There was an error subscribing, please refresh and try again.');
            }
            
        });
        
        e.preventDefault();
        
    });
    
    var $upcomingCourse = $(".upcoming_course");
    
    if ( $upcomingCourse.length ) {
        
        $upcomingCourse.hover(function(e) {
            
            $(this).addClass('upcoming_hover');
             
        }, function() {
            
            $(this).removeClass('upcoming_hover');
            
        });
    
        $upcomingCourse.click(function(e) {
            
            var href = $(this).attr('course-href');
            
            window.location.href = href;
            
        });
       
    }
    
/*    if ( $coachingBlock.length ) {
        
        $coachingBlock.jScrollPane();
        
        var $coachingApi = $coachingBlock.data('jsp');
        
        // 5 seconds should be more than enough time for the site to load (I hope)
        setTimeout(function() {
            $coachingApi.reinitialise();
        }, 5000);
        
    }  */
    
/*    if ( $pagecontent.length ) {
        $pagecontent.jScrollPane();
    } */
    
    if ( $courseBlock.length ) {
        
        $courseBlock.jScrollPane();
        
        var $courseApi = $courseBlock.data('jsp');
        
        // 5 seconds should be more than enough time for the site to load (I hope)
        setTimeout(function() {
            $courseApi.reinitialise();
        }, 5000);
    }
    
    function edgiesForward() {
    
        if ( $body.length ) {
            
            var api = $body.data('jsp');
            
            api.scrollBy(-120); 
            
        }        
       
    }
    
    function edgiesBackwards() {
        
        if ( $body.length ) {
            
            var api = $body.data('jsp');
            
            api.scrollBy(120); 
            
        }
        
    }
    
    jQuery('.forward').click(function(e) {
        
        edgiesForward();
    
        e.preventDefault();
        
    });
    
    jQuery('.backward').click(function(e) {
        
        edgiesBackwards();
        
        e.preventDefault();
        
    });
    
    function greyThemOut(what)
    {
        if ( what == 'heads' )
        {
            jQuery('.head').not('.selected_head').fadeTo('fast', 0.2);
            jQuery('.selected_head').fadeTo('fast', 1);
        }
        else if ( what == 'bodies' )
        {
            jQuery('.body').not('.selected_body').fadeTo('fast', 0.2);
            jQuery('.selected_body').fadeTo('fast', 1);
        }
        else if ( what == 'legs' )
        {
            jQuery('.leg').not('.selected_leg').fadeTo('fast', 0.2);
            jQuery('.selected_leg').fadeTo('fast', 1);
        }        
    }
    
    function builderUpdate()
    {
        var hhead_id = jQuery('#head_id').val();
        var bbody_id = jQuery('#body_id').val();
        var llegs_id = jQuery('#legs_id').val();
        
        var ajax_head = jQuery('#ajax-head');
        var ajax_body = jQuery('#ajax-body');
        var ajax_legs = jQuery('#ajax-legs');
        
        if ( hhead_id.length && hhead_id !== 0 )
        {
            ajax_head.find('img').remove();
            ajax_head.append('<img src="'+theme_url+'img/builder/heads/'+hhead_id+'.png" />');
        }
        
        if ( bbody_id.length && bbody_id !== 0 )
        {
            ajax_body.find('img').remove();
            ajax_body.append('<img src="'+theme_url+'img/builder/bodies/'+bbody_id+'.png" />');
        }
        
        if ( llegs_id.length && llegs_id !== 0 )
        {
            ajax_legs.find('img').remove();
            ajax_legs.append('<img src="'+theme_url+'img/builder/legs/'+llegs_id+'.png" />');
        }
    }
    
    function namePopup()
    {
        if ( $head_selected && $body_selected && $leg_selected )
        {
            $box_showing = true;
            $('#name_popup').fadeIn();
        }
        else
        {
            $box_showing = false;
            $('#name_popup').fadeOut();
        }
    }
    
    function hidePopup()
    {
        $box_showing = false;
        $('#name_popup').fadeOut();
    }
    
    function hide_people()
    {
        $('.person', $people_items).fadeOut();
    }
    
    function remove_select_state()
    {
        $("#filter li").removeClass('selected');
    }
    
    function resizeEvents()
    {
        var $body          = $("body");
        var windowHeight   = jQuery(window).height();
        var courseBlock    = jQuery('.course_block');
        var upcomingCourse = jQuery('#upcoming_courses .upcoming_course');
        var whiteWrapping  = jQuery('#white-wrapping');
        
        if ( $body.length ) {
            
            var $bodyApi = $body.data('jsp');
            $bodyApi.reinitialise(); 
            
        }
        
        windowWidth    = jQuery(window).width();
        
        var factoredHeight = 0;
        
        if ( courseBlock.length && !$coachingBody.length )
        {
            if ( windowHeight < 600 ) {
                factoredHeight = windowHeight - 150;    
            } else {
                factoredHeight = windowHeight - 200;
            }
            
            courseBlock.height(factoredHeight);
            
            courseBlock.jScrollPane();
            
            var $courseApi = courseBlock.data('jsp');
            $courseApi.reinitialise();

        }
        
        if ( upcomingCourse.length ) {
            
            if ( windowHeight < 700 ) {
                
                if ( whiteWrapping.length ) {
                    
                    whiteWrapping.hide();
                    
                }
                
                upcomingCourse.eq(1).hide();
                
            } else {
                
                if ( whiteWrapping.length ) {
                    
                    whiteWrapping.show();
                    
                }
                
                upcomingCourse.eq(1).show();
                
            }
            
        }        
        
    }
    

//	jQuery('#cycle').cycle({
//		fx: 'fade'
//	});

//	jQuery('figure.gallery-item a').attr('rel','gallery');
//	jQuery('figure.gallery-item a[rel="gallery"]').fancybox();

});

