var slideshow, $content, $wrapper;
var ch = 368;

jQuery.noConflict();
$j = jQuery;
$j().ready(
  function()
  {
    // configure a couple of pointers to the DOM
    $wrapper = $j('#flash-wrapper');
    $content = $j('#flash');
    
    $j('#slideshow').jcarousel({
      easing: 'easeInBack',
      animation: 700,
      visible:1,
      scroll:1,
      auto:7,
      itemLastOutCallback: {
        onBeforeAnimation: function(){},
        onAfterAnimation: function(s,el,i,x,y){
          if( i == s.size() ){
            s.options.auto = 0;
            s.stopAuto();
          }
        }
      }
    });
    //slideshow = new Slideshow( '#flash', 7000 ); // element id, interval in milliseconds
    
    // are we deep linking anywhere?
    var qs = new Querystring();
    // support both 'pg' and 'page' attributes
    if( qs.get('pg') || qs.get('page') ){
      var pg = qs.get('pg');
      if( qs.get('page') ) pg = qs.get('page');
      if( pg.charAt(pg.length-1)!='/' ) pg += '/';  // append a forward slash to urls if not present
      loadSect( pg );
    }
    
    // hijack top nav clicks
    bindNavs();
    
    // load latest from blog
    getAtomFeed();
    //getRssFeed();
    
    // update tweets
    getTweetsFromRESTAPI();
  }
);



function getTweetsFromRESTAPI()
{
  $j.jsonp(
    {
      url: "http://twitter.com/statuses/user_timeline.json?screen_name=VSBrooksInc",
      callback: "callback",
      callbackParameter: "callback",
      success: function( json ) {
        //dbug.log( json );
        var max_tweets = 3;
        var tweets  = json;
        var $tweets = $j( '#tweets' );
        for( var i=0; i<(tweets.length<max_tweets?tweets.length:max_tweets); i++ ){
          var tweet     = tweets[i];
          var myDate    = new Date( tweet.created_at );
          var time_str  = myDate.toLocaleString();
          var re        = new RegExp( '(http:\/\/[a-zA-Z0-9.-\/]*)', "g" );
          var txt       = tweet.text.replace( re, '<a target="_blank" href="$1">$1</a>' );
          
          var html  = '<div class="tweet">';
          //html += '<img height="50" align="left" src="'+tweet.user.profile_image_url+'" class="frame profile-img">';
          html += '<p><span class="from"><a target="_blank" href="http://twitter.com/'+tweet.user.screen_name+'">'+tweet.user.screen_name+'</a></span>: '+txt+'</p>';
          html += '<span class="time">'+new Date( time_str ).toRelativeTime()+'</span>';
          html += '</div><div class="clear"></div>';
          $tweets.append( html );
        }
      }
    }
  );
}

function getTweetsFromSearchAPI()
{
	$j.jsonp(
    {
      url: "http://search.twitter.com/search.json",
      data: 'q=from%3AVSBrooksInc',
      callback: "callback",
      callbackParameter: "callback",
      success: function( json ) {
        var max_tweets = 3;
        var tweets  = json;
        var $tweets = $j( '#tweets' );
        for( var i=0; i<(tweets.results.length<max_tweets?tweets.results.length:max_tweets); i++ ){
          var tweet     = tweets.results[i];
          var myDate    = new Date( tweet.created_at );
          var time_str  = myDate.toLocaleString();
          var re        = new RegExp( '(http:\/\/[a-zA-Z0-9.-\/]*)', "g" );
          var txt       = tweet.text.replace( re, '<a target="_blank" href="$1">$1</a>' );
          
          var html  = '<div class="tweet">';
          html += '<img height="50" align="left" src="'+tweet.profile_image_url+'" class="frame profile-img">';
          html += '<p><span class="from"><a target="_blank" href="http://twitter.com/'+tweet.from_user+'">'+tweet.from_user+'</a></span>: '+txt+'</p>';
          html += '<span class="time">'+new Date( time_str ).toRelativeTime()+'</span>';
          html += '</div><div class="clear"></div>';
          $tweets.append( html );
        }
      }
    }
  );
};



function getAtomFeed()
{
	//dbug.log( 'getRssFeed()' );
  $j.ajax({
    type: "GET",
    url: '/_rss/?url=http://vsbrooks.blogspot.com/feeds/posts/default',
    //dataType:($j.browser.msie) ? "text" : "xml",
    dataType:"xml",
    success: function( d )
    {
      showAtomFeed( d );
    },
    error: function( e )
    {
      showAtomFeed( e.responseText ); // this is throwing an error but the response is actually good so...
      //dbug.log( 'error' );
      //dbug.log( e.status );
      //dbug.log(e.responseText);
    },
    complete: function( e )
    {
      //dbug.log(e);
    }
  });
};
function showAtomFeed( d )
{
  var max_posts = 3;
  for( var i=0; i<($j( d ).find('entry').length<max_posts?$j( d ).find('entry').length:max_posts); i++ ){
    var $item = $j( d ).find('entry').eq(i);
    //var thumbnail   = $item.find('media\\:thumbnail');  // works in firefox but not in chrome
    var thumbnail   = $item.find("[nodeName=media:thumbnail]");
    //alert( thumbnail );//dbug.log( thumbnail );
    thumbnail = thumbnail.length ? thumbnail.attr('url') : '';
    var title       = $item.find('title').text();
    var link        = $item.find('link[rel="alternate"]').attr('href');
    var content     = $item.find('content').text();
    // take control of images embedded within content and scale them down to size
    var re        = new RegExp( /<img (style="[\d\w\s;:]*")/ );
    content = content.replace( re, '<img class="frame" style="margin:5px 5px 0 0; width:90px;height:auto;float:left;"' );
    // remove embedded video due to size issues
    re = new RegExp( /<embed[\d\w\s=":\/.\?\-&;#]*>/ );
    content = content.replace( re, '' );
    var pubDate     = $item.find('published').text();
    var myDate      = new Date();
    myDate          = myDate.setISO8601( pubDate );
    
    var html = "<div class=\"post-wrapper\">";
    html += "<div class=\"post\">";
    if( thumbnail != '') html += "<img class=\"frame left\" style=\"margin: 0pt 5px 0pt 0pt;\" src=\""+thumbnail+"\"/>";
    html += "<p class=\"time\">" + myDate.toRelativeTime() + "</p>";
    html += "<h5 class=\"postTitle\"><a href=\"" + link + "\" target=\"_blank\">" + title + "<\/a><\/h5>";
    html += "<div class=\"clear\"></div>";
    //html += "<p class=\"body\">" + content + "</p>";
    //html += "<a href=\"" + link + "\" target=\"_blank\">more &raquo;<\/a><\/div><\/div>";
    $j('#blog').append( $j(html) );
  }
}



function getRssFeed()
{
	//dbug.log( 'getRssFeed()' );
  $j.ajax({
    type: "GET",
    //url: 'http://lcl.vsbrooks.com/_rss/?url=http://news.discovery.com/rss/news/',
    url: 'http://lcl.vsbrooks.com/_rss/?url=http://twitter.com/statuses/user_timeline/102426957.rss',
    //url: 'http://lcl.vsbrooks.com/_rss/?url=http://vsbrooks.blogspot.com/feeds/posts/default',
    dataType:($j.browser.msie) ? "text" : "xml",
    success: function( d )
    {
      //dbug.log( 'success' );
      var max_posts = 2;
      for( var i=0; i<($j( d ).find('item').length<max_posts?$j( d ).find('item').length:max_posts); i++ ){
        //dbug.log( i );
        var $item = $j( d ).find('item').eq(i);
        var title = $item.find('title').text();
        var link = $item.find('link').text();
        var description = $item.find('description').text();
        var pubDate = $item.find('pubDate').text();
        dbug.log( pubDate );
        var myDate    = new Date( pubDate );
        var time_str  = myDate.toLocaleString();
        
        var html = "<div class=\"post-wrapper\">";
        html += "<div class=\"post\">";
        //html += "<img class=\"frame left\" style=\"margin: 0pt 5px 0pt 0pt;\" src=\"_img/blog2.jpg\"/>";
        html += "<p class=\"time\">" + new Date( time_str ).toRelativeTime() + "</p>";
        html += "<h5 class=\"postTitle\"><a href=\"" + link + "\" target=\"_blank\">" + title + "<\/a><\/h5>";
        
        html += "<p class=\"body\">" + description + "</p>";
        html += "<a href=\"" + link + "\" target=\"_blank\">more &raquo;<\/a><\/div><\/div>";
        $j('#blog').append( $j(html) );
      }
    },
    error: function( e )
    {
      dbug.log( 'error' );
      //dbug.log( e.status );
      //dbug.log(e.responseText);
    },
    complete: function( e )
    {
      //dbug.log(e);
    }
  });
};


/**
* Returns a description of this past date in relative terms.
* Takes an optional parameter (default: 0) setting the threshold in ms which
* is considered "Just now".
*
* Examples, where new Date().toString() == "Mon Nov 23 2009 17:36:51 GMT-0500 (EST)":
*
* new Date().toRelativeTime()
* --> 'Just now'
*
* new Date("Nov 21, 2009").toRelativeTime()
* --> '2 days ago'
*
* // One second ago
* new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime()
* --> '1 second ago'
*
* // One second ago, now setting a now_threshold to 5 seconds
* new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime(5000)
* --> 'Just now'
*
*/
Date.prototype.toRelativeTime = function(now_threshold)
{
  var delta = new Date() - this;
 
  now_threshold = parseInt(now_threshold, 10);
 
  if (isNaN(now_threshold)) {
    now_threshold = 0;
  }
 
  if (delta <= now_threshold) {
    return 'Just now';
  }
 
  var units = null;
  var conversions = {
    millisecond: 1, // ms -> ms
    second: 1000, // ms -> sec
    minute: 60, // sec -> min
    hour: 60, // min -> hour
    day: 24, // hour -> day
    month: 30, // day -> month (roughly)
    year: 12 // month -> year
  };
 
  for (var key in conversions) {
    if (delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }
 
  // pluralize a unit when the difference is greater than 1.
  delta = Math.floor(delta);
  if (delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
};
 
/*
* Wraps up a common pattern used with this plugin whereby you take a String
* representation of a Date, and want back a date object.
*/
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};

// parse an ISO8601 formatted string and return a js date object
Date.prototype.setISO8601 = function(dString)
{
  var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;

  if (dString.toString().match(new RegExp(regexp))) {
    var d = dString.match(new RegExp(regexp));
    var offset = 0;

    this.setUTCDate(1);
    this.setUTCFullYear(parseInt(d[1],10));
    this.setUTCMonth(parseInt(d[3],10) - 1);
    this.setUTCDate(parseInt(d[5],10));
    this.setUTCHours(parseInt(d[7],10));
    this.setUTCMinutes(parseInt(d[9],10));
    this.setUTCSeconds(parseInt(d[11],10));
    if (d[12])
    this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
    else
    this.setUTCMilliseconds(0);
    if (d[13] != 'Z') {
      offset = (d[15] * 60) + parseInt(d[17],10);
      offset *= ((d[14] == '-') ? -1 : 1);
      this.setTime(this.getTime() - offset * 60 * 1000);
    }
  } else {
    this.setTime(Date.parse(dString));
  }
  return this;
};


String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function()
{
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function()
{
	return this.replace(/\s+$/,"");
}





function bindNavs()
{
  $j('#top-nav li' ).click(
    function()
    {
      $j( this ).find('a').click();
    }
  );
  $j('#top-nav li a, #footer-nav li a, .hijack').click(
    function()
    {
      $j('#top-nav li').each(
        function()
        {
          var $this = $j( this );
          $this.removeClass( 'selected' );
          var cls = $this.attr('class');
          $j( cls.split(' ') ).each(
            function()
            {
              var icls = this;
              $j( icls.split('-') ).each(
                function()
                {
                  if( this == 'selected' ) $this.removeClass( icls );
                }
              )
            }
          );
        }
      );
      var cls = $j( this ).parent().attr('class');
      $j( this ).parent().addClass( cls+'-selected' );
      $j( this ).parent().addClass( 'selected' );
      
      loadSect( this.href );
      $j.scrollTo( 0, 300 );
      return false;
    }
  )
}

// alternative to binding the top nav
function bindNav()
{
  $j('#top-nav li a, .content li a').livequery( 'click',
    function( e )
    {
      loadSect( this.href );
      return false;
    }
  )
}


//---------------------------------------------------------------------
//  handle loading sections into the content block
//---------------------------------------------------------------------
function loadSect( href )
{
  //dbug.log( 'href: '+href );
  loading();
  $j.ajax({
    type: "GET",
    url: href,
    success: function( markup ){
      // if we have height information then adjust the content height
      var h = $j(markup).css('height');
      if( h == 'auto' || h == undefined ) h = '368px'; // set a default height
      $content.animate({ 
        height: h
      }, 
      {
        queue:false,
        duration: 800
      });
      $content.html( markup );
      loadingDone();
      pageTracker._trackPageview( href );
    },
    error: function( e )
    {
      //alert('error');
      //alert( e.status );
      //alert(e.responseText);
      //dbug.log( 'error' );
      //dbug.log( e.status );
      //dbug.log(e.responseText);
    },
    complete: function( e )
    {
      //alert('complete');
    }
  });
}
function loading()
{
  $content.css({opacity:.1});
  if( $wrapper.find('#loading').size() == 0 ){
    $wrapper.append( '<img id="loading" src="/_img/loadingAnimation.gif">' );
    var top   = '170px';
    var left  = ($content.width() - $j('#loading').width())/2 + 'px';
    $j('#loading').css({top:top,left:left});
  }
}
function loadingDone()
{
  $j('#loading').remove();
  $content.animate({ 
    opacity: 1
  }, 800 );
}



//---------------------------------------------------------------------
//  preload images
//---------------------------------------------------------------------
$j.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    $j("<img>").attr("src", arguments[i]);
  }
}
var imgs = [];
$j( 'img' ).each( 
  function()
  {
    imgs.push( this.src );
  }
);
$j.preloadImages( imgs.join('","') );




//---------------------------------------------------------------------
//  slideshow feature
//---------------------------------------------------------------------
function Slideshow( id, interval ){
  var self = this;
  self.id       = id;
  self.el       = $j( id );
  self.interval = interval;
  self.paused   = false;
  self.init();
}
Slideshow.prototype = {
  init: function()
  {
    var self = this;
    self.timeout = setTimeout( "slideshow.next()", self.interval );
  },
  next: function()
  {
    var self = this;
    clearTimeout( self.timeout );
    if( !self.paused ){
      var current = self.el.find( '.current' );
      if( current.size() ){
        var next = current.next();
        if( !next.size() ) next = self.el.find( '.slide' ).eq(0);
        if( $j.browser.msie ){
          current.removeClass('current').css({display:'none'});
          next.addClass('current').css({display:'block'});
        } else {
          current.removeClass('current').fadeOut( 1000 );
          next.addClass('current').fadeIn( 1000 );
        }
      }
      self.timeout = setTimeout( "slideshow.next()", self.interval );
    }
  },
  stop: function()
  {
    this.paused = true;
  }
}



//---------------------------------------------------------------------
//  client messaging
//---------------------------------------------------------------------
function alrt( msg )
{
  if( $j('body').find('#alrt').length ){
    $j('body').find('#alrt').remove();
    clearTimeout( tymer );
  }
  var bw = $j('body').width();
  $j('body').append( '<div id="alrt"></div>' );
  var aw = $j('#alrt').width();
  var ml = ((bw - aw)/2);
  $j('#alrt').css({marginLeft:ml+'px'});
  //console.log( $j('#alrt').width() );
  var str = '<p>';
      str += msg;
      str += '</p>';
  $j('#alrt').html( str );
  $j('#alrt').append( '<a class="close" onclick="$j(\'#alrt\').remove(); clearTimeout( tymer );"><img src="/_img/btn-alrt-close.png"></a>' );
  $j('#alrt').css({opacity:0,display:"block"});
  $j('#alrt').animate({ opacity: 0.90}, 700 );  
  tymer = window.setTimeout("$j('#alrt').animate({opacity: 0}, 1500, function(){ $j(this).remove() } )",4000);
}



//---------------------------------------------------------------------
//  dbug.log functionality
//---------------------------------------------------------------------
dbug = {
	firebug: false, debug: false, log: function(msg) {},
	enable: function() { if(this.firebug) this.debug = true; dbug.log = console.debug; dbug.log('enabling dbug');	},
	disable: function(){ if(this.firebug) this.debug = false; dbug.log = function(){}; }
}
if( typeof console != "undefined" ){ // safari, firebug
	if( typeof console.debug != "undefined" && ! $j.browser.safari ){ // firebug, skip chrome
		dbug.firebug = true; 
    dbug.enable();
    //if( window.location.href.indexOf("debug=true")>0 ) dbug.enable();
	}
}
