
(function( $ ){

  $.fn.adManager = function( options ) {  
	var sampleAds = new Array();
		
	
    var settings = {
      availableAds        : null,
      delay : 60000,
      startIndex:0
	  
    };
    
    
      // If options exist, lets merge them
      // with our default settings
      

      // Tooltip plugin code here
		return this.each(function(){
		if ( options ) { 
        $.extend( settings, options );
      }
		var me = this;
		
		me.dims = calculateSize(me);
		me.myAds=getSpecificAds(me.dims);
	//	console.log(dims);
	//	console.log(myAds);
		//$me.data("myAds");
		me.startIndex= Math.floor(Math.random()*me.myAds.length);
		switchAd(me);
		setInterval(function(m){switchAd(m);},120000,me);
		me.startIndex= Math.floor(Math.random()*me.myAds.length)
		setInterval(function(m){switchAd(m);},180000,me);
		me.startIndex= Math.floor(Math.random()*me.myAds.length)
		setInterval(function(m){switchAd(m);},240000,me);

    
	function calculateSize(obj){
		$obj = $(obj);
		var h =  $obj.height();
		var w = $obj.width();
		var size =  new Object();
		size.height=h;
		size.width = w;
		return size;
	}
	function getSpecificAds(obj){
		var specificAds = new Array();
		for(var i in settings.availableAds){
			if(settings.availableAds[i].height <= obj.height && settings.availableAds[i].width <= obj.width){
				specificAds.push(settings.availableAds[i]);
			}
		}
		return specificAds;
	
	}
	function switchAd(me){
		var ad = me.myAds;
		ad = ad[me.startIndex];
		me.startIndex++;
		if(me.startIndex == me.myAds.length)me.startIndex=0;
		var $obj = $(me);
		var $orig = $obj.html();
		var orig_size = me.dims;
		if(typeof ad != 'undefined'){
			$obj.animate({"width":2},1000);
			$obj.html(ad['html']);
			var height = Math.max(ad.height,orig_size.height);
			var width = Math.max(ad.width,orig_size.width);
			$obj.stop(true,true).animate({"height":ad.height,"width":width},1000);
		}
	}
	
	});
	
  };
})( jQuery );
