﻿// Navigation Controller
var navController = {
    current: Object,
    headNav: Object,
    navLink: Object,
    clicked: Boolean,
    init: function () {
        this.current = $('#header ul').attr('class');
        this.headNav = $('#header ul');
        this.navLink = $('#header ul li a, #logo')
        this.clicked = false;
        this.run();
    },
    run: function () {
        this.navLink.hover(function () {
            navController.headNav.removeClass().addClass($(this).attr('rel'));
        }, function () {
            if (!navController.clicked) {
                navController.headNav.removeClass().addClass(navController.current);
            }
        });

        this.navLink.click(function () {
            navController.clicked = true;
            navController.headNav.removeClass().addClass($(this).attr('rel'));
        });

        $('#logo').hover(
            function () {
                $('#nav_home').addClass('hover');
            },
            function () {
                $('#nav_home').removeClass('hover');
            });
    }
}


// Color Changer
var color = {
    links       : function(newColor){
        $('#content a').stop().animate({ color : "#" + newColor }, 'slow');    
    },
    chameleon   : function(newColor){
        $('.chameleon').stop().animate({ backgroundColor : "#" + newColor }, 'slow');    
    },
    background  : function(newColor){
        $('#hero, #footer').stop().animate({ backgroundColor : "#" + newColor }, 'slow');
    },
    all  : function(newColor){
        $('.chameleon').stop().animate({ backgroundColor : "#" + newColor }, 'slow');
        $('#content a:not(a.chameleon)').stop().animate({ color : "#" + newColor }, 'slow'); 
    }
}


// external anchor controller
var anchorController = {
    init : function(){
       
        $('a[rel*=external]').live('click',function(){
            window.open(this.href);
            _gaq.push(['_trackEvent', 'Lightburn', 'External Link Clicked', $(this).attr('href')]);
            return false;
        });
    }
}


// Case Study Scroller
var caseStudy = {
    studies     : Object,
    prev        : Object,
    next        : Object,
    current     : Number,
    init        : function(){
        this.studies = $('div.study');
        this.prev = $('#prevStudy');
        this.next = $('#nextStudy');
        this.current = 1;
        this.run();
    },
    run         : function(){            
        this.prev.click(function(e){            
            $('div.study.on').fadeOut('normal', function(){
            
                $(this).removeClass('on');
                
                // Go to previous slide
                if (caseStudy.current == 1){
                    caseStudy.studies.eq(caseStudy.studies.length - 1).fadeIn('normal').addClass('on');
                    caseStudy.current = caseStudy.studies.length;
                }else{
                    caseStudy.current --;
                    caseStudy.studies.eq(caseStudy.current - 1).fadeIn('normal').addClass('on');
                }
            });        
            e.preventDefault();
        });
        
        this.next.click(function(e){
            $('div.study.on').fadeOut('normal', function(){
            
                $(this).removeClass('on');            
        
                // Go to next slide
                if (caseStudy.current == caseStudy.studies.length){
                    caseStudy.studies.eq(0).fadeIn('normal').addClass('on');
                    caseStudy.current = 1;
                }else{
                    caseStudy.current ++;
                    caseStudy.studies.eq(caseStudy.current - 1 ).fadeIn('normal').addClass('on');
                }                               
            });
            e.preventDefault();
        });
    }
}


var portfolio = {
    site: Object,
    large: Object,
    height: Number,
    init: function () {
        this.site = $('#portfolio li:not(#portfolio li.large)');
        this.large = $('#portfolio li.large');
        this.run();
    },
    run: function () {
        this.site.hover(function () {
            $(this).find('img').stop(true, true).fadeOut('fast');
        }, function () {
            $(this).find('img').stop(true, true).fadeIn('fast');
        });

        this.large.hover(function () {
            portfolio.height = $(this).find('.descHolder').innerHeight();
            $(this).find('.description').stop(true, false).animate({
                'height': portfolio.height
            }, 'slow', 'easeOutQuint');
        }, function () {
            $(this).find('.description').stop(true, false).animate({
                'height': '34px'
            }, 'slow', 'easeInOutQuint');
        });

        if ($(window).width() < 520) {
            $('#portfolio li h4 a').live('click', function () {
                $('html, body').animate({ scrollTop: 0 }, 'slow');
            });
        }
    }
}


// Slideshow Controller
var slideShowController = {
    images          : Object,
    init            : function(){
        this.images = $('div#slideshow img');
        this.run();
    },
    run             : function(){
        var currentImage = 0;
        var newHeight = 0;
        
        // Initial Setup
        $('div#slideshowBottom').prepend('<div id="description"><p>' + $('div#slideshow img.on').attr('alt') + '</p></div>');
        
        // Sets up pagination and stage if there is more than one image.
        if(this.images.length > 1){
            $('div#slideshow div#description').prepend('<ul></ul>');
            for(var i = 1; i <= this.images.length; i++){
                $('div#slideshow div#description ul').append('<li><a href="#" rel=' + i + '>' + i + '</a></li>');
            }
            $('div#slideshow div#description ul li:first a').addClass('current');
        }
        
        
        // Image Changer
        $('div#slideshow div#description ul li a').click(function(e){
            if(!$(this).hasClass('current')){

                // Sets the height so the first transition goes smoothly
                $('div#slideshowBottom').height($('div#slideshowBottom img.on').height());

                $('div#slideshow div#description ul li a.current').removeClass('current')
                $(this).addClass('current')
                currentImage = $(this).attr('rel')-1;
                
                $('div#slideshow div#description').slideUp(function(){
                    $('div#slideshow img.on').fadeOut('normal', function(){
                        $(this).removeClass('on')
                        newHeight = slideShowController.images.eq(currentImage).height();
                        if($('div#slideshowBottom').height() != newHeight){
                            $('div#slideshowBottom').animate({height:newHeight}, 1000, function(){
                                slideShowController.imageSwitch(currentImage);
                            });
                        }else{
                            slideShowController.imageSwitch(currentImage);
                        }
                    });
                });
            }
            e.preventDefault();
        });        
    },
    // fades in new image
    imageSwitch     : function(imageID){
        this.images.eq(imageID).fadeIn('normal', function(){
            $(this).addClass('on');
            $('div#slideshow div#description').slideDown();
            slideShowController.changeDesc();
        });    
    },
    // fades in new image
    changeDesc      : function(){
        $('div#slideshow div#description p').html($('div#slideshow img.on').attr('alt'));
    }
}


// Blog Controller
var blog = {
    errors  : Boolean,
    init    : function(){
        this.errors = false;
        
        // Helps wordpress be cooler
            $('.post:last').addClass('last');

        // Removes empty lizards               
            $('#controls li span.chameleon:empty').parent().css('display','none');
        
        // Shows / hides reply button
            $('.commentlist li').hover(function(){
                $(this).find('.reply:not(li li .reply)').css('display','block');
            }, function(){
                $(this).find('.reply:not(li li .reply)').css('display','none');
            });
        
        this.checkComments();
    },
    // Comment error checking
    checkComments   : function(){    
        $('#submitBtn').click(function(e){

            if(blog.errors == true){
                $('#errors ul').html('');
            }
                
            if($('#author').val() == ''){
                blog.makeErrorHolder();
                $('#errors ul').append('<li>Your name is required</li>');
                e.preventDefault();
            }
            if($('#email').val() == ''){
                blog.makeErrorHolder();
                $('#errors ul').append('<li>Your email is required</li>');
                e.preventDefault();
            }
            if($('#comment').val() == ''){
                blog.makeErrorHolder();
                $('#errors ul').append('<li>If you\'re not going to write anything, what\'s the point of commenting?</li>');
                e.preventDefault();
            }
            
            if(blog.errors == true){
                $('#errors').slideDown('normal');
            }
        });
    },
    makeErrorHolder : function(){
        if(this.errors == false){
            $('#commentform fieldset').append('<div id="errors"><ul></ul></div>');
            this.errors = true;
        }    
    }
}

// Input Controller
var input = {
    init    : function(){
        $('input:text, textarea').focus(function(){
            if($(this).val() == $(this).attr('defaultValue')){
                $(this).val('');
            }
        });
        
        $('input:text, textarea').blur(function(){
            if($(this).val() == ''){
                $(this).val($(this).attr('defaultValue'));
            }
        });
    }
}


var contact = {
    name        : Object,
    email       : Object,
    message     : Object,
    sendBtn     : Object,
    error       : Boolean,
    init        : function(){
        this.name = $('input#Name');
        this.email = $('input#Email');
        this.message = $('textarea#Message');
        this.sendBtn = $('a#send');
        this.error = false;
        this.run();
    },
    run         : function(){
        this.sendBtn.click(function(e){
        
            if(contact.name.val() == '*Name' || contact.name.val() == ''){
                contact.error = true;
                contact.name.animate({color:'#af1616'}, 'fast');
                if($('.nameError').length == 0){
                    contact.name.after('<span class="error nameError"><span>Enter your name</span></span>');
                }
            }else{
                $('span.nameError').remove();
                contact.name.animate({color:'#666666'}, 'fast');
            }
            if(contact.email.val() == '*Email Address' || contact.email.val() == ''){
                contact.error = true;
                contact.email.animate({color:'#af1616'}, 'fast');
                if($('.emailError').length == 0){
                    contact.email.after('<span class="error emailError"><span>Enter your e-mail address</span></span>');
                }
            }else{
                $('span.emailError').remove();
                contact.email.animate({color:'#666666'}, 'fast');
            }
            if(contact.message.val() == '*Message' || contact.message.val() == ''){
                contact.error = true;
                contact.message.animate({color:'#af1616'}, 'fast');
                if($('.messageError').length == 0){
                    contact.message.after('<span class="error messageError"><span>Please say something :(</span></span>');
                }
            }else{
                $('span.messageError').remove();
                contact.message.animate({color:'#666666'}, 'fast');
            }
            
            if(contact.error == true){
                color.background('af1616');
                e.preventDefault();
                $('span.error').fadeIn('fast');
                contact.error = false;
            }else{
                _gaq.push(['_trackEvent', 'Contact Form', 'Form Submit', contact.name.val()]);
                $('form#contactform').submit();
            }
        });
        
    }
}


var socials = {
    newHeight   : Number,
    firstTime   : Boolean,
    init        : function(){
        this.firstTime = true;
        $('.twitter').tweet({username: 'lightburn', count: 1});
        this.run();
    },
    run         : function(){    

        $('#social li a').click(function(e){
        
            if(!$(this).hasClass('on')){
                
                _gaq.push(['_trackEvent', 'Footer', 'Footer Social Link Clicked', $(this).parent().attr('id')]);
                
                // Switch Buttons
                $('#social li a.on').removeClass('on');
                $(this).addClass('on');
            
                // Animate Transition
                $('#socialHolder').height($('#socialHolder .on').innerHeight());
                $('#socialHolder .on').fadeOut('fast', function(){
                    $(this).removeClass('on');
                    $('#socialHolder .' + $('#social li a.on').attr('rel')).addClass('on');
                    
                    if($('.socialSlide.on').hasClass('flickr') && socials.firstTime == true){
                        socials.getFlickr(); 
                        socials.firstTime = false;
                    }
                    
                    socials.newHeight = $('#socialHolder .on').height();
                                        
                    if( $('#socialHolder').height() != socials.newHeight){
                        $('#socialHolder').animate({
                            height:socials.newHeight
                        }, 500, function(){
                            $('#socialHolder .on').fadeIn('fast');
                        });
                    }   
                });
            }
            e.preventDefault();
        });
    },
    getFlickr      : function(){
    
        $.ajax({
            type : 'GET',
            url: 'http://api.flickr.com/services/feeds/photos_public.gne?id=44149998@N03&lang=en-us&format=json&jsoncallback=?',
            dataType: 'jsonp',
            success: function(data){
                $.each(data.items, function(i, item){
                    $("<img/>").attr("src", item.media.m.replace('_m.jpg','_s.jpg')).appendTo(".flickr");

                    if (i < 5) {
                        $('.flickr').find('img:last').wrap('<a href="' + item.link + '" rel="external"></a>');
                    } else {
                        $('.flickr').find('img:last').wrap('<a href="' + item.link + '" rel="external" class="last"></a>');
                        return false;
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                $('.flickr').append('<p>A gremlin ate our photos.</p>');
            }
        });
    }
}

var mobile = {
    winW: Object,
    resizeTimer: Object,
    init: function () {
        this.winW = $(window).width();
        this.resizeTimer;
        this.run();
    },
    run: function () {
        $(window).resize(function () {
            clearTimeout(mobile.resizeTimer);
            mobile.resizeTimer = setTimeout(mobile.howBigAmI, 100);
        });
        mobile.howBigAmI();
    },
    howBigAmI: function () {
        mobile.winW = $(window).width();

        if ($.browser.msie && $.browser.version.substr(0, 1) < 9) {
            if (mobile.winW < 520) {
                $('#portfolio li:nth-child(2n + 2), #portfolio li:nth-child(3n+3)').css({'margin-right' : '0' }); 
            }
        }
    }
};

// Page Initialization
function initialize(){
    navController.init();
    anchorController.init()
    caseStudy.init();
    portfolio.init();
    slideShowController.init();
    blog.init();
    contact.init();
    input.init()
    socials.init();
    mobile.init();
}


// Start
$(document).ready(function(){
    initialize();    
});

(function($) {
 
  $.fn.tweet = function(o){
    var s = {
      username: ["seaofclouds"],              // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      avatar_size: null,                      // [integer]  height and width of avatar if displayed (48px max)
      count: 3,                               // [integer]  how many tweets to display?
      intro_text: null,                       // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                       // [string]   do you want text AFTER your tweets?
      join_text:  null,                       // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",      // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                 // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",             // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",   // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at", // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                     // [string]   optional loading text, displayed while tweets load
      query: null                             // [string]   optional search query
    };
    
    if(o) $.extend(s, o);
    
    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\">$1</a>"))
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>"))
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+s.username.join("%2BOR%2B")+'">#$1</a>'))
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(a|A)wesome/gi, 'AWESOME'))
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(e|E)pic/gi, 'EPIC'))
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(&lt;)+[3]/gi, "<tt class='heart'>&#x2665;</tt>"))
        });
        return $(returning);
      }
    });

    function relative_time(time_value) {
      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);
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < 120) {
      return 'about a minute ago';
      } else if(delta < (45*60)) {
      return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (90*60)) {
      return 'about an hour ago';
      } else if(delta < (24*60*60)) {
      return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
      return '1 day ago';
      } else {
      return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

    return this.each(function(){
      var list = $('<ul class="tweet_list">').appendTo(this);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>'
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>'
      var loading = $('<p class="loading">'+s.loading_text+'</p>');
      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }
      var query = '';
      if(s.query) {
        query += 'q='+s.query;
      }
      query += '&q=from:'+s.username.join('%20OR%20from:');
      var url = 'http://search.twitter.com/search.json?&'+query+'&rpp='+s.count+'&callback=?';
      if (s.loading_text) $(this).append(loading);
      $.getJSON(url, function(data){
        if (s.loading_text) loading.remove();
        if (s.intro_text) list.before(intro);
        $.each(data.results, function(i,item){
          // auto join text based on verb tense and content
          if (s.join_text == "auto") {
            if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
              var join_text = s.auto_join_text_reply;
            } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
              var join_text = s.auto_join_text_url;
            } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
              var join_text = s.auto_join_text_ed;
            } else if (item.text.match(/^(\w*ing) .*/i)) {
              var join_text = s.auto_join_text_ing;
            } else {
              var join_text = s.auto_join_text_default;
            }
          } else {
            var join_text = s.join_text;
          };

          var join_template = '<span class="tweet_join"> '+join_text+' </span>';
          var join = ((s.join_text) ? join_template : ' ')
          var avatar_template = '<a class="tweet_avatar" href="http://twitter.com/'+ item.from_user+'"><img src="'+item.profile_image_url+'" height="'+s.avatar_size+'" width="'+s.avatar_size+'" alt="'+item.from_user+'\'s avatar" title="'+item.from_user+'\'s avatar" border="0"/></a>';
          var avatar = (s.avatar_size ? avatar_template : '')
          var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';
          var date = ' <a href="http://twitter.com/'+item.from_user+'/statuses/'+item.id+'" title="view tweet on twitter" class="time">- '+relative_time(item.created_at)+'</a>';
          
          // until we create a template option, arrange the items below to alter a tweet's display.
          list.append('<li>' + avatar + join + text + date + '</li>');

          list.children('li:first').addClass('tweet_first');
          list.children('li:odd').addClass('tweet_even');
          list.children('li:even').addClass('tweet_odd');
        });
        if (s.outro_text) list.after(outro);
      });

    });
  };
})(jQuery);
