/**
 * Loads a doubleclick ad into a div using an iframe
 * @version 1.0
 * @notes 
 */

$.widget("ui.dartad", {
	_init: function(){
		// Check for required plugins and options
		if(!(this.options.siteID)) throw "siteID must be defined in $.dartad options"

		// Create the ad container
		this._init();
	},
	destroy: function(){
		$.widget.prototype.apply(this, arguments); // Default destroy
	},
	load: function(){
		this._load();
	},
	refresh: function(){
		this._refresh();
	},
	/**
	 * Renders an ad to the element
	 */
	_init: function(){
		this._setSize();
		var iframe = document.createElement("iframe");
		iframe.src = this._generateUrl();
		iframe.style.width = this.options.width + "px";
		iframe.style.height = this.options.height + "px";
		iframe.setAttribute("toolbar", "no");
		iframe.setAttribute("bgcolor", "transparent");
		iframe.setAttribute("scrolling", "no");
		iframe.setAttribute("frameBorder", "0");
		$(this.element).get(0).appendChild(iframe);
	},
	/**
	 * Refreshes an existing ad
	 */
	_refresh: function(){
		var iframe = $(this.element).find("iframe");
		iframe.attr("src", this._generateUrl());
	},
	/**
	 * Generates the ad and image url requests to doubleclick
	 * @params type The type can be either "img" or "link"
	 * @returns url The generated url
	 */
	_generateUrl : function(){
		// Prepare random number to make url unique. This prevents caching.
		
		// Establish ad url (http://ad.doubleclick.net/jump/nwswk.cqfive/zonename;sz=0x0;ord=1234)
		var url = "http://ad.doubleclick.net/adi/" + this.options.siteID + "/";
		//url += this.options.width + "x" + this.options.height;
		//url += ";sz=" + this.options.width + "x" + this.options.height;
		url += this.options.keyvalue;
		url += ";bgcolor=0x000000";
		url += ";sz=" + this.options.size;
		url += ";tile=" + this.options.tile;
		url += ";ord=" + this.options.ord;
		return url;
	},
	/**
	 * Sets the max width and height of iframe from requested sizes
	 */
	_setSize : function (){
		var sizes = this.options.size.split(',');
		for(var i = 0; i < sizes.length; i++) {
			this.options.width = Math.max(sizes[i].split('x')[0], this.options.width);
			this.options.height = Math.max(sizes[i].split('x')[1], this.options.height);
		}
	}

});

$.extend($.ui.dartad, {
	getter: "",
	defaults: {
		siteID: "",
		size: "",
		keyvalue: "",
		width: 0,
		height: 0,
		tile: 0,
		ord: Math.random().toString()
	}
});
