 
var stradBaseURL = "http://richads.startribune.com/";
/**
 * @author Kelly Anderson
 */
var stradData = null;
var stradQueue = [];
var stradIsReady = false;
var adHolder = new Object;
var stradBeconQueue = new Array;

stjQuery(document).ready(function(){
	stradIsReady = true;
});

function placeAd(adID){
		stradData = null;
		var script_filename = stradBaseURL + 'd/getAdInfo.php?aid=' + adID;
		document.write("<script language=\"javascript\" type=\"text/javascript\" src=\"" + script_filename + "\"></script>");
}

function beconPop(){
	if(stradBeconQueue.length > 0){
		stjQuery("#vtimg").load(beconPop);
		stjQuery("#vtimg").attr("src", stradBeconQueue.shift());
	}
}

function executeAdQueue(){
	stjQuery.each(stradQueue, function(qIndex, qItem){
			placeAd(qItem);
	});
}

function drawAD(data){
		fullDeliveryString = "<div id=\"stradID"+ data.stradID +"\" class=\"expandableAD\">";
		stjQuery.each(data.items, function(i,item){
				if(!document.getElementById("vtimg" + data.stradID)){
					strBecon = "<img id=\"vtimg"  + data.stradID + "\" src=\"" + stradBaseURL + "adTrack/track.php?do=i&ad_id=" + data.stradID + "&creative_id=" + item.id + "\" style=\"border: none;\" />";
					document.write(strBecon);
				}
				curElement = stjQuery("<div id=\""+ item.container.id +"\"></div>");
				deliveryString = "";
				deliveryString += "<div id=\""+ item.container.id +"\" style=\""; 
				deliveryString += "position: " + item.container.position.dom_level + "; ";
				deliveryString += "width: " + item.container.width + "; ";
				deliveryString += "height: " + item.container.height + "; ";
				deliveryString += "overflow: visible; ";
				deliveryString += item.container.position.side + ": " + item.container.position.coordinate.x + "; ";
	 			deliveryString += item.container.position.vSide + ": " + item.container.position.coordinate.y + "; ";
				if(item.container.defaultVisible){
					deliveryString += "display: block; ";
				}else{
					deliveryString += "display: none; ";
				}				
				deliveryString += "\">";
				
				switch(item.content.type){
					case "swf":
						deliveryString += "<embed name=\"swf_" + item.container.id + "\" id=\"swf_" + item.container.id + "\" src=\"" + stradBaseURL + "c/" + item.content.src + "\" height=\"" + item.content.height + "\" width=\"" + item.content.width + "\" align=\"middle\" swliveconnect=\"true\" type=\"application/x-shockwave-flash\" flashvars=\" \"  pluginspage=\"http://www.adobe.com/go/getflashplayer\" allowscriptaccess=\"always\" quality=\"high\" wmode=\"transparent\" />";
						break;
					case "img":
						deliveryString += "<img src=\"" + stradBaseURL + "c/" + item.content.src + "\" style='border: none;' />";
						break;
				}
				insturmentationScript = "";
				
				adHolder[item.container.id] = new Object;
				adHolder[item.container.id].ad_id = data.stradID;
				adHolder[item.container.id].placementInfo = item;
				
				if(item.container.position.relative == "document"){
					insturmentationScript += "stjQuery(\"body\").prepend(stjQuery(\""+ item.container.id +"\").replaceWith(\"\"));";
				} 
				insturmentationScript += "\n";
				stjQuery.each(item.events, function(ei, event){
							if(event.handler == 'immediate'){
								insturmentationScript += "executeAction(stjQuery(\"#" + item.container.id + "\"), eval(" + stjQuery.toJSON(event) + "));\n";
							}else{
								insturmentationScript += "stjQuery(\"" + item.container.id + "\").bind(\"" + event.handler + "\", " + stjQuery.toJSON(event) + ", handleEvent ); \n"
							}
				});				
				stjQuery.each(data.events, function(ei, event){
							if(event.handler == 'immediate'){
								insturmentationScript += "executeAction(stjQuery(\"#" + event.target + "\"), eval(" + stjQuery.toJSON(event) + "));\n";
							}else{
								insturmentationScript += "stjQuery(\"#stradID" + data.stradID + "\").bind(\"" + event.handler + "\", " + stjQuery.toJSON(event) + ", handleEvent);\n";
							
							}
				});				
				
				deliveryString += "</div>";
				deliveryString = "<a href=\"" + stradBaseURL + "adTrack/track.php?do=c&ad_id=" + data.stradID + "&creative_id=" + item.id + "\" target=\"_blank\">" + deliveryString + "</a>";
				fullDeliveryString += deliveryString;
		});
	fullDeliveryString += "</div>";
	if(!document.getElementById("vtimg" + data.stradID)){
		document.write(strBecon);
	}
	document.write(fullDeliveryString);
	document.write("<script language=\"JavaScript\">" + insturmentationScript + "</script>");
}

function handleEvent(e){
		element = stjQuery("#" + e.data.target);
		executeAction(element, e.data);
}

function trackEvent(ad_id, item, event){
	var strTrackParams = "";
	if(strTrackParams.length < 1){
		strTrackParams += "?";
	}else{
		strTrackParams += "&";
	}
	
	if(event.action == "show"){
		strTrackParams += "do=i";
	}else{
		//strTrackParams += "do=c";
		return;
	}
	strTrackParams += "&ad_id=" + ad_id;
	if(event.targetCID){
		strTrackParams += "&creative_id=" + event.targetCID;
	}else{
		strTrackParams += "&creative_id=" + item.id;
	}

	if(item.actions[event.action].trackingEventID != null){
		strTrackParams += "&event_id=" + item.actions[event.action].trackingEventID;
	}	

	stjQuery("#vtimg"+ad_id).attr("src", stradBaseURL + "adTrack/track.php" + strTrackParams);
	

}

function executeAction(element, event){
		if(!element.attr("id")){
			return;
		}
		var elementData = adHolder[element.attr("id")].placementInfo;
		var curAction = elementData.actions[event.action];
		
		element.css(curAction.preCSS).animate({
						'background-color': element.css('background-color')
					}, curAction.delay).animate(curAction.cssParameters, curAction.duration, "linear", function(){
						element.css(curAction.postCSS)
					}
				);
		if(curAction.flashAction == "restart"){
			document.getElementById(elementData.content.id).StopPlay();
			document.getElementById(elementData.content.id).Rewind();
			document.getElementById(elementData.content.id).Play();
		}
		trackEvent(adHolder[element.attr("id")].ad_id, elementData, event);
}

/**
 * flashembed 1.0.0. Adobe Flash embedding script
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/flash-embed.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Version : 1.0.0 - Tue Feb 03 2009 10:48:14 GMT-0000 (GMT+00:00)
 */ 
(function() { 
		
/* http://code.google.com/p/swfobject/source/browse/tags/swfobject_2_1/src/swfobject.js */ 
		
//{{{ utility functions 
		
var jQ = typeof stjQuery == 'function';


// from "Pro JavaScript techniques" by John Resig
function isDomReady() {
	
	if (domReady.done)  { return false; }
	
	var d = document;
	if (d && d.getElementsByTagName && d.getElementById && d.body) {
		clearInterval(domReady.timer);
		domReady.timer = null;
		
		for (var i = 0; i < domReady.ready.length; i++) {
			domReady.ready[i].call();	
		}
		
		domReady.ready = null;
		domReady.done = true;
	} 
}

// if stjQuery is present, use it's more effective domReady method
var domReady = jQ ? stjQuery : function(f) {
	
	if (domReady.done) {
		return f();	
	}
	
	if (domReady.timer) {
		domReady.ready.push(f);	
		
	} else {
		domReady.ready = [f];
		domReady.timer = setInterval(isDomReady, 13);
	} 
};	


// override extend opts function 
function extend(to, from) {
	if (from) {
		for (key in from) {
			if (from.hasOwnProperty(key)) {
				to[key] = from[key];
			}
		}
	}
	
	return to;
}	


// JSON.asString() function
function asString(obj) {
	 
	switch (typeOf(obj)){
		case 'string':
			obj = obj.replace(new RegExp('(["\\\\])', 'g'), '\\$1');
			
			// flash does not handle %- characters well. transforms "50%" to "50pct" (a dirty hack, I admit)
			obj = obj.replace(/^\s?(\d+)%/, "$1pct");
			return '"' +obj+ '"';
			
		case 'array':
			return '['+ map(obj, function(el) {
				return asString(el);
			}).join(',') +']'; 
			
		case 'function':
			return '"function()"';
			
		case 'object':
			var str = [];
			for (var prop in obj) {
				if (obj.hasOwnProperty(prop)) {
					str.push('"'+prop+'":'+ asString(obj[prop]));
				}
			}
			return '{'+str.join(',')+'}';
	}
	
	// replace ' --> "  and remove spaces
	return String(obj).replace(/\s/g, " ").replace(/\'/g, "\"");
}


// private functions
function typeOf(obj) {
	if (obj === null || obj === undefined) { return false; }
	var type = typeof obj;
	return (type == 'object' && obj.push) ? 'array' : type;
}


// version 9 bugfix: (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function() {
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}

function map(arr, func) {
	var newArr = []; 
	for (var i in arr) {
		if (arr.hasOwnProperty(i)) {
			newArr[i] = func(arr[i]);
		}
	}
	return newArr;
}
	
function getHTML(p, c) {
	
	var ie = document.all;
	var html = '<object width="' +p.width+ '" height="' +p.height+ '"';
	
	// force id for IE or Flash API cannot be returned
	if (ie && !p.id) {
		p.id = "_" + ("" + Math.random()).substring(9);
	}
	
	if (p.id) {	
		html += ' id="' + p.id + '"';	
	}
	
	if (p.w3c || !ie) {
		html += ' data="' +p.src+ '" type="application/x-shockwave-flash"';		
	} else {
		html += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';	
	}
	
	html += '>'; 
	
	if (p.w3c || ie) {
		html += '<param name="movie" value="' +p.src+ '" />'; 	
	}

	// parameters
	var e = extend({}, p);	
	e.width = e.height = e.id = e.w3c = e.src = null;
	
	for (var k in e) {
		if (e[k] !== null) {
			html += '<param name="'+ k +'" value="'+ e[k] +'" />';
		}
	}	

	// flashvars
	var vars = "";
	
	if (c) {
		for (var key in c) {
			if (c[key] !== null) {
				vars += key +'='+ (typeof c[key] == 'object' ? asString(c[key]) : c[key]) + '&';
			}
		}
		vars = vars.substring(0, vars.length -1);
		html += '<param name="flashvars" value=\'' + vars + '\' />';
	}
	
	html += "</object>";	
	
	return html;

}

//}}}


function Flash(root, opts, flashvars) {
	
	var version = flashembed.getVersion(); 
	
	// API methods for callback
	extend(this, {
			
		getContainer: function() {
			return root;	
		},
		
		getConf: function() {
			return conf;	
		},
	
		getVersion: function() {
			return version;	
		},	
		
		getFlashvars: function() {
			return flashvars;	
		}, 
		
		getApi: function() {
			return root.firstChild;	
		}, 
		
		getHTML: function() {
			return getHTML(opts, flashvars);	
		}
		
	});

	// variables	
	var required = opts.version; 
	var express = opts.expressInstall;
	
	
	// everything ok -> generate OBJECT tag 
	var ok = !required || flashembed.isSupported(required);
	
	if (ok) {
		opts.onFail = opts.version = opts.expressInstall = null;
		root.innerHTML = getHTML(opts, flashvars);
		
	// fail #1. express install
	} else if (required && express && flashembed.isSupported([6,65])) {
		
		extend(opts, {src: express});
		
		flashvars = {
			MMredirectURL: location.href,
			MMplayerType: 'PlugIn',
			MMdoctitle: document.title
		};
		
		root.innerHTML = getHTML(opts, flashvars);	
		
	// fail #2. 
	} else { 
	
		// fail #2.1 custom content inside container
		if (root.innerHTML.replace(/\s/g, '') !== '') {
			// minor bug fixed here 08.04.2008 (thanks JRodman)
			
		
		// fail #2.2 default content
		} else {
			root.innerHTML = 
				"<h2>Flash version " + required + " or greater is required</h2>" + 
				"<h3>" + 
					(version[0] > 0 ? "Your version is " + version : "You have no flash plugin installed") +
				"</h3>" + 
				"<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer'>here</a></p>";
		}
	}
	
	// onFail
	if (!ok && opts.onFail) {
		var ret = opts.onFail.call(this);
		if (typeof ret == 'string') { root.innerHTML = ret; }	
	}
	
}

window.flashembed = function(root, conf, flashvars) { 
	
//{{{ construction
	
	// root must be found / loaded	
	if (typeof root == 'string') {
		var el = document.getElementById(root);
		if (el) {
			root = el;	
		} else {
			domReady(function() {
				flashembed(root, conf, flashvars);
			});
			return; 		
		} 
	}
	
	// not found
	if (!root) { return; }


	// setup opts
	var opts = {
		
		// very common opts
		width: '100%',
		height: '100%',		
		
		// flashembed defaults
		allowfullscreen: true,
		allowscriptaccess: 'always',
		quality: 'high',	
		
		
		// flashembed specific options
		version: null,
		onFail: null,
		expressInstall: null, 
		w3c: false
	};
	
	
	if (typeof conf == 'string') {
		conf = {src: conf};	
	}
	
	extend(opts, conf);		
	
	return new Flash(root, opts, flashvars);
	
//}}}
	
	
};


//{{{ static methods

extend(window.flashembed, {

	// returns arr[major, fix]
	getVersion: function() {
	
		var version = [0, 0];
		
		if (navigator.plugins && typeof navigator.plugins["Shockwave Flash"] == "object") {
			var _d = navigator.plugins["Shockwave Flash"].description;
			if (typeof _d != "undefined") {
				_d = _d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				var _m = parseInt(_d.replace(/^(.*)\..*$/, "$1"), 10);
				var _r = /r/.test(_d) ? parseInt(_d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
				version = [_m, _r];
			}
			
		} else if (window.ActiveXObject) {
			
			try { // avoid fp 6 crashes
				var _a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
				
			} catch(e) {
				try { 
					_a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
					version = [6, 0];
					_a.AllowScriptAccess = "always"; // throws if fp < 6.47 
					
				} catch(ee) {
					if (version[0] == 6) { return; }
				}
				try {
					_a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				} catch(eee) {
				
				}
				
			}
			
			if (typeof _a == "object") {
				_d = _a.GetVariable("$version"); // bugs in fp 6.21 / 6.23
				if (typeof _d != "undefined") {
					_d = _d.replace(/^\S+\s+(.*)$/, "$1").split(",");
					version = [parseInt(_d[0], 10), parseInt(_d[2], 10)];
				}
			}
		} 
		
		return version;
	},
	
	isSupported: function(version) {
		var now = flashembed.getVersion();
		var ret = (now[0] > version[0]) || (now[0] == version[0] && now[1] >= version[1]);			
		return ret;
	},
	
	domReady: domReady,
	
	// returns a String representation from JSON object 
	asString: asString,
	
	
	getHTML: getHTML
	
});

//}}}


// setup stjQuery support
if (jQ) {
	
	stjQuery.prototype.flashembed = function(conf, flashvars) { 
		return this.each(function() { 
			flashembed(this, conf, flashvars);
		});
	};

}

})();


