/*global AjaxRequest, DataStorage*/

/**
* Created for SmartKage by Infrared5
* 
* @author Kyle Kellogg (unless otherwise noted)
* @update 08.05.2011
*/

var first = true,
	html_data = '',
	i,
	prevAddress = '',
	accountOpen = false,
	active_kiosk_id = -1;

var locationData = {
	AZ: [{
		"name": "Inside Pitch",
		"address": "1125 W. Pinnacle Peak Bldg #4",
		"city": "Phoenix",
		"state": "AZ",
		"zip": "85027",
		"contact": "(Fred Speck) fspeck@insidepitchaz.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	CA: [{
		"name": "All Star Academy",
		"address": "2901 Mead Ave.",
		"city": "Santa Clara",
		"state": "CA",
		"zip": "94028",
		"contact": "(Linda Lange) lindalange@earthlink.net",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name":	"On Deck Baseball Training",
			"address": "7675 San Fernando Rd.",
			"city": "Burbank",
			"state": "CA",
			"zip": "",
			"contact": "(Glen Raasch) glenraasch@on-deckbaseball.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		},
		{
			"name": "On Deck Training",
			"address": "2499 Willow St.",
			"city": "Signal Hill",
			"state": "CA",
			"zip": "90755",
			"contact": "(Mike Rogers) ondeckcages@aol.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		},
		{
			"name": "Frozen Ropes",
			"address": "10710 Thornmint Rd.",
			"city": "San Diego",
			"state": "CA",
			"zip": "92127",
			"contact": "(Curt--Ron Witmeyer) sandiego@frozenropes.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	CO: [{
		"name": "Marc Johnson Sport Center",
		"address": "12000 E. Easter Ave.",
		"city": "Englewood",
		"state": "CO",
		"zip": "80111",
		"contact": "(Marc Johnson) customerservice@marcjohnsonssportscenter.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name": "Slammers",
			"address": "1878 S. Wadsworth  Blvd.",
			"city": "Lakewood",
			"state": "CO",
			"zip": "80232",
			"contact": "(Mark Holzemer) mholzemer@slammersbaseball.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	CT: [{
		"name": "Bobby Valentine Sports Academy",
		"address": "72 Camp Ave.",
		"city": "Stamford",
		"state": "CT",
		"zip": "06907",
		"contact": "(Mitch Hoffman) mitch@bobbyvacademy.com",
		"facility_id": 2,
		"kiosks": [
			{
				"id": 3,
				"serial_number": "33333"
			}
		]
	}],
	FL: [{
		"name": "Line Drive Indoor Baseball",
		"address": "3125 Jupiter Park Circle",
		"city": "Jupiter",
		"state": "FL",
		"zip": "33458",
		"contact": "(Roger Lachapelle) insidebaseball@comcast.net",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name": "Hit-n-Run Baseball",
			"address": "115 Central Park Place",
			"city": "Sanford",
			"state": "FL",
			"zip": "32771",
			"contact": "(Mike Jackson) mjackson@hit-n-run.net",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		},
		{
			"name": "Big League Experience",
			"address": "6472 Parkland Dr.",
			"city": "Sarasota",
			"state": "FL",
			"zip": "34243",
			"contact": "(Mike Lavalliere) contact@bigleaguex.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	GA: [{
		"name": "DiamondStarz",
		"address": "8950 Hwy 5, Suite B",
		"city": "Douglasville",
		"state": "GA",
		"zip": "30134",
		"contact": "(Rich Newport) rndiamondstarz@gmail.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	IL: [{
		"name": "Bo Jackson Elite Sports",
		"address": "15440 W. 167th St.",
		"city": "Lockport",
		"state": "IL",
		"zip": "60441",
		"contact": "( Ryan Malone-mgr. Jim Thompson-owner) ryan@cangelosibaseball.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	MA: [{
		"name": "Strike One",
		"address": "199 Newbury St",
		"city": "Danvers",
		"state": "MA,",
		"zip": "01923",
		"contact": "(Mark Lombardi) mlombardi@strikeone.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	MD: [{
		"name": "B.A.T.T Academy",
		"address": "200 Penrod Ct.",
		"city": "Glen Burnie",
		"state": "MD",
		"zip": "21060",
		"contact": "(Larry Williams) thebatt@verizon.net",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	MI: [{
		"name": "Spring Training Indoor Baseball",
		"address": "27088 Morelli Dr.",
		"city": "Chesterfield",
		"state": "MI",
		"zip": "48051",
		"contact": "(Jeff Damore) springtraining5@yahoo.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	MN: [{
		"name": "Players Only Baseball Academy",
		"address": "9805 Hamilton Rd.",
		"city": "Eden Prairie",
		"state": "MN",
		"zip": "55344",
		"contact": "(Tom Nevers, Gene Larkin) neverslarkinbaseball@playersonlyinc.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	MO: [{
		"name": "The Yard",
		"address": "624 B NE Jones Industrial Dr.",
		"city": "Lee's Summit",
		"state": "MO",
		"zip": "64064",
		"contact": "(Gerald Barker) theyard@theyardkc.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name": "All-Star Performance Center",
			"address": "3390 Tree Court Industrial Lane",
			"city": "St. Louis",
			"state": "MO",
			"zip": "63122",
			"contact": "(Matt Whiteside) mwhiteside@all-starperformance.net",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	NC: [{
		"name": "CBC Baseball",
		"address": "1108-F Continental Blvd.",
		"city": "Charlotte",
		"state": "NC",
		"zip": "28273",
		"contact": "(Dave Collins) davecollins3@gmail.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	NJ:	[{
		"name": "Hit Doctor Baseball Academy",
		"address": " 333 Preston Ave., Unit 1",
		"city": "Voorhees",
		"state": "NJ",
		"zip": "08043",
		"contact": "(Joe Barth) hitdoctor@thehitdoctor.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	NY: [{
		"name": "Prospect Sports",
		"address": "171D Milbar Blvd.",
		"city": "Farmingdale",
		"state": "NY",
		"zip": "11735",
		"contact": "(Bryan Goelz) info@prospectsportsli.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	OH: [{
		"name": "DNA Sports Center",
		"address": "731 US RT. 50",
		"city": "Milford",
		"state": "OH",
		"zip": "45150",
		"contact": "(Mike Meszeros) mike@dnasportscenter.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name": "Diamond Indoor Sports",
			"address": "23409 Detroit Rd.",
			"city": "Westlake",
			"state": "OH",
			"zip": "44145",
			"contact": "(TJ Donovan) dis@diamondindoorsports.com, info@diamondindoorsports.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	PA: [{
		"name": "Bianco Training Center",
		"address": "105 Springfield Lane.",
		"city": "Canonsburg",
		"state": "PA",
		"zip": "15317",
		"contact": "(Matt Bianco)  smalls2255@aol.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	TN: [{
		"name": "365 Baseball Academy",
		"address": "334 Free Hill Rd.",
		"city": "Hendersonville",
		"state": "TN",
		"zip": "37075",
		"contact": "(Shay Horseman) info@365baseballacademy.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	TX: [{
		"name": "Baseball Solutions",
		"address": "9300 Anderson Mill Rd., Ste 100",
		"city": "Austin",
		"state": "TX",
		"zip": "78729",
		"contact": "(Andrew Prater) aprater@baseballsolutions.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name": "D-Bat",
			"address": "15605 Wright Brothers Dr.",
			"city": "Addison",
			"state": "TX",
			"zip": "75001",
			"contact": "(Cade Griffis) cade@dallasbat.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		},
		{
			"name": "Baseball USA",
			"address": "2626 W. Sam Houston Pkwy N.",
			"city": "Houston",
			"state": "TX",
			"zip": "77043",
			"contact": "(Don Lewis) donl@baseballusa.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	VA: [{
		"name": "Virginia Baseball Club",
		"address": "13199 Gordon Blvd.",
		"city": "Woodbridge",
		"state": "VA",
		"zip": "22191",
		"contact": "(Mike Murray) mike.murray33@verizon.net",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	},
		{
			"name": "Richmond Baseball South Academy",
			"address": "2240 Oak Lake Blvd",
			"city": "Midlothian",
			"state": "VA",
			"zip": "23112",
			"contact": "(Rich Graham) rbasouth@aol.com",
			"facility_id": 0,
			"kiosks": [
				{
					"id": 0,
					"serial_number": "00000"
				}
			]
		}],
	WA: [{
		"name": "Diamond Sports Training Center",
		"address": " 13799 24th St., East",
		"city": "Sumner",
		"state": "WA",
		"zip": "98390",
		"contact": "(Nevin Garthwaite) garthwaite@comcast.net",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	WI: [{
		"name": "South	Hitters Baseball Academy",
		"address": "4726 Six Mile Rd.",
		"city": "Racine",
		"state": "WI",
		"zip": "53402",
		"contact": "(R.J Fergus) rfergus@wi.rr.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}],
	INTL: [{
		"name": "Home Run Baseball Academy",
		"address": "695 Westney Rd., South, Units 6,7,8",
		"city": "Ajax",
		"state": "ON",
		"zip": "L1S6M9",
		"contact": "info@homerunacademy.com",
		"facility_id": 0,
		"kiosks": [
			{
				"id": 0,
				"serial_number": "00000"
			}
		]
	}]
};

/**
* Fades account back in to full opacity
*/
function accountFadeIn() {
	jQuery( '#account-inner' ).stop().fadeTo( 800, 1 );
}

/**
* Will animate opening / closing the login box
*/
function opencloseAccount( isOpen ) {
	if ( !isOpen ) {
		jQuery( '#video-wrapper' ).stop().animate( { top: '-53px' }, { duration: 800 } );
		jQuery( '#content-wrapper' ).stop().animate( { left: '-12px' }, { duration: 800 } );
		jQuery( '#account' ).css( 'background-image', 'url(images/SS_open_loginbox.png)' ).stop().animate( {
				width: '259px',
				height: '53px'
			},
			{
				duration: 800,
				complete: accountFadeIn
			} );
	} else {
		jQuery( '#video-wrapper' ).stop().animate( { top: '-36px' }, { duration: 800 } );
		jQuery( '#content-wrapper' ).stop().animate( { left: '0px' }, { duration: 800 } );
		jQuery( '#account' ).css( 'background-image', 'url(images/SS_login.png)' ).stop().animate( {
				width: '124px',
				height: '36px'
			},
			{
				duration: 800,
				complete: accountFadeIn
			} );
	}
}

/**
* Sets the links that should be active based on current deep-linked value
*/
function setActiveLinks() {
	var address = jQuery.address.value();
	var pages = address.substr( 1 ).split( '/' );
	i = 0;
	var ds = document.getElementById( 'nav' ).getElementsByTagName( 'div' ),
		dds = document.getElementById( 'innerNavHolder' ).getElementsByTagName('ul')[0].getElementsByTagName('li'),
		divs = [];
		
	for ( i = 0; i < ds.length; i++ ) {
		divs.push( ds[i] );
	}
	
	for ( i = 0; i < dds.length; i++ ) {
		divs.push( dds[i] );
	}
	
	jQuery( '#nav div' ).removeClass( 'selected' );
	
	if ( pages[0].length === 0 ) {
		var first_div = divs[0];
		jQuery( first_div ).addClass( 'selected' );
	} else {
		while ( i < divs.length ) {
			if ( jQuery( divs[i] ).text() === pages[0] ) {
				jQuery( divs[i] ).addClass( 'selected' );
				break;
			}
			i++;
		}
	}
	
	if ( pages.length > 1 && pages[0] !== 'register' ) {
		var sublinkwrapper = document.getElementById( 'sub-link-wrapper' ),
			links = (sublinkwrapper !== null) ? sublinkwrapper.getElementsByTagName( 'a' ) : [];
		i = 0;
		while ( i < links.length ) {
			if ( jQuery( links[i] ).text().toLowerCase().search( pages[1].toLowerCase() ) > -1 ) {
				jQuery( links[i] ).addClass( 'selected' );
				break;
			}
			i++;
		}
	}
}

/**
* Handles mouse over for subnavigation links (in content area)
* Should be ported to CSS
* 
* @param evt Event object (jQuery)
*/
function linkOverHandler( evt ) {
	if ( !jQuery( this ).hasClass( "selected" ) ) {
		jQuery( this ).addClass( "over" );
	}
}

/**
* Handles mouse out for subnavigation links (in content area)
* Should be ported to CSS
* 
* @param evt Event object (jQuery)
*/
function linkOutHandler( evt ) {
	if ( !jQuery( this ).hasClass( "selected" ) ) {
		jQuery( this ).removeClass( "over" );
	}
}

/**
* Handles mouse click for subnavigation links (in content area)
* 
* @param evt Event object (jQuery)
*/
function linkClickHandler( evt ) {
	jQuery( "#sub-link-wrapper a" ).removeClass( "selected" );
	jQuery( "#sub-link-wrapper a").removeClass( "over" );
	jQuery( this ).addClass( "selected" );
	
	this.blur();
	
	evt.preventDefault();
}

/**
* Handles mouse click for scheduling links (in content area)
* 
* @param evt Event object (jQuery)
*/
function schedulingClickHandler( evt ) {
	this.blur();
	if ( evt.preventDefault ) { evt.preventDefault(); }
	return;
}

/**
* Handles mouse over for navigation links
* Animates background color change
* 
* @param evt Event object (jQuery)
*/
function navOverHandler( evt ) {
	if ( !jQuery( this ).hasClass( "selected" ) ) {
		jQuery( this ).addClass( "over" );
		jQuery( this ).stop().animate( {
				backgroundColor: "#00f"
			}, 800 );
	}
}

/**
* Handles mouse out for navigation links
* Animates background color change
* 
* @param evt Event object (jQuery)
*/
function navOutHandler( evt ) {
	if ( !jQuery( this ).hasClass( "selected" ) ) {
		jQuery( this ).removeClass( "over" );
		jQuery( this ).stop().animate( {
				backgroundColor: "#d40000"
			}, 800 );
	}
}

/**
* Handles mouse click for navigation links
* Animates background color change
* 
* @param evt Event object (jQuery)
*/
function navClickHandler( evt ) {
	jQuery( "#nav div" ).removeClass( "selected" );
	jQuery( "#nav div").removeClass( "over" );
	jQuery( '#innerNavHolder ul li' ).removeClass( "selected" );
	jQuery( '#innerNavHolder ul li' ).removeClass( "over" );
	jQuery( this ).addClass( "selected" );
	jQuery( this ).stop().animate( {
			backgroundColor: "#d40000"
		}, 800 );
	
	this.blur();
	this.parentNode.blur();
	
	if ( evt.preventDefault) { evt.preventDefault(); }
}

/**
* Handles mouse click for inner navigation link(s)
* Animates background color change
* 
* @param evt Event object (jQuery)
*/
function innerNavClickHandler( evt ) {
	jQuery( "#nav div" ).removeClass( "selected" );
	jQuery( "#nav div").removeClass( "over" );
	jQuery( '#innerNavHolder ul li' ).removeClass( "selected" );
	jQuery( '#innerNavHolder ul li' ).removeClass( "over" );
	jQuery( this ).parent().addClass( "selected" );
	jQuery( this ).parent().stop().animate( {
			backgroundColor: "#d40000"
		}, 800 );
	
	this.blur();
	
	if ( evt.preventDefault) { evt.preventDefault(); }
}

/**
* Handles mouse click for login link
* Fades content out, replaces by showing/hiding divs, adds listeners or classes as necessary
* Proceeds to go to the function opencloseAccount() once animation is complete
* 
* @param evt Event object (jQuery)
*/
function accountClickHandler( evt ) {
	var isOpen = !!accountOpen;
	
	jQuery( '#account-inner' ).stop().fadeOut( 800, function() {
		var $this = jQuery(this);
		$this.css( {'right': '0px', 'width': '100%', 'height': 'auto'} );
		
		if ( isOpen ) {
			jQuery( '#login-form' ).hide();
			jQuery( '#logged-in' ).hide();
			jQuery( '#login' ).show();
			
			jQuery( '#loginLink' ).click( accountClickHandler );
			$this.removeClass( 'open' );
		} else {
			jQuery( '#login' ).hide();
			jQuery( '#logged-in' ).hide();
			jQuery( '#login-form' ).show();
			
			$this.addClass( 'open' );
		}
		
		opencloseAccount( isOpen );
	} );
	
	accountOpen = !(!!accountOpen);
	
	if ( evt !== null && evt !== undefined ) {
		evt.preventDefault();
	}
	this.blur();
}

/**
* Ease of use function to handle adding event listeners to individual subnav / scheduling links
*/
function addLinkHandlers() {
	if ( jQuery.address.value().indexOf( 'register' ) < 0 ) {
		jQuery( "#sub-link-wrapper a" ).each( function() {
			jQuery( this ).mouseover( linkOverHandler );
			jQuery( this ).mouseout( linkOutHandler );
			jQuery( this ).click( linkClickHandler );
		} );
	} else {
		jQuery( "div.schedulingNext a" ).each( function() {
			jQuery( this ).click( schedulingClickHandler );
		} );
	}
}

/**
* Ease of use function to handle adding event listeners to individual nav links
*/
function addNavHandlers() {
	jQuery( "#nav div" ).each( function() {
		jQuery( this ).mouseover( navOverHandler );
		jQuery( this ).mouseout( navOutHandler );
		jQuery( this ).click( navClickHandler );
	} );
	
	jQuery( '#innerNavHolder ul li a' ).click( innerNavClickHandler );
}

/**
* Ease of use function to handle adding event listeners to individual account links
*/
function addAccountHandlers() {
	jQuery( "#loginLink" ).click( accountClickHandler );
}

/**
* If able, this will tell the videos on the homepage to play
* If not able, this will replace them with static images
* If iOS (special case), this will replace them with static images
*/
function playVids() {
	if ( jQuery.address.value() === '/' ) {
		var vid = document.getElementById( 'vid' );
		var stats = document.getElementById( 'stats' );
		
		if ( window.navigator.userAgent.toLowerCase().search( (/ip(h)?(o|a)(d|ne)/i) ) > -1 ) {
			jQuery( vid ).remove();
			jQuery( stats ).replaceWith( '<img src="images/SS_measureofperformancehome.png"/>' );
			return;
		}
		
		if ( !vid || !stats ) {
			return;
		}
		
		if ( (vid.hasOwnProperty && vid.hasOwnProperty('play')) || vid.play !== undefined ) {
			vid.play();
		} else {
			jQuery( vid ).replaceWith( '<img src="images/vidPlaceholder.jpg" />' );
		}
		
		if ( (stats.hasOwnProperty && stats.hasOwnProperty('play')) || stats.play !== undefined ) {
			stats.play();
		} else {
			jQuery( stats ).replaceWith( '<img src="images/SS_measureofperformancehome.png"/>' );
		}
	}
}

/**
* Handles changing the locations listed on the Locations page.
* 
* @param state The selected item text (state abbreviation, all caps) from the dropdown
*/
function handleLocationData( state ) {
	if ( locationData[state] !== null && locationData[state] !== undefined ) {
		var html = '';
		for ( i = 0; i < locationData[state].length; i++ ) {
			var obj = locationData[state][i];
			var contactRegEx = /\(([^\)]+)\) (.*)/;
			var matches = obj.contact.match( contactRegEx );
			var email = matches[2];
			var contactName = matches[1];
			var contactLink = '<a href="mailto:' + email + '">' + contactName + '</a>';
			html += '<div class="locationWrapper"><div class="locationName">' + obj.name + '</div><div>' + obj.address + '</div><div>' + obj.city + ', ' + obj.state + ' ' + obj.zip + '</div><div>' + contactLink + '</div></div>';
		}
		
		jQuery( '#results' ).html( html );
	} else {
		jQuery( '#results' ).html( 'Currently, there are no facilities in this state.' );
	}
}

/**
* Event handler for changing state dropdown on Locations page
* 
* @param evt Event object (jQuery)
*/
function locationChange( evt ) {
	var option = jQuery('#state_select').children(':selected');
	var val = option.attr( 'value' );
	
	handleLocationData( val );
}

/**
* Handles the initial location change on Locations page
*/
function initialLocationChange() {
	handleLocationData( 'AL' );
}

/**
* Handles changing locations listed on Scheduling page
* 
* @param state The selected item text (state abbreviation, all caps) from the dropdown
*/
function handleStateChange( state ) {
	var facility = document.getElementById( 'facility_select' );
	var type = facility.tagName.toLowerCase();
	var option;
	
	if ( type === 'div' ) {
		var replacement = document.createElement( 'select' );
		replacement.name = 'facility';
		replacement.id = 'facility_select';
		
		var divs1 = facility.getElementsByTagName( 'div' );
		if ( divs1.length < 1 ) { return; }
		var content_wrapper = divs1[0];
		var divs2 = content_wrapper.getElementsByTagName( 'div' );
		
		for ( i = 0; i < divs2.length; i++ ) {
			option = document.createElement( 'option' );
			option.value = option.text = divs2[i].innerHTML;
			try { replacement.add( option, replacement.options[null] ); }
			catch ( e ) { replacement.add( option, null ); }
		}
		
		facility.parentNode.insertBefore( replacement, facility );
		facility.parentNode.removeChild( facility );
		facility = replacement;
	}
	
	for ( i = facility.options.length - 1; i > -1; i-- ) {
		facility.remove( i );
	}
	
	for ( i = 0; i < locationData[state].length; i++ ) {
		var obj = locationData[state][i];
		option = document.createElement( 'option' );
		option.value = option.text = obj.name;
		try { facility.add( option, facility.options[null] ); }
		catch ( er ) { facility.add( option, null ); }
	}
	
	jQuery('#facility_select').change();
}

/**
* Change event listener for state dropdown on Scheduling page
* 
* @param evt Event object (jQuery)
*/
function stateChange( evt ) {
	var option = jQuery(this).children(':selected');
	var val = option.attr( 'value' );
	
	handleStateChange( val );
}

var months = [
		'Jan',
		'Feb',
		'Mar',
		'Apr',
		'May',
		'Jun',
		'Jul',
		'Aug',
		'Sep',
		'Oct',
		'Nov',
		'Dec'
	],
	date_map,
	sent_date = new Date();

/**
* Util function to create & display available times for a specific date, for a specific location
* 
* @param date Date object
*/
function set_times_for_date( date ) {
	if ( date === undefined || date === null ) {
		date = new Date();
	}
	
	var $time = jQuery('#time_select');
	if ( $time !== undefined && $time !== null ) {
		$time.html('');
		
		var frag = document.createDocumentFragment(),
			y = date.getFullYear(),
			yobj = date_map[y] || {},
			m = date.getMonth(),
			mobj = yobj[m] || {},
			d = date.getDate(),
			array = mobj[d] || [],
			opt;
		
		if ( array.length > 0 ) {
			$time.removeAttr('disabled');
			for ( var i = 0; i < array.length; i++ ) {
				opt = document.createElement('option');
				
				var pm = (i>=12);
				var ampm = pm ? 'pm' : 'am';
				var ampm2 = ampm;
				var start;
				var end;
				
				if ( i === 0 ) {
					start = 12;
					end = 1;
				} else {
					start = i;
					end = i+1;
					
					if ( i === 12 ) {
						start = 12;
						end = 1;
					} else if ( i > 12 ) {
						start = Math.abs(i-12);
						end = start+1;
						
						if ( end === 12 && pm ) {
							ampm2 = 'am';
						}
					}
				}
					
				var val = start + ampm + ' - ' + end + ampm2;
				
				opt.setAttribute('value', val);
				opt.innerHTML = val;
				
				frag.appendChild( opt );
			}
		} else {
			$time.attr('disabled', 'disabled');
			opt = document.createElement('option');
			opt.setAttribute('value', 'No times available');
			opt.innerHTML = 'No times available';
			frag.appendChild(opt);
		}
		
		$time.append(frag);
		
		jQuery('#time_select').removeAttr('disabled');
		jQuery('#routine_select').removeAttr('disabled');
	}
}

/**
* Completion handler for calls made to back end to get times for specific location on a specific date
* 
* @param req Request object
*/
function timesReceived( req ) {
	var array = ''+req.responseText;
	array = array.replace( (/[\n\r]/g), '' );
	array = array.replace( (/\",\"/g), '"*SPLIT*"' );
	array = array.split( '"*SPLIT*"' );
	
	if ( array === undefined || array === null || !jQuery.isArray( array ) ) {
		jQuery().toastmessage('showToast', { type:'error', text:'Received bad dates from the server.' });
		return;
	}
	
	array[0] = (''+array[0]).substring(2);
	var last_item = (''+array[array.length-1]);
	array[array.length-1] = last_item.substring(0, last_item.length-2);
	
	date_map = {};
	
	for ( var i = 0; i < array.length; i++ ) {
		var date = new Date( ''+array[i] ),
			y = date.getFullYear(),
			m = date.getMonth(),
			d = date.getDate();
			
		if ( !date_map[y] ) {
			date_map[y] = {};
		}
		
		if ( !date_map[y][m] ) {
			date_map[y][m] = {};
		}
		
		if ( !date_map[y][m][d] ) {
			date_map[y][m][d] = new Array(24);
		}
		
		date_map[y][m][d][ date.getHours() ] = true;
	}
	
	set_times_for_date( new Date( sent_date ) );
	jQuery('#datepicker').datepicker( 'refresh' );
	jQuery('#submit_schedule').removeAttr('disabled');
}

/**
* Error handler for calls made to back end to get times for specific location on a specific date
* 
* @param req Request object
*/
function timesError( req ) {
	jQuery().toastmessage('showToast', { type:'error', text:'Error communicating with server when trying to get available dates.' });
}

/**
* Util function to make call to back end to get times for a specific date at a specific facility
* 
* @param date Date object
*/
function get_times_for_date( date ) {
	if ( date === undefined || date === null ) {
		date = new Date();
	}
	
	date = months[ date.getMonth() ] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' 0:00:00 AM';
	sent_date = date;
	
	jQuery('#time_select').attr('disabled','disabled');
	jQuery('#routine_select').attr('disabled','disabled');
	
	var state		= ''+(jQuery('#state_select').attr('value')||jQuery('#state_select').val()),
		facility	= ''+(jQuery('#facility_select').attr('value')||jQuery('#facility_select').val()),
		obj,
		o,
		n;
	for ( var i = 0; i < locationData[state].length; i++ ) {
		o = locationData[state][i];
		n = ''+o.name;
		if ( n === facility ) {
			obj = o;
			break;
		}
	}
	
	if ( o !== undefined ) {
		var kiosks = [],
			data;
		
		for ( i = 0; i < o.kiosks.length; i++ ) {
			if ( jQuery.inArray( o.kiosks[i], kiosks ) < 0 ) {
				kiosks.push( o.kiosks[i] );
			}
		}
		
		for ( i = 0; i < kiosks.length; i++ ) {
			active_kiosk_id = kiosks[i].id;
			data = JSON.stringify( {
				"command": "GET_AVAILABLE_TIMES",
				"userId": DataStorage.get_data('email'),
				"sessionToken": DataStorage.get_data('sessionID'),
				"availabilityRequest": {
					"kioskSerialNumber": kiosks[i].serial_number,
					"from": date
				}
			} );
			
			AjaxRequest.post({
						"url": "http://209.20.89.111:5080/sswebserver/Schedule",
						"parameters": data,
						"onSuccess": timesReceived,
						"onError": timesError
					});
		}
	} else {
		jQuery().toastmessage('showToast', { type:'error', text:'Could not find that facility in order to get available dates for it.' });
	}
}

/**
* Change handler for facility dropdown on Scheduling page
* 
* @param evt Event object (jQuery)
*/
function facilityChanged( evt ) {
	jQuery('#submit_schedule').attr('disabled', 'disabled');
	var date = jQuery('#datepicker').datepicker( 'getDate' ) || new Date();
	date.setDate( 1 );
	get_times_for_date( date );
	jQuery('#datepicker').datepicker( 'refresh' );
}

/**
* Get only states which have facilities for displaying in Scheduling page dropdown
*/
function get_active_states() {
	var arr = [];
	var a;
	for ( a in locationData ) {
		if ( locationData.hasOwnProperty(a) ) {
			arr.push( a );
		}
	}
	return arr;
}

/**
* Util function to set attribute & val at the same time
* 
* @param selector Selector to identify object
* @param value Value to set
*/
function jsetVal( selector, value ) {
	var $el = jQuery(selector),
		v = value||'';
	$el.attr('value',v).val(v);
}

/**
* Util function to fill in all registration values if capable
*/
function fillRegisterValues() {
	var user_obj;
	try {
		JSON.parse(DataStorage.get_data('user'));
	} catch (e) {
		user_obj = {};
	}
	var user = jQuery.extend( true, {}, user_obj );
	
	//	Map:
	//	.firstName
	//	.lastName
	//	.guardianFirstName = '';							/*	NOT SET	*/
	//	.guardianLastName = '';								/*	NOT SET	*/
	//	.email
	//	.webSite
	//	.im
	//	.phone
	//	.mobile
	//	.password = '';										/*	NOT SET	*/
	//	.addresses = [{
	//		addressType: 'PRIMARY',
	//		street1
	//		street2: '',									/*	NOT SET	*/
	//		apartmentNumber: '',							/*	NOT SET	*/
	//		city: '',										/*	NOT SET	*/
	//		state
	//		country: '',									/*	NOT SET	*/
	//		postalCode
	//		phone
	//		mobile
	//	}];
	//	.profile = {
	//		gender
	//		birthDate
	//		height
	//		weight
	//		bats
	//		throws
	//		primaryPosition
	//		secondaryPosition
	//		schoolTeam
	//		schoolCoachName
	//		schoolCoachEmail
	//		summerTeam
	//		summerCoachName
	//		summerCoachEmail
	//		otherTeam: '',										/*	NOT SET	*/
	//		otherCoachName: '',									/*	NOT SET	*/
	//		otherCoachEmail: ''									/*	NOT SET	*/
	//	};
	//	.academicProfile = {
	//		schoolCode: 'UNK',
	//		schoolName
	//		schoolCity
	//		schoolState
	//		grade
	//		graduationDate
	//		major
	//		satScore
	//		actScore
	//		rank
	//		gpa
	//		status: 'COMMITTED'
	//	};
	
	var keyLength = 0;
	for ( var param in user ) {
		if ( user.hasOwnProperty(param) ) {
			keyLength++;
		}
	}
	
	if ( user !== undefined && user !== null && keyLength > 0 ) {
		jsetVal( '#firstName', user.firstName );
		jsetVal( '#lastName', user.lastName );
		jsetVal( '#email', user.email );
		jsetVal( '#website', user.webSite );
		jsetVal( '#im', user.im );
		jsetVal( '#phone', user.phone );
		jsetVal( '#mobile', user.mobile );
		//	password
		//	password
		jsetVal( '#address', user.addresses[0].street1 );
		var states = ['AL','AK','AR','AZ','CA','CO','CT','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','ME','MD','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI','WV','WY'];
		jQuery('#state_select').attr('value', ''+user.addresses[0].state).val(''+user.addresses[0].state);
		jsetVal( '#zip', user.addresses[0].postalCode );
		//	Skip phone
		//	Skip phone
		//	Skip mobile
		//	Skip mobile
		jQuery('#sex').attr('value', ''+user.profile.gender).val(''+user.profile.gender);
		var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		var bday = new Date( user.profile.birthDate );
		bday = '' + months[ bday.getMonth() ] + ' ' + bday.getDate() + ', ' + bday.getFullYear();
		jsetVal( '#birthdate', bday );
		var heights = ["4'11","5'0","5'1","5'2","5'3","5'4","5'5","5'6","5'7","5'8","5'9","5'10","5'11","6'0","6'1","6'2","6'3","6'4","6'5","6'6","6'7","6'8","6'9","6'10","6'11","7'0"];
		var height = +user.profile.height;
		var heightFeet = Math.floor(height/12);
		var heightInches = height%12;
		height = ""+heightFeet+"'"+heightInches;
		jQuery('#height_select').attr('value', ''+height).val(''+height);
		jsetVal( '#weight', user.profile.weight );
		var bt = ['R','L','S'];
		jQuery('#bats_select').attr('value', ''+user.profile.bats).val(''+user.profile.bats);
		jQuery('#throws_select').attr('value', ''+user.profile.throws).val(''+user.profile.throws);
		var positions = ['P','C','FB','SB','SS','TB','LOF','COF','ROF'];
		jQuery('#primaryPosition_select').attr('value', ''+user.profile.primaryPosition).val(''+user.profile.primaryPosition);
		jQuery('#secondaryPosition_select').attr('value', ''+user.profile.secondaryPosition).val(''+user.profile.secondaryPosition);
		jsetVal( '#schoolTeam', user.profile.schoolTeam );
		jsetVal( '#schoolCoachName', user.profile.schoolCoachName );
		jsetVal( '#schoolCoachEmail', user.profile.schoolCoachEmail );
		jsetVal( '#summerTeam', user.profile.summerTeam );
		jsetVal( '#summerCoachName', user.profile.summerCoachName );
		jsetVal( '#summerCoachEmail', user.profile.summerCoachEmail );
		jsetVal( '#school', user.academicProfile.schoolName );
		jsetVal( '#schoolCity', user.academicProfile.schoolCity );
		jQuery('#schoolState_select').attr('value', ''+user.academicProfile.schoolState).val(''+user.academicProfile.schoolState);
		jsetVal( '#grade', user.academicProfile.grade );
		var gday = new Date( user.academicProfile.graduationDate );
		gday = '' + months[ gday.getMonth() ] + ' ' + gday.getDate() + ', ' + gday.getFullYear();
		jsetVal( '#graduationDate', gday );
		jsetVal( '#major', user.academicProfile.major );
		jsetVal( '#sat', user.academicProfile.satScore );
		jsetVal( '#act', user.academicProfile.actScore );
		jsetVal( '#rank', user.academicProfile.rank );
		jsetVal( '#gpa', user.academicProfile.gpa );
	}
}

/**
* Util function to determine if an object is empty or not
* 
* @param obj Object to test
*/
function obj_has_props( obj ) {
	for ( var a in obj ) {
		if ( obj.hasOwnProperty(a) ) {
			return 1;
		}
	}
	return 0;
}

/**
* Handles replacing content area content on each new page
* Also sets & houses callbacks for datepicker events if on Scheduling page
*/
function replaceContent() {
	var val = jQuery.address.value().toLowerCase();
	var state;
	
	jQuery( '#contentHolder' ).html( html_data );
	jQuery( '#contentHolder' ).stop().fadeTo( 800, 1 );
	
	setActiveLinks();
	
	addLinkHandlers();
	
	if ( val.indexOf( 'schedule' ) > -1 ) {
		jQuery( '#datepicker' ).datepicker({
			onChangeMonthYear: function( year, month, inst ) {
				var new_date = new Date( year, Math.max(0, month-1), 1, 0, 0, 0, 0 );
				get_times_for_date( new_date );
				set_times_for_date( new_date );
			},
			onSelect: function( dateText, inst ) {
				jQuery('#time_select').attr('disabled','disabled');
				jQuery('#routine_select').attr('disabled','disabled');
				set_times_for_date( new Date(dateText) );
			},
			beforeShowDay: function( date ) {
				date = new Date(date);
				var y = +date.getFullYear(),
					m = +date.getMonth(),
					d = +date.getDate(),
					test_date = new Date(),
					ty = +test_date.getFullYear(),
					tm = +test_date.getMonth(),
					td = +test_date.getDate(),
					bool = false,
					style = 'disabledDate disabled',
					popup = 'No available times for this date';
				
				//	Ensure that the user isn't in a previous year, month or day (of current month) to prevent scheduling of earlier dates.
				if ( y >= ty && m >= tm ) {
					if ( m === tm && d < td ) {
						return [bool, style, popup];
					}
					
					if ( date_map !== undefined && date_map !== null && obj_has_props(date_map) ) {
						var yobj = date_map[y] || {},
							mobj = yobj[m] || {},
							arr = mobj[d] || [],
							i = 0,
							a;
						
						i = arr.length - 1;
						while ( i > -1 ) {
							a = arr[i];
							if ( a !== undefined && a !== null && a === true ) {
								bool = true;
								style = '';
								popup = undefined;
								break;
							}
							i--;
						}
					}
				}
				
				return [bool, style, popup];
			}
		});
		
		state = document.getElementById( 'state_select' );
		
		var states = get_active_states();
		for ( i = 0; i < states.length; i++ ) {
			var option = document.createElement( 'option' );
			option.value = option.text = states[i];
			try { state.add( option, state.options[null] ); }
			catch ( e ) { state.add( option, null ); }
		}
		
		handleStateChange( states[0] );
		
		state = document.getElementById( 'state_select' );
		if ( state ) { jQuery(state).change( stateChange ); jQuery(state).change(); }
		
		var facility = document.getElementById( 'facility_select' );
		if ( facility ) { jQuery(facility).change( facilityChanged ); jQuery(facility).change(); }
		
		jQuery('#contentHolder').css('visibility', 'visible');
		
		return;
	}
	
	if ( val.indexOf( 'register' ) > -1 ) {
		var vals = val.substr( 1 ).split( '/' );
		var section = '#wrapper' + (''+vals[1]).toString();
		jQuery( 'div.page' ).hide();
		jQuery( section ).show();
		fillRegisterValues();
		jQuery( '.schedulingNext a.next' ).click( function( evt ) {
			var $this = jQuery(this),
				tt = $this.attr('href') || '',
				submit = false,
				section;
			
			if ( tt === '' ) {
				if ( (/next/i).test( $this.html() ) ) {
					section = 1;
				} else {
					section = 3;
					submit = true;
				}
			} else {
				tt = +tt.substring( tt.length-1 );
				section = tt-1;
			}
			
			if ( FormHelper.validate_section( section ) ) {
				if ( submit ) {
					FormHelper.submit_register();
				} else {
					jQuery.address.value( $this.attr('href') );
				}
			}
		} );
		
		jQuery( '#legal' ).click( function( evt ) {
			window.open( 'legal.html', '_blank', 'channelmode=0, directories=0, fullscreen=0, height=200, left=100, location=0, menubar=0, resizable=0, scrollbars=1, status=0, titlebar=0, toolbar=0, top=100, width=200', false );
		} );
	} else if ( val.indexOf( 'locations' ) > -1 ) {
		state = document.getElementById( 'state_select' );
		if ( state ) {
			jQuery(state).change( locationChange );
		}
		initialLocationChange();
	} else if ( val.indexOf( 'contact' ) > -1 ) {
		jQuery( '#message' ).click( function( evt ) {
			var win = window.open( 'mailto:info@smartkage.com', '_blank' );
			
			win.close();
		} );
	}
	
	playVids();
	
	jQuery('#contentHolder').css('visibility', 'visible');
	jQuery( '#contentHolder a.deeplink' ).address();
}

/**
* Completely hides the right wrapper, ensures proper BG image on the content area and switches content
*/
function showInner() {
	jQuery( '#right-wrapper' ).hide();
	jQuery( '#content' ).css( 'background-image', 'url(images/SS_maincontent_textarea.png)' );
	replaceContent();
}

/**
* Adds the tagline where the right wrapper used to be
*/
function addTagline() {
	jQuery( '#header-right' ).css( 'background-image', 'url(images/SS_maincontent_center.png)' );
	
	if ( jQuery( '#header-right + #tagline' ).length === 0 ) {
		var tagline = '<div id="tagline"></div>';
		jQuery( '#header-right' ).after( tagline );
		jQuery( '#tagline' ).stop();
		jQuery( '#tagline' ).css( 'width', '0px' ).animate( {
				width: '239px'
			},
			{
				duration: 700
			} );
	}
}

/**
* Removes the tagline
*/
function removeTagline() {
	jQuery( '#tagline' ).remove();
}

/**
* Shows the right wrapper, ensures proper BG image on the header area and switches content
*/
function hideInner() {
	jQuery( '#right-wrapper' ).show();
	jQuery( '#right-wrapper' ).css( 'overflow-x', 'visible !important' ).css( 'overflow-y', 'visible !important' );
	
	jQuery( '#right-mid' ).css( 'width', '370px' ).css( 'position', 'relative' ).css( 'left', '-13px' ).css( 'z-index', '1004' );
	
	jQuery( '#header-right' ).css( 'background-image', 'url(images/SS_homepage_upperleft.png)' );
	replaceContent();
}

/**
* Swtiches content BG image to be that of the home page size rather than the inner content size
*/
function hideContent() {
	jQuery( '#content' ).css( 'background-image', 'url(images/SS_homepage_textarea.png)' );
}

/**
* Overall control for showing and hiding the inner content and right wrapper
*/
function showHideInner() {
	if ( jQuery.address.value() !== '/' ) {
		jQuery( '#right-wrapper' ).css( 'overflow-x', 'hidden !important' ).css( 'overflow-y', 'hidden !important' );
		jQuery( '#right-wrapper' ).stop();
		jQuery( '#right-wrapper' ).animate( {
				width: '0px'
			},
			{
				duration: 1000,
				complete: showInner
			} );
		
		jQuery( '#header-right' ).stop();
		jQuery( '#header-right' ).animate( {
				width: '312px'
			},
			{
				duration: 300,
				complete: addTagline
			} );
		
		jQuery( '#content' ).stop();
		jQuery( '#content' ).css( 'background-image', 'url(images/SS_maincontent_textarea.png)' ).animate( {
				width: '622px'
			},
			{
				duration: 1000
			} );
		
		jQuery( '#nav-right-top .overlay' ).stop().fadeTo( 1000, 1 );
		jQuery( '#nav-right-bottom .overlay' ).stop().fadeTo( 1000, 1 );
		
		if ( !isLoggedIn() ) {
			jQuery( '#videoHolder' ).stop().fadeTo( 1000, 0 );
			jQuery( '#vidMask' ).stop().fadeTo( 1000, 0 );
		}
	} else {
		jQuery( '#right-wrapper' ).show().stop().animate( {
				width: '370px'
			},
			{
				duration: 1000,
				complete: hideInner
			} );
		
		jQuery( '#tagline' ).stop();
		jQuery( '#tagline' ).animate( {
				width: '0px',
				left: '517px'
			},
			{
				duration: 1000,
				complete: removeTagline
			} );
		
		jQuery( '#header-right' ).stop();
		jQuery( '#header-right' ).animate( {
				width: '195px'
			},
			{
				duration: 1000
			} );
		
		jQuery( '#content' ).stop();
		jQuery( '#content' ).animate( {
				width: '260px'
			},
			{
				duration: 1000,
				complete: hideContent
			} );
				
		jQuery( '#nav-right-top .overlay' ).stop().fadeTo( 1000, 0 );
		jQuery( '#nav-right-bottom .overlay' ).stop().fadeTo( 1000, 0 );
		
		if ( !isLoggedIn() ) {
			jQuery( '#videoHolder' ).stop().fadeTo( 1000, 1 );
			jQuery( '#vidMask' ).stop().fadeTo( 1000, 1 );
		}
	}
}

/**
* Starts the content switching, switches between homepage and inner content, adds link handlers to all sub navigation, sets the active links, and replaces pesky form components
*/
function fillContent( data ) {
	html_data = data;
	if ( !first ) {
		jQuery( '#contentHolder' ).stop().fadeTo( 800, 0, function() {
			jQuery('#contentHolder').css('visibility', 'hidden');
		} );
	} else {
		jQuery('#contentHolder').css('visibility', 'hidden');
		jQuery( '#contentHolder' ).html( data );
		fillRegisterValues();
		first = false;
		
		setActiveLinks();
		
		playVids();
	}
	
	showHideInner();
}

/**
* Handles loading new content when a change in the deep-linked value is triggered
*/
function changeAddress( evt ) {
	var val,
		$this = jQuery(this);
	
	if ( $this.attr('href') && $this.attr('href') !== undefined ) {
		val = $this.attr('href');
	} else {
		if ( evt.value && evt.value !== undefined ) {
			val = evt.value;
		} else {
			$().toastmessage( 'showToast', {type: 'error', text: 'Could not change address'} );
			return;
		}
	}
	
	val = val.substr(1).replace( (/\//g), '.' ) + '.html';
	if ( val === '.html' ) {
		val = 'home' + val;
	} else if ( val.indexOf( 'register' ) > -1 ) {
		if ( prevAddress && prevAddress.indexOf( 'register' ) > -1 ) {
			var vals = jQuery.address.value().toLowerCase().substr( 1 ).split( '/' );
			var section = '#wrapper' + vals[1].toString();
			jQuery( 'div.page' ).hide();
			jQuery( section ).show();
			return;
		} else {
			val = 'register.html';
		}
	} else if ( val.indexOf( 'schedule' ) > -1 ) {
		var d = new Date();
		if ( +DataStorage.get_data( 'loggedIn' ) < 1 || isNaN( +DataStorage.get_data( 'loggedIn' ) ) || Date( DataStorage.get_data( 'expires' ) ) < d ) {
			DataStorage.store_data( 'loggedIn', 0, d );
			DataStorage.store_data( 'expires', d, d );
			jQuery.address.value( '/' );
			return;
		}
	}
	
	jQuery( '#contentHolder' ).removeClass( 'contact' );
	if ( val.indexOf( 'contact' ) > -1 ) { jQuery( '#contentHolder' ).addClass( 'contact' ); }
	
	AjaxRequest.post( {
		"url": val,
		"onSuccess": function( req ) { fillContent( req.responseText ); },
		"onError": function( req ) { fillContent( req.responseText ); }
	} );
	
	prevAddress = jQuery.address.value().toLowerCase();
}

/**
* Animates account area closing
*/
function closeAccount() {
	jQuery( '#account-inner' ).stop().fadeTo( 800, 0, function() {
		jQuery( '#account-inner' ).css( {'right': '0px', 'width': '110px', 'height': '2em'} );
		jQuery( '#logged-in' ).hide();
		jQuery( '#login-form' ).hide();
		jQuery( '#login' ).show();
		jQuery( '#account-inner' ).removeClass( 'open' );
		opencloseAccount( true );
	} );
	
	accountOpen = false;
}

/**
* Handes content switching & animating fade in for new welcome text w/ user email and "inner" navigation
*/
function loginCompleteAnimation() {
	var fadeTime = 800,
		email = DataStorage.get_data( 'email' ),
		isOpen;
	email = (''+email).toUpperCase();
	
	isOpen = false;
	accountOpen = true;
	
	jQuery( '#account-inner' ).stop().fadeTo( fadeTime, 0, function() {
		var $this = jQuery(this);
		$this.css( {'right': '0px', 'width': '100%', 'height': 'auto'} );
		
		jQuery( '#login' ).hide();
		jQuery( '#logged-in' ).show();
		jQuery( '#login-form' ).hide();
		jQuery( '#logged-in-username' ).html( email );
		jQuery( '#logout' ).click( logout );
		jQuery( '#account-inner' ).stop().fadeTo( fadeTime, 1, function() {
			jQuery( '#videoHolder' ).stop(true, true).hide( 400, function() {
				jQuery( '#videoHolder' ).css('display', 'none');
				jQuery( '#innerNavHolder' ).stop(true, true).show( 400 );
			} );
			jQuery( '#vidMask' ).stop(true, true).hide( 400, function() {
				jQuery( '#vidMask' ).css('display','none');
			} );
		} );
		
		$this.addClass( 'open' );
		
		opencloseAccount( isOpen );
	} );
}

/**
* Handles logging out animations & process
* Handles removing "inner" nav & fading in video & video holder
*/
function logout() {
	DataStorage.delete_data( 'id' );
	DataStorage.delete_data( 'email' );
	DataStorage.delete_data( 'sessionID' );
	DataStorage.delete_data( 'expires' );
	
	jQuery( '#account-inner' ).stop().fadeTo( 800, 0, function() {
		jQuery( '#account-inner' ).removeClass( 'open' );
		jQuery( '#login-form' ).hide();
		jQuery( '#logged-in' ).hide();
		jQuery( '#login' ).show();
		jQuery( '#account-inner' ).removeAttr('style').css( 'width', '100%' );
		accountOpen = false;
	} );
	opencloseAccount( true );
	
	jQuery( '#innerNavHolder' ).stop(true, true).hide( 400, function() {
		jQuery( '#innerNavHolder' ).css('display', 'none');
		jQuery( '#videoHolder' ).stop(true, true).show( 400 );
		jQuery( '#vidMask' ).stop(true, true).show( 400 );
	} );
}

function isLoggedIn() {
	var expires = DataStorage.get_data('expires') || '',
		exdate = new Date(expires),
		email = DataStorage.get_data('email') || '',
		today = new Date();
		
	if ( exdate > today ) {
		return true;
	}
	return false;
}

/**
* Checks whether the user is logged in or not, if logged in & active will start animation of logging in process.
* 
* @IMPORTANT! Not meshing w/ timecodes from server, so everything is a bit off.
*/
function checkLoggedIn() {
	if ( isLoggedIn() ) {
		jQuery( '#account-inner' ).stop().fadeTo( 800, 0, function() {
			jQuery( '#account-inner' ).css( 'right', '0px' ).css( 'width', '100%' ).css( 'height', 'auto' );
			jQuery( "#loginLink" ).click( accountClickHandler );
			jQuery( '#account-inner' ).addClass( 'open' );
			jQuery( '#video-wrapper' ).stop().animate( { top: '-53px' }, { duration: 800 } );
			jQuery( '#content-wrapper' ).stop().animate( { left: '-12px' }, { duration: 800 } );
			jQuery( '#account' ).css( 'background-image', 'url(images/SS_open_loginbox.png)' ).stop().animate( {
					width: '259px',
					height: '53px'
				},
				{
					duration: 800,
					complete: function() { accountFadeIn(); loginCompleteAnimation(); }
				} );
		} );
		
		accountOpen = true;
	}
}

/**
* Main function, fires when DOM is ready
*/
function readyHandler() {
	jQuery( 'a' ).mouseup( function() { this.blur(); } );
	addNavHandlers();
	addAccountHandlers();
	checkLoggedIn();
	
	$.address.change( changeAddress );
	jQuery( 'a.deeplink' ).address();
	
	jQuery.easing.def = 'easeOutExpo';
}

jQuery( document ).ready( readyHandler );
