var ViewComponent = Class.create();

var scripts;
var preloads;
var srcs;
var html;
var loadedscripts;

Object.extend(Object.extend(ViewComponent.prototype, EventDispatcher.prototype),
				{
					initialize : function(container){
						
						this.buildInterface(container);
						this.createListener();
						
					
					},
					buildInterface : function(container){
						
						this.container = $(container);
					
					},
					createListener : function(){
						
						this.serviceHandle = this.handleService.bind(this);
					
					},
					handleService : function(eAja){
						
						this.dispatchEvent("beforeChange", this.container);

						// Remove old scripts from header
						if (scripts.length > 0)
						{
							for (i = 0; i < scripts.length; i++)
							{
								$$('head')[0].removeChild(scripts[i]);
							}
							scripts = [];
						}

						// Parse string for <script> src="" tags, ITIS, and append then to HTML head
						parts = eAja.responseText.split('<script');

						srcs = [];
						preloads = [];
						j = 0;
						for (i = 2; i < (parts.length + 2); i++)
						{
							if (parts[(i - 2)].indexOf('"text/javascript" src="') >= 0)
							{
								// This is a part that CONTAINS the script tag and all html that follows, before the next script tag

								// Strip down to the js src file uri
								srcs[j] = parts[(i - 2)].split('src="')[1].split('"')[0];

								// Append the script to the HTML head
								script = new Element('script', {'type': 'text/javascript', 'src': srcs[j]}); 
								$$('head')[0].appendChild(script);
								scripts[scripts.length] = script;

								// Begin monitoring the loading of the current script file
								preloads[j] = new Image(1,1);
								preloads[j].src = srcs[j];

								j++;
							}
						}

						html = eAja.responseText;
						this.finishLoading((eAja.containerid != '' ? eAja.containerid : this.container.id), new Date().getTime());
					},
					
					finishLoading : function(containerid, starttime)
					{
						loadedscripts = 0;

						for (i = 0; i < preloads.length; i++)
						{
							if (preloads[i].complete) loadedscripts++;
						}

						if (loadedscripts == preloads.length || (new Date().getTime() - starttime) > 3000) // Give up after 3 seconds and load anyways... This is a cheap way to get around IE6 not registering the .complete value for non-image Image Objects, even if they do in fact load into memory.
						{
							// Parse string for <script> tags that contain raw script, ITIS, and run them
							for (i = 0; i < html.extractScripts().length; i++)
							{
								if (html.extractScripts()[i] != '' && html.extractScripts()[i] != null)
								{
									eval(html.extractScripts()[i]);
								}

							}

							$(containerid).innerHTML = html;		
							view.dispatchEvent("afterChange", this.container);			
						}else{
							// Wait and retry
							window.setTimeout('view.finishLoading(\''+containerid+'\', \''+starttime+'\')', 500);
						}
					}
				}
			);