var userAgent = window.navigator.userAgent
var isIE = (window.navigator.userAgent.indexOf("MSIE") != -1);
var isFirefox = (window.navigator.userAgent.indexOf("Firefox") != -1);
var isIE6 = (parseFloat(userAgent.substring(userAgent.indexOf("MSIE ") + 5)) <= 6);
var isIE7 = (window.navigator.userAgent.indexOf("MSIE 7") != -1);
var isSafari = (navigator.userAgent.indexOf("Safari") > 0);

var var_dump = (typeof(console) == 'undefined' || isSafari) ? function (obj) 
{
	if (isSafari) console.log(Object.toJSON(obj))

	return true;

} : console.log;

PeriodicalExecuter.prototype.registerCallback = function() {
  this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
}

PeriodicalExecuter.prototype.stop = function() {
  clearInterval(this.intervalID);
}



String.prototype.trim = function () {
	  return this.replace(/^\s*/, "").replace(/\s*$/, "");
}




if (typeof(UI) != 'undefined')
	UI.defaultWM.options.blurredWindowsDontReceiveEvents = true;



Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // update the request counter
    Ajax.activeRequestCount--;
};

/*
Ajax.Responders.register({
onCreate: function() {
	if (Ajax.activeRequestCount > 0)
		Ajax.Request.abort();


	var_dump("# of request is "+Ajax.activeRequestCount);
	//if($('indicator1') && Ajax.activeRequestCount>0)
	//$('indicator1').show();
	//
	//
},
onComplete: function() {
	//if($('indicator1') && Ajax.activeRequestCount==0)
	//$('indicator1').hide();
},
onUninitialized: function() {
	//if($('indicator1') && Ajax.activeRequestCount==0)
	//$('indicator1').hide();
}
});
*/


UI.Window.addMethods({
	set: function(html) {

		this.setContent('<div id="ajax-loader">Loading your request, <br>please hold...</div>');

		var options = this.options;

		if (! options.url)
		{
			this.setContent(html);

			document.fire('rapid:update', {trigger: this.content.select('form'), content: html});

			return this;
		}

		var options = Object.extend({
			method: "GET",
			evalScripts: true,
			onComplete: function(request) 
			{                

					var me = this;
					var html = request.responseText;

					this.observe('shown', function () {

var_dump('shown');


					me.content.style.visibility = 'hidden';

					me.setSize(options.width, options.height)
						.setPosition(options.top, options.left)          
						.setContent(html);

						});

											
					//$('ajax-loader').fade();


					document.fire('rapid:update');
					this.fire('content');

					
			}.bind(this)
		}, this.options);
							
		new Ajax.Request(options.url, options);                    
		
		return this;
	}
});




Effect.BlindLeft = function(element) {
  return Effect.BlindUp(element, Object.extend({
    scaleX: true, scaleY: false
  }, arguments[1] || {}));
};

Effect.BlindRight = function(element) {
  return new Effect.Parallel([
    Effect.BlindUp(element, { scaleX: true, scaleY: false, sync: true }),
      new Effect.Move(element, { sync: true, x: $(element).getWidth(), y: 0 })
    ], arguments[1] || {});
  };


var  Dispatcher = Dispatch = Class.create(new Ajax.Base());
Dispatcher.prototype = {

	initialize: function (url, options)
	{
		this.options = options || {};
		hostsplit = window.location.host.split('.');
		this.host = hostsplit[hostsplit.length -2 ];
		this.form = null;
		this.timeout = this.timeoutMax;
		this.timeoutMax = 2;

		this.options = Object.extend({}, options);
		//this.setOptions(options);

    if (! this.options.callback) this.options.callback = null;

		this.errorClass = this.options.error || 'rapid-error';

    if (typeof(url) == 'object' && url.tagName == 'FORM')
    {
    	this.form = url;
    	this.options.parameters = Object.extend(Form.serialize(this.form, true), this.options.parameters);
    	this.options.replace    = this.form.parentNode;
			this.options.method 		= 'post';
			
    	this.dispatch((this.options.url) ? this.options.url : this.form.action);

    } else
    if (typeof(url) == 'object') // weird json access check
    {
    	this.access(url);

    } else
    if (typeof(url) == 'string')
    {
			this.dispatch(url);
    }

	},

	scrollIntoView: function (node)
	{


		if (0)
		{

			if (replace)
			{


				/*
					 replace.update(request.responseText);
					 var offset = replace.cumulativeScrollOffset();
					 var size = replace.getDimensions();

					 var y = (document.body.cumulativeScrollOffset()[1] - size.height) + 300;


					 var scroll = replace.getScrollDimensions();

					 window.scrollTo(0, y);
					 */
				/*  This works ...it only needs one condition then it will be perfect
						var box = replace;
						while(! box.hasClassName('box_white')) {
						box = box.up();
						}
						box.up().scrollTo();
						*/

				//	return;

			}

			/*
				 if (window.location.href == rapid.location.getInstruction(rapid.location.previousURL).href)
				 if (replace = $(rapid.location.previousReplace))
				 replace.update(request.responseText);
				 */

		} else
		{

		}




	},

	dispatch: function (url)
	{
		rapid.location.busy = true;

		var form = this.form;
		var options = this.options;
		var errorClass = this.errorClass;


		options.onComplete = function (request)
		{
			rapid.location.busy = false;

			var json = {};
			var data = '';
			
			if (request.headerJSON)
				json = request.headerJSON;

			if (request.responseText)
				data = request.responseText.toString();

			if (redirect = request.getHeader('Redirect'))
			{
				window.top.location.href = redirect;
				return;
			}

			var replace = Try.these(
				function () { return $(options.replace); },
				function () { return rapid.location.defaultReplace; }
			) || false;

			if (typeof(window[this.host]) == 'object')
			{
				base = window[this.host];

				//if (typeof(base[options.callback]) == 'undefined' || ! base[options.callback] == 'function')
				//
				
				if (! options.callback || typeof(base[options.callback]) != 'function' 
				&& (options.callback && typeof(window[options.callback.split('.')[0]][options.callback.split('.')[1]]) != 'function'))
				{


					if (request.request.parameters.forward == 'true')
					{
						window.scrollTo(0,0);
						if (replace && data) replace.update(data);
						document.fire('rapid:update', {trigger:options.trigger, content:data});
					}

				} else
				if ( typeof(json.errors) == 'undefined')
				{
					window.scrollTo(0,0);

					if (options.callback && options.callback.indexOf('.') > -1)
					{
						var cbsplits = options.callback.split('.');
						var cbfile = cbsplits[0];
						var cbcall = cbsplits[1];

						outcome = window[cbfile][cbcall](options.event, request, options);

					} else
					{
						outcome = base[options.callback](options.event, request, options);
					}

					if (outcome)
					{
						if (replace && data) 
						{
							replace.update(data);
							document.fire('rapid:update', {trigger:options.trigger, content:data});
						}

					} else
					if (outcome == null) 
					{

						if (replace && data) 
						{
							replace.update(data);
							document.fire('rapid:update', {trigger:options.trigger, content:data});
						}


					} else
					{

					}	
				}

			} else
			if (replace)
			{
					replace.update(data);
					document.fire('rapid:update', {trigger:options.trigger, content:data});
			}

			data.evalScripts();

			/*
			setTimeout(function () {
				eval(data.extractScripts().toString());
			}, 300);
			*/


/*
			$$('a.trigger').each(function (node)
			{
				node.href = node.href.substring(node.href.indexOf('#rf'));			
			});
			
			if (replace.getStyle('display') == 'none')
			{
				new Effect.Appear(replace, { queue: { position:'front', scope:'replace' } });        
			}
*/

			$A(document.getElementsByClassName(errorClass)).each(function(error)
			{
						error.parentNode.removeChild(error);
			});

			//options.parameters = null;

			if (form && typeof json.errors != 'undefined')
			{
					var done = {};
					var errors = json.errors;	
					var elements = form.getElements(); 
					var min = null;
					var indexes = [];

					document.fire('rapid:update', {trigger:form});

					elements.each(function (fnode, index) 
					{
						var next = fnode.next();

						var name = fnode.getAttribute('name');

						if (typeof(errors[name]) == 'undefined' || done[name]) return $continue;

						if (! done[name]) done[name] = true;

						if (fnode.type.toUpperCase() == 'RADIO' || fnode.type.toUpperCase() == 'HIDDEN' || fnode.type.toUpperCase() == 'CHECKBOX')
							fnode.insert({ before : '<div style="top: 38px" align="right" class="' + errorClass + '"><strong>' + errors[name] + '</strong></div>'});
						else	
							fnode.insert({ after : '<div style="" align="right" class="' + errorClass + '"><strong>' + errors[name] + '</strong></div>'});

						if (min == null && fnode.getAttribute('tabIndex'))
							min = fnode.getAttribute('tabindex');

					});


					elements.each(function (input, index)
					{
						if (input.type == 'hidden')
							return $continue;

						if (input.getAttribute('tabindex') == min)
						{
							setTimeout(function () {
								// removed 
								//try { input.focus().activate(); } catch (e) {}
								}, 300);
						}

					});
				

			} else
			{


				/*
				if (replace = $(options.replace))
				{
						replace.update(request.responseText);

				}

				if (replace.down().id == replace.id)
				{
					replace.up().update(replace.innerHTML);
				} */

				/*
				if (h2 = $(options.replace).select('h1', 'h2'))
				{
					if (h2.length)
					{
						h2[0].innerHTML = $(options.trigger).innerHTML;

						new Effect.Appear(h2[0], {duration: 0.1});
					}
				}

				if (replace.getStyle('display') == 'none')
					new Effect.Appear($(options.replace), {duration: 0.1});
				*/
			}

/*
			if (json != null && typeof json.notices != 'undefined')
			{
					$H(json.notices).each(function(node)
					{
							var name = node[0];

							var value = node[1];
							var element = $(name);

							if (element) // && ! Element.hasClassName(element.nextSibling, 'rapid-error'))
							{
									try
									{

											element.innerHTML = value;

											new Effect.Appear(element,      { queue: { position:'front',    scope:'notices' } });
											new Effect.Fade(element,        { queue: { delay:5.0, position:'end',   scope:'notices' } });

									} catch (e) { }

							}

					});

			} 

*/

		}.bindAsEventListener(this);


		if (! options.parameters)
			options.parameters = {};

		if (! options.method)
			options.method = 'get';

		if (this.form)
			options.method = 'post';


		new Ajax.Request(url, options);
	}

}

var RapidLocation = Class.create();
RapidLocation.prototype =
{
  child: null,
	title: null,
	currentURL: null,
  previousURL: null,
  previousReplace: null,
	defaultReplace: 'replace',
  triggers: {},
	busy: false,
	initialize: function (base)
	{
		rapid.location = this;

		this.child = base;

		this.title = this.child.title;

		this.previousURL = window.location.href;
		this.dest = window.location.protocol + '//' + window.location.host;
		this.defaultReplace = base.replace || 'replace';

		document.observe('rapid:update', function (event)
		{
			var forms = $A($$('form'));

			var focus;

			if (event.memo.length)
				$A(event.memo).each(function (form) {
					if (form.tagName == 'FORM')
					{
						// For each input element on the form  
						$A($(form).getInputs()).each(function(input) {  

						  if (! input.hasClassName('readOnlyInput')) {  
								focus = input;

						   	throw $break;  
						  }  
						});  

						forms.push($(form));
					}
				});

			forms = forms.reverse();

			forms.each (function (form) {
				var inputs = form.getElements();

				var offset = '10' + parseInt(Math.random() * 100);

				inputs.each(function (input, index) {
					if (input.type == 'hidden') return $continue;

					var index = parseInt(offset) + parseInt(index);

					input.setAttribute('tabindex', index);
				});

			});

			if (focus) 
				setTimeout(function () {
					// removed by the big man
					//try { focus.focus().activate(); } catch (e) {}
				}, 300);

		});

		/*
    document.observe('mousedown', function (event)
    {
			var trigger = event.element();
			var form = false;
			var callback;

			if (trigger.tagName == 'A' && trigger.down()
				&& trigger.down().tagName == 'IMG') 
			trigger = trigger.down();

			if (event.button == 2 && trigger.tagName == 'IMG')
			{
			var_dump(trigger);
				alert('Please do not take our images.');
				event.stop();
			}
		});
		*/

    document.observe('click', function (event)
    {
      var trigger = this.getTrigger(event);

			dump(trigger + '\n');

			if (isFirefox && ! event.isLeftClick()) return;

			var form = false;

			if (trigger.tagName == 'INPUT' && trigger.type.toUpperCase() == 'SUBMIT')
			{
				while (trigger.tagName != 'FORM')
				trigger = trigger.up();

				form = true;
			}

			var callback = this.getTriggerCallback(trigger);

			event.stop();

			if (! form && trigger.className.indexOf('trigger') == -1) return;

			var href = rapid.location.getLink(trigger);

			var inst = rapid.location.getInstruction(href);

			if (! href && callback)
				inst.callback = callback;

			if (event.ctrlKey && event.isLeftClick())
			{
				window.open(href);

				return;
			} 
			
			/*
			if (this.currentURL != inst.link)
			{
				if (typeof(this.child.changeTitle) != 'undefined')
					this.child.changeTitle(inst.link);


				rapid.location.currentURL = inst.link

			} else
			{
				//return;
			}
			*/

			inst.event = event;

			document.fire('rapid:preupdate', {trigger: inst.trigger, data: inst});

			if (! (inst.callback && inst.callback.indexOf('.') != -1) 
			&& (typeof(base[inst.callback]) == 'undefined' 
			|| ! base[inst.callback] == 'function'))
			{
				this.previousURL = inst.href;

				if (href)
					window.location.href = href;
				inst.trigger = trigger;
				rapid.location.getDocument(inst, event);
			

			} else
			{
				var outcome = false;

				inst.trigger = trigger;


				if (inst.callback && inst.callback.indexOf('.') > -1)
				{
					var cbsplits = inst.callback.split('.');
					var cbfile = cbsplits[0];
					var cbcall = cbsplits[1];

					if (! $('source-' + cbfile))
					{
						var headID = document.getElementsByTagName("head")[0];         
						var newScript = document.createElement('script');
						newScript.id = 'source-' + cbfile;
						newScript.type = 'text/javascript';
						newScript.onload = function ()
						{
							if (! window[cbfile] && window[cbfile][cbcall])
								throw cbfile + ":" + cbcall + " trigger is undefined";

							outcome = window[cbfile][cbcall](event, null, inst);

							rapid.location.determine(form, outcome, event, inst);
						}

						newScript.src = '/assets/javascripts/' + cbfile + '.js';

						headID.appendChild(newScript);

					} else
					{
						if (! window[cbfile] && window[cbfile][cbcall])
							throw cbfile + ":" + cbcall + " trigger is undefined";

						outcome = window[cbfile][cbcall](event, null, inst);

						this.determine(form, outcome, event, inst);
					}

				}  else
				{
					if (! base[inst.callback])
						throw inst.callback + " trigger is undefined";

					outcome = base[inst.callback](event, null, inst);

					this.determine(form, outcome, event, inst);

				}


			}

    }.bindAsEventListener(this));

		var inst = this.getInstruction(this.previousURL);

		setTimeout(function(){ this.handleDocumentChange(inst); }.bind(this), 100);
	},

	isFormTrigger: function (trigger)
	{

		return false;
	},

  getTriggerCallback: function (trigger)
  {
		switch (trigger.tagName)
		{
			case 'FORM':
			case 'INPUT':
			case 'BUTTON':
			case 'A':
				if (trigger.className.indexOf('trigger') > -1)
					return trigger.className.substring(trigger.className.indexOf('trigger')+8).split(' ')[0].trim();

				break;
						
			case 'SPAN':
				if (trigger.hasClassName('pointer') && trigger.className.indexOf('trigger') > -1)
					return trigger.className.substring(trigger.className.indexOf('trigger')+8).split(' ')[0].trim();

				break;

			default:
		}

		if (trigger.hasClassName('trigger') &&  !inst.callback)
				inst.callback = rapid.location.defaultReplace;

		return null;
	},

	getTrigger: function (event)
	{
		var trigger = event.element();

		if (trigger.tagName == 'IMG' && trigger.up()
				&& trigger.up().tagName == 'A') 
			trigger = trigger.up();

		if (trigger.tagName == 'SPAN' && trigger.up()
				&& trigger.up().tagName == 'A') 
			trigger = trigger.up();

		return trigger;
	},

	click: function (name)
	{


	},

	determine: function (form, outcome, event, inst)
 	{

				inst.forward = true;

				if (outcome)
				{
					this.previousURL = inst.href;

					if (typeof(outcome) == 'object')
						inst = outcome;

					if (form) return new Dispatcher(inst.trigger, inst); 

					if (inst.href)
						window.location.href = inst.href;
					else
						rapid.location.getDocument(inst, event);

				} else
				if (outcome == null) 
				{
					inst.forward = false;
					if (form) return new Dispatcher(inst.trigger, inst); 
					rapid.location.getDocument(inst, event);
				} else
				{
					if (form) return new Dispatcher(inst.trigger, inst); 
				}	

	},

	getLink: function (trigger)
	{
		var classes = $A(trigger.classNames());

		var callback;

		//var href = trigger.href.split('#rf:')[0];
		if (! trigger.href)
			trigger.href = '';

		/* new test way */
		var href = typeof(trigger.action) != 'undefined';

		href = (! href) ? trigger.href : trigger.action;

		/* original way 
		var href = typeof(trigger.href) != 'undefined';

		href = (! href) ? trigger.action : trigger.href;
		*/

		if (! href) return null;

		if (href.indexOf('http') > -1) href = href.split(rapid.location.dest)[1];

		if (href.indexOf('rf:') > -1)
			href = href.substring(href.lastIndexOf('rf:')+3).split(':')[0];

		if (classes.join('').indexOf('replace-') == -1)
			href += ':' + this.defaultReplace;
		else
		  classes.each(function (node) {
				if (! node) return;

				if(node.indexOf('replace-') > -1)
				{
				href += ':' + node.split('replace-')[1];

				return $break;
				}
				});

		classes.each(function (node) {
				if (node.indexOf('trigger-') > -1)
				{
				href += ':' + node.split('trigger-')[1];

				return $break;

				/*	
						trigger.onclick = function ()
						{
						if (typeof(window[window.location.host.split('.')[0]]) == 'object')
						{
						var name = node.split('trigger-')[1];
						var obj = window[window.location.host.split('.')[0]];

						if (typeof(obj[name]) == 'function') 
						callback = obj[name];
						}

						return false;

						};
						*/
				}


		});

		if (href)
			return '#rf:' + href;

		return false;

	},
	
	clickDocument: function  (inst)
	{


		return true;
/*

		if (! trigger.hasClassName('rf'))
		{
			//trigger.href = href;
			//trigger.addClassName('rf');
			href = '';
		}	 else
		{
			href = '';

			if (trigger.href.indexOf('page=+') > -1)
			{
				var page = parseInt(trigger.href.match(/page=\+([0-9])+/)[1]) || 1;

				href = trigger.href.replace(/page=\+[0-9]+/, 'page=+' + (page+1));	

				trigger.href = href;

			} else
				if (trigger.href.indexOf('page=-') > -1)
				{
					//var page = parseInt(trigger.href.match(/page=\-([0-9])+/)[1]) || 1;

					if (page > 1)
					{
						href = trigger.href.replace(/page=\-[0-9]+/, 'page=-' + (page-1));	

						trigger.href = href;
					}
				}

		}

*/



		/*
			 if (inst.link)
			 {
			 rapid.location.triggers[inst.link] = trigger;

			 inst.callback = callback;

			 rapid.location.getDocument(inst, true);
			 }

			 if (inst.link
			 && inst.link.substr(inst.link.indexOf(':')+1) == trigger.href.substring(node.href.lastIndexOf(':/')+1))
			 {
			 if (node.up().tagName == 'LI')
			 node.up().addClassName('selected');
			 else
			 node.addClassName('selected');
			 }
			 */

	},

	getDocument: function (inst, event)
	{

		if (this.busy) return;
		if (! inst) return;

		var link = inst.link;
		var href = inst.href;
		var replace = inst.replace;
		var callback = inst.callback;
		var triggers = this.triggers;
		var trigger = inst.trigger;

      var afterFinish = function ()
      {
				if (replace)
        	this.previousReplace = replace;

				pinst = this.getInstruction(this.previousURL);

        if (! trigger && this.previousURL)
        {
					trigger = this.triggers[pinst.link];
				}

				if (1)
        {
//					console.log(inst.forward)

					//this.previousURL = href;

          new Dispatcher(link,
          {
						parameters: {forward: (inst.forward) ? 'true' : 'false'},
            replace: replace || this.defaultReplace,
            callback: callback,
            trigger: trigger,
						event: event
          });

          if (trigger && trigger.up())
          {

/*
						var li = (trigger.up().tagName == 'LI') ? true : false;
						
            var list = trigger.up().up().select((li) ? 'li' : 'a');

            var node = (li) ? trigger.up() : trigger;

            list.each(function (node) { node.removeClassName('selected'); });

            node.addClassName('selected');
*/
          }
        }

      }.bindAsEventListener(this);

		if (link)
		{
				afterFinish();

				if ($(replace) && $(replace).innerHTML)
				{
					var size = $(replace).getDimensions();
					var pos = $(replace).cumulativeOffset();

					var id = $(replace).id;
					var rep = $(replace);

					/*
					var style = "position: relative; top: 0px; left: 0px; width: #{width}px; "
							.interpolate({top: pos[0], left: pos[1], width: size.width, height: size.height + 11});

					if (! rep.hasClassName('replace'))
					{
						rep.id = '';
						rep = rep.wrap('div', {id: id, class: 'replace', style: style});
					}*/

			
					if (0)
					new Animator({
						duration: 100,
						interval: 20,
						onComplete: function() { 

							$(rep).down().update('<div style="padding-top: ' + parseInt((size.height/2) - 10)  
								+ 'px;" class="loading">--- Loading ---</div>');


							  new Animator({
									duration: 200,
									interval: 50,
									onComplete: function() {

									afterFinish();
										

								}}).addSubject(new NumericalStyleSubject(rep, 'opacity', 0.0, 1)).play();


						}}).addSubject(new NumericalStyleSubject(rep, 'opacity', 1, 0.3)).play();


				}


      if ($(this.previousReplace) && typeof(Effect) != 'undefined')
      {
	// buggey?	
	//			Effect.toggle($(this.previousReplace), 'slide', {afterFinish: afterFinish, duration: 0.7, limit:2, scope: 'bars'} );
	
        //new Effect.Fade($(this.previousReplace), { afterFinish: afterFinish, duration: 0.1 });
      } else
      {
    //    afterFinish();
      }

		}

	},

	getInstruction: function (href)
	{
		var link, replace, callback;
		
		if (! href)
		{
			href = window.location.href;
		}

		link = href.split("#rf:")[1] || '/';

		if (link && link.indexOf(':') > -1)
		{
			var splits = link.split(':');

			if (splits.length > 2)
				callback = link.split(':')[2]

			if (splits.length > 1)
				replace = link.split(':')[1]

			if (splits.length > 0)
				link = link.split(':')[0]
		}


		return {href:href, link:link, replace:replace, callback:callback, forward: true };
	},

	handleDocumentChange: function (inst)
	{
		var load = (inst) ? true : false;
		var inst = (load) ? inst : this.getInstruction();
		var href = inst.href;
		var link = inst.link;
		//delete inst;

		if (load && link == '/')
		{
			this.previousURL = href;
		}

		var run = (load && (link != '/')) || (! load && this.previousURL != href);
		//var run = (load && (link != '/' && link != document.location.pathname)) || (! load && this.previousURL != href);
		//var run = load || (! load && this.previousURL != href);
		//

    if (run)
    {

			//if (link == '/') inst.link =  href.split(rapid.location.dest)[1];

			this.previousURL = inst.href;

			if (this.currentURL != inst.link)
			{
				if (typeof(this.child.changeTitle) != 'undefined')
					this.child.changeTitle(inst.link);

				rapid.location.currentURL = inst.link

			} else
			{
				//return;
			}




      this.getDocument(inst);
		}

		/*
		var href = '#rf:' + href.split(dest)[1];
		if (this.previousURL)
				if (! run)
		if (! run && href.substring(href.lastIndexOf(':/')+2) != this.previousURL.substring(this.previousURL.lastIndexOf(':/')+2))
				run = true;

		*/

		/*

		if (! link)
		{
			if (! run && this.previousURL.indexOf('#rf') > -1)
				if (! href.split('#rf')[1])
					run = true;
		//	if (href.indexOf('#rf') > -1 && this.previousURL.indexOf('#rf') > -1)
		} 

		if (link)
		{

			if (this.previousURL && this.previousURL.indexOf('#rf') > -1)
			{
				if (this.previousURL.split('#rf:')[1].split(':')[0] != link)
				{
				//	run = true;
				}
			} else
			{
				run = false;
			}
	

				
		}		


		if (run)
		{
				this.getDocument(inst);
		}
*/

		setTimeout(function(){ this.handleDocumentChange(); }.bind(this), 100);
	}


}







  var Rapid = {};

  Rapid.Options = Class.create(UI.Options,
  {
    getLayout: function (type)
    {
      retval = null;

      var manager = (this.manager) ? this.manager : UI.defaultWM;

      switch (type)
      {
        default:
          retval =
          {
            wm:      manager,
            windows: manager['windows'](),
            area:    manager['getViewport']().getDimensions()
          };

          retval.rows = retval.cols = Math.ceil(Math.sqrt(retval.windows.length));

          retval.last = retval.cols - (retval.rows * retval.cols - retval.windows.length);

          if (retval.last < 0)
          {
            retval.rows--;
            retval.last = retval.cols - (retval.rows * retval.cols - retval.windows.length);
          }

      }

      return retval;
    },

    serialize: function ()
    {
      var layout  = this.getLayout();
      var wm      = layout.wm;
      var windows = layout.windows;
      var layouts = [];
      var shadows = this.getShadows();

      var retval  = null;

      windows.each(function(win, num)
      {
        var bounds = win.getBounds();

        layouts[num] =
        {
          top:    parseInt(bounds.top)    - shadows.top,
          left:   parseInt(bounds.left)   - shadows.left,
          width:  parseInt(bounds.width)  + shadows.width,
          height: parseInt(bounds.height) + shadows.height
        };

      });

      retval =
      {
        layout: layouts,
        area:   layout.area
      };

      return Object.toJSON(retval);
    },

    options:
    {
      version: '0.1',
      first: 'Pedram', last: 'Nimreezi', email: 'pedram@rapidframework.org'
    }
  });


  Rapid.Alert = Class.create(Rapid.Options,
  {
    initialize: function (options)
    {
      this.setOptions(options)

    },

    setContent: function (win, content)
    {
      win.setContent(win.content.innerHTML + content
        + '<p><hr style="-moz-opacity: 0.4; opacity: 0.4; filter: alpha(opacity=40);"/></p>');
    },

    activate: function ()
    {
      var self = Rapid.Alert.instance;

      var content = arguments[0];

      var layout  = self.getLayout();
      var windows = layout.windows;

      windows.each(function (win, num)
      {
        if (win.element.id == 'rapid_alert-lightbox')
        {
          //$('overlay').style.zIndex = win.lastZIndex - 1;
          //win.element.style.zIndex = win.lastZIndex;
          self.setContent(win, content)

          win.show(true).center();
        }
      });
    },

    prepareIE: function(height, overflow){
      bod = document.getElementsByTagName('body')[0];
      bod.style.height = height;
      bod.style.overflow = overflow;

      htm = document.getElementsByTagName('html')[0];
      htm.style.height = height;
      htm.style.overflow = overflow;
    },

    options:
    {
      version: '0.1'
    }

  });







/*
Rapid.Alert.instance = new Rapid.Alert();
var alert = Rapid.Alert.instance.activate.bindAsEventListener(this);
*/

var rapid = {};
document.observe('dom:loaded', function ()
{

document.fire('rapid:update');

var isParentWindow = window.parent.top == this ? true : false;
var isAdminWindow = (isParentWindow && window.location.search.substring(1).indexOf('rapid=admin') > -1) ? true : false

if (isAdminWindow)
{
	var doc = window.location.pathname;
	var host = window.location.hostname;
	document.observe('dom:loaded', function () {

    var win = new UI.URLWindow(
    {
				name: 'admin',
        theme: 'bluelighting',
        bottom: 400,
        width: 919,
				minWidth: 690,
        height: 510,
        shadow: true,
        url: '/rapid/admin/index/url=' + doc.substring(1)
    }).setHeader('Rapid Framework Admin for ' + host).center().show();


	});
}


		//if (! isAdminWindow)
	  //	 rapid.location = new RapidLocation();

		//EventSelectors.start(Rules);

		if (! Prototype.Browser.MobileSafari)
		{
			// remove flash
		}

		var version = parseFloat(navigator.appVersion.split('MSIE')[1]);

		if ((version >= 5.5) && (version < 7) && (document.body.filters))
		{
/*
			$$('.png-fix').each(function(poElement)
			{
*/
				// if IE5.5+ on win32, then display PNGs with AlphaImageLoader

/*
				var cBGImg = poElement.currentStyle.backgroundImage;
				var cImage = cBGImg.substring(cBGImg.indexOf('"') + 1, cBGImg.lastIndexOf('"'));

				poElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + cImage + "', sizingMethod='scale')";
				poElement.style.backgroundImage = "none";
*/




			//});

		}

});

		function pngFix () {
				for(var i=0; i<document.images.length; i++) {
					var img = document.images[i]

/*
					var cBGImg = poElement.currentStyle.backgroundImage;
					var cImage = cBGImg.substring(cBGImg.indexOf('"') + 1, cBGImg.lastIndexOf('"'));

					poElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + cImage + "', sizingMethod='scale')";
					poElement.style.backgroundImage = "none";
*/
					var imgName = img.src.toUpperCase()
					if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
						var imgID = (img.id) ? "id='" + img.id + "' " : ""
						var imgClass = (img.className) ? "class='" + img.className + "' " : ""
						var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
						var imgStyle = "display:inline-block;" + img.style.cssText 
						if (img.align == "left") imgStyle = "float:left;" + imgStyle
						if (img.align == "right") imgStyle = "float:right;" + imgStyle
						if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle		
						var strNewHTML = "<span " + imgID + imgClass + imgTitle
						+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
						+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
						+ "(src=\'" + img.src + "\', sizingMethod='image');\"></span>" 
						img.outerHTML = strNewHTML
//alert(strNewHTML);
						i = i-1
					}
				}
		}

		if (isIE6)
			document.observe('dom:loaded', pngFix)
							.observe('rapid:update', pngFix);
