var gOverride = {
  urlBase: 'http://gridder.andreehansson.se/releases/latest/',
  gColor: '#000',
  gColumns: 24,
  gOpacity: 0.06,
  gWidth: 10,
  pColor: '#000',
  pHeight: 8,
  pOffset: 0,
  pOpacity: 0.2,
  center: false,
  gEnabled: true,
  pEnabled: true,
  setupEnabled: true,
  fixFlash: true,
  size: 960
};


(function($) {


  /**
   * jQuery.ScrollTo - Easy element scrolling using jQuery.
   * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
   * Dual licensed under MIT and GPL.
   * Date: 5/25/2009
   * @author Ariel Flesler
   * @version 1.4.2
   *
   * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
   */
  (function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})($);
  
  
  /**
   * jQuery.rgbToHex - Converts an RGB string to a HEX string (forces length 6)
   */
  $.rgbToHex = function(rgbString) {
  	var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  	if ( ! parts) {
  		if (rgbString.length < 6) {
  			var parts = rgbString.split('');
  			delete (parts[0]);
  			for (var i = 1; i <= 3; ++i) {
  				parts[i] = parts[i] + parts[i];
  			}
  			return parts.join('');
  		}
  		else {
  			return rgbString;
  		}
  	}
  	else {
  		delete (parts[0]);
  		for (var i = 1; i <= 3; ++i) {
  			parts[i] = parseInt(parts[i]).toString(16);
  			if (parts[i].length == 1) parts[i] = parts[i] + parts[i];
  		}
  		return parts.join('');
  	}
  };
  
  
  /**
   * jQuery.fn.invert - Inverts a selection based on the last filter/find/etc.
   */
  $.fn.invert = function(selector) {
    var self = this.end().not(this);
    
    if (selector)
      self = self.filter(selector);
    
    return self;
  };
  
  
  /**
   * Add a hover effect to an element (Proud specific functionality)
   */
  $.fn.buttonHover = function() {
    var opts  = {
      duration: 'fast',
      queue: false
    };
    
    return $(this)
      .filter('[data-color]')
      .each(function() {
        var self  = $(this),
            color = self.data('color');
        
        self.hover(
          function() {
            self.animate({ backgroundColor: color }, opts);
          },
          function() {
            self.animate({ backgroundColor: '#000' }, opts);
          }
        );
      })
      .end();
  };
  
  
  $(function() {
    
    
    // Add accordion functionality
    (function() {
      
      // Default animation options
      var
        options = {
          duration: 'fast',
          queue: false
        };
      
      // Define custom animation
      $.ui.accordion.animations.custom = function(options) {
        this.slide(options, {
          duration: 'slow',
          easing: 'easeInOutExpo'
        });
      };
      
      $('.accordion')
        .accordion({ // Add accordion functionality
          active: false,// Collapsed by default
          collapsible: true,
          header: '> .accordion_item > .accordion_header',
          changestart: function(event, ui) {
            // Revert contracting item to default color
            ui.oldHeader.not('.ui-state-hover').parent().animate({
              backgroundColor: '#000'
            }, options);
            
            var newHeader = ui.newHeader.parent();
            newHeader.css('backgroundColor', newHeader.data('color'));
          }
        })
        .find('.accordion_header')
        .hover( // Define hover event handlers
          function() {
            var self = $(this).parent();
            self.animate({
              backgroundColor: self.data('color')
            }, options);
          },
          function() {
            var self = $(this)
              .not('.ui-state-active')
              .parent()
              .animate({
                backgroundColor: '#000'
              }, options);
          }
        );
    })();
    
    
    // Add hover effect to buttons with an assigned colour value
    $('a.button[data-color]').buttonHover();
    
    
    // Add hover effect to project list items and project thumbnails
    $('#project_list .project, #project_thumbnails .thumbnail')
      .hover(
        function() {
          $('img', this).stop(true, true).fadeOut(150);
        },
        function() {
          $('img', this).stop(true, true).fadeIn(300);
        }
      );
    
    // Folio thumbnail functionality
    (function() {
      
      var
        media = $('#project_media');
      
      // Check the media container exists before progressing
      if (media.size() > 0) {
        
        var
          win = $(window),
          caption = $('#project_caption'),
          captionOffsetTop = caption.offset().top - 4;
        
        // Set the height of the media container
        media
          .width(media.width())
          .height(media.height());
        
        // Fade out media container and caption
        hideMedia = function(callback) {
          media.add(caption).animate({
            opacity: 0
          }, 150, callback);
        },
        
        // Sets the height of the media container
        sizeMedia = function(height, callback) {
          //console.log(height);
          media.animate({
            height: height
          }, 300, callback);
        },
        
        // Fade in media container and caption
        showMedia = function(callback) {
          media.add(caption).animate({
            opacity: 1
          }, 300, callback);
        },
        
        focusMedia = function() {
          if (win.scrollTop() > captionOffsetTop) {
            $.scrollTo(captionOffsetTop, 200);
          }
        },
        
        // Load image into media container
        loadImage = function(src, captionText) {
          
          // Check the target src is different
          if (src != media.data('src')) {
          
            // Set the src
            media.data('src', src);
            
            // Switch classes
            media.removeClass('video video-widescreen video-normal').addClass('image');
            
            // Scroll to the media container
            focusMedia();
          
            // Fade out media container
            hideMedia(function() {
              
              // Empty media container
              media.empty();
              
              // Change caption text
              caption.text(captionText);
              
              // Create image
              var img = $('<img>')
                .appendTo(media)
                .load(function() {
                  
                  // Check media height is correct
                  if (media.height() != img.height()) {
                    
                    // Adjust the media container height to fit the image
                    sizeMedia(img.height(), function() {
                    
                      // Fade in media container
                      showMedia();
                    });
                  }
                  else {
                    
                    // Media container is the correct size already
                    // Fade in media container
                    showMedia();
                  }
                })
                .error(function() {
                  
                  // Display error
                  media.addClass('image_error').empty();
                  
                  // Display error via caption
                  caption.text('Error: Image load failed');
                  
                  // Fade in media container
                  showMedia();
                })
                .attr('src', src);
            });
          }
        },
        
        showVimeo = function(iframe, src) {
          iframe
            .load(function() {
              showMedia();
            })
            .attr('src', src)
            .appendTo(media);
        },
        
        // Load a Vimeo player
        loadVimeo = function(vimeoUrl, captionText, ratio) {
          
          // Check the target src is different
          if (vimeoUrl != media.data('src')) {
            
            // Set the src
            media.data('src', vimeoUrl);
            
            if (ratio == null)
              ratio = 'widescreen';
            
            var
              iframe = $('<iframe frameborder="0" class="vimeo_player" />'),
              
              height = (ratio == 'widescreen') ? 258 : 344,
              color = $.rgbToHex(caption.css('color')),
              mediaClass = (ratio == 'widescreen') ? 'video video-widescreen' : 'video video-normal',
              
              src = vimeoUrl.replace(/https?:\/\/(?:www\.)?vimeo.com\/([0-9]+)(\?.+)?/, 'http://player.vimeo.com/video/$1?title=0&byline=0&portrait=0&autoplay=0&api=1&color=' + color);
            
            iframe
              .width(460)
              .height(height);
            
            // Switch classes
            media.removeClass('image').addClass(mediaClass);
            
            // Scroll to the media container
            focusMedia();
          
            hideMedia(function() {
              
              // Empty media container
              media.empty();
              
              // Change caption text
              caption.text(captionText);
              
              if (media.height() != height) {
                sizeMedia(height, function() {
                  
                  showVimeo(iframe, src);
                });
              }
              else {
                showVimeo(iframe, src);
              }
            });
          }
          
        };
        
        $('#project_thumbnails > .thumbnail')
          .filter('[href*="vimeo.com/"]')
            .click(function() {
              var self = $(this);
              loadVimeo(self.attr('href'), self.attr('title'), self.data('ratio'));
              return false;
            })
          .invert()
            .click(function() {
              var self = $(this);
              loadImage(self.attr('href'), self.attr('title'));
              return false;
            })
          .end()
          .first()
            .trigger('click');
      
      }
      
    })();
    
    
    // Google Maps
    (function() {
      
      var
        // Get container(s)
        gmap = $('#gmap').empty();
      
      // Check there is a map element before progressing
      if (gmap.size() > 0) {
      
        // Define a global function for the script below callback
        gmapInit = function() {
          
          // Loop containers
          gmap.each(function() {
            
            var
              self = $(this),
              
              // Get lat and lng from element data
              ll = self.data('ll').split(','),
              
              // Create LatLng instance
              latlng = new google.maps.LatLng(ll[0], ll[1]),
              
              // Create Google map instance
              map = new google.maps.Map(this, {
                zoom: self.data('zoom'),
                center: latlng,
                mapTypeControl: false,
                panControl: false,
                zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL
                  },
                scaleControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              }),
              
              // Create the marker image
              icon = new google.maps.MarkerImage(self.data('icon'), false, false, new google.maps.Point(12, 32)),
              
              // Add the marker to the map
              marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: icon,
                shadow: false
              });
            
          });
        };
        
        // Async
        $.getScript('http://maps.google.com/maps/api/js?sensor=false&callback=gmapInit');
      }
      
    })();
    
    
    // Grid toggle
    (function() {
      
      var
        body = $('body'),
        glyph = /Mac|iPad|iPod|iPhone/.test(navigator.platform) ? '&#9783;' : 'Toggle Grid';
      
      $('<a id="toggle_grid" title="Toggle Grid">')
        .html(glyph)
        .click(function() {
          body.toggleClass('grid');
          return false;
        })
        .appendTo('#footer');
      
    })();
    
    
  });
}(window.jQuery));
