
Home.prototype              = new Utils();
Home.prototype.constructor  = Home;
function Home( config ) {
  this.default_hash         = '#/creativity/yas';
  this.default_creativity   = 'yas';
  this.default_technology   = 'erik';
  this.default_business     = 'melanie';
  this.current_section      = 'creativity';
  
  this.json_path        = 'home/'; // Appended to WP URL.
  this.cast_img_path    = 'home/'; // Appended to media URL.
  this.quote_num        = 0; // Value will be between 1-4: innerHTML of #quotes-nav anchor
  this.quote_width      = $( '#quotes-home' ).width();
  
  this.back_width       = 1200;
  this.back_start_x     = ( ( this.quote_width -this.back_width ) /2 );
  this.back_interval    = 0;
  
  this.mid_width        = 1200;
  this.mid_start_x      = ( ( this.quote_width -this.mid_width ) /2 );
  
  this.fore_width       = 1600;
  this.fore_start_x     = ( ( this.quote_width -this.fore_width ) /2 );
  this.fore_anim_width  = 2000;
  this.fore_anim_incr   = this.fore_anim_width /4;
  
  this.mf_ratio         = this.fore_width / this.mid_width;
  
  
  // Attach config values to Class.
  for( key in config ) {
    this[ key ]  = config[ key ];
  }
  
  var self  = this;
  	
  // Remove SEO content.
  $( '#quotes-home blockquote' ).html( '' );
  $( '#quotes-home #quote-silhouette img' ).remove();
  $( '#project #slide-copy' ).html( '' );
  $( '#project #slide-mask img' ).remove();
  $( '#project #slide-img' ).hide();
  
  // Call init when SWFAddress is ready to go.
  window.SWFAddress.onInit  = function() {
    self.init();
  }
}


/*
 * @description Build the quotes nav based on JSON request for sub-pages.
 * @return null
 */
Home.prototype.buildQuotesNav   = function() {
  var self      = this;
  var hash      = location.hash;
  var path      = self.hashToPath( hash );
  var segments  = path.split( '/' );
  
  // AJAX request quotes from WP.
  var ajax_url  = self.wp_url + 'get-sub-pages/?parent=' + self.json_path + self.current_section;
  $.ajax( {
    "url":  ajax_url, 
    "dataType":   "json", 
    "success":    function( data, status, xhr ) {
      // Remove the old list items from the nav
      $( '#quotes-nav li' ).remove();
      
      var html        = String( ''
        + '<li id="{quote-slug}">'
          + '<a href="{quote-hash}">{quote-num}</a>'
        + '</li>'
      );
      
      // Append new list items.
      for( key in data ) {
        var quote_slug   = data[ key ].post_name;
        var quote_hash   = '#/' + segments[ 0 ] + '/' +quote_slug;
        var quote_num    = Number( key ) +1;
        var quote_html   = html;
        quote_html       = quote_html.replace( '{quote-slug}', quote_slug );
        quote_html       = quote_html.replace( '{quote-hash}', quote_hash );
        quote_html       = quote_html.replace( '{quote-num}', quote_num );
        $( '#quotes-nav' ).append( quote_html );
      }
      
      // Highlight the selected nav element.
      $( '#quotes-nav li#' +self.current_cast ).addClass( 'selected' );
      
      // Swap out the text on the label.
      $( '#quotes-controls label span' ).html( segments[ 0 ] );
      
    }, 
    // Utils.prototype.ajaxError( xhr, status, error, url )
    "error":  function( xhr, status, error ) { self.ajaxError( xhr, status, error, ajax_url ); }
  } );
}


/*
 * @description Registered with SWFAddress to fire whenever location.hash changes.
 * @return null
 */
Home.prototype.changeHash  = function() {
  var self  = this;
  var hash  = window.SWFAddress.getValue();
  var path  = hash.substring( 1 );
  
  self.sanitizeTags( top.location );
  
  if( hash.length <= 1 ) {
    var valhash  = self.default_hash.substring( 1 );
    window.SWFAddress.setValue( valhash );
    return false;
  }
  
  // Check for cast member in hash.
  var segments  = path.split( '/' );
  var section   = segments[ 0 ];
  var cast      = segments[ 1 ];
  if( ! cast ) {
    cast            = self[ 'default_' +section ];
    var newhash     = String( '/' + section + '/' + cast );
    window.SWFAddress.setValue( newhash );
  }
  
  // Update the main nav link.
  var sel_main    = '#sub-nav li#' +section;
  $( '#sub-nav li' ).removeClass( 'selected' );
  $( sel_main ).addClass( 'selected' );
  
  // Update the quotes nav link.
  var sel_quote   = '#quotes-nav li#' +cast;
  $( '#quotes-nav li' ).removeClass( 'selected' );
  $( sel_quote ).addClass( 'selected' );
  
  // Check if we need to update the #quotes-nav with new section links.
  if( section != self.current_section ) {
    self.current_section  = section;
    self.current_cast     = cast;
    self.buildQuotesNav();
  }
  
  // Update the latest values.
  self.current_section  = section;
  self.current_cast     = cast;
  
  self.loadContent();
  
  return false;
}


/*
 * @description Initialize the class and set up events.
 * @return null
 */
Home.prototype.init   = function() {
  var self  = this;
  
  // Check for existing querystring and rewrite as location.hash.
  if( location.search ) {
    var hash      = self.querystringToHash( location.search );
    var redir     = location.pathname + hash;
    top.location  = redir;
    return false;
  }
  
  // Rewrite top nav and quote nav links' querystrings as hash.
  $( '.ajax-nav li a' ).each( function() {
    var hash  = self.querystringToHash( $( this ).attr( 'href' ) );
    $( this ).attr( 'href', hash );
  } );
  $( '#quotes-nav li' ).removeClass( 'selected' );
  
  // Add omniture calls to top nav links.
  $( 'ul#sub-nav li a' ).click( function() {
    if( window.s_wdpro ) {
      window.s_wdpro.trackClick( this );
    }
  } );
  
  // Set background placements and start the clouds.
  $( '#quotes-bkgd-back' ).css( 'left', ( self.back_start_x -self.back_width ) );
  $( '#quotes-bkgd-mid' ).css( 'left', self.mid_start_x );
  $( '#quotes-bkgd-fore' ).css( 'left', self.fore_start_x );
  self.startClouds();
  
  // Set SWFAddress events.
  window.SWFAddress.onChange  = function() {
    self.changeHash();
  }
  
}


/*
 * @description Load the AJAX content and images.
 * @return null
 */
Home.prototype.loadContent   = function() {
  var self      = this;
  var hash      = window.SWFAddress.getValue();
  var path      = hash.substring( 1 );
  var segments  = path.split( '/' );
  
  // If there is no cast memeber, exit the function.
  if( ! segments[ 1 ] )  return;
  
  var img_loaded      = 0; // Count the image loads so everything is ready before animations.
  var cast_img        = new Image();
  var proj_img        = new Image();
  var cast_data;
  var proj_data;
  
  function compileData() {
    var data      = {};
    data.cast     = cast_data;
    data.project  = proj_data;
    data.images   = {};
    data.images.cast      = cast_img;
    data.images.project   = proj_img;
    self.showContent( data );
  }
  
  // Load the cast data.
  var cast_ajax_url   = self.wp_url + self.json_path + path + '/';
  $.ajax( {
    "url":        cast_ajax_url, 
    "dataType":   "json", 
    "success":    function( data, status, xhr ) {
      // Load the cast image.
      cast_data           = data;
      var cast_img_path   = self.media_url + self.cast_img_path + path + '.png';
      
      cast_img.onerror   = function() {
        if( typeof window.console != 'undefined' ) {
          console.log( 'Missing image: ' +cast_img_path );
        }
        cast_img_path      = self.media_url + self.cast_img_path + 'missing.png';
        cast_img.src       = cast_img_path;
        cast_img.onerror   = '';
      };
      
      cast_img.onload    = function() {
        img_loaded ++;
        if( img_loaded == 2 ) compileData();
      };
      
      cast_img.alt       = data.post_title;
      cast_img.src       = cast_img_path;
      
    }, 
    //Utils.prototype.ajaxError( xhr, status, error, url )
    "error": function( xhr, status, error ) { self.ajaxError( xhr, status, error, cast_ajax_url ); }
  } );
  
  // Load the project data.
  var proj_ajax_url   = self.wp_url + 'get-sub-pages/?parent=' + self.json_path + path;
  $.ajax( {
    "url":    proj_ajax_url, 
    "dataType":   "json", 
    "success":    function( data, status, xhr ) {
      // Load the project image.
      proj_data           = data;
      var proj_img_path   = self.media_url + self.cast_img_path + 'projects/' + data.post_name + '.jpg';
      
      proj_img.onerror  = function() {
        if( typeof window.console != 'undefined' ) {
          console.log( 'Missing image: ' +proj_img_path );
        }
        proj_img_path     = self.media_url + self.cast_img_path + 'proj-missing.jpg';
        proj_img.src      = proj_img_path;
        proj_img.onerror  = '';
      }
      
      proj_img.onload   = function() {
        img_loaded ++;
        if( img_loaded == 2 )   compileData();
      }
      
      proj_img.alt      = data.post_title;
      proj_img.src      = proj_img_path;
    }, 
    "error":  function( xhr, status, error ) { self.ajaxError( xhr, status, error, proj_ajax_url ); }
  } );
}


/*
 * @description Show the content after it's been loaded.
 * @return null
 */
Home.prototype.showContent   = function( data ) {
  var self        = this;
  var hash        = location.hash;
  var path        = self.hashToPath( hash );
  var segments    = path.split( '/' );
  var img_class   = 'silhouette-' + segments[ 1 ];
  if( data.images.cast.src.indexOf( 'missing' ) != -1 )  img_class   = 'silhouette-melanie-chang';
  
  // Figure out if we're going left or right based on #quotes-nav anchor innerHTML.
  var curr_quote_num  = $( '#quotes-nav .selected a' ).text();
  //Utils.prototype.trim( str )
  curr_quote_num      = self.trim( curr_quote_num );
  var dirn  = 'left';
  if( curr_quote_num > self.quote_num )   dirn  = 'right';
  
  // All animation sequences complete at 2000ms.
  var end_out_x   = ( ( dirn == 'left' ) ? self.quote_width : -self.quote_width ) + 'px';
  var start_in_x  = ( ( dirn == 'left' ) ? -self.quote_width : self.quote_width ) + 'px';
  
  // Animate quote.
  $( '#quote' ).animate(
    { "left": end_out_x }, 
    800, 'easeInExpo', function() {
      $( '#quote' ).css( 'left', start_in_x );
      
      // Set next image.
      $( '#quote-silhouette img' ).remove();
      $( '#quote-silhouette' ).append( data.images.cast );
      $( '#quote-silhouette' ).removeClass();
      $( '#quote-silhouette' ).addClass( img_class );
      
      // Set next quote.
      $( '#quote blockquote' ).html( data.cast.post_html );
      $( '#quote blockquote' ).removeClass();
      $( '#quote blockquote' ).addClass( 'quote-' +segments[ 1 ] );
      
      setTimeout( function() {
        $( '#quote' ).animate(
          { "left": "0px" }, 
          800, 'easeOutExpo'
        );
      }, 400 );
    }
  );
  
  // Animate project a bit later.
  setTimeout( function() {
    $( '#project-slide' ).animate(
      { "left": end_out_x }, 
      800, 'easeInExpo', function() {
        $( '#project-slide' ).css( 'left', start_in_x );
        
        // Set next project image.
        $( '#project #slide-mask img' ).remove();
        $( '#project #slide-mask' ).append( data.images.project );
        $( '#project #slide-img' ).show();
        
        // Set next project copy.
        $( '#project #slide-copy' ).html( data.project.post_html );
        
        setTimeout( function() {
          $( '#project-slide' ).animate(
            { "left": "0px" }, 
            800, 'easeOutExpo'
          );
        }, 200 );
      }
    );
  }, 400 );
  
  // Animate backgrounds: fore, mid.
  var fore_x  = Math.round( ( self.fore_anim_incr *( curr_quote_num -1 ) ) -self.fore_start_x ) * -1;
  //var mid_x   = Math.round( fore_x * self.mf_ratio );
  var mid_x   = Math.round( ( ( self.fore_anim_incr * self.mf_ratio ) * ( curr_quote_num -1 ) ) -self.mid_start_x ) * -1;
  
  $( '#quotes-bkgd-fore' ).animate(
    { "left": fore_x }, 
    2200, 'easeInOutQuint'
  );
  $( '#quotes-bkgd-mid' ).animate(
    { "left": mid_x }, 
    2200, 'easeInOutQuint'
  );
  
  self.quote_num  = curr_quote_num;
  
}


/*
 * @description Starts the cloud animation scrolling left to right.
 * @return null
 */
Home.prototype.startClouds  = function() {
  var self  = this;
  self.back_interval  = setInterval( function() {
    var curr_x  = Number( $( '#quotes-bkgd-back' ).css( 'left' ).replace( 'px', '' ) );
    var new_x   = curr_x +1;
    if( new_x > self.back_start_x )   new_x   = self.back_start_x -self.back_width; // Reset the position to loop
    $( '#quotes-bkgd-back').css( 'left', new_x );
  }, 60 );
}





