
var QWebPage = QWebControl.extend('QWebPage', {

	url : "",
	call_stack : [],
	controls_index : {},
	base_href : "",
	request_url : "",
	instance_id : null,
	_event_callback_js_data : null,
	
	MaxZIndex : 100000001,
	
	// this is the constructor
	init : function() // can add params
	{
		this._super();
		// this.viewstate = {}; viewstate to the webpage
		
		jQuery(this).bind("ev_jsParamsUpdated", function () 
			{
				var page_title = this.getJsParam("page_title");
				var page_description = this.getJsParam("page_description");
				var page_keywords = this.getJsParam("page_keywords");
				
				if (page_title)
					this.setPageTitle(page_title);
				if (page_description)
					this.setPageDescription(page_description);
				if (page_keywords)
					this.setPageKeywords(page_keywords);

				// alert(page_title);
			});
	},
	
	load : function()
	{
		// works to this point // alert('loading page');
	},
	
	_internalAfterLoad : function()
	{
		// alert("_internalAfterLoad");
		var ref_this = this;

		jQuery.history.init(function (hash) {ref_this._internalHashChanged(hash);});
		/* jQuery(window).hashchange(function() { ref_this._internalHashChanged(location.hash); });
        ref_this._internalHashChanged(location.hash); */
		
		jQuery("#___qWebAjaxLoader").css({"position" : "fixed", "padding" : "2px 6px 2px 6px",
			"border-right" : "1px solid #727218", "border-bottom" : "1px solid #727218", 
			"top" : "0px", "left" : "0", "background-color" : "#F6F6D0", "width" : "72px", "height" : "16px"});
			
		jQuery("#___qWebAjaxLoader img").css({"display" : "block", "float" : "right", "width" : "16px", "height" : "16px"});
		jQuery("#___qWebAjaxLoader div").css({"display" : "block", "float" : "left", "width" : "52px", "font-weight" : "bold", "font-size" : "11px", "line-height" : "14px"});
	},
	
	showLoadingIcon : function()
	{
		jQuery("#___qWebAjaxLoader").show();
	},
	
	hideLoadingIcon : function()
	{
		jQuery("#___qWebAjaxLoader").hide();
	},
	
	_internalHashChanged : function (hash)
	{
		var ref_this = this;
		if (hash && (hash.length > 0))
		{
			// the hash has changed, we need to trigger the events specified
			var send_vars = "";
			var send_pos = 0;
			
			for (var i = 0; i < this.call_stack.length; i++)
			{
				if (send_pos > 0)
					send_vars += "&";
				send_vars += "__qwl" + send_pos + "=" + urlencode(this.call_stack[i]);
				send_pos++;
			}
	
			send_vars += "&__qajax=1&__qid=" + urlencode(this.instance_id);
			
			this.showLoadingIcon();
			
			jQuery.ajax({
				type: "POST",
				url: this.base_href + this.request_url + "?" + send_vars,
				data: {"___q" : hash},
				dataType : "text",
				success: function (msg) {
					try
					{
						eval(msg);
						ref_this.hideLoadingIcon();
					}
					catch (ex)
					{
						var err_msg;
						if (ex.message)
							err_msg = ex.message;
						else
							err_msg = ex;
	
						GetQWebPage().setDebugText(err_msg + 
							"<br/>\n<br/>\n<br/>\n================================================================================<br/>\n<br/>\n<br/>\n" + msg, 
							true);
							
						ref_this.hideLoadingIcon();
					}
				},
				error: function (request, textStatus, errorThrown) {
                    ref_this.hideLoadingIcon();
					alert(textStatus + " : " + request.status);
                }
			});
			// window.location = this.base_href + this.request_url + "?___q=" + hash;
		}
		this.onHashChanged(hash);
	},
	
	setHashInBrowser : function (hash)
	{
		// set the new hash but do not trigger any event
		jQuery.history.load(hash, true);
		
		this.onHashChanged(hash);
	},
	
	onHashChanged : function (hash)
	{
		
	},
	
	setHash : function (hash)
	{
		// set the new hash and trigger events
		jQuery.history.load(hash);
	},
	
	getHash : function ()
	{
		if (window.location.hash)
			return window.location.hash.replace(/^#/, '');
		else
			return null;
	},
	
	getPageLink : function (hash)
	{
		/*
		for (var x in window.location)
			alert(x + " : " + window.location[x]);
		var hash = this.getHash();
		if (hash && (hash.length > 0))
			return window.location.href + "#" + hash;
		else
		*/
		return window.location.href;
	},
	
	copyPageLink : function (hash)
	{
		var link = this.getPageLink();
		// jQuery.copy(link);
		alert(link);
	},
	
	replaceDomElement : function(element_id, html_text, rebuild_js)
	{
		if (element_id == this.fullId)
			jQuery("body").html(html_text);
		else
			jQuery('#' + element_id).before(html_text).remove();
	},
	
	getQWebControlById : function(element_id)
	{
		// alert(this.controls_index[element_id]);
		if (this.controls_index[element_id])
			return this.controls_index[element_id];
		return null;
	},
	
	addJsDynamically : function(file, attrs, wait_on_vars)
	{
		if (wait_on_vars)
		{
			for (var x = 0; x < wait_on_vars.length; x++)
			{
				if (window[wait_on_vars[x]] === undefined)
				{
					var ref_this = this;
					setTimeout(function () {ref_this.addJsDynamically(file, attrs, wait_on_vars)}, 100);
					return;
				}
			}
		}
		
		var script = document.createElement("script");
		script.type = "text/javascript";
		// load async for other domains : script.async = true;
		script.src = file;
		document.getElementsByTagName("head")[0].appendChild(script);
	},

	addCssDynamically : function(file, attrs)
	{
		var link = document.createElement("link");
		link.type = "text/css";
		link.rel = "stylesheet";
		link.href = file;
		document.getElementsByTagName("head")[0].appendChild(link);
	},

	addResourceDynamically : function(file, type, attrs, wait_on_vars)
	{
		if (type == "js")
			this.addJsDynamically(file, attrs, wait_on_vars);
		else if (type == "css")
			this.addCssDynamically(file, attrs);
		else
			throw "Unknown resource type : " + type;
		
	},
	
	removeResourceDynamically : function(file, type)
	{
		if (type == "css")
			this.removeCssDynamically(file);
		else
			throw "Unknown resource type : " + type;
	},

	removeCssDynamically : function(file)
	{
		var head = document.getElementsByTagName("head")[0];
		var links = head.getElementsByTagName("link");

		for (var i = 0; i < links.length; i++)
		{
			var href = links[i].getAttribute("href");
			if (href == file)
			{
				links[i].parentNode.removeChild(links[i]);
			}
		}
	},
	
	setDebugText : function (text, is_error)
	{
		var elem = jQuery("#QWebApp_DEBUG_DIV__");
		
		if (text)
		{
			elem.html(text);
			elem.show();
			
			if (is_error)
			{
				// {'background-color': '#ffe', 'border-left': '5px solid #ccc'}
				// {backgroundColor: '#ffe', borderLeft: '5px solid #ccc'}
				elem.css({"padding" : "10px", "background-color" : "white", "color" : "black"});
			}
		}
		else
			elem.hide();
	},
	
	isWebPage : function ()
	{
		return true;
	},
	
	manageEventCallbackJsData : function ()
	{
		if (this._event_callback_js_data)
		{
			for (var i = 0; i < this._event_callback_js_data.length; i++)
			{
				var event = this._event_callback_js_data[i];
				// id, type, params

				var element = null;
				if (!event[0])
					event[0] = this.className;
				else
					element = this.getQWebControlById(event[0]);
				if (element)
				{
					element.onAfterEvent(event[1], event[2]);
					// alert("onAfterEvent: " + event[0] + ":" + event[1] + " :: " + event[2]);
				}
				else
				{
					if (this.className == event[0])
						this.onAfterEvent(event[1], event[2]);
					else
					{
						var err_data = "";
						for (var x in event)
							err_data += x + ": " + event[x] + ";\n";
						alert("Error: manageEventCallbackJsData, Not found: \n" + err_data);
					}
				}
			}

			delete this._event_callback_js_data;
			this._event_callback_js_data = null;
		}
	},
	
	setPageTitle : function (page_title)
	{
		// jQuery("title", document.getElementsByTagName("head")[0]).html(page_title);
		document.title = page_title;
		// alert(document.title);
	},
	
	setPageDescription : function (page_description)
	{
		jQuery("meta[name=description]", document.getElementsByTagName("head")[0]).attr("content", page_description);
	},
	
	setPageKeywords : function (page_keywords)
	{
		jQuery("meta[name=keywords]", document.getElementsByTagName("head")[0]).attr("content", page_keywords);
	}
});


