/*
 * This library is a prerequisite to using the widget-incl script and should be
 * included prior to any inclusions of widget-incl.js. This library dynamically
 * includes any other third-party scripts needed by the widget scripting mechanism.
 * It also offers various utility functions used by the widget-incl script.
 *
 * See http://vegaspedia.vegas.com/index.php?n=Dev.WicketJSONResponseFilter
 */

// Cyllenius namespace
if (typeof(Cyllenius) == "undefined")
{
	Cyllenius = {
		host: document.getElementsByTagName("script")[document.getElementsByTagName("script").length-1].src,
		getDomainFromUrl: function(url) {
			var domainrx = new RegExp("^.*\//[^\/]*","i");
			return url.match(domainrx);
		},
		now: function(){
			return +new Date;
		},
		indexOf: function( elem, array ) {
			for ( var i = 0, length = array.length; i < length; i++ )
			// Use === because on IE, window == document
				if ( array[ i ] === elem )
					return i;

			return -1;
		},
		log: function(out) {
			if (typeof console != 'undefined')
				console.log(out);
			else
			{
				if (typeof Cyllenius.logs == 'undefined')
					Cyllenius.logs = [];
				Cyllenius.logs.push(out);
			}


		}
	}
}

Cyllenius.Widget = {
	isDebugging: false,
	debug: function(debugHtml)
	{
		if (typeof Cyllenius.Widget.$debugWrapper == 'undefined')
		{
			$("body").append("<div class='ajaxDebugWrapper'><div></div>AJAX debug <span id='debugClear' onclick='$(\"#debugClear ~ *\").remove();'>(clear)</span>:<div id=\"ajaxDebug\"></div></div>");
			Cyllenius.Widget.$debugWrapper = $(".ajaxDebugWrapper");
		}
		return Cyllenius.Widget.$debugWrapper.append(debugHtml);
	},
	ajaxSubmitsOverridden: false,
	afterDynamicLoadCallbacks: [],
	_overrideAjaxSubmits: function(insertTo)
	{
		if(!Cyllenius.Widget.ajaxSubmitsOverridden && "undefined" != typeof Wicket && "undefined" != typeof Wicket.Ajax)
		{
			Cyllenius.Widget.ajaxSubmitsOverridden = true;
			// Save a reference to hte Wicket createTransport method to revert to it after initial JSON request
			if ("undefined" == typeof Cyllenius.Widget.wicketCreateTransport)
				Cyllenius.Widget.wicketCreateTransport = Wicket.Ajax.createTransport;

			// Override the wicket AJAX methods in order to catch the success event after all resources are loaded
			if (typeof(wicketSubmitFormById) != "undefined")
			{
				if (typeof(Cyllenius.Widget.origWicketSubmitFormById) == "undefined")
				{
					Cyllenius.Widget.origWicketSubmitFormById = wicketSubmitFormById;
				}
				if (typeof(Cyllenius.Widget.origWicketSubmitForm) == "undefined")
				{
					Cyllenius.Widget.origWicketSubmitForm = wicketSubmitForm;
				}
				if (typeof(Cyllenius.Widget.origWicketAjaxPost) == "undefined")
				{
					Cyllenius.Widget.origWicketAjaxPost = wicketAjaxPost;
				}
				if (typeof(Cyllenius.Widget.origWicketAjaxGet) == "undefined")
				{
					Cyllenius.Widget.origWicketAjaxGet = wicketAjaxGet;
				}

				var onSuccess = function(successHandler){
					if (typeof(successHandler) != "undefined" && successHandler != null)
						successHandler();
					Cyllenius.Widget._overrideAjaxSubmits(insertTo);
					Cyllenius.Widget._executeCustomCallback(insertTo, 'onAfterDynamicLoad');
					// Need to clear Wicket AJAX transports, otherwise Wicket will try to reuse the last transport which is likely
					// not our JSON overriden transport.
					Wicket.Ajax.transports = [];
				}
				wicketSubmitFormById = function(formId, url, submitButton, successHandler, failureHandler, precondition, channel){
					Cyllenius.Widget.origWicketSubmitFormById(formId, url, submitButton, function(){onSuccess(successHandler)}, failureHandler, precondition, channel);
				}
				wicketSubmitForm = function(form, url, submitButton, successHandler, failureHandler, precondition, channel){
					Cyllenius.Widget.origWicketSubmitForm(form, url, submitButton, function(){onSuccess(successHandler)}, failureHandler, precondition, channel);
				}
				wicketAjaxPost = function(url, body, successHandler, failureHandler, precondition, channel){
					Cyllenius.Widget.origWicketAjaxPost(url, body, function(){onSuccess(successHandler)}, failureHandler, precondition, channel);
				}
				wicketAjaxGet = function(url, successHandler, failureHandler, precondition, channel){
					Cyllenius.Widget.origWicketAjaxGet(url, function(){onSuccess(successHandler)}, failureHandler, precondition, channel);
				}
			}
			Wicket.Ajax.createTransport = function(){
				var transport = {
						header: {},
						open: function(getOrPost, url, async){
							this.url = url;
						},
						setRequestHeader: function(attr, val){
							// JSON requests don't support setting headers, so we pass these
							// values as URL params and parse them in JSONResponseFilter
							this.header[attr] = val;
						},
						send: function(body){
							if (typeof(body) == "undefeined" || body == null)
								body = "nobody=true";
							for(attr in this.header)
							{
								body+=  (body.search("&$") != -1 ? "" : "&") + encodeURIComponent(attr) + "=" + encodeURIComponent(this.header[attr]);
							}
							$.getJSON(this.url + "&" + body + "&json=true&jsoncallback=?", function(data){
								transport.responseText = data.response;
								if (window.ActiveXObject) {
									// wicket expects a doc object in IE
									var xmldoc = new ActiveXObject("Microsoft.XMLDOM")
								    xmldoc.async="false";
								    xmldoc.loadXML(data.response);
									transport.responseXML = xmldoc;
								}
								else
									transport.responseXML = data.response;
								transport.readyState = 4;
								transport.status = "";
								transport.ajaxRedirectURL = data.ajaxRedirectURL;
								transport.hasFeedback = data.hasFeedback;
								transport.onreadystatechange();

								if (typeof(data.ajaxRedirectURL) == "undefined" || data.ajaxRedirectURL == null || data.ajaxRedirectURL == "")
								{
									// Set back to wicket createTransport so that we don't request wicket resources using JSON.
									Cyllenius.Widget.ajaxSubmitsOverridden = false;
									Wicket.Ajax.createTransport = Cyllenius.Widget.wicketCreateTransport;
								}
							});
						},
						getResponseHeader: function(attr){
							if (attr == 'Ajax-Location' && typeof(transport.ajaxRedirectURL) != 'undefined')
							{
								return transport.ajaxRedirectURL;
							}
							else
								return null;
						},
						onreadystatechange: function(){},
						abort: function(){}
					};
				return transport;
			};
		}
	},
	_onAfterDynamicLoad: function(callback)
	{
		Cyllenius.Widget.afterDynamicLoadCallbacks.push(callback);
	},
	_processAfterDynamicLoadCallbacks: function()
	{
		while(fn = Cyllenius.Widget.afterDynamicLoadCallbacks.shift())
		{
			if (Cyllenius.Widget.isDebugging)Cyllenius.Widget.debug("<div>Calling: <span style='color: green;'>" + fn.toString() + "</span></div>");
			if ('function' == typeof(fn) ) fn();
		}
		if (Cyllenius.Widget.isDebugging)Cyllenius.Widget.debug("<hr/>");
	},
	/*
	 * Note that overriding FORM submits will work better when using a Wicket
	 * QueryStringCodingStrategy. If using a coding strategy where parameters are
	 * coded to the path, Wicket can have problems due to the form being submitted
	 * with a GET and all params appended to the URL via a query string.
	 */
	_overrideSubmits: function(insertTo)
	{
		Cyllenius.Widget._executeCustomCallback(insertTo, "onBeforeOverrideSubmits");

		var goNoGo = false;

		$("#" + insertTo + " form").submit( function() {
			Cyllenius.Widget._executeCustomCallback(insertTo, "onBeforeJSONFormSubmit", this);
			$.ajax({
				url: $(this).attr("action").replace(/(.*IFormSubmitListener::\/).*/, "$1"),
				type: "GET",
				async: false,
				dataType: "jsonp",
				data: $(this).serialize() + "&JSONFormSubmit=true",
				jsonp: "json=true&jsoncallback",
				form: this,
				success: function(data) {
					if (data.hasFeedback)
					{
						Cyllenius.Widget.ajaxSubmitsOverridden = false;
						$('#' + insertTo).append("<script>Cyllenius.Widget._executeCustomCallback('" + insertTo + "', 'onAfterJSONFormHasFeedback', $('#" + this.form.id + "')[0]);Cyllenius.Widget._onAfterDynamicLoad(function(){Cyllenius.Widget._overrideSubmits('" + insertTo + "');Cyllenius.Widget._overrideAjaxSubmits('" + insertTo + "');Cyllenius.Widget._executeCustomCallback('" + insertTo + "', 'onAfterDynamicLoad');});<\/script>").html(data.response);
						goNoGo = false;
					}
					else if (data.redirectURL)
					{
						// Using setTimeout so back button works in FF.
						setTimeout('location.href="' + data.redirectURL + '"', 0);
					}
					else
					{
						goNoGo = true;
					}
					Cyllenius.Widget._executeCustomCallback(insertTo, "onAfterJSONFormSuccess", this.form);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					Cyllenius.Widget._executeCustomCallback(insertTo, "onJSONFormError", this.form, errorThrown)
				}
			});
			return goNoGo;
		});
	},
	_onAfterInitialLoad: function(insertTo)
	{
		Cyllenius.Widget._executeCustomCallback(insertTo, "onAfterInitialLoad");
	},
	_executeCustomCallback: function(insertTo, callbackName, ctx, args)
	{
		// If callback script overrides
		if (insertTo in Cyllenius.Widget &&
			callbackName in Cyllenius.Widget[insertTo])
		{
			return Cyllenius.Widget[insertTo][callbackName].apply(ctx, args || []);
		}
	},
	loadWidget: function(script)
	{
		if ("undefined" == typeof $(script).attr("widgetIncluded"))
		{
			var widgetUrl =  $(script).attr("widget");
			var insertTo = $(script).attr("insertTo");
			var server = Cyllenius.getDomainFromUrl(script.src) || window.location.protocol + "//" + window.location.host;

			var callbacksrc = $(script).attr("callbacksrc");
			if ("undefined" != typeof callbacksrc)
			{
				callbacksrc = (callbacksrc.indexOf("/") == 0 ? callbacksrc : "/" + callbacksrc)
				Cyllenius.Includer.includeJavaScript(callbacksrc, function(){
					doAjaxLoad(insertTo, widgetUrl, server);
				});
			}
			else
				doAjaxLoad(insertTo, widgetUrl, server);

			$(script).attr("widgetIncluded", "1");
		}

		function doAjaxLoad(insertTo, widgetUrl, server)
		{
			modifiedUrl = Cyllenius.Widget._executeCustomCallback(insertTo, "onBeforeInitialLoad", null, [widgetUrl]);
			if (modifiedUrl)
				widgetUrl = modifiedUrl;

			$.ajax({
				url: server + (widgetUrl.indexOf("/") == 0 ? widgetUrl : "/" + widgetUrl),
				type: "GET",
				async: false,
				dataType: "jsonp",
				cache: true,
				jsonp: "json=true&jsoncallback",
				success: function(data) {
					var $insertTo = $('#' + insertTo); 
					$insertTo.append("<script>Cyllenius.Widget._onAfterDynamicLoad(function(){Cyllenius.Widget._overrideSubmits('" + insertTo + "');Cyllenius.Widget._overrideAjaxSubmits('" + insertTo + "');Cyllenius.Widget._executeCustomCallback('" + insertTo + "', 'onAfterDynamicLoad');Cyllenius.Widget._onAfterInitialLoad('" + insertTo + "');});<\/script>").html(data.response);
					Cyllenius.Widget.numWidgetsLoading--;
					// GW - 4/1/2010 since this is dynamically added HTML, need to let TL know about change
					if ($insertTo.length > 0) VDCtoTL.tlProcessNode($insertTo[0]);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				  alert(errorThrown);
				}
			});
		}
	}
}

Cyllenius.Includer = {
	loading: [],
	loaded: [],
	readyCallbacks: [],
	includeJavaScript: function(jsFile, onloadCallback, cache){
		var head = document.getElementsByTagName("head")[0];
		var script = document.createElement("script");

		if (cache === false)
		{
			var ts = Cyllenius.now();
			// try replacing _= if it is there
			var ret = jsFile.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
			// if nothing was replaced, add timestamp to the end
			jsFile = ret + ((ret == jsFile) ? (jsFile.match(/\?/) ? "&" : "?") + "_=" + ts : "");
		}

		var domain = Cyllenius.getDomainFromUrl(Cyllenius.host);
		if ((jsFile.indexOf("http://") == 0 || jsFile.indexOf("https://") == 0) || domain == null)
			script.src = jsFile;
		else
			script.src = domain + jsFile;

		this.loading.push(script.src);

		// Handle Script loading
		var done = false;

		// Attach handlers for all browsers
		script.onload = script.onreadystatechange = function(){
			if ( !done && (!this.readyState ||
					this.readyState == "loaded" || this.readyState == "complete") ) {
				done = true;
				if (typeof onloadCallback != 'undefined')
					onloadCallback();
				Cyllenius.Includer.loaded.push(Cyllenius.Includer.loading.splice(Cyllenius.indexOf(this.src, Cyllenius.Includer.loading)[0], 1));
				if (Cyllenius.Includer.loading.length == 0)
				{
					while(Cyllenius.Includer.readyCallbacks.length > 0)
					{
						Cyllenius.Includer.readyCallbacks.shift()();
					}
				}
				head.removeChild( script );
			}
		};

		head.appendChild(script);

		// We handle everything using the script element injection
		return undefined;
 	},
 	onRequestedScriptsLoaded: function(callback){
 		if (this.loading.length == 0)
			callback();
		else
			this.readyCallbacks.push(callback);
 	}
}

Cyllenius.Includer.includeJavaScript('/common/js/jquery/jquery-core.js', function(){
	$().ready(function(){
		if (Cyllenius.Widget.isDebugging)Cyllenius.Widget.debug().ajaxSuccess(function(evt, request, settings){
			$(this).append("<div>" + jQuery.active + " Successful request for " + settings.url + " " + settings.async + "</div>");
		});

		$(document).ajaxStop(function(){
			if (Cyllenius.Widget.isDebugging)Cyllenius.Widget.debug("<hr/><div>Callbacks after all scripts loaded via AJAX: " + Cyllenius.Widget.afterDynamicLoadCallbacks.length + "</div>");
			Cyllenius.Widget._processAfterDynamicLoadCallbacks();

			if (Cyllenius.Widget.isDebugging)Cyllenius.Widget.debug("<div><span style='color: navy;'>Number of widgets loading: " + Cyllenius.Widget.numWidgetsLoading + "</span></div>");
			if (Cyllenius.Widget.numWidgetsLoading == 0)
			{
				// reset the ready function
				if (Cyllenius.Widget.isDebugging)Cyllenius.Widget.debug("<div><span style='color: red;'>Resetting ready function...</span></div>");
				jQuery.fn.extend({
					ready: jQuery.fn.jqready
				});
			}
		});

		/*
		 * Overriding jQuery.ready for support when a page is loaded via a JSON/AJAX
		 * request. The _onAfterDynamicLoad function maintains an array of callback
		 * functions that are to be executed after an entire page/widget is
		 * dynamically loaded via a JSON request. If any $().ready functions existed
		 * on the AJAX loaded widget they will be delayed until all dynamically
		 * included scripts on the page get loaded. The above ajaxStop handles
		 * firing of the callbacks which can be added by using $().ready on the AJAX
		 * loaded page.
		 */
		jQuery.fn.extend({
			jqready: jQuery.fn.ready
		});
		jQuery.fn.extend({
			ready: Cyllenius.Widget._onAfterDynamicLoad
		});

		/*
		 * This is a hack to override bad jQuery behavior. The jQuery.ajax function
		 * checks if the dynamically loaded script src has the same domain as the
		 * current location. If so then it uses an XMLHttpRequest to load the
		 * script which causes synchronous script loading, which we rely on, to
		 * malfunction. So we reevaluate the ajax function after setting a scoped
		 * location variable with a host that will never be equal to the script
		 * host.
		 *
		 * jQuery 1.4 mappings:
		 *
		 * jQuery = c
		 * jsre = O
		 * now = K
		 * jsc = qb
		 * rurl = vb
		 * rquery = ma
		 * window = A
		 * document = s
		 * undefined = w
		 * rts = ub
		 *
		 * jQuery 1.4.1 mappings:
		 *
		 * jQuery = c
		 * jsre = N
		 * now = J
		 * jsc = pb
		 * rurl = ub
		 * rquery = ja
		 * window = z
		 * document = r
		 * undefined = v
		 * rts = tb
		 */
		var srcUrl = $("script[widget]:first").attr("src");
		var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec(srcUrl);
		if (parts == null || ('undefined' == typeof parts[2] || parts[2] == location.host))
			eval("var location={host: \"lame_hack\",protocol:window.location.protocol};N = /=\\?(&|$)/;ub = /^(\\w+:)?\\/\\/([^\\/?#]+)/;ja = /\\?/;tb = /(\\?|&)_=.*?(&|$)/;now=Cyllenius.now;pb=Cyllenius.now();z=window;r=document;v=undefined;c=jQuery;jQuery.ajax=" + jQuery.ajax.toString());

		Cyllenius.Widget.numWidgetsLoading = 0;
		$("script[widget]").each(function(){
			Cyllenius.Widget.numWidgetsLoading++;
			Cyllenius.Widget.loadWidget(this);
		});
	});

});
// setting window.loaded because because the wicket-event js does a
// document.write in IE otherwise, which doesn't work when loaded via AJAX
window.loaded = true;
// Including wicket-event JS so we can insure it is loaded prior to
// wicket-ajax.js.
Cyllenius.Includer.includeJavaScript('/mytrip/app/resources/org.apache.wicket.markup.html.WicketEventReference/wicket-event.js');
// Cyllenius.Includer.includeJavaScript('/mytrip/app/resources/org.apache.wicket.ajax.WicketAjaxReference/wicket-ajax.js');

//GW - adding TL facade in the cases where only the widget lib is included
//TeaLeaf facade
window.VDCtoTL = function () {
	
	var TLexists = function () {
		return window.TeaLeaf != null && window.TeaLeaf != 'undefined' && window.TeaLeaf != undefined;
	};
	
	return {
		tlQueueKey : function (e) {
			if (!e) e = window.event;
			if (TLexists() && TeaLeaf.Client && TeaLeaf.Client.tlQueueKey) 
				TeaLeaf.Client.tlQueueKey(e);
		},
	
		tlAddEvent : function (e) {
			if (!e) e = window.event;
			if (TLexists() && TeaLeaf.Client && TeaLeaf.Client.tlAddEvent)
				TeaLeaf.Client.tlAddEvent(e);
		},
	
		tlProcessNode : function (el) {
			if (TLexists() && TeaLeaf.Client && TeaLeaf.Client.tlProcessNode)
				TeaLeaf.Client.tlProcessNode(el);
		}
	};
}();