﻿var Cookies = {
	/*
		get( cookieName )
		Gets the value for the requested cookie, or returns null 
		when empty.
	*/
	get: function( name )
	{
		var re = new RegExp( "(\;|^)[^;]*(" + name + ")\=([^;]*)(;|$)" );
		var match = re.exec( document.cookie );
		return match != null ? match[ 3 ] : null;
	},

	/*
		set( cookieName, value, [days] )
		Sets a cookie for name to the given value
	*/
	set: function( name, value, days )
	{
		var expires = "";
		if( days )
		{
			var date = new Date();
			date.setTime( date.getTime() + days * 24 * 60 * 60 * 1000 );
			expires = "; expires=" + date.toGMTString();
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	},

	/*
		remove( cookieName )
		Removes a cookies value
	*/
	remove: function( name )
	{
		Cookies.set( name, "", -1 );
	}
};

if( !window.Event ) 
	var Event = new Object();

Object.extend( Event, {
	KEY_END:    35,
	KEY_HOME:   36,
	KEY_NUM0:   48,
	KEY_NUM9:   57,
	KEY_PAD0:   96,
	KEY_PAD9:   105,
	KEY_PADDOT: 110,
	KEY_F1:     112,
	KEY_F2:     113,
	KEY_F3:     114,
	KEY_F4:     115,
	KEY_F5:     116,
	KEY_F6:     117,
	KEY_F7:     118,
	KEY_F8:     119,
	KEY_F9:     120,
	KEY_F10:    121,
	KEY_F11:    122,
	KEY_F12:    123,
	KEY_PERIOD: 190,
	isFKey: function( event )
	{
		return event.keyCode >= this.KEY_F1 
			&& event.keyCode <= this.KEY_F12;
	},
	isNumberKey: function( event )
	{
		return (event.keyCode >= this.KEY_NUM0
			&&  event.keyCode <= this.KEY_NUM9)
			|| (event.keyCode >= this.KEY_PAD0
			&&  event.keyCode <= this.KEY_PAD9);
	},
	isNavKey: function( event )
	{
		return event.keyCode == this.KEY_BACKSPACE
			|| event.keyCode == this.KEY_TAB
			|| event.keyCode == this.KEY_RETURN
			|| event.keyCode == this.KEY_ESC
			|| event.keyCode == this.KEY_LEFT
			|| event.keyCode == this.KEY_UP
			|| event.keyCode == this.KEY_RIGHT
			|| event.keyCode == this.KEY_DOWN
			|| event.keyCode == this.KEY_DELETE
			|| event.keyCode == this.KEY_HOME
			|| event.keyCode == this.KEY_END;
	}
} );

Object.extend( String.prototype, {
	startsWith: function( prefix )
	{
		return this.indexOf( prefix ) === 0;
	},

	endsWith: function( suffix )
	{
		var startPos = this.length - suffix.length;
		if( startPos < 0 )
			return false;
		return this.lastIndexOf( suffix, startPos ) == startPos;
	},

	trimLeft: function()
	{
		return this.replace( /^\s+/, "" );
	},

	trimRight: function()
	{
		return this.replace( /\s+$/, "" );
	},
	
	trim: function()
	{
		return this.trimLeft().trimRight();
	}
} );

if( !window.Page ) 
	var Page = new Object();

Object.extend( Page, {
	/* disableEnterKey */
	disableEnterKey: true,
	
	/*
		init
		Performs any code required at page load
	*/
	init: function()
	{
		if( typeof setupAllTabs == "function" )
		{
			setupAllTabs();
			if( window.attachEvent )
				Event.observe( window, "unload", disposeAllTabs, false );
		}
		
		if( window.navigator.userAgent.toLowerCase().indexOf( "googlebot" ) == -1 )
		{
			this.enhanceAnchors();
			//if( !SmartScroll.loaded )
			//	this.focusElement();
		
			//if( this.disableEnterKey )
			//	Event.observe( document, "keypress", this.onKeyPress, false );
		}
	},
	
	/*
		onKeyPress
		...
	*/
	onKeyPress: function( e )
	{
		if( e.keyCode == Event.KEY_RETURN )
		{
			var element = Event.element( e );
			//alert( e.keyCode + " " + element.tagName );
			
			/*if( /^input$/i.test( element.tagName ) )
			{
				var list = document.forms[0].elements;
				for( var item = null, i = 0, assign = false; null != (item = list[ i ]); i++ )
				{
					if( assign && !/^hidden$/i.test( item.type ) )
					{
						try{ item.focus(); }
						catch( ex ){ }
						break;
					}
					
					if( element.id == item.id )
						assign = true;
				}
			}*/
			
			if( !/^textarea|select$/i.test( element.tagName ) )
				Event.stop( e );
		}
	},

	/*
		focusFirstInput
		...
	*/
	focusElement: function( d )
	{
		if( !d && document.forms && document.forms.length !== 0 ) d = document.forms[ 0 ]; 
		if( !d )  return;
		for( var e = null, i = 0; null != (e = d.elements[ i ]); i++ )
		{
			if( /^text|password$/.test( e.type ) && e.value.length === 0 )
			{
				e.focus();
				break;
			}
		}
	},
	
	/*
		enhanceAnchors
		Add's targets to external relevance links for XHTML compliance
	*/
	enhanceAnchors: function( parent )
	{
		var anchors = !parent ? document.getElementsByTagName( "a" ) : parent.getElementsByTagName( "a" );
		for( var a = null, i = 0; null != (a = anchors[ i ]); i++ )
		{
			var rel = a.rel || "";
			if( /^external/.test( rel ) )
			{
				var parts = rel.split( " ", 2 );
				a.target = parts.length > 1 ? parts[ 1 ] : "_blank";
				
				if( a.target == "enlarged" )
				{
					a.onclick = this.popImage;
					a.onmouseover = function()
					{
						window.status = "Large image: " + this.href;
						return true;
					};
				}
				else
				{
					a.onmouseover = function()
					{
						window.status = "External link: " + ( this.title || this.href );
						return true;
					};
				}
			}
			else if( rel == "email" )
			{
				a.onmouseover = function()
				{
					window.status = "Contact " + ( this.title || this.innerHTML.replace( /<[^>]+>/gi, "" )) + " <" + this.href.substring( 7 ) + ">";
					return true;
				};
			}
			else
			{
				a.onmouseover = function()
				{
					window.status = ( this.title || this.innerHTML.replace( /(<[^>]+>)|[\r\n\t]+/gi, "" ) ).replace( /&amp;/gi, "&" );
					return true;
				};
			}
			
			a.onmouseout = function()
			{
				window.status = "";
			};
		}
	},
	popImageAutoClose: false,
	popImage: function()
	{
		if( document.pop )
		{
			try
			{
				document.pop.close();
				document.pop = null;
			}
			catch( ex )
			{}
		}
		
		/// based on: http://www.howtocreate.co.uk/perfectPopups.html
		var win = document.pop = window.open( '', this.target, 'width=500,height=500,menubar=0,location=0,resizable=1,statusbar=0,scrollbars=no' );
		if( !win ){ return true; }
		
		win.document.write('<html><head><title>'+(this.title || this.href)+'<\/title><script type="text\/javascript">\n'+
		'function resizeWinTo() {\n'+
		'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
		'var oH = document.images[0].height, oW = document.images[0].width;\n'+
		'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
		'window.doneAlready = true;\n'+ //for Safari and Opera
		'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
		'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
		'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
		'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
		'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
		'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
		'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
		'//var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
		'//var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
		'//if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
		'}\n'+
		'<\/script>'+
		'<\/head><body onload="resizeWinTo();"'+(Page.popImageAutoClose?' onblur="self.close();"':'')+'>'+
		(document.layers?('<layer left="0" top="0">'):('<div style="position:absolute;left:0px;top:0px;display:table;">'))+
		'<img src='+this.href+' alt="Loading image ..." title="" onload="resizeWinTo();">'+
		(document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');

		win.document.close();
		if( win.focus ) { win.focus(); }
		return false;
	}
} );
Event.observe( window, "load", Page.init.bind( Page ), false );

var SmartScroll = {
	fieldX: "__smartscroll_x",
	fieldY: "__smartscroll_y",
	loaded: false,
	
	/* init */
	init: function( form )
	{
		this.form = $( document.forms[ 0 ] );
		if( this.form )
		{
			this.event_save = this.save.bindAsEventListener( this );
			Event.observe( this.form, "submit", this.event_save, false );
			this.load();
			
			__doPostBack = this.__doPostBack.bind( this );
		}
	},
	
	/* load */
	load: function()
	{
		var coords = this.getXY();
		if( coords.x !== 0 || coords.y !== 0 )
		{
			this.loaded = true;
			window.scrollTo( coords.x, coords.y );
		}
	},
	
	/* save */
	save: function( e )
	{
		var coords = this.getCoordinates();
		this.setX( coords.x );
		this.setY( coords.y );
		
		if( this.event_save )
		{
			Event.stopObserving( this.form, "submit", this.event_save, false );
			delete this.event_save;
		}
	},
	
	/* getCoordinates */
	getCoordinates: function()
	{
		return {
			x: document.body.scrollLeft || document.documentElement.scrollLeft || window.pageXOffset || 0,
			y: document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset || 0
		};
	},
	
	/* getXY */
	getXY: function()
	{
		return {
			x: this.getX(),
			y: this.getY()
		};
	},
	
	/* getX */
	getX: function()
	{
		return parseInt( $( this.fieldX ).value, 10 ) || 0;
	},
	
	/* setX */
	setX: function( value )
	{
		$( this.fieldX ).value = value;
	},
	
	/* getY */
	getY: function()
	{
		return parseInt( $( this.fieldY ).value, 10 ) || 0;
	},
	
	/* setY */
	setY: function( value )
	{
		$( SmartScroll.fieldY ).value = value;
	},
	
	__doPostBack: function( eventTarget, eventArgument )
	{
		if( !this.form.onsubmit || ( this.form.onsubmit() != false ) )
		{
			//alert( 'eventTarget: ' + eventTarget + '\neventArgument: ' + eventArgument );
			this.save();
			this.form.__EVENTTARGET.value = eventTarget;
			this.form.__EVENTARGUMENT.value = eventArgument;
			this.form.submit();
		}
	}
};
//Event.observe( window, "load", SmartScroll.init.bind( SmartScroll ), false );

