(function(){
	/*
	 * Videoplaza client-side JavaScript support code
	 * Copyright (c) 2008 by Videoplaza, www.videoplaza.com
	 * email: info@videoplaza.com
	 */
	var videoplaza_js_support = window.videoplaza_js_support = {
		/*
		 * === Initialization ============================================================
		 */
		COMPANION_BANNER_JAVASCRIPT: "COMPANION_BANNER_JAVASCRIPT",
		externalTrackingQueue: [],
		externalTrackingQueuePointer: 0,
		htmlCompanionZones: [],
		htmlCompanionZonesMap: {},
		emarfiMap: [],
		eventHandlers: {},
		callbacks: [],
		pluginConfig: {},
		init : function() {
			// Init externalTrackingQueue
			for (var i = 0; i < 10; i++) {
				this.externalTrackingQueue.push(undefined);
			}
			var req = "" + window.location;
			req = req.substring(req.lastIndexOf("/"), req.length);
			if (req.indexOf("#") != -1) {
				pluginConfigArray = req.substring(req.indexOf("#") + 1, req.length).split(";");
				for (var i in pluginConfigArray) {
					var name = pluginConfigArray[i].split("=")[0];
					var value = pluginConfigArray[i].split("=")[1];
					videoplaza_js_support.pluginConfig[name] = value;
				}
			}
		},
		/*
		 * === Flash Callbacks ===========================================================
		 */
		onPluginLoaded : function() {
			return videoplaza_js_support.pluginConfig;
		},
		
		load : function(src, id) {
		},
	
		show : function(banner) {
			this.loadHTMLZone(banner);
		},
		
		openWin : function(url) {
			window.open(url,"_blank","");
		},
		
		formSend : function(text) {
		 	videoplaza_js_support.getPlugin().sendTextToFlash(text);
		},
		
		externalTracker : function(url) {
			// don't mess with the urls for external tracking
			this.callImage(url);
		},
		
		// Event handling
		onEvent : function(event) {
			for (var handler in this.eventHandlers) {
				try { this.eventHandlers[handler](event) } catch(e) {};
			}
		},
		
		/*
		 * === Javascript API ============================================================
		 */

		registerEventHandler : function(handler) {
			// registration with the function itself as the key prevents 
			// duplicate handler registration of same handlers
			this.eventHandlers[handler] = handler;
		},
		
		/*
		 * === Banner functions ==========================================================
		 */

		loadHTMLZone : function(options) {
			var url = options.src;
			var elementId = options.zone_id;
			var zone = this.getHTMLZone(elementId);
			var method = options.zone_method;
			if (!zone) {
				return;
			}
			if (method == "INNER_HTML") {
				this.loadTpircs(url, function(data){
					zone.innerHTML = data.html;
				});
			} else if (method == "IFRAME") {
				this.loadEmarfi(url, zone);
			}
		},
		
		/*
		 * === Zone functions ===================================================================== 
		 */
		
		addHTMLZone: function(elementOrId, description, width, height) {
			var element;
			var elementId;
			if (elementOrId.constructor === String) {
				elementId = elementOrId;
				element = document.getElementById(elementOrId);
			} else if (elementOrId.id) {
				elementId = elementOrId.id;
				element = elementOrId;
			}
			if (element && elementId) {
				var zoneData = {type:this.COMPANION_BANNER_JAVASCRIPT, name:elementId, desc:description, width:width, height:height};
				var zoneMapData = {type:this.COMPANION_BANNER_JAVASCRIPT, name:elementId, element:element, desc:description, width:width, height:height};
				this.htmlCompanionZones.push(zoneData);
				this.htmlCompanionZonesMap[elementId] = zoneMapData;
			}
		},
		
		getHTMLZone : function(elementId) {
			var zone = this.htmlCompanionZonesMap[elementId];
			if (zone) {
				zone = zone.element;
			} else {
				zone = document.getElementById(elementId);
			}
			return zone;
		},

		getHTMLZones : function() {
			return this.getHTMLCompanionZones();
		},
		
		// Deprecated
		getHTMLCompanionZones : function() {
			return this.htmlCompanionZones;
		},
		
		// Used by AS2 because it is bad on encoding post requests ("&" gets encoded twice when calling xml.sendandload)
		postZones : function(post_url, post_string) {
			var keepOn = true;
			var xmlhttp=false;

			// Hack for IE
			/*@cc_on @*/
			/*@if (@_jscript_version >= 5)
				try {
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (E) {
						xmlhttp = false;
					}
				}
			@else
				xmlhttp = false;
			@end @*/
			
			if (!xmlhttp && typeof XMLHttpRequest != "undefined") {
			
				try {
			      xmlhttp = new XMLHttpRequest();
			    } catch (e) {
			      xmlhttp = false;
			    }
			
			}
		
			if (xmlhttp) {
				xmlhttp.open("POST", post_url, true);
				xmlhttp.setRequestHeader( 
				    "Content-Type", 
				    "application/x-www-form-urlencoded; charset=UTF-8" 
				); 
				xmlhttp.onreadystatechange = function() {
				  	if (xmlhttp.readyState==4) {
				  		resp_string = xmlhttp.responseText;
				  		videoplaza_js_support.formSend(resp_string);
				  	}
				}
				xmlhttp.send(post_string);
			}
			
		},
		
		/*
		 *  === Utilities ==========================================================================
		 */
		
		appendParameter : function(url, name, value) {
			var hasQuery = url.indexOf("?") > -1;
			return url + (hasQuery ? "&" : "?") + name + "=" + value;
		},
		
		callImage : function(url) {
			/*
			if (url.indexOf("${timestamp}") != -1) {
				var time = new Date();
				url = url.replace("${timestamp}", time.getTime());
			}*/
			
			var img = new Image();
			img.src = url;
			this.externalTrackingQueue[this.externalTrackingQueuePointer++] = img;
			this.externalTrackingQueuePointer %= 10;
		},

		evalReplace : function(url, context) {
			var result = url;
			var matches = url.match(/\$\{([^}]+)\}/g);
			if (matches.length <= 0)
				return result;
			// Start at i=1, since it contains the original string and not a match
			for (var i=0; i<matches.length;i++) {
				var replace = matches[i];
				var replacement = replace.substring(2, replace.length-1); // Removes ${ and }
				var value = false;
				if (context) {
					try { value = eval("context." + replacement); } catch(e) {}
				}
				if (!value) {
					try { value = eval(replacement); } catch(e) {}					
				}
				if (value) {
					result = result.replace(replace, value);
				}
			}
			return result;
		},

		loadHiddenEmarfi : function(src) {
			var e = document.createElement("if"+"ra"+"me");
			e.style.display = "none";
			e.width = "1px";
			e.height = "1px";
			e.src = src;
			document.body.appendChild(e);
		},

		loadEmarfi : function(src, element) {
            var width = src.match(/zwidth=(\d+)/)[1];
            var height = src.match(/zheight=(\d+)/)[1];;
            element.innerHTML = '<if'+'ra'+'me border="0" frameborder="0" src="'+src+'" scrolling="no" marginwidth="0" marginheight="0" hspace="0" vspace="0" width="'+width+'" height="'+height+'">'+'</if'+'ra'+'me>';
		},
		
		loadTpircs : function(url, callback) {
			if (!callback)
				return;
			// Append the call-back function name as a parameter
			var callbackUrl = this.appendParameter(url, "cf", "window.videoplaza_js_support.callbacks["+this.callbacks.length+"]");
			// Bind a call-back function to window so we can find it later
			this.callbacks.push(callback);
			var e = document.createElement("sc"+"ri"+"pt");
			e.src = callbackUrl;
			e.type = "text/javascript";
			document.body.appendChild(e);
		},
		
		/*
		 * Used by flash to know whether vpsupport is loaded or not.
		 */
		isHere : function() {
			return true;
		}
		
	};
	videoplaza_js_support.init();
})();