$(document).ready(fetchHSWIads);

function findAdZones(delimiter) {
    if (typeof(delimiter) == 'undefined') delimiter = '|';
    //find all the zones
	adZones = '';
	$('.hswiAd').sort(
		function(a,b){
			if($(a).attr("order") < $(b).attr("order")){
				return -1;
			}else if($(a).attr("order") > $(b).attr("order")) {
				return 1;
			}else{
				return 0;
			}
		}).each(
		function(){
			if (adZones.length > 0) adZones += delimiter;
			adZones += $(this).attr("zoneid")	
		});
	return adZones;
}

function fetchHSWIads(){
	// check if there are any adds to fill...
	if ($('.hswiAd').length > 0)
	{
		//lets build a URL
		adCallLocation = 'http://orion.netwebfarm.com/www/delivery/spc.php';
		adDisplayConf = Math.floor(Math.random()*99999999);
		charset = (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));
	
		//find all the zones
		adZones = findAdZones();
	
		//get the s variables from one on the zones
		adSource = $('.hswiAd:eq(0)').attr("source");
		// if it isn't closed with a ';', do so
		if (adSource.substr(adSource.length - 1) !== ';')
		{
			adSource += ';';
		}
		// add campaign id and referrer
		adSource += 'cid='+ getCampaignId( ".dailystrength.org" ) +';';
		adSource += 'refurl='+document.referrer.toLowerCase()+';';
	
		//put all the pieces together
	
		urlToGetAds = adCallLocation + "?zones=" + adZones + "&source=" + adSource + "&" + adSource.replace(/;/g, "&") + "&ref=" + document.location.href + "&charset=" + charset + "&loc=" + document.location.href + "&r=" + adDisplayConf 
	
		//get the ads ans start watching
		$.getScript(urlToGetAds, adtest)
	}
	
	return true;
}

function adtest(){
	placeHSWIads();
	return true;
	
}

function placeHSWIads(){
	if (typeof(waitForHSWIads) != 'undefined') clearTimeout(waitForHSWIads);
	if (typeof(OA_output) != "undefined"){
		$(".hswiAd").each(fillAdSpace);
	}else{	
		waitForHSWIads = setTimeout("adtest()", 500);
	}
}

function gimmieAdByZone(zoneid){
	return OA_output[zoneid];	
}

function fillAdSpace(){
	//we should probably make this work so no matter what data we get it will function
	if (OA_output[$(this).attr("zoneid")]){	
		
		//setup the j object
		//need to get the values somewhere most likely a comment inside the ad
		j = new Object();
		j.html = OA_output[$(this).attr("zoneid")];
		if (j.html.search(/pegasus.netwebfarm.com/i) > 0){
			j.contenttype = "local";
		}else{
			j.contenttype = "remote";
		}
		
		ad = $(this);
		
		var oac = parseCmds(j.html);
		
		//these should be the sizes from the ad
		if (oac.ad.getValue("positionsize")){
			j.width = oac.ad.getValue("positionsize")['x']
			j.height  = oac.ad.getValue("positionsize")['y']
		}
		else if (oac.zone.getValue("positionsize"))
		{
			j.width = oac.zone.getValue("positionsize")['x'];
			j.height = oac.zone.getValue("positionsize")['y'];
		}
		else
		{
			return;
		}
		
		if (oac.zone.get("positionsize")) { // see if we have a positionsize comment 
			// get our width and height from j.html 
			var pw = Number(oac.zone.getValue("positionsize")['x']);
			var ph = Number(oac.zone.getValue("positionsize")['y']);

			// set initial sizes 
			ad.width(pw)
			  .height(ph)
			  .parent()
			  	.width(pw)
			  	.height(ph); // set the parent div's size 
				
			// the banner height may be different 
			var bh = Number(j.height);
			var bw = Number(j.width);

			// if they are not equal, we need to setup the clip areas 

			if ((pw != bw) || (ph != bh)) {
				ad.attr("bw", bw)
				  .attr("bh", bh)
				  .attr("pw", pw)
				  .attr("ph", ph)
				  .mouseover(function(){
						$(this).css({'clip': 'rect(0px ' + $(this).attr('bw') + 'px ' + $(this).attr('bh') + 'px 0px)'});
						var off = $(this).offset();
						var offset = {'left':off.left, 
									  'top':off.top, 
									  'right':off.left + parseInt($(this).attr('bw')), 
									  'bottom': off.top + parseInt($(this).attr('bh'))};
						var adId = '#' + $(this).attr('id');

						$('#doc').bind('mousemove', function(e){
							if (e.clientX < offset.left || e.clientX > offset.right || e.clientY < offset.top || e.clientY > offset.bottom) {
								$(adId).trigger('mouseout');
								$(this).unbind('mousemove');
							}
						});

				  })
				  .mouseout(function(){
						$(this).css({'clip': 'rect(0px ' + $(this).attr('pw') + 'px ' + $(this).attr('ph') + 'px 0px)'});
				  })
				  .parent()
				  	.css("z-index", "101");
			}

		}else{ 
			// otherwise just use the ad size 
			if (j.width.length && j.height.length){
				ad.width(Number(j.width))
				  .height(Number(j.height))
				  .parent()
				  	.width(Number(j.width))
				  	.height(Number(j.height)); // set the parent div's size 
			}
		}

		// should we hide the ad. 
		if (oac.zone.get("type") == 'float' 
				|| oac.ad.get("trans")
				|| oac.zone.get("trans"))
			ad.hide();

		// do we need a close button 
		if(oac.zone.get("type") == 'float')
			ad.append('<div class="closefloat" style="width:' + j.width + 'px;">FECHAR</div>')
			  .parent()
				.removeClass("hswiAdContainer")
				.addClass("hswiFloatingAdContainer");

		// place the ad 
		if (j.contenttype == "remote")	{ //must be HTML
			//var adframeId = "frame-" + ad.attr("id");
			//ad.append('<iframe id="' + adframeId + '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="javascript:parent.gimmieAdByZone(' + $(this).attr("zoneid") + ')" height="' + j.height + '" width="' + j.width + '"></iframe>');

			var adframeId = "frame-" + ad.attr("id");
			ad.append('<iframe id="' + adframeId + '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="" height="' + j.height + '" width="' + j.width + '"></iframe>');
			adframe = $("#" + adframeId)[0].contentWindow;
			adframe.document.write('<html><head></head><body style="margin:0px;padding:0px;">');
			adframe.document.write(j.html);
			adframe.document.write('</body></html>');
			setTimeout('$("#' + adframeId + '")[0].contentWindow.document.close();', 10000);
		}else{
			ad.append(j.html);	
		}

			// if the ad isn't visible, we need to do something to make it that way
		if (ad.is(":hidden")){
			// if we have  show time we should automatically trigget the hide action
			var ah = (oac.ad.getValue("show"));

			// calculate how long to show the ad 
			var s = ((oac.ad.getValue("show")) ? oac.ad.getValue("show") * 1000 : 10000);

			// find possible transition
			var t = ((oac.ad.get("trans")) ? oac.ad.get("trans") : oac.zone.get("trans"));
			switch(t){
				case 'slide':
					// assign the right display for the close function 
					ad.children(".closefloat").click(function(){$(this).parent().parent().slideUp();});

					// create the display for the close function 
					tf = function(){if ($(this).is(":hidden")) $(this).slideDown("def", function(){if($(this).is(":visible")) setTimeout("$('#" + $(this).attr('id') + "').parent().slideUp()", s)});};
					break;
				case 'fade':
				default:
					// assign the right display for the close function 
					ad.children(".closefloat").click(function(){$(this).parent().parent().fadeOut();});

					// create the display for the close function 
					tf = function(){if ($(this).is(":hidden"))$(this).fadeIn("def", function(){ if($(this).is(":visible")) setTimeout("$('#" + $(this).attr('id') + "').parent().fadeOut()", s)});};
					break;	
			}

			/* need to make sure the load event for the window hasn't already fired.
		   		if it has, then go ahead a trigger the display */
			(typeof(adLoadComplete) != 'undefined') ? tf.call(ad) : ad.load(tf);
		}		
	}
}

/* OpenX Functions */

//Function to create a command set object.  This will parse all the commands found in
//txtToParse and store those commands in a command object set.
function parseCmds(txtToParse){
	var cmds = {zone:new openXCmd, ad:new openXCmd};
	re = /!--\s*(ZONE|AD):([^\-]*)\s*-->/g;
	if (txtToParse.match(re))
		$.each(txtToParse.match(re), function(){
			if (this.match(re)){
			if (jQuery.browser.safari || jQuery.browser.msie || ( typeof(re) != 'function' && typeof(re) != 'object') )
				re =  /!--\s*(ZONE|AD):([^\-]*)\s*-->/g;
			
				var res = re.exec(this);
				cmdtype = $.trim(res[1].toLowerCase());
				// Only read a zone command once 
				if (cmdtype != 'zone' || !cmds.zone.locked){
					$.each(res[2].toLowerCase().split(":"), function(){
						// seperate the values and commands 
						var v = /([^ \(]*)(\(?.*\)?)/.exec($.trim(this));
						v[2] = $.trim(v[2].replace(/^\((.*)\)$/, "$1"));

						if (v[2].match(/([0-9]+)x([0-9])/i)){ // check if any of the values are xy coordinates 
							v[2] = {x:v[2].split(/x/i)[0], y:v[2].split(/x/i)[1]}
						}else if(v[2].match(/([^ \(]+)(\(.*\))/)){ // see if the have sub parameters 
							var subi = v[2].match(/([^ \(]+)(\(.*\))/)
							v[2] = {};
							v[2][subi[1]]=subi[2].replace(/^\((.*)\)$/, "$1");
						}

						if (typeof(v[1]) != "undefined" && v[1].length > 0) cmds[cmdtype][v[1]] = v[2];
					});

					if (cmdtype.toLowerCase() == 'zone') cmds.zone.locked = true;
				}// end zone dup check 
			}
		});

	return cmds;
}

//Class definition for one individual command
function openXCmd(){
	// get the name of the value 
	this.get = function(r){
		switch(typeof(this[r])){
			case 'string':
				return this[r];
				break;
			case 'object':
				for (var i in this[r])
					return i;
				break;
			default:
				return null;	
		}
	}

	// get the actual value 
	this.getValue = function(r){return ((typeof(this[r]) != 'undefined') ? this[r] : null);}
}
