var adverts;
var bannerFeed;
var adTimer;

Adverts = function( ) {
  this.init( );
}

$.extend(Adverts.prototype, {
  items:   [],
  current: -1,

  init: function ( ) { },
  
  next: function( ) {
    if ( this.current == -1 ) {
      if ( this.items.length >= 0 ) {
        this.current = Math.floor( Math.random( ) * this.items.length );
      }
    } else {
      this.current = ( this.current + 1 < this.items.length ) ? this.current + 1 : 0;
    }
    
    return this.current;
  },
  
  currentItem: function( ) {
    return this.items[ this.current ];
  },
  
  nextItem: function( ) {
    return this.items[ this.next( ) ];
  },
  
  showNext: function( container ) {
    var adImage;
    var nextBanner;
    
    nextBanner = this.items[ this.next( ) ];
    container.append( nextBanner.toHTML( ) );
    
    adImage = $( container ).find( "img#adimage" );
    if ( adImage.length > 0 ) {
      adImage[0].src = nextBanner.src;
    }
  }
} );

Advert = function( ) {
  this.init( );
}

$.extend(Advert.prototype, {
  name:   '',
  src:    '',
  href:   '',
  alt:    '',
  type:   '',
  width:  '',
  height: '',
  
  init: function( ) { },
  
  toHTML: function( ) {
    switch( this.type ) {
      case "swf":
        return '<object id="adplayer_' + this.name + '" name="adplayer_' + this.name + '" type="application/x-shockwave-flash" height="' + this.height + '" width="' + this.width + '" data="' + this.src + '" wmode="opaque">'
             + '<param name="allowScriptAccess" value="always" />'
             + '<param name="quality" value="best" />'
             + '<param name="movie" value="' + this.src + '" />'
             + '<param name="scale" value="noborder" />'
             + '<param name="allowfullscreen" value="false" />'
             + '<param name="wmode" value="opaque" />'
             + this.alt
             + '</object>';
      default:
        return '<a href="' + this.href + '" target="_blank"><img id="adimage" alt="' + this.alt + '" /></a>';
    }
  }
} );

$(document).ready( function( ) {
  if ( $("#adverts").length > 0 ) {  
    $.getJSON( "/adverts/adverts.json", function( ads ) {
      bannerFeed = new Adverts( );
      
      $.each( ads, function( key, value ) {
        var newAd;
        
        newAd = new Advert( );
        newAd.name = key;
        $.extend( newAd, value );
        bannerFeed.items.push( newAd );
        
        if ( newAd.type !== "swf" ) {
          try {
            newAd.cached = new Image( ).src( newAd.src );
          } catch ( e ) { }
        }
      } );
      
      if ( bannerFeed.items.length <= 0 ) {
        clearInterval( adTimer );
        return;
      }
      
      adverts = $( "#adverts" );
      adverts.empty( );
      bannerFeed.showNext( adverts );
    } );
    
    adTimer = setInterval( function( ) {
      if ( adverts && ( $( adverts )[0].id === "adverts" ) ) {
        adverts.empty( );
        bannerFeed.showNext( adverts );
      }
    }, 15000 );
  }
} );
