/*

Developed by:

      ___           ___                 
     /__/|         /__/\        ___     
    |  |:|         \  \:\      /  /\    
    |  |:|          \  \:\    /  /:/    
  __|  |:|      _____\__\:\  /__/::\    
 /__/\_|:|____ /__/::::::::\ \__\/\:\__ 
 \  \:\/:::::/ \  \:\~~\~~\/    \  \:\/\
  \  \::/~~~~   \  \:\  ~~~      \__\::/
   \  \:\        \  \:\          /__/:/ 
    \  \:\        \  \:\         \__\/  
     \__\/         \__\/               

*/

//_stat(1,'video','bonus','click');

_stat = function(paramID,paramCat,paramType,paramAction){
	api.callMethod('stats.hit',{data:{cat:paramCat,id:paramID,type:paramType,action:paramAction}});
}


/*******************************
             Cufon
*******************************/
	
// header breadcrumb
Cufon.replace('header h2.breadcrumb', { 
	fontFamily: 'Vonnes',
	color: '-linear-gradient(#C4C4C4, #A4A4A4)',
	hover: {
		color: '#9A9A9A'
	}
});
// header section
Cufon.replace('header h2.section', { 
	fontFamily: 'Vonnes',
	color: '-linear-gradient(#7A7A7A, #3A3A3A)'
});
// menu font replacement
Cufon.replace('#home #content li h4', { 
	fontFamily: 'Vonnes',
	color: '-linear-gradient(#808080, #3A3A3A)',
	hover: {
		color: '#3A3A3A'
	}
});
// achievement popup
Cufon.replace('#content .achievement h3, #content .certificate h3', { 
	fontFamily: 'Vonnes'
});


/*******************************
          Ready Event
*******************************/


sbcu.readyEvent = function() {
	
	// what are we dealing with
	sbcu.iPad = sbcu.isiPad();
	sbcu.iPhone = sbcu.isiPhone();
	
	// os detection
	$.os = {
		name: (sbcu.iPad || sbcu.iPhone) ? 'mobileSafari' : (/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase()))[0].replace('sunos', 'solaris')
	};
	
	// iDevice specific event ternarys
	sbcu.handleClick = (sbcu.iPad || sbcu.iPhone) ? ('touchstart') : ('click');
	sbcu.handleDown = (sbcu.iPad || sbcu.iPhone) ? ('touchstart') : ('mousedown');
	sbcu.handleUp = (sbcu.iPad || sbcu.iPhone) ? ('touchend') : ('mouseup');
	
	// Attach custom stylesheets
	if(sbcu.iPad || sbcu.iPhone || $.os.name == 'mac' || $.browser.safari) {
		$('head').append('<link rel="stylesheet" type="text/css" charset="utf-8" href="style/browsers/mac.css" />');
	}
	
	// Prompt for chrome frame install if configured
	if($.browser.msie && parseInt($.browser.version) < 7 && sbcu.config.chromeFrameRequired) {
		sbcu.chromeFrameInstall();
	}
	
	
	$('#get-privacy').click(function(){
		$('#privacy-policy').reveal({animation:'fade'});
		return false;
	});
	
	//$(".chzn-select").chosen();
	//take over
	
	var divTakeOver='#take-over';
	var isTakeOver = $(divTakeOver);
	var canUpdateA=0;
	var canUpdateB=0;
	if(isTakeOver){
			
			$('#update-account').hide();
			
			$(divTakeOver).reveal({
			     animation: 'fade',                   //fade, fadeAndPop, none
			     closeonbackgroundclick: false
			});
			
			
			//$(".chzn-select").chosen();
			
			var checkObj = {};
			function listenTakeOver(){
				checkObj.riders=new Array();
				checkObj.jobs=new Array();
					var check_a=0; var check_b=0;
				$(".theRiderTypes input").each(function(){
					var isChecked = $(this).attr('checked');
					var pVal = $(this).val();
					if(isChecked){
						check_a+=1; 
						checkObj.riders.push(pVal);
					}
				});
				$(".theJobFunctions input").each(function(){
					var isChecked = $(this).attr('checked');
					var pVal = $(this).val();
					if(isChecked){
						check_b+=1; 
						checkObj.jobs.push(pVal);
					}
				});
			
				return ((check_a>0) && (check_b>0)) ? true :false;
			};
			//on each check
			$('#checks input').click(function(){
				
				var isValid = listenTakeOver();
				if(isValid) $('#update-account').show();
			});

			
			$('#update-account').click(function(){
				var isValid = listenTakeOver();
				if(isValid){
					var jobs = checkObj.jobs.join(",");
					var riders = checkObj.riders.join(",");
					api.callMethod("users.updateRiderJobs",{
						data:{RiderTypes:riders,JobFunctions:jobs},
						callback:function(theResponse){
							$(divTakeOver).trigger('reveal:close');
						}
					});
				}
					
			});
		
	}

	/*******************************
			Event Handlers
	*******************************/
	// shorthand	
	var config = sbcu.config,
		handleClick = sbcu.handleClick,
		handleDown = sbcu.handleDown,
		handleUp = sbcu.handleUp
	;
	
	var handler = sbcu.handler = {
		// tabs
		tabs: {
			click: function(event) {
				// cache
				var $tab = $(this);
				var $tabs = $('#content .tabs li');
				var $link = $tab.find('a');
				var $tabContent = $('#content .tab');
				
				if(!$tab.hasClass('active')) {
					var section = $link.attr('class');
					$tab.removeClass('hover');
					// record history
					$.address.value(section+'/'); 
					// fix tabs
					$tabs.removeClass('active');
					$tab.addClass('active');
					$tabContent
						.removeClass('open')
						.filter('#'+section)
							.addClass('open')
					;
				}
				event.stopImmediatePropagation();
				return false;
			},
			// handles hash change event for tabs
			hash: function(event) {
				if(typeof(event.pathNames[0]) != 'undefined') {
					var section = event.pathNames[0];
					$('#'+section)
						.addClass('open')
						.siblings('.tab')
							.removeClass('open')
					;
					$('#content .tabs .'+section)
						.parent()
							.addClass('active')
							.siblings()
								.removeClass('active')
					;
				}
			}
		},
		account: {
			process: {
				login: function(email, password, params) {
					var settings = {
						onSuccess: function() {},
						onFailure: function() {},
						onError: function() {}
					};
					$.extend(settings, params);
					$.ajax({
						data: {
							email: email,
							password: password	
						},
						dataType: 'json',
						type: "POST",
						url: config.services.login,
						error: settings.onError,
						success: function(response) {
							if(typeof response == 'undefined') {
								settings.onError(response);
							}
							else {
								if(!response.failed) {
									settings.onSuccess(response);	
								}
								else {
									settings.onFailure(response);
								}
							}
						}
					});						
				},
				logout: function(params) {
					var settings = {
						onSuccess: function() {},
						onFailure: function() {},
						onError: function() {}
					};
					$.extend(settings, params);
					$.ajax({
						dataType: 'json',
						type: "POST",
						url: config.services.logout,
						error: settings.onError,
						success: function(response) {
							if(typeof response == 'undefined') {
								settings.onError(response);
							}
							else {
								if(!response.failed) {
									settings.onSuccess(response);	
								}
								else {
									settings.onFailure(response);
								}
							}
						}
					});						
				},
				forgotPassword: function(email, params) {
					var settings = {
						onSuccess: function() {},
						onFailure: function() {},
						onError: function() {}
					};
					$.extend(settings, params);
					$.ajax({
						data: {
							email: email
						},
						dataType: 'json',
						type: "POST",
						url: config.services.forgotPassword,
						error: settings.onError,
						success: function(response) {
							if(typeof response == 'undefined') {
								settings.onError(response);
							}
							else {
								if(!response.failed) {
									settings.onSuccess(response);	
								}
								else {
									settings.onFailure(response);
								}
							}
						}
					});						
				}
			},
			panel: {
				login: function() {
					var email = $('#email').val();
					var password = $('#password').val();
					var $header = $('#login-panel .login-form h4');
					var accountHandler = sbcu.handler.account;
					var errors = sbcu.config.errors;
					
					if(!sbcu.isEmail(email)) {
						$header
							.addClass('error')
							.html(errors.email)
						;
						return false;					
					}
					accountHandler.process.login(email, password, {
						onError: function(response) {
							$header
								.addClass('error')
								.html(errors.server.general)
							;
						},
						onFailure: function(response) {
							// use return message if specified
							var error = typeof response.errors[0] != 'undefined' 
								? response.errors[0]
								: errors.server.general
							;
							$header
								.addClass('error')
								.html(error)
							;
						
						},
						onSuccess: function(response) {
							var $user = $('header .user');
							$user
								.addClass('active')
								.find('.logged-in b')
									.html(response.data.Name)
							;
							accountHandler.panel.cancel();
							// refresh page
							window.location.reload()
						}
					});
				},
				forgotPassword: function(){
					var email = $('#forgot-email').val();
					var $header = $('#login-panel .password-form h4');
					var accountHandler = sbcu.handler.account;
					var errors = sbcu.config.errors;
					
					if(!sbcu.isEmail(email)) {
						$header
							.addClass('error')
							.html(errors.email)
						;
						return false;						
					}
					accountHandler.process.forgotPassword(email, {
						onError: function(response) {
							$header
								.addClass('error')
								.html(errors.server.general)
							;
						},
						onFailure: function(response) {
							// use return message if specified
							var error = typeof response.errors[0] != 'undefined' 
								? response.errors[0]
								: errors.server.general
							;
							$header
								.addClass('error')
								.html(error)
							;
						
						},
						onSuccess: function(response) {
							$header
								.addClass('error')
								.html('Password sent to your e-mail')
							;
						}
					});				
				},
				logout: function() {
					var accountHandler = sbcu.handler.account;
					accountHandler.process.logout({
						onSuccess: function(response) {
							var $user = $('header .user');
							$user.removeClass('active');
							// refresh page
							var base = $('base').attr('href');
							window.location = base + './';
						}
					});
					return false;
				},
				show: function() {
					var $loginPanel = $('#login-panel');
					var $loginForm = $loginPanel.find('.login-form');
					var $passwordForm = $loginPanel.find('.password-form');
					var $login = $loginForm.find('.log-in');
					var $cancel = $loginForm.find('.cancel');
					var $send = $passwordForm.find('.send');
					
					// show modal
					$.dimScreen(300, 0.5);
					$('#dimmer').bind('click', sbcu.handler.account.panel.cancel);
					$loginPanel.show();
					// focus on first input field
					$loginForm.find('input:visible').eq(0)[0].focus();
					// add keyboard events
					$(window)
						.bind('keydown.submit', function(event) {
							var enterKey = 13,
								escapeKey = 27,
								keyCode = event.keyCode
							;
							// enter key
							if(keyCode == enterKey) {
								if($loginForm.visible()) {
									$login.addClass('down');
								}
								else if($passwordForm.visible()) {
									$send.addClass('down');	
								}
							}
							// escape key
							if(keyCode == escapeKey) {
								$cancel.addClass('down');
							}
						})
						.bind('keyup.submit', function(event) {
							var enterKey = 13,
								escapeKey = 27,
								keyCode = event.keyCode
							;
							if(keyCode == enterKey) {
								if($loginForm.visible()) {
									$login.removeClass('down');
									sbcu.handler.account.panel.login();
								}
								else if($passwordForm.visible()) {
									$send.removeClass('down');
									sbcu.handler.account.panel.forgotPassword();	
								}
							}
							if(keyCode == escapeKey) {
								$cancel.removeClass('down');
								sbcu.handler.account.panel.cancel();	
							}
						}
					);
					return false;
				},
				showLoginForm: function() {
					var $loginPanel = $('#login-panel');
					var $loginForm = $loginPanel.find('.login-form');
					var $passwordForm = $loginPanel.find('.password-form');
					$passwordForm.hide();
					$loginForm.fadeIn(300);
					return false;
				},
				showPasswordForm: function() {
					var $loginPanel = $('#login-panel');
					var $loginForm = $loginPanel.find('.login-form');
					var $passwordForm = $loginPanel.find('.password-form');
					$loginForm.hide();
					$passwordForm.fadeIn(300);
					return false;
				},
				cancel: function() {
					var $loginPanel = $('#login-panel');
					var $loginForm = $loginPanel.find('.login-form');
					var $passwordForm = $loginPanel.find('.password-form');
					// unbind submit enter key
					$(window).unbind('.submit');
					// hide modal
					$.unDimScreen(300);
					$passwordForm.hide();
					$loginForm.show();
					$loginPanel.hide();
					return false;
				}
			}
		},
		progress: {
			toggle: {
				click: function() {
					var $toggle = $(this);
					var $details = $toggle.next('.details');
					var $detailContent = $details.children();
					// open panel
					if(!$toggle.hasClass('hide')) {
						$toggle.addClass('hide');
						$detailContent.css('opacity',0);
						$details
							.stop()
							.slideDown({
								duration: 350,
								easing: 'easeOutQuad',
								complete: function() {
									$detailContent
										.stop()
										.animate({opacity: 1}, 300)
									;	
								}
							})
						;
					}
					else {
						$toggle.removeClass('hide');
						$detailContent
							.stop()
							.animate({opacity: 0}, 300, function() {
								$details
									.stop()
									.slideUp(350, 'easeOutQuad')
								;
							})
						;
					}
				}
			}
		},
		store: {
			deleteEmployee: {
				click: function() {
					if( confirm(config.messages.confirmDelete) ) {
						var $user = $(this).parents('li');
						var userID = $user.find('.id').html();
						// delete content
						$.ajax({
							data: {
								id: userID
							},
							dataType: 'json',
							type: "GET",
							url: config.services.userDelete,
							error: function() {
								// alert standard messsage
								alert(config.errors.server.general);
							},
							success: function(response) {
								// hide loader
								if(typeof(response.failed) == 'undefined') {
									alert(config.errors.server.general);							
								}
								else if(response.failed) {
									if(response.errors) {
										var errorMessage = '';
										$.each(response.errors, function() {
											errorMessage += response.errors+' ';	
										});
										alert(errorMessage);
									}
								}
								else {
									$user.fadeOut(400);
								}
							}
						});						
					}
					return false;
				}
			}
		},
		employee: {
			bonusVideo: {
				play: {
					click: function($this) {
						var $image = $this.find('.posterframe img');
						var $li = $this;
						var $flv = $this.find('.flv');
						var $videoEmbed = $('#videos .video-embed');
						var $scaledImage = $('#videos .scale');
						var $start = $('#videos .start');
						
						_stat($li.data('id'),'video','bonus','click');
						
						$.dimScreen(300, 0.8, function() {
							// grab width
							var position = $li.position();
							// if a scale exists dont redo
							if(!$scaledImage.exists()) {
								$start.css('visibility', 'hidden');
								// grab flv id
								var flvID = $flv.html();
								// grab html for youtube embed
								var html = sbcu.youtubeEmbed(flvID, {
									width: '907px',
									height: '538px',
									wmode: 'window',
									bgColor: '#000000'
								});
								// add youtube embed code
								$videoEmbed
									.find('.youtube')
										.html(html)
								;
								$image
									.clone()
									// store position for return animation
									.data('position', position)
									.css({
										top: position.top, 
										left: position.left,
										width: '152px',
										height: '98px'
									})
									.addClass('scale')
									.appendTo('#videos')
									.animate({ 
										top: '20px',
										left: '0px',
										width: '907px',
										height: '538px'
									}, 400, function() {
										$videoEmbed.show();
									})
								;				
							}
						});
					}
				},
				close: {
					click: function() {
						var $videoEmbed = $('#videos .video-embed');
						var $scaledImage = $('#content .scale');
						var position = $scaledImage.data('position');
						$videoEmbed.hide()
						// clear movie, fixes ie play bug
						$videoEmbed.find('.youtube').empty();
						// wait longer bc ie is slower garbage collection
						var animationDelay = ($.browser.msie)
							? 250
							: 150
						;
						setTimeout(function() {
							$scaledImage
								.animate({
									top: position.top, 
									left: position.left,
									width: '152px',
									height: '98px'
								}, 400, function() {
									$.unDimScreen(300);
									$(this).remove();	
								})
							;
						}, animationDelay);
					}
				}
				
			}
		},
		test: {
			featureVideo: {
				click: function($this) {
					$this
						.hide()
						.next('.embed')
							.show()
					;
					return false;	
				},
				hide: function() {
					$('#overview .video')
						.find('.poster')
							.show()
							.end()
						.find('.embed')
							.hide()
					;
				}
			},
			photo: {
				arrow: {
					mouseenter: function() {
						$(this)
							.animate({
								scale: [1.2, 1.2]	
							}, 150)
						;
					},
					mouseleave: function() {
						$(this)
							.animate({
								scale: [1, 1]	
							}, 150)
						;						
					},
					click: function($this) {
						var $this = $(this);
						var $photoThumbs = $('#photos li');
						var $popup = $('#photos .photo-popup');
						var $ui = $('#photos .photo-popup .close, #photos .photo-popup .prompt');
						var index = $popup.find('.image img').data('index');
						var numThumbs = $photoThumbs.size();
						var animationDuration = 0;
						
					//	_stat($this.data('id'),'photo','test','click');
						
						
						// cycle through images
						index = (index == (numThumbs-1)) 
							? 0
							: index+1
						;
						var position = $photoThumbs.eq(index).position();
						var $newImage = $photoThumbs
							.eq(index)
							.find('.fullsize img')
							.clone()
						;
						// use clone to find image width
						var $imgClone = 
							$newImage
							.clone()
							.addClass('offstage')
							.appendTo($('body'))
						;
						var width = $imgClone.width();
						var height = $imgClone.height();
						$imgClone.remove();
						var $galleryClone = $newImage
							.clone()
							.data('position', position)
							.data('index', index)
						;
						$ui.hide();
						$popup
							.css({
								width: $popup.width(),
								height: $popup.height()
							})
							.find('.image')
								// remove old images
								.children()
									.remove()
									.end()
								// add new photo
								.append($galleryClone)
								.end()
							// animate to final resting position
							.animate({
								opacity: 1,
								width: width,
								height: height,
								top: '35px',
								left: ((909-width)/2)+'px'	
							}, animationDuration, 'easeOutQuad', function(){
								$ui.not('.disabled').fadeIn(animationDuration);
							})
						;
					}
				},
				open: {
					click: function($this) {
						var $overlay = $('#photos .overlay');
						var $popup = $('#photos .photo-popup');
						var $photoThumbs = $('#photos li');
						var $ui = $('#photos .photo-popup .close, #photos .photo-popup .prompt');
						var position = $this.position();
						var index = $photoThumbs.index($this);
						var numThumbs = $photoThumbs.size();
						// use clone to find image width
						var $imgClone = $this
							.find('.fullsize img')
							.clone()
						;
						var width = $imgClone
							.addClass('offstage')
							.appendTo($('body'))
							.width()
						;
						$imgClone.remove();
						var $galleryClone = $this
							.find('.fullsize img')
							.clone()
							.data('position', position)
							.data('index', index)
						;
						var animationDuration = ($.browser.msie)
							? 0
							: 400
						;
						$overlay.fadeIn(400);
						$ui.hide();
						$popup
							.find('.image')
								// remove old images
								.children()
									.remove()
									.end()
								// add new photo
								.append($galleryClone)
								.end()
							.css({
								top: position.top,
								left: position.left,
								opacity: 0.6
							})
							.show()
							// animate to final resting position
							.animate({
								opacity: 1,
								width: width,
								top: '35px',
								left: ((909-width)/2)+'px'	
							}, 450, 'easeOutQuad', function() { 
								if($.browser.msie) {
									$(this).css('filter','');	
								}
								$ui.fadeIn(animationDuration);
							})
						;						
					}
				},
				close: {
					click: function() {
						var $overlay = $('#photos .overlay');
						var $popup = $('#photos .photo-popup');
						var $ui = $('#photos .photo-popup .close, #photos .photo-popup .prompt');
						var position = $popup.find('.image img').data('position');
						var index = $popup.find('.image img').data('index');
						var thumbSRC = $('#photos li').eq(index).find('img').attr('src');
						var animationDuration = ($.browser.msie)
							? 0
							: 400
						;
						$overlay.fadeOut(400);
						$ui.fadeOut(animationDuration);
						
						var currentPosition = {
							top: parseInt($popup.css('top'), 10),
							left: parseInt($popup.css('left'), 10)
						}
						
						setTimeout(function() {
							$popup
								.css({ 
									width: ($popup.width() / 2),
									top: (currentPosition.top + Math.abs((currentPosition.top - position.top) / 2)),
									left: (currentPosition.left + Math.abs((currentPosition.left - position.left) / 2))
								})
								.find('img')
									.attr('src', thumbSRC)
									.end()
								.animate({
									opacity: 0.6,
									top: position.top,
									left: position.left,
									width: '105'
								}, 450, 'easeOutQuad', function() {
									$popup.hide();	
								})
							;
						}, 150);
					}
				}
			},
			video: {
				play: {
					click: function($this) {
						var $image = $this.find('.posterframe img');
						var $li = $this.parent();
						var $flv = $this.find('.flv');
						var $videoEmbed = $('#videos .video-embed');
						var $scaledImage = $('#videos .scale');
						var $start = $('#videos .start');
					
						//let's run a stat
						_stat($li.attr('data-id'),'video','test','click');
						
						// grab width
						var position = $li.position();
						// if a scale exists dont redo
						if(!$scaledImage.exists()) {
							$start.css('visibility', 'hidden');
							// grab flv id
							var flvID = $flv.html();
							// grab html for youtube embed
							var html = sbcu.youtubeEmbed(flvID);
							// add youtube embed code
							$videoEmbed
								.find('.youtube')
									.html(html)
							;
							$image
								.clone()
								// store position for return animation
								.data('position', position)
								.css({
									top: position.top, 
									left: position.left,
									width: '267px',
									height: '150px'
								})
								.addClass('scale')
								.appendTo('#videos')
								.animate({ 
									top: '27px',
									left: '26px',
									width: '853px',
									height: '506px'
								}, 400, function() {
									$videoEmbed.show();
								})
							;				
						}
					}
				},
				close: {
					click: function() {
						var $videoEmbed = $('#videos .video-embed');
						var $scaledImage = $('#content .scale');
						var position = $scaledImage.data('position');
						$videoEmbed.hide()
						
						
						
						// clear movie, fixes ie play bug
						$videoEmbed.find('.youtube').empty();
						// wait longer bc ie is slower garbage collection
						var animationDelay = ($.browser.msie)
							? 250
							: 150
						;
						setTimeout(function() {
							$scaledImage
								.animate({
									top: position.top, 
									left: position.left,
									width: '267px',
									height: '150px'
								}, 400, function() {
									$(this).remove();	
								})
							;
						}, animationDelay);
					}
				}
				
			},
			// test start button handlers
			start: {
				click: function() {
					var $quiz = $('#content .quiz');
					var $ready = $('#content .ready');
					// disable all start buttons
					$ready.addClass('hide');
					$quiz.show();
				}
			},
			hide: {
				click: function() {
					var $quiz = $('#content .quiz');
					var $ready = $('#content .ready');
					// disable all start buttons
					$ready.removeClass('hide');
					$quiz.hide();	
				}
			},
			// test complete handlers
			complete: {
				click: function() {
					// grab answers
					var $quiz = $('#content .quiz form');
					var $loader = $('#content .quiz .loading');
					var $message = $quiz.find('.message');
					// show loader
					$loader.show();
					$message.hide();
					// each form
					var answerCSV = '';
					var questionCount = $('.question').size();
					// optimized loop
					for(var index=1; index<=questionCount; index++) {
						var answer = $('input[name=question'+index+']:checked').val();
						if(typeof(answer) == 'undefined') {
							answer = 0;
						}
						answerCSV += (index==1)
							? answer
							: ',' + answer
						;
					}
					var testID = $('#test-id').val();
					// hit test validation
					$.ajax({
						data: {
							answers: answerCSV,
							id: testID
						},
						dataType: 'json',
						type: "POST",
						url: config.services.quiz,
						error: function() {
							$loader.fadeOut(400);
							$message
								.addClass('error')
								.html(config.errors.server.general)
								.fadeIn(100);
							;
							// error handling goes here	
						},
						success: function(response) {
							var $questions = $quiz.find('.question');
							// hide loader
							$loader.fadeOut(400);
							// Get rid of old invalid questions
							$questions.removeClass('incorrect');
							if(typeof(response.failed) == 'undefined') {
								$message
									.addClass('error')
									.html(config.errors.server.general)
									.fadeIn(100);
								;								
							}
							else if(response.failed) {
								var data = response.data
								// add marker for incorrect questions
								if(data.incorrectQuestions) {
									var incorrectQuestions = data.incorrectQuestions;
									$.each(incorrectQuestions, function(index, question) {
										var questionIndex = question - 1;
										$questions.eq(questionIndex).addClass('incorrect');
									});
								}
								// add error messages
								if(response.errors) {
									var errorMessage = '';
									$.each(response.errors, function() {
										errorMessage += response.errors+' ';	
									});
									setTimeout(function() {
										$message
											.addClass('error')
											.html(errorMessage)
											.fadeIn(100);
										;
									}, 500);
								}
							}
							else {
								var data = response.data
								var $video = $('#overview .video');
								$message
									.addClass('success')
									.hide()
								;
								if(typeof(data.achievementMessage != 'undefined')) {
									var achievementMessage = data.achievementMessage;	
								}
								// hide youtube video for overlay issues
								$video
									.find('.embed')
										.hide()
										.end()
									.find('.poster')
										.show()
								;						
								// show certificate
								if(typeof(data.finished) != 'undefined' && data.finished) {
									sbcu.handler.test.showCertificate();
								}								
								// show achievement
								else {
									sbcu.handler.test.showAchievement(achievementMessage);
								}
							}
						}
					});					
				}
			},
			showCertificate: function() {
				var $certificate = $('#content .certificate');
				$.dimScreen(300, 0.8, function() {
					if($.browser.msie) {
						$certificate.show();
					}
					else {
						// add audio
						var $audio = $('<audio/>')
							.attr('autobuffer','autobuffer')
							.attr('autoplay','autoplay')
						;
						// add sound
						$('<source/>')
							.attr('src','media/sounds/fanfare.mp3')
							.appendTo($audio)
						;
						$('<source/>')
							.attr('src','media/sounds/fanfare.ogg')
							.appendTo($audio)
						;
						$certificate.fadeIn(400);	
						$certificate.append($audio);
					}
				});
			},
			showAchievement: function(message) {
				var $achievement = $('#content .achievement');
				var $achievementMessage = $achievement.find('p');
				var $stamp = $achievement.find('.stamp');
				
				// add text
				$achievementMessage.html(message);
				
				$.dimScreen(300, 0.8, function() {
					if($.browser.msie) {
						$achievement.show();
						$stamp.show();
					}
					else {
						// add audio
						var $audio = $('<audio/>')
							.attr('autobuffer','autobuffer')
							.attr('autoplay','autoplay')
						;
						// add sound
						$('<source/>')
							.attr('src','media/sounds/complete.mp3')
							.appendTo($audio)
						;
						// add sound
						$('<source/>')
							.attr('src','media/sounds/complete.ogg')
							.appendTo($audio)
						;
						// add stamp
						$stamp
							.transform({
								scale: [1.5, 1.5]
							})
							.css('opacity', 0)
						;
						$achievement.fadeIn(400);	
						$achievement.append($audio);
						setTimeout(function() {
							$stamp.animate({
								opacity: 1,
								scale: [1, 1]
							}, 400, 'easeOutQuad');
						}, 1000);
					}
				});
			}
		}
	};

	sbcu.section = sbcu.findSection();
	
	/*******************************
	           Login Code  
	*******************************/
	// Login is on all pages
	var $login = $('header .login');
	var $loginPanel = $('#login-panel');
	var $email = $('#email');
	var $forgotEmail = $('#forgot-email');
	var $password = $('#password');
	
	var $logoutButton = $('header .user .logout a');
	
	var $forgotPassword = $loginPanel.find('.forgot');
	var $returnToLogin = $loginPanel.find('.return');
	
	var $loginButton = $loginPanel.find('.log-in');
	var $cancelButton = $loginPanel.find('.cancel');
	var $sendButton = $loginPanel.find('.send');
	var $buttons = $loginPanel.find('.buttons div');
	
	$login.bind('click', handler.account.panel.show);
	// preserve prompt text values
	$email.inputPrompt('e-mail address');
	$forgotEmail.inputPrompt('e-mail address');
	$password.inputPrompt('password');
	// hover and down class on buttons
	$buttons
		.hoverClass()
		.downClass()
	;
	// do actions
	$loginButton.bind('click', handler.account.panel.login);
	$cancelButton.bind('click', handler.account.panel.cancel);
	$sendButton.bind('click', handler.account.panel.forgotPassword);
	$logoutButton.bind('click', handler.account.panel.logout);
	// change panels
	$returnToLogin.bind('click', handler.account.panel.showLoginForm);
	$forgotPassword.bind('click', handler.account.panel.showPasswordForm);
	
	//new downloads nav
	$downsNav = $('#download-nav');
	$downsLink= $('#download-link');
//	$downsNav.hide();
	$downsLink.bind('mouseover',function(){
		$downsNav.show();
	});
	$downsLink.bind('mouseleave',function(e){
		if(e.pageY > 60){
			$downsNav.hide();
		}
	});
	$downsNav.bind('mouseleave',function(){
		$downsNav.hide();
	});
	
	
	/*******************************
	        Section Specific
	*******************************/
	
	if(sbcu.section == 'home') {
		
		var handler = handler.home;
		
		
	}
	
	if(sbcu.section == 'downloads') {
		
		$('#download-items li').click(function(){
			var aLink = $(this).find('a').attr('href');
			window.open(aLink);
			return false;
		});
		
		
	}
	if(sbcu.section == 'sign-up') {
		
		
		
		var $fullName = $('#full-name');
		var $email = $('#e-mail');
		var $password = $('#pass');
		var $accountNumber = $('#account-number');
		var $signupForm = $('#content .left form');
		var $submitButton = $signupForm.find('.submit');
		
		var $JobFunctions = $('#JobFunctions');
		var $RiderTypes = $('#RiderTypes');
		
		
		$(".theJobFunctions input").click(function(){
			var isSome = $(this).attr('checked');
			var cVal = $('#JobFunctionsVal').val();
				//$('#JobFunctionsVal').val(newVal);
		});
		
		$(".theRiderTypes input").click(function(){
			var isSome = $(this).val();
			var newVal = (isSome) ? 'full' : '';
			//$('#RiderTypesVal').val(newVal);
		});
			
	
			
		var form = config.form;
		
		// default text
		$fullName.inputPrompt(form.defaultText.fullName);
		$email.inputPrompt(form.defaultText.email);
		$password.inputPrompt(form.defaultText.password);
		$accountNumber.inputPrompt(form.defaultText.accountNumber);		
		
		
		
		// submit button styles
		$submitButton
			.hoverClass()
			.downClass()
		;
		
		// validate register form on submit
		$signupForm.validateForm(form.validation, {
			onFailure: function(errors) {
				var $errors = $('#content .errors');
				// generate errors
				var errorList = '<ul>';
				jQuery.each(errors, function(i, error) {
					errorList += '<li>'+error+'</li>';						  
				});
				errorList += '</ul>';
				$errors
					.html(errorList)
					.show()
				;
				return false;
			},
			inlinePrompt: false
		});
		
	}
	if(sbcu.section == 'shop') {
		var handler = handler.store;
		
		var $tabs = $('#content .tabs li');
		var $formFields = $('#content select');
		var $progressToggle = $('#content .panel .toggle');
		var $listView = $('#content .list-view > li');
		var $storeSelect = $('#store-select select');
		var $sortSelect = $('#sort');
		
		// store swap
		$storeSelect
			.bind('change', function() {
				var base = $('base').attr('href');
				window.location = base + $(this).val();
			})
			.uniform()
		;
		// sort swap
		$sortSelect
			.bind('change', function() {
				var base = $('base').attr('href');
				window.location = base + $(this).val();
			})
		;
		
		// handle history event
		$.address.change(sbcu.handler.tabs.hash);
		// add form styling
		$formFields.uniform();
		// attach tab events
		$tabs
			.hoverClass()
			.bind('click', sbcu.handler.tabs.click)
		;
		
		$listView
			.followLink()
			.find('.delete')
				.bind('click', handler.deleteEmployee.click)
		;
		
		$progressToggle
			.hoverClass()
			.bind('click', sbcu.handler.progress.toggle.click)
		;
		
		$listView
			.hoverClass()
			.downClass()
			.find('.delete')
				.hoverClass()
		;
		
		
		/* Add / Edit User Form */
		var form = config.form;
		
		/* Extend form config with new employee specific text */
		$.extend(form, {
			validation: {
				fullName: [{
					identifier: 'full-name',
					type: 'empty',
					prompt: 'Please enter your employee\'s full name'
				}],
				email: [{
					identifier: 'e-mail',
					type: 'empty',
					prompt: 'Please enter your employee\'s email'
				}]
			}
		}, true);
		
		
		
		$('#employees button[type=submit]')
			.hoverClass()
			.downClass()
		;
		var $employeeForm = $('#employees form.inline');
		var $fullName = $('#full-name');
		var $email = $('#e-mail');
		var $password = $('#pass');
		// preserve prompt text values
		$fullName.inputPrompt('Employee\'s Full Name');
		$email.inputPrompt('e-mail address');
		$password.inputPrompt('password');
		// validate register form on submit
		$employeeForm.validateForm(form.validation, {
			onFailure: function(errors) {
				var $errors = $('#content .errors');
				// generate errors
				var errorList = '<ul>';
				jQuery.each(errors, function(i, error) {
					errorList += '<li>'+error+'</li>';						  
				});
				errorList += '</ul>';
				$errors
					.html(errorList)
					.show()
				;
				return false;
			},
			inlinePrompt: false
		});
		
	}
	if(sbcu.section == 'employee') {
		
		
		var TheAccord = $( "#accordion" ).accordion({ autoHeight: false,active: false,
	    collapsible: true});
		
		$('#course-select').change(function(){
			var opt = $(this).val();
			//alert(TheAccord);
			//TheAccord.accordion("activate",opt);
		});
		
		
		var handler = handler.employee;
		
		var $incompleteTests = $('#content #tests li');
		var $unlockedVideos = $('#content #videos li:not(.locked');
		var $bonusVideoThumb = $('#videos li:not(.locked)');
		var $bonusVideoClose = $('#videos .video-embed .close');
		
		$unlockedVideos
			.hoverClass()
			.touchClass()
			.followLink()
		;
		
		$incompleteTests
			.hoverClass()
			.touchClass()
			.followLink()
		;
		
		/* Bonus Video */
		$bonusVideoThumb
			.smoothHover(200)
			.smoothDown(200, {
				instantOn: true,
				click: handler.bonusVideo.play.click
			})
		;
		
		$bonusVideoClose
			.smoothHover(200)
			.smoothDown(200, {
				instantOn: true,
				click: handler.bonusVideo.close.click
			})
		;
		
	}
	if(sbcu.section == 'test') {
		// cache		
		var $tabs = $('#content .tabs li');
		var $start = $('#content .start');
		var $hide = $('#content .ready .close');
		var $complete = $('#content .complete');
		var $formFields = $('#content .radio');
		
		var $featureVideoPoster = $('#overview .video .poster');
		
		var $videoThumb = $('#videos .thumb');
		var $videoClose = $('#videos .video-embed .close');
		
		var $photoThumb = $('#photos li');
		var $photoClose = $('#photos .photo-popup .close');
		var $photoImage = $('#photos .photo-popup .image');
		
		var $modalButtons = $('#content .achievement .main-menu, #content .certificate .main-menu, #content .certificate .print');
		
		var $downloads = $('#tools .right li');
		
		
		$('#tools .right li').click(function(){
			_stat($(this).attr('data-id'),'download','test','click');
		});
		
		
		var handler = handler.test;
		
		
		// handle history event
		$.address.change(sbcu.handler.tabs.hash);
		// add form styling
		$formFields.uniform();
		
		// attach events
		$tabs
			.hoverClass()
			.bind('click', handler.featureVideo.hide)
			.bind('click', sbcu.handler.tabs.click)
		;
		// quiz start and hide handlers
		$start
			.smoothHover(200)
			.smoothDown(0, {
				instantOn: true,
				click: handler.start.click
			})
		;
		$hide
			.hoverClass()
			.click(handler.hide.click)
		;
		
		$complete
			.not('.disabled')
				.smoothHover(200)
				.smoothDown(0, {
					instantOn: true,
					click: handler.complete.click
				})
		;
		$featureVideoPoster
			.smoothHover(200)
			.smoothDown(0, {
				instantOn: true,
				click: handler.featureVideo.click
			})
		;
		
		/* Video Tab */
		$videoThumb
			.smoothHover(200)
			.smoothDown(200, {
				instantOn: true,
				click: handler.video.play.click
			})
		;
		
		$videoClose
			.smoothHover(200)
			.smoothDown(200, {
				instantOn: true,
				click: handler.video.close.click
			})
		;
		
		/* Photo Tab */
		$photoThumb
			.smoothHover(200)
			.smoothDown(200, {
				instantOn: true,
				click: handler.photo.open.click
			})
		;
		$photoClose
			.smoothHover(200)
			.smoothDown(200, {
				instantOn: true,
				click: handler.photo.close.click
			})
		;	
		$photoImage
			.bind('click', handler.photo.arrow.click)
		;
		
		/* Tools Tab */
		$downloads
			.hoverClass()
			.downClass()
			.touchClass()
			.followLink()
		;
		
		$modalButtons
			.hoverClass()
			.downClass()
		;
	}
	
	if(sbcu.section == 'info') {
		// cache
		var $tabs = $('#content .tabs li');	
		
		// attach events
		$.address.change(sbcu.handler.tabs.hash);
		$tabs
			.hoverClass()
			.bind('click', sbcu.handler.tabs.click)
		;
		
	}	
}

$(document).ready(sbcu.readyEvent); 



