/*
--------------------------------------------------

Allstate Teen
Site-Wide Scripts [application.js]

Joe Morrow [joe.morrow@acquitygroup.com]
5/26/2010

Copyright (c) 2008-2010 Acquity Group LLC

--------------------------------------------------
*/


$(document).ready(function() {
	
	// The following is used for the custom select boxes.
	//$("body select").msDropDown();

  	//Pops up game in new window from Games Page
  	$('.newWindow').live('click', function(e){
  	  var $a = $(this);
  	  var href = $a.attr('href');
  	  
  	  params  = 'width='+screen.width;
  	  params += ', height='+screen.height;
  	  params += ', top=0, left=0'
  	  params += ', fullscreen=yes';
  	
  	  newwin=window.open(href,'window', params);
  	  if (window.focus) {newwin.focus()}
  	  return false;
  	});
  
	// Paging Functions for Contact Gallery
	$('a.pageLink').click(function() {
		$('div.pageSet').addClass('hidden');
		$('div' + $(this).attr('href')).removeClass('hidden');
		$('a.pageLink').removeClass('activePageLink');  
		$(this).addClass('activePageLink');  
		return false;
	});

	// Show and hide mobile info on registration page
	$('#communcation-email').click(function() {
		$('fieldset.phone').addClass('hidden');
	});
	
	$('#communication-text').click(function() {
		$('fieldset.phone').removeClass('hidden');
	});
	
	// Gives each field a title tag with the text from the label
	// Custom titles set for month/year fields
	$('.inline-prompt').each(function() {
		$(this).attr("title", $("label[for='" + $(this).attr('id') + "']").html());
		if ($(this).attr('id') == 'approvalFeedback') {
			$(this).attr("title", 'Please use this space to provide any additional input you may have.');
		}
		if ($(this).attr('id') == 'birth-month') {
			$(this).attr("title", 'mm');
		}
		if ($(this).attr('id') == 'birth-day') {
			$(this).attr("title", 'dd');
		}
		if ($(this).attr('id') == 'birth-year') {
			$(this).attr("title", 'yyyy');
		}
		if ($(this).attr('id') == 'license-month') {
			$(this).attr("title", 'mm');
		}
		if ($(this).attr('id') == 'license-year') {
			$(this).attr("title", 'yy');
		}	
		if ($(this).attr('id') == 'graduation-month') {
			$(this).attr("title", 'mm');
		}
		if ($(this).attr('id') == 'graduation-year') {
			$(this).attr("title", 'yy');
		}
		if ($(this).attr('id') == 'phone-area') {
			$(this).attr("title", '123');
		}
		if ($(this).attr('id') == 'phone-exchange') {
			$(this).attr("title", '456');
		}
		if ($(this).attr('id') == 'phone-number') {
			$(this).attr("title", '7890');
		}
		if ($(this).attr('id') == 'comments') {
			$(this).attr("title", 'Please use this space to provide your comments');
		}
	}).focus(function() {
		if ($(this).val() == $(this).attr("title"))
			$(this).val("").removeClass("inline-prompt");
	}).blur(function() {
		if ($(this).val() == "")
			$(this).val($(this).attr("title")).addClass("inline-prompt");
	});
	

	// Remove italics from textarea on contract approval page on click
//	$('#approvalFeedback').click(function() {
//		$(this).removeClass('unfocusedTextarea');
//	});

	// Home page carousel paging
	$('a.prev').click(function() {
	    var selected = $('div.carousel.selected');
	    if (selected.prev('div.carousel').length != 0)
	        selected.addClass('hidden').removeClass('selected').prev().addClass('selected').removeClass('hidden');
	});
	$('a.next').click(function() {
	    var selected = $('div.carousel.selected');
	    if (selected.next('div.carousel').length != 0)
	        selected.addClass('hidden').removeClass('selected').next().addClass('selected').removeClass('hidden');
	});

	// Module Page Navigation
	$("#prevModule a").click(function() {
		modulePrev("modulePlaceholder");
		return false;
	});
	$("#nextModule a").click(function() {
		moduleNext("modulePlaceholder");
		return false;
	});
	
});

// Hide login on pages that need it removed 
	$(document).ready(function() {
		$("body.contractApproval #utility-nav").addClass("hidden");
		$("body.Login.profile #utility-nav").addClass("hidden");
	});

//IE6 Layering with BGI Frame
//	$(document).ready(function() {
//		$("body.home #licenseContainer").bgiframe();
//	});
	
	
// Z-index Layering in IE6
//$(document).ready(function() {	
//	if($('body').hasClass('browserIE7') || $('body').hasClass('browserIE6')) {
//		var zIndexNumber = 1000;
//		$('li').each(function() {
//			$(this).css('zIndex', zIndexNumber);
//			zIndexNumber -= 10;
//		});	
//	}
//});

//Show License Popup
	$(document).ready(function() {
		$("a#viewLicense").click(function() {
			$("#licenseContainer").removeClass("hidden");
			var modalBackground = document.createElement('div');
			modalBackground.className = 'modalbackground';
			document.body.appendChild(modalBackground);
			return false;			
		});		
	});
		
	
//Hide License Popup
	$(document).ready(function() {
		$(".modalclose").click(function() {
			$("#licenseContainer").addClass("hidden");
			$(".modalbackground").removeClass("modalbackground");
		});
	});

	$(document).ready(function() {
		$(".modalbackground").click(function() {
			$("#licenseContainer").addClass("hidden");
			$(".modalbackground").removeClass("modalbackground");
		});
	});
	
	
// Show opt-out on edit page
	$(document).ready(function() {
		$("#body.registrationEdit fieldset.optOut").removeClass("hidden");
	});

// browser detectors ($.browser is deprecated in jQuery 1.3 and $.support isn't helpful when targeting style rules)
function isIE6() {
	if (typeof($.isIE6) == "undefined") {
		jQuery.extend({
			isIE6: ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined)) ? true : false
		});
	}
	return $.isIE6;
}

// Scrolls to Promise Video when Promise Now sign is clicked on
function goToByScroll(id){
		$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

// Shows Text Before Creating Password
$(document).ready(function() {
 
	$('#password-create-clear').show();
	$('#password-create').hide();
 
	$('#password-create-clear').focus(function() {
		$('#password-create-clear').hide();
		$('#password-create').show();
		$('#password-create').focus();
	});
	$('#password-create').blur(function() {
		if($('#password-create').val() == '') {
			$('#password-create-clear').show();
			$('#password-create').hide();
		}
	});
 
	$('.default-value').each(function() {
		var default_value = this.value;
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
	});
 
});

// Shows Text Before Confirming Password
$(document).ready(function() {
 
	$('#password-confirm-clear').show();
	$('#password-confirm').hide();
 
	$('#password-confirm-clear').focus(function() {
		$('#password-confirm-clear').hide();
		$('#password-confirm').show();
		$('#password-confirm').focus();
	});
	$('#password-confirm').blur(function() {
		if($('#password-confirm').val() == '') {
			$('#password-confirm-clear').show();
			$('#password-confirm').hide();
		}
	});
 
	$('.default-value').each(function() {
		var default_value = this.value;
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
	});
 
});

// Modal Handlers
var setVideoName = function(name, link) {
	$("#videoModal .infoText a").attr("href", link).html(name);
};	


// Module Page Handlers
var moduleFadeOut = function(callback) {
	$("#module .moduleFlag, #prevModule a, #nextModule a, #moduleDescription").fadeOut((isIE6()) ? 0 : 800, callback);
	return false;
};

var moduleFadeIn = function(callback) {
	$("#prevModule a, #nextModule a").fadeIn((isIE6()) ? 0 : 800, callback);
	return false;
};

var moduleDestroy = function(moduleID) {
	// Destroy the module
	swfobject.removeSWF(moduleID);
	// Replace the module container, if necessary
	$("#moduleDescription").show(0, function() {
		if ($("div#" + moduleID).length == 0)
			$("#moduleDescription").after('<div id="' + moduleID + '" class="hidden"></div>');
	});
	return false;
};	

var modulePrev = function(moduleID) {
/* Developer Note 6/22/2010:
1.  Todo:  Need to add code here to enable the previous module, once more than one module is available.
*/
	if (typeof(console) != "undefined")
		console.log("previous module");

	// Destroy the current module
	moduleDestroy(moduleID);
	return false;
};

var moduleNext = function(moduleID) {
/* Developer Note 6/22/2010:
1.  Todo:  Need to add code here to enable the next module, once more than one module is available.
*/
	if (typeof(console) != "undefined")
		console.log("next module");

	// Destroy the current module
	moduleDestroy(moduleID);
	return false;
};

var loadModule = function(swfPath, moduleID, flashvars, params, attrs, callback) {

	if (flashvars == null)
		flashvars = {};
	if (params == null)
		params = {};
	if (attrs == null) 
		attrs = {};

	// Init default params
	params.width = (params.width != null) ? params.width : "660";
	params.height = (params.height != null) ? params.height : "440";
	params.quality = (params.quality != null) ? params.quality : "high";
	params.align = (params.align != null) ? params.align : "middle";
	params.play = (params.play != null) ? params.play : "play";
	params.loop = (params.loop != null) ? params.loop : "true";
	params.scale = (params.scale != null) ? params.scale : "showall";
	params.wmode = (params.wmode != null) ? params.wmode : "transparent";
	params.devicefont = (params.devicefont != null) ? params.devicefont : "false";
	params.bgcolor = (params.bgcolor != null) ? params.bgcolor : "#ffffff";
	params.menu = (params.menu != null) ? params.menu : "true";
	params.allowFullScreen = (params.allowFullScreen != null) ? params.allowFullScreen : "false";
	params.allowScriptAccess = (params.allowScriptAccess != null) ? params.allowScriptAccess : "always";
	params.salign = (params.salign != null) ? params.salign : "";
	params.type = (params.type != null) ? params.type : "application/x-shockwave-flash";
	params.pluginspage = (params.pluginspage != null) ? params.pluginspage : "http://www.adobe.com/go/getflashplayer";

	// Load the SWF
	swfobject.switchOffAutoHideShow();
	swfobject.embedSWF(swfPath, moduleID, params.width, params.height, '9.0.0', 'media/flash/expressInstall.swf', flashvars, params, attrs, callback);
	return false;
};

var moduleBegin = function(swfPath, moduleID, flashvars, params, attrs, callback) {
	// Load the SWF
	loadModule(swfPath, moduleID, flashvars, params, attrs, callback);
	// Turn off the navigation
	moduleFadeOut();
	return false;
};

// Module Flash Communication
var moduleEnd = function(moduleID, returnData) {
	// Turn on the navigation
	moduleFadeIn();

/* Developer Note 6/22/2010:
1.  Todo:  Need to add code here to pass the JSON-formatted value object to the backend system.

	if (typeof(console) != "undefined")
		console.log(returnData);
	return false;
*/
	
	/* Displays received var/value pairs for clarity. Delete after backend knows what they're getting. */
	alert("ActionScript says: moduleID = " + moduleID);
	var arr = new Array();
	arr = ['userID', 'completed'];
	for (var item in returnData) {
    	alert("ActionScript says: " + arr[item] + " = " + returnData[item]);
	}
	/* This is a hard-coded response back to Flash. Replace values with backend data after backend response. */
	thisMovie("modulePlaceholder").sendToActionScript({'claimReward': 'true', 'earnedLessons': '07/24'});
};


// Module Flash Communication


function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

// Contract Flash Communication
function sendFromRecorder(_obj){
	var arr = new Array();
	var msg = '';
	arr = ['mediaType', 'mediaContent', 'mediaPath', 'firstName', 'lastName', 'userEmail', 'parentEmail', 'userMessage', 'termsPost', 'termsEULA', 'timeStamp']
	for (var item in _obj) {
		//alert(item + '] ' + arr[item] + " : " + _obj[item] + " ");
		msg = msg + arr[item] + "=" + _obj[item] + "&";
	}
	createContract(msg);
}

// Show and hide gallery on home page		
function toggleVisibilityGallery(id) {
   var e = document.getElementById(id);
   var dropdown_3 = document.getElementById("galleryDropdown");
   
   if(e.style.display == 'block') {
      e.style.display = 'none';
      dropdown_3.className = "more_3";
   }else{
      e.style.display = 'block';
      dropdown_3.className = "less_3";
   }
}
   
// Show and hide txtgMayhem element on home page	
function toggleVisibilityMayhem(id) {
   var e = document.getElementById(id);
   var dropdown_6 = document.getElementById("mayhemDropdown");
   
   if(e.style.display == 'block') {
      e.style.display = 'none';
      dropdown_6.className = "more_6";
   }else{
      e.style.display = 'block';
      dropdown_6.className = "less_6";
   }
}

// Show and hide safeRewarded element on home page	
function toggleVisibilitySafeRewarded(id) {
   var e = document.getElementById(id);
   var dropdown_3 = document.getElementById("safeRewardedDropdown");

   if(e.style.display == 'block') {
      e.style.display = 'none';
      dropdown_3.className = "more_3";
   }else{
      e.style.display = 'block';
      dropdown_3.className = "less_3";
   }
}

//Show and hide Rewards
$(document).ready(function() { 
  
// First hide #thanksRewards and .rewardsRight except for Drive 'n Lessons (or whichever one) rewards and arrow.
$(".rewardsRight").hide();
$("#rewardsRightWrapper .rewardsRight:first").show();
$(".bluePrizeButton:first").addClass('selected');

$(".bluePrizeButton").click(function() {
    $('.bluePrizeButton').removeClass('selected');
    $(this).addClass('selected');
    $(".rewardsRight").hide();
    $("#rewardsRightWrapper .rewardsRight").eq($(this).closest("li").index()).fadeIn('normal');
    return false;
});


//The following are to display the thank you message(s) and replace .bluePrizeButton with .prizeClaimed
$(".rewardsRight .claimRewardBtn input").click(function() {
    $(".rewardsRight").hide();
    $("#thanksRewardsGeneral").show();
    //or $("#thanksRewardsMusic").show();	  
	  return false;
});

$("#driveInLessons .claimRewardBtn input").click(function() {
	  $("#liDriveN span").removeClass("bluePrizeButton");
	  $("#liDriveN span").removeClass("selected");
	  $("#liDriveN span").addClass("prizeClaimed");
	  $(".prizeClaimed").unbind();
	  return false;
});

$("#streetSleuth .claimRewardBtn input").click(function() {
	  $("#liStreetSleuth span").removeClass("bluePrizeButton");
	  $("#liStreetSleuth span").removeClass("selected");
	  $("#liStreetSleuth span").addClass("prizeClaimed");
	  $(".prizeClaimed").unbind();
	  return false;
});

$("#greatRace .claimRewardBtn input").click(function() {
	  $("#liGreatRace span").removeClass("bluePrizeButton");
	  $("#liGreatRace span").removeClass("selected");
	  $("#liGreatRace span").addClass("prizeClaimed");
	  $(".prizeClaimed").unbind();
	  return false;
});

});

// Parents Side Toggle on New Teen Driver Home Page
$(document).ready(function() {
	$("#parentsBtn").click(function() {	
		
		$(".parentsContent").toggleClass('hidden');
		$(this).toggleClass('alt');
		return false;		
	});
});

//The following is for the Lines videos for the Videos page.
var currentEpisode = 0;
var episodeIds = ["xXPWdqaiGeY","yPUKATr4jxE","QQshFS-oA_Y","NEEfOyWYORo","7KEeJeNe_mo","jZnaCrde4CI","K6hIVQGPauY","xwHxmyWCMOw"];

// This function is called when an error is thrown by the player
function onPlayerError(errorCode) {
	alert("An error occured of type:" + errorCode);
}

// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("ytPlayer");
	ytplayer.addEventListener("onError", "onPlayerError");
 }

//Function that loads new video
function loadNewVideo(epId) {
	if (ytplayer) {
		currentEpisode = epId;
		ytplayer.loadVideoById(episodeIds[currentEpisode]);
		
		showSynopsis(currentEpisode+1);
		window.scrollTo(0,0);
	}
}

// show the appropriate content block under the flash window
function showSynopsis(epId)	{
	document.getElementById("synopsisMain_ep1").className = "hidden";
	document.getElementById("synopsisMain_ep2").className = "hidden";
	document.getElementById("synopsisMain_ep3").className = "hidden";
	document.getElementById("synopsisMain_ep4").className = "hidden";
	document.getElementById("synopsisMain_ep5").className = "hidden";
	document.getElementById("synopsisMain_ep6").className = "hidden";
	document.getElementById("synopsisMain_ep7").className = "hidden";
	document.getElementById("synopsisMain_ep8").className = "hidden";
	document.getElementById("synopsisMain_ep" + epId).className = "synopsisMain";
}


$(document).ready(function() {

// Opens new centered 800x600 window
	$.fn.popCenteredWindow = function(options) {
		// Declare some default values.
		var defaults = {
			width: 800,
			height: 600
		};

		// Merge the defaults with the options parameter.
		var options = $.extend(defaults, options);

		// For each of these objects...
		return this.each(function() {
			// Get a handle to this HTML object.
			obj = $(this);

			// Set the left and top.
			options.left = (screen.width - options.width)/2;
			options.top = (screen.height - options.height)/2;

			// If user provided a URL, use that; otherwise use the HREF.
			var url = $(this).attr("href");

			// Concatenate the window.open() function's options.
			var features = "width=" + options.width + ",height=" + options.height+ ",left=" + options.left + ",top=" + options.top;

			// Add an onClick() handler to this object.
			obj.click(function(){
				// On click, open a new window with these arguments.
				window.open(url, options.name, features);
				return false;
			});
		});
	};

	$(".mindGamesWindow").popCenteredWindow();
});


$(document).ready(function() {

// Opens new centered 900x700 window
	$.fn.popCenteredWindow = function(options) {
		// Declare some default values.
		var defaults = {
			width: 1100,
			height: 700
		};

		// Merge the defaults with the options parameter.
		var options = $.extend(defaults, options);

		// For each of these objects...
		return this.each(function() {
			// Get a handle to this HTML object.
			obj = $(this);

			// Set the left and top.
			options.left = (screen.width - options.width)/2;
			options.top = (screen.height - options.height)/2;

			// If user provided a URL, use that; otherwise use the HREF.
			var url = $(this).attr("href");

			// Concatenate the window.open() function's options.
			var features = "width=" + options.width + ",height=" + options.height+ ",left=" + options.left + ",top=" + options.top;

			// Add an onClick() handler to this object.
			obj.click(function(){
				// On click, open a new window with these arguments.
				window.open(url, options.name, features);
				return false;
			});
		});
	};

	$(".gamesWindow").popCenteredWindow();
});



