var loader_opts = {
        lines: 12,
        length: 6,
        width: 2,
        radius: 8,
        color: '#999999',
        speed: 1.2,
        trail: 100,
        shadow: false
    },
    loader_timer,
    ieversion = 100;
    
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
    ieversion = Number(RegExp.$1);
}

function showLoader(selector) {
    var target = $(selector),
        wrapper = $('<div class="loader"><div class="inner"></div></div>'),
        inner = $('.inner', wrapper);
    
    target.append(wrapper);
    inner.spin(loader_opts);
    
    clearTimeout(loader_timer);
    loader_timer = setTimeout(function() {
        wrapper.css({'opacity':'1'}); 
    }, 300);
}

function hideLoader(selector) {
    var target = $(selector),
        wrapper = $('.loader', target),
        inner = $('.inner', wrapper);
        
    wrapper.css({'opacity':'0'});
    
    clearTimeout(loader_timer);
    loader_timer = setTimeout(function() {
        wrapper.spin();
        wrapper.remove();
    }, 200);
}

// IE friendly clone function
function cloneObject(obj)
{
    var type = obj.tagName,
        classes = obj.attr('class'),
        html = obj.html(),
        new_el = document.createElement(type),
        new_obj = $(new_el);
    
    new_obj.addClass(classes);
    new_obj.html(html);
    return new_obj;
}

function mapInit()
{
    var map = $('.map:eq(0)'),
        blips = $('.blip', map),
        details = $('.locations', map),
        transition = 200,
        offset = "-204px",
        animating = false;
    
    $('.location-item', details).css({'right':offset,'opacity':'0'});
    
    blips.click(function() {
        var t = $(this);
        if (animating || t.hasClass('active')) {return false}
        animating = true;
        var location_id = t.attr('id'),
            location_details_id = location_id + "_details",
            location_details_obj = $('#'+location_details_id),
            current_active_clip = blips.filter('.active'),
            current_active_details = $('.active', details);
        
        blips.removeClass('active');
        t.addClass('active');
        
        function swapLocation() {
            if (current_active_details.length)
            {
                current_active_details.removeClass('active');
                current_active_details.hide();
            }
            location_details_obj.show().addClass('ff');
            location_details_obj.animate({'right':'0','opacity':'1'}, transition, function() {
                location_details_obj.addClass('active').removeClass('ff');
                animating = false;
            });
        }
        
        if (current_active_details.length)
        {
            current_active_details.addClass('ff').animate({'right':offset,'opacity':'0'}, transition, function() {
                current_active_details.removeClass('ff');
                swapLocation();
            });
        }
        else
        {
            swapLocation();
        }
    });    
}

function registrationFormInit()
{
    var form = $('.registration-form:eq(0)');
   
    function update_renderer(option_box, value) {

        option_box.find('input').val(value);
        option_box.parent('.gutter').find('.count').text(value);

        if (value == 0 && option_box.hasClass('active'))
        {
            option_box.removeClass('active');
            option_box.parents('.gutter').children('.option-selected-active').removeClass('option-selected-active').addClass('option-selected');
        }
        else if (value != 0 && option_box.hasClass('active') == false)
        {
            option_box.addClass('active');
            option_box.parents('.gutter').children('.option-selected').removeClass('option-selected').addClass('option-selected-active');
            
        }
    };
 
    function optionButtons() {
        var option_set = $('.option-set:eq(0)'),
            options = $('.option', option_set),
            option_selectors = $('.option-selected', option_set);
        
        options.click(function() {
            var t = $(this),
                count_box;

            //First, we check if it's already active
            if (t.hasClass('active'))
            {
                return false;
            }
            update_renderer($(this), 1);
        });

        option_selectors.children('.increment').click(function() {

            var t = $(this),
                option_box = t.parents('.gutter').children('.option'),
                count = t.parents('.option-selected-active').children('.count'),
                value_input = option_box.find('input'),
                new_value = parseInt(value_input.val() || 0) + 1;

            update_renderer(option_box, new_value);
        });

        option_selectors.children('.decrement').click(function() {

            var t = $(this),
                option_box = t.parents('.gutter').children('.option'),
                count = t.parents('.option-selected-active').children('.count'),
                value_input = option_box.find('input'),
                new_value = parseInt(value_input.val() || 0) - 1;

            if (new_value < 0)
                new_value = 0;

            update_renderer(option_box, new_value);
        });

        /* Prepopulate everything */
        options.each(function(index, option) {
            option = $(option);
            var value = option.find('input').val();
            update_renderer(option, value);
        });
    }
    
    optionButtons();
}

function homeMasonry()
{
    var grid = $('.grid:eq(0)');
    
    function mqtest() {
        if (Modernizr.mq('only all and (max-width: 767px)')) {
            grid.isotope({
                itemSelector: '.grid-box',
                filter: ':not(.spacer-box)',
                masonry: {
                    columnWidth: grid.width()
                }
            });
        }
        else if (Modernizr.mq('only all and (min-width: 768px)') || !Modernizr.mq()) {
            grid.isotope({
                itemSelector: '.grid-box',
                filter: '',
                masonry: {
                    columnWidth: 192
                }
            });
        }
    }
    
    mqtest();
    
    $(window).smartresize(function() {
        mqtest();
    });
}

function replace_urls_with_as(text, target)
{
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, '<a href="$1"'+(target ? ' target="'+target+'"' : '')+'>$1</a>'); 
}

function loadTweets() {
    $('.twitter-feed').each(function(i, twitter_feed){
        twitter_feed = $(twitter_feed);
        var twitter_account = twitter_feed.attr('data-twitter-account'),
            twitter_url = "http://twitter.com/" + twitter_account,
            text_wrapper = $('.text-wrapper:eq(0)', twitter_feed),
            limit = twitter_feed.attr('data-tweet-limit');

        showLoader(twitter_feed);

        $.getJSON('http://twitter.com/status/user_timeline/' + twitter_account + '.json?count=' + limit + '&callback=?', function(data) {       
            $.each(data, function(index, tweet) {
                var tweet_el = $('<div class="tweet"/>'),
                    tweet_text_el = $('<p />'),
                    tweet_date_el = $('<p />'),
                    tweet_a_el = $('<a target="_blank" />');

                tweet_text_el.html(replace_urls_with_as(tweet.text, '_blank'));
                tweet_a_el.text(tweet.created_at.substr(0, tweet.created_at.lastIndexOf(":")));
                tweet_a_el.attr('href', twitter_url + "/status/" + tweet.id_str);

                tweet_date_el.append(tweet_a_el);
                tweet_el.append(tweet_text_el);
                tweet_el.append(tweet_date_el);
                text_wrapper.append(tweet_el);
            });
            hideLoader(twitter_feed);
        });
    });
}

function newsFilter()
{    
    var grid = $('.grid:eq(0)'),
        filters = $('.news-wall .filter'),
        grid_items = $('.grid-box'),
        selector = '',
        no_results_el = $('<p class="grid-box no-results">There are no news items within this category.</p>');
    
    function doMasonry(filter) {
        if (filter != "" && !$(filter).length)
        {
            filter = '.no-results';
        }
    
        grid.isotope({
            itemSelector: '.grid-box',
            filter: filter
        });
    }
        
    function getSelector()
    {
        var active_filters = $('.active', filters),
            active_filters_obj = {};
            
        selector = '';
        
        // Extend into one object
        active_filters.each(function() {
            var t = $(this),
                t_filter_obj = $.parseJSON(t.data('filter').replace(/'/g,'"'));
                
            active_filters_obj = $.extend(active_filters_obj, t_filter_obj);
        });
        
        $.each(active_filters_obj, function(name, value) {
            if (value!='*')
            {
                var this_filter = '[' + name + '=' + '"' + value + '"]';
                selector += this_filter;
            }
        });
        return(selector);
    }
    
    $('li', filters).click(function() {
        var t = $(this),
            p = t.parent();
            
        if (t.hasClass('active')) { return false; }
        
        $('.active', p).removeClass('active');
        t.addClass('active');
        doMasonry(getSelector());
    });
    
    grid.append(no_results_el);
    
    doMasonry(getSelector());    
}

function init_slideshow(selector, slides)
{
    var interval_ms = 7000,
        interval_id = false,
        index = 0,
        slide_element = $(selector);
    
    function preload_image(data)
    {
        var img = $('<img />');
        img.attr('src', data.file_name);
    }
    
    function next_slide()
    {
        index = (index + 1) % slides.length;
        
        var slide = slides[index];
        
        change_slide(slide);
    }
    
    function change_slide(data)
    {
        //change the image
        var img = $('img', slide_element).first(),
            new_img = $('<img />');
        new_img.load(function(){
            new_img.css({
                left: new_img.width()*-0.5,
                top: new_img.height()*-0.5
            });
        });
        new_img.attr({
            src: data.file_name,
            alt: data.alt
        });
        new_img.css({
            opacity: 0
        });
        img.stop(true, false);
        img.parent().append(new_img);
        img.animate({
            opacity: 0
        }, {
            duration: 1000,
            complete: function()
            {
                $('img', slide_element).not(new_img).remove();
                img.remove();
            }
        });
        new_img.animate({
            opacity: 1
        }, 1000);
        
        //change text
        var content_box = $('.box-content', slide_element),
            header = $('.header-heading', content_box),
            text_selectors = [{
                property: 'title',
                selector: '.header-heading'
            },{
                property: 'subtitle',
                selector: '.box-heading'
            },{
                property: 'text',
                selector: '.box-text'
            }];
        
        content_box.stop(true, false);
        header.stop(true, false);
        
        header.animate({
            opacity: 0
        }, {
            duration: 300,
            complete: function()
            {
                content_box.animate({
                    bottom: -content_box.height()
                }, {
                    duration: 500,
                    complete: function()
                    {
                        var has_content = false,
                            has_inner_content = false,
                            show_title = false;
                        $.each(text_selectors, function(i, v){
                            var text_element = $(v.selector, content_box);
                            if (data[v.property])
                            {
                                text_element.html(data[v.property]);
                                if (v.property == 'title')
                                {
                                    show_title = true;
                                }
                                else
                                {
                                    has_inner_content = true;
                                }
                                has_content = true;
                            }
                            else
                            {
                                text_element.html('');
                            }
                        });

                        //change link
                        var link = $('.follow a', content_box);
                        if (data.link)
                        {
                            link.attr('href', data.link).show();
                            has_inner_content = true;
                            has_content = true;
                        }
                        else
                        {
                            link.hide();
                        }
                        
                        if (has_inner_content)
                        {
                            $('.box-inner-wrapper', content_box).show();
                        }
                        else
                        {
                            $('.box-inner-wrapper', content_box).hide();
                        }

                        if (has_content)
                        {
                            content_box.show();
                        }
                        else
                        {
                            content_box.hide();
                        }

                        content_box.animate({
                            bottom: 0
                        }, {
                            duration: 500,
                            complete: function()
                            {
                                if (show_title)
                                {
                                    header.animate({
                                        opacity: 1
                                    }, 300);
                                }
                            }
                        });
                    }
                });
            }
        });
    }
    
    function stop()
    {
        if (interval_id !== false)
        {
            clearInterval(interval_id);
            interval_id = false;
        }
    }
    
    function start()
    {
        //set the slider
        interval_id = setInterval(function(){
            next_slide();
        }, interval_ms);
    }
    
    //preload all images
    $.each(slides, function(i, slide){
        preload_image(slide);
    });
    
    //start sliding
    start();
    
    //stop when you mouse over
    slide_element.hover(function(){
        //in
        stop();
    }, function(){
        //out
        start();
    });
}

function reveal_secret_emails() {
    
    $(".secret-email").each(function() {
        var container = $(this);
        
        // empty <a> inside the container to allow setting other attributes on it, e.g. classes/ids etc
        var tag = container.find("a");
        var email_address = container.attr("data-email").replace(email_secret_string, "@");
        var subject_line = '';
        if(container.attr("data-subject")) {
            subject_line = "?subject=" + escape(container.attr("data-subject"));
        }
        tag.attr("href", "mailto:" + escape(email_address) + subject_line)
           .attr("title", "Email " + email_address)
           .html(email_address);
    });
}

$(document).ready(function() {

    $('html').removeClass('no-js').addClass('js');

	// Page switch
	var main = $('.main').filter(':eq(0)'),
	    body = $('body'),
	    template = main.attr('id');
	    
	switch(template)
	{
		case "home":
		    homeMasonry();
		    loadTweets();
			break;
		case "contact":
		    mapInit();
	        break;
	    case "ctm_registration":
	        registrationFormInit();
	        break;
	    case "archive":
	        /*$('.archive-nav:eq(0)').tabSet({
	            card_selector : '.archive-year',
	            card_heading_selector : '.year-heading'
	        });*/
	        newsFilter();	        
	        break;
	}
	
	$('.box-heading').each(function() {
	    var t;
	    $('a', this).length ? t = $('a', this) : t = $(this);	    
	    var text_nodes = t.text().split(" ");
	    
	    t.empty();
	    
	    $.each(text_nodes, function(index, value) {
	        var text_node_span = $('<span />');
	        
	        text_node_span.html(value);
	        t.append(text_node_span);
	    });
	});
	
	// Form inputs
	$('.field').each(function() {
	    var t = $(this),
	        parent = t.parent(),
	        label = $('label', t),
    	    input = $('input, textarea', t);    	    
	    input.focus(function() {
	        t.addClass('focus');
	    }).blur(function() {
	        t.removeClass('focus');
	        var opacity_val;	        
	        input.val() != "" ? opacity_val = "0" : opacity_val = "";
	        if (parent.hasClass('search')) {
	            label.css({'opacity':opacity_val});
	        }
	    });
	});
	
	$('.mobile-menu').change(function(){
	    var href = $(this).val();
	    if (href != "") {
	        window.location = href;
	    }        
	});
	
	// Webkit text refresh to avoid occasional font-face quirk
	body.css({'-webkit-font-smoothing':'antialiased'});
	setTimeout(function() {
	    body.css({'-webkit-font-smoothing':''});
	}, 1000);
    
    reveal_secret_emails();

});

