/*////////////////////////

        ODD London
        Jesson Yip

////////////////////////*/


// Variables
var slides_timer,
    carousel_delay = 7000,
    carousel_transition = 800,
    slideshow_transition = 600;

var default_email_1 = 'info',
    default_email_2 = 'oddlondon.com';


// Init
$(document).ready(function() {

    // Create map
    map_init();

    // Formatting
    $('#philosophy .slide').each(function(){
        var h = $(this).find('h1, h2, h3').first();
        h.html(h.text().replace('We are','We are<br>'));
    });

    // Accordion
    accordion();

    // Special
    slideshow();
    team();
    email();

    // Carousel
    carousel();

    // Heights
    height_match('#foot li');
    height_match('#latest_updates div.copy');
    height_match('#services p');
    //height_match_with_next('dl.transport dt');
    
    // Transport
    $('dl.transport dd').each(function(){
        var dd = $(this);
        var dt = dd.prev();
        var dd_height = dd.height();
        var dt_height = dt.height();
        if (dd_height < dt_height) dd.css({'padding-top': Math.round((dt_height - dd_height) / 2) + 'px'});
    })

    // Search
    search_toggle();

    // News trim
    news_trim();

    // Remove image titles
    $('img').removeAttr('title');

    video();

});


// Team
team = function() {

    // Team prep
    if ($('#team div.people_listing').children().length) {

        // Elements
        var team = $('#team div.people_listing'),
            person = team.children(),
            first = person.first(),
            siblings = first.siblings(),
            links = $('<div id="team_nav" class="people_listing_small carousel manual" />').appendTo('#team');


        team.height(first.height());

        person.each(function(){

            // Register heights
            var p = $(this);
            p.height(p.height());

            // Generate links
            p.find('div.frame img').clone().appendTo(links).click(team_change);

        });

        links.children(":nth-child(4n)").addClass('row_end');

        while (links.children('img').length) {
            links.children("img:lt(8)").wrapAll("<div class='slide' />");
        }

        links.children('div.slide').wrapAll('<div class="carousel_content" />');

    }

}


// Team change
team_change = function() {

    l = $(this);
    i = (l.parent().index() * 8) + l.index();
    
    var team = $('#team div.people_listing');
    var people = team.children().hide();
    var next = people.eq(i).show()

    team.animate({'height':next.css('height')}, 200);

    return false;

}


// Accordion
accordion = function() {

    list = $('dl.accordion');
    if (list.length) {
        list.find('dt').click(function(){
            var title   = $(this).toggleClass('active');
            var content = title.next().toggleClass('active').slideToggle();
            title.siblings('dt').removeClass('active');
            content.siblings('dd').slideUp();
        });
    }

}


// Map
map_init = function() {

    if ($('#map_canvas').length) {

        var center = new google.maps.LatLng(51.5237,-0.1);
        var map_options = {
            zoom: 15,
            center: center,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            panControl: false,
            scrollwheel: false
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

        var image = 'http://jessonyip.com/dev/odd/wp-content/uploads/2011/08/marker.png';
        var location = new google.maps.LatLng(51.523629,-0.100318);
        var map_marker = new google.maps.Marker({
            position: location,
            map: map,
            icon: image
        });

    }

}




// News trim
news_trim = function() {
    $('body.news.listing article').each(function(){
        var article = $(this);
        var section = article.find('section');
        var copy = section.find('> div');
        var side_height = section.next().height();
        if (section.height() > side_height) {

            // Link
            var link = $('<a href="#" class="button_link toggle"><span class="button"></span><span class="text option">Read full story</span><span class="text option hide">Collapse</span></a>').appendTo(section);

            // Calculations
            var copy_height = copy.height();
            var copy_line_height = parseInt(copy.css('line-height'));
            var copy_space = (side_height - (section.height() - copy_height));
            var copy_line_space = Math.floor(copy_space / copy_line_height);
            var copy_trimmed_height = copy_line_space * copy_line_height;
            var copy_trimmed_remainder = copy_space - copy_trimmed_height

            // Trim
            copy.css({'height' : copy_trimmed_height + 'px', 'margin-bottom' : copy_trimmed_remainder + 'px'});

            // Class
            article.addClass('trimmed');

            // Toggle
            link.click(function(){
                if (article.hasClass('trimmed')) {
                    copy.animate({'height' : copy_height + 'px', 'margin-bottom' : 0});
                } else {
                    copy.animate({'height' : copy_trimmed_height + 'px', 'margin-bottom' : copy_trimmed_remainder + 'px'});
                }
                link.find('.option').toggleClass('hide');
                article.toggleClass('trimmed');
                return false;
            });

        }
    });
}





// Slideshow
slideshow = function() {

    // Praise prep
    if ($('#praises').children().length) {

        // Elements
        var slideshow = $('#praises'),
            praise = slideshow.children(),
            first = slideshow.children().first(),//.addClass('slideshow'),
            siblings = first.siblings();

        // Slideshow layout
        slideshow_layout();

        // Unite photos & copy
        siblings.find('img').appendTo(first.children('div.frame')).hide();
        siblings.find('div.copy').appendTo(first.children('div.quote'));
        siblings.remove();
        first.children('div').addClass('slideshow');

        // Slideshow layout
        setTimeout(slideshow_layout, 50);
        setTimeout(slideshow_layout, 500); // Backup for font change


    }

}


// Slideshow layout
slideshow_layout = function() {

    // Elements
    var slideshow = $('#praises'),
        praise = slideshow.children(),
        first = slideshow.children().first();//.addClass('slideshow'),

    // Register heights
    praise.find('div.copy').each(function(){
        var copy = $(this);
        copy.height(copy.find('blockquote').height() + copy.find('cite').height() + 34 +34);
    });
    first.find('div.quote').height(first.find('div.copy').height());

}


// Carousel init
carousel = function() {

    // Element loop
    $('.carousel').each(function(){

        // Elements
        var carousel = $(this),
            slides   = carousel.find('div.slide');

        // Paginate
        if (slides.length > 1) {

            // Elements
            var content    = carousel.children('div.carousel_content').width(carousel.width() * slides.length),
                pagination = content.next();

            // Pagination create
            if (carousel.hasClass('titled')) {
                pagination = $('<div class="pagination titled"></div>').appendTo(carousel);
                slides.each(function(){
                    var title = $(this).find('div.copy').find('h1, h2, h3').first().text();
                    pagination.append('<a href="#"><span class="indicator"></span>' + title.replace('e are', 'e\'re ') + '</a>')                    
                });
                pagination.append('<div class="pointer"></div>');
            } else {
                pagination = $('<div class="pagination dotted"></div>').appendTo(carousel);
                for (i = 0; i < slides.length; i++) {
                    $('<a href="#">' + i + '</a>').appendTo(pagination);
                }
            }

            // Pagination classes
            var buttons = pagination.children(':not(.pointer)');

            buttons.first().addClass('first active');
            buttons.last().addClass('last');

            // Pagination click
            buttons.click(function(){

                // Button
                var button = $(this);
                var index  = button.index()
                button.addClass('active').siblings().removeClass('active');

                // Transition
                content.stop().animate({'margin-left' : - (index * carousel.width()) + 'px'}, carousel_transition);

                if (carousel.hasClass('titled')) {
                    pointer = carousel.find('div.pointer');
                    button_position = button.children('span.indicator').offset();
                    pagination_position = button.parent().offset();
                    pointer.stop().animate({'left' : button_position.left - pagination_position.left+ 'px'}, carousel_transition);
                }

                // Feature band colour
                if (carousel.attr('id') == 'feature') {
                    $('#band').children().stop().removeClass('next');
                    if (!$('#band').children().eq(index).hasClass('active')) {
                        $('#band').children().eq(index).hide().addClass('next').fadeIn(carousel_transition/2, function(){
                            $(this).addClass('active').removeClass('next')
                                .siblings().removeClass('active').removeClass('next');
                        });
                    }
                }

                // Remove default                
                return false;

            });

            // Autoplay
            if (!carousel.hasClass('manual').length) {
                if (!slides_timer) slides_timer = setTimeout(slides_play, carousel_delay);
                carousel.hover(function(){ carousel.addClass('hover') }, function(){ carousel.removeClass('hover') });
            }

        }

        // Fade edges
        if (carousel.hasClass('fade')) {
            carousel.append('<div class="fader fader_left" /><div class="fader fader_right" />');
        }

    });

    // Title Layout
    setTimeout(carousel_layout, 50);
    setTimeout(carousel_layout, 500); // Backup for font change

}


// Carousel layout
carousel_layout = function() {

    // Element loop
    $('div.pagination.titled').each(function(){

        // Element
        var pagination = $(this);
        var title      = pagination.find('a');

        // Spacing
        var title_widths = 0;
        title.each(function(){ 
            title_widths += $(this).outerWidth();
        })

        var spacing_width = pagination.width() - title_widths;
        title.not('.last').each(function(){ 
            $(this).css({'margin-right' : Math.floor(spacing_width / (title.length - 1)) + 'px'});
        });

    });

}


// Carousel autoplay
slides_play = function() {

    // Element loop
    $('.carousel:not(.hover, .manual)').each(function(){

        // Elements
        var carousel   = $(this),
            pagination = carousel.find('.pagination');

        // Trigger
        if (pagination.length) {
            var active = pagination.children('.active');
            if (active.index() < pagination.children('a').length - 1) active.next().click();
            else active.siblings(':first-child').click();
        }

    });

    // Element loop
    $('div.slideshow').each(function(){

        // Elements
        var slideshow = $(this),
            slides    = slideshow.children();

        if (slides.length > 1) {
            slides.first().fadeOut(slideshow_transition, function(){
                var curr = $(this);
                var next = curr.next().fadeIn(slideshow_transition);
                var parent = curr.parent();
                curr.appendTo(curr.parent());
            }).parent().animate({'height': slides.first().next().height()}, slideshow_transition * 2);
        }

    });

    // Loop
    slides_timer = setTimeout(slides_play, carousel_delay);

}


// Height match
height_match = function(elements) {
    var tallest_height = 0;
    $(elements).each(function(){
        tallest_height = Math.max($(this).height(), tallest_height);
    }).height(tallest_height);
}


// Height match with next
height_match_with_next = function(elements) {
    $(elements).each(function(){
        var first = $(this);
        var next = first.next();
        var tallest_height = Math.max(first.innerHeight(), next.innerHeight());
        first.height(tallest_height);
        next.height(tallest_height);        
    });
}


// Search
search_toggle = function() {

    // Search variables
    var search       = $('#search'),
        search_form  = $('form', search),
        search_div   = $('> div', search_form),
        search_input = $('#s', search_form),
        search_transition = 300;

    if (!$('body.search').length) {
    
        // Search focus listener
        search_input.focus(function(){
            search_div.stop().animate({'margin-left': '7px', 'margin-right': '7px', 'width': '170px'}, search_transition)
            search_form.addClass('active');
        }).blur(function(){
            if (!$.trim(search_input.val()).length) {
                search_div.stop().animate({'margin-left': '2px', 'margin-right': '2px', 'width': '1px'}, search_transition, function(){
                    search_form.removeClass('active');
                });
            }
        });
    
        // Search toggle
        search.children().click(function(){
            if (search_div.width() == 1) search_input.focus();
            else if ($(this).is('.icon') && $.trim(search_input.val()).length) search_form.submit();
            return false;
        });

    } else {

        // Search submit
        $('#search .icon').click(function(){
            if ($.trim(search_input.val()).length) search_form.submit();
        })

    }

}


// Email
email = function() {
    $('span.email_hidden').each(function() {
        var link = $(this),
            address = link.html();
        if (address.indexOf('&nbsp;‘AT’&nbsp;')) {
            address = address.split('&nbsp;‘AT’&nbsp;');
            if (address.length == 2) {
                address = $.trim(address[0]) + '@' + $.trim(address[1]);
                link.replaceWith('<a href="mailto:' + address + '">' + address + '</a>');
            }
        }
    });
}


// Video
video = function() {
    $('#video_button').click(function(){
        var button = $(this),
            video   = button.attr('data-id'),
            colour = button.attr('data-colour');
        $('<iframe src="http://player.vimeo.com/video/'+ video +'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1&amp;color=' + colour.substring(1) + '" width="693" height="390" frameborder="0"></iframe>')
            .insertBefore(button).siblings().remove();
    });
}


