/*
 * this sexy script is written by Andres Gonzalez
 
 
 */

/*
 *  Create namespace object if it doesn't exist
 */
if (typeof RWR == "undefined" || !RWR) {
  var RWR = {};
  RWR.ads = {};
} else if (!CIESIN.ads) {
  RWR.ads = {};
}

/*
 * define pacakges, which contain ads to rotate
 */
RWR.ads.packages = {
  /*
   * package
   */
  'banner-top':
  [
    {
      title: "Modern Metro Studios",
      img: '/imgs/ads/momet_digital_swp.gif',
      link: 'http://www.modernmetro.com/',
      linktype: 'web'
    }
  ],
  /*
   * package
   */
  'banner-bottom':
  [
    {
      title: "Hudson House",
      img: '/imgs/ads/hudson_house_lrg.gif',
      link: 'http://www.hudsonhousenyack.com/',
      linktype: 'web'
    },
    {
      title: "The King and I Thai Restaurant",
      img: '/imgs/ads/kingandi_swp.gif',
      link: 'http://www.kingandinyack.com/',
      linktype: 'web'
    },
    {
      title: "Marcello's",
      img: '/imgs/ads/marcello_swp.gif',
      link: 'http://www.marcellosgroup.com/',
      linktype: 'web'
    }
  ]
};

/*
 * preload images
 */
for(var pkg in RWR.ads.packages){
    if(RWR.ads.packages.hasOwnProperty(pkg)){
      $(RWR.ads.packages[pkg]).each(function(){
        $('<img/>')[0].src = this.img; // magic.
      });
    }
  }

/*
 * this is where the magic happens.
 */
RWR.ads.swap = function(elem, pkg){
  var random = Math.floor(Math.random()*pkg.length);
  var ad = pkg[random];
  var timeout;
  var wait = 9000; // 9 secs.
  var img_elem;
  
  elem.attr('title', ad.title);
  elem.children().attr('alt', ad.title);
  elem.children().attr('src', ad.img);
  
  switch(ad.linktype){
    case 'web':
      elem.attr('href', ad.link);
	  elem.attr('target', '_blank');
      break;
    case 'email':
      elem.attr('href', 'mailto:'+ad.link);
      break;
    default:
        if(console){
          console.warn("wrong value for link type. only 'web' or 'email' are accepted");
        }
      break; 
  }
  
  timeout = setTimeout(function(){
    RWR.ads.swap(elem,pkg);
  }, wait);
};

RWR.ads.init = function(){
  for(var pkg in RWR.ads.packages){
    if(RWR.ads.packages.hasOwnProperty(pkg)){
      RWR.ads.swap($('#'+pkg), RWR.ads.packages[pkg]);
    }
  }
}

$(document).ready(RWR.ads.init); // ready-set-go!
