
/* ==================================================
                Onload Routines
================================================== */

$(document).ready(function(){

	// This automatically closes if the user clicks outside the modal or presses the "ESC" key
	$("#modal-focus, .close-modal").click(function(){
		closeModal(false, false);
		return false;
	});
	$(document).keypress(function(e){  
		if (e.keyCode == 27 && modalState == 1)
			closeModal(false, false);
	});
	$(".do-close").click(function(){
		closeModal(false, true);
		return false;
	});

	// add loading image
	$('body').bind('ajaxSend', function(e, xhr, settings){
		ajaxShowLoading(settings.thisEl, settings.loadingID);
	}).bind('ajaxComplete', function(e, xhr, settings){
		ajaxHideLoading(settings.loadingID);
	});

	// smart inputs
	$("input.smartput").focus(smartFocus);
	$("input.smartput").blur(smartBlur);

	// init the sign in section
	initializeSignInOptions();

	// init sign out buttons
	$("#subnav_logout, .do-sign-out").click(function(){
		var str = 'You have selected to log off of the Online Bookstore.\n';
		if (hasCart)
			str += 'All inventory you have reserved in your cart will be released.\n';
		str += '\nContinue?';

		if (confirm(str))
			return true;

		return false;
	});

	/* ==================================================
	=====================================================
	    	    S I T E   N A V I G A T I O N
	=====================================================
	================================================== */

	/* ==================================================
			          D R O P  D O W N
	================================================== */

	$("#sddm li").hover( function() {
		$(this).children("ul:first").animate({ opacity:"show", height:"show" }, "fast");
	}, function() {
		$(this).children("ul:first").animate({ opacity:"hide", height:"hide" }, "fast");
	});

	$("#sddm li").click( function() {
		var isOpen = !$(this).data('open');
		$(this).children("ul:first").toggle(isOpen);
		$(this).data('open', isOpen);
	});	

	/* ==================================================
	=====================================================
					   T I C K E R
	=====================================================
	================================================== */

	if ($('#js-news').length)
		$('#js-news').ticker();


	/* ==================================================
	=====================================================
					  O R D E R I N G
	=====================================================
	================================================== */

	/* ==================================================
				  I T E M   P R I C I N G
	================================================== */

	// Focus
	$(".pricing .option, .pricing .do-not-purchase").hover(function() {
		$(this).siblings(".selected").removeClass("focus");
		$(this).not(".selected").addClass("focus");
		}, function() {
		$(this).siblings(".selected").addClass("focus");
		$(this).not(".selected").removeClass("focus");
	});

	// Select
	$(".pricing .option, .pricing .do-not-purchase").click(function() {

		if (!$(this).hasClass("selected")) {
			$(this).siblings(".option, .do-not-purchase").removeClass("selected").removeClass("focus");
			$(this).addClass("selected").addClass("focus");
			$(this).find(":radio").attr("checked", "checked");

			countAdoptionSelections();
		}
	});

	$(".pricing .option .ebookInfo").hover(function(event) {
		event.stopPropagation();
	});

	$(".pricing .option .ebookInfo").click(function(event) {
		event.stopPropagation();
	});

	$(".pricing .option .ebookInfo .ebookReq").click(function() {

		var thisDetailToggle = $(this).parents(".item").find(".details-toggle");
		var thisDetails = $(this).parents(".item").find(".details");

		if ($(this).parents(".option").find(".audio").length)
			var reqTab = thisDetails.find('ul.tabs li:contains("Requirements (Audio)")');
		else
			var reqTab = thisDetails.find('ul.tabs li:contains("Requirements (eBook)")');
		if (reqTab.length) {
			reqTab.siblings("li").removeClass("active"); //Remove any "active" class
			reqTab.addClass("active").show(); //Activate Requirement tab
			thisDetails.find(".tabbed").hide(); //Hide all tabbed content

			var activeTab = reqTab.find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).show(); //Show Requirement tab content
		}

		// show the tabbed content
		if (thisDetailToggle.length) {
			thisDetailToggle.text('Hide Details');
			thisDetails.slideDown();
		}
	});

	$(".pricing .option .ebookInfo .ebookDRM").click(function() {

		var thisDetailToggle = $(this).parents(".item").find(".details-toggle");
		var thisDetails = $(this).parents(".item").find(".details");

		var drmTab = thisDetails.find('ul.tabs li:contains("Digital Rights")');
		if (drmTab.length) {
			drmTab.siblings("li").removeClass("active"); //Remove any "active" class
			drmTab.addClass("active").show(); //Activate DRM tab
			thisDetails.find(".tabbed").hide(); //Hide all tabbed content

			var activeTab = drmTab.find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).show(); //Show DRM tab content
		}

		// show the tabbed content
		if (thisDetailToggle.length) {
			thisDetailToggle.text('Hide Details');
			thisDetails.slideDown();
		}
	});

	/* ==================================================
				T A B B E D   D E T A I L S
	================================================== */

	// Show/Hide tabbed content
	$(".details-toggle").click(function() {
		if ($(this).text() == 'Hide Details') {
			$(this).text('Show Details');
			$(this).parents(".item").find(".details").slideUp();
		}
		else {
			$(this).text('Hide Details');
			$(this).parents(".item").find(".details").slideDown();
		}
	});

	// Show tabbed content, with GBB tab active
	$(".gbb-show").click(function() {
		var thisDetailToggle = $(this).parents(".item").find(".details-toggle");
		var thisDetails = $(this).parents(".item").find(".details");

		var gbbTab = thisDetails.find('ul.tabs li:contains("Guaranteed Buyback")');
		if (gbbTab.length) {
			gbbTab.siblings("li").removeClass("active"); //Remove any "active" class
			gbbTab.addClass("active").show(); //Activate GBB tab
			thisDetails.find(".tabbed").hide(); //Hide all tabbed content

			var activeTab = gbbTab.find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).show(); //Show GBB tab content
		}

		// show the tabbed content
		if (thisDetailToggle.length) {
			thisDetailToggle.text('Hide Details');
			thisDetails.slideDown();
		}
	});


	// Hide all tabbed content
	$(".details .tabbed").hide();
	$(".details").each(function(){
		// try to activate Summary tab
		var summaryTab = $(this).find('ul.tabs li:contains("Summary")');
		if (summaryTab.length) {
			summaryTab.addClass("active").show(); //Activate Summary tab
			var activeTab = summaryTab.find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).show(); //Show Summary tab content
		}
		else {
			$(this).find("ul.tabs li:first").addClass("active").show(); //Activate first tab
			$(this).find$(".tabbed:first").show(); //Show first tab content
		}
    });

	$("ul.tabs li").click(function() {
		// don't do anything if already active
		if ($(this).hasClass("active"))
			return false;

		$(this).siblings("li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(this).parents(".details").find(".tabbed").hide(); //Hide all tabbed content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});

	/* ==================================================
	=====================================================
						  C A R T
	=====================================================
	================================================== */

	/* ==================================================
				 Z E B R A   S T R I P E S
	================================================== */

	$('#cart-contents tr:even').addClass('alt');

	$('#optional-study-aids .item-recommendations:odd').addClass('alt');

	/* ==================================================
				P R I C I N G   M A T R I X
	================================================== */

	// Focus
	$(".pricing-matrix .option").hover(function() {
		$(this).siblings(".selected").removeClass("focus");
		$(this).not(".selected").addClass("focus");
		}, function() {
		$(this).siblings(".selected").addClass("focus");
		$(this).not(".selected").removeClass("focus");
	});

	// Select
	$(".pricing-matrix .option").click(function() {
		clickBuyWidget($(this));
		return false;

		if (!$(this).hasClass("selected")) {
			clickBuyWidget($(this));
			return false;
		}
	});

	$(".simpler-trigger").bind("click focus", function() {
		$(this).parents("ul").find(".simpler").animate({ opacity:"show", height:"show" }, "normal");
	});
	
	// Show pretty select box
	$("select.select-markup").selectBox();

	if ($('#cart-total').length)
		$('#cart-total').containedStickyScroll();

	/* ==================================================
	=====================================================
			          P A G E   A C T I O N S
	=====================================================
	================================================== */

	// COURSE CAPTCHA SECTION
	if ($("#course-captcha").length) {
		$("#courseCaptchaForm").submit(function(){

			var challenge_field = $("#recaptcha_challenge_field").val();
			var response_field = $("#recaptcha_response_field").val();

			if ($.trim(response_field) != '') {
				closeModal(false, true);

				if ($("form[name='courseSubmitBottom']").length)
					var courseSubmitForm = $("form[name='courseSubmitBottom']");
				else if ($("form[name='courseSubmitTop']").length)
					var courseSubmitForm = $("form[name='courseSubmitTop']");
				else
					var courseSubmitForm = null;

				if (courseSubmitForm) {
					courseSubmitForm.find("input[name='recaptcha_challenge_field']").attr({'value':challenge_field});
					courseSubmitForm.find("input[name='recaptcha_response_field']").attr({'value':response_field});
					courseSubmitForm.submit();
				}
			}
			else
				DoFail($("#recaptcha_response_field")[0], "Please enter the reCAPTCHA words.");

			return false;
		});
	}

	// MATERIALS PAGE
	if ($("form[name='BookMaterialBuy']").length) {

		$("form[name='BookMaterialBuy']").submit(function(){
			return CanAdopt($(this), 'adoption')
		});

		// update selected count
		countAdoptionSelections();

		// zebra materials
		if ($(".course .item").length) {
			$(".course").each(function() {
				var altClass = 'alt';
				$(this).find(".item").each(function() {
					altClass = (altClass == '') ? 'alt' : '';
					$(this).addClass(altClass);
				});
			});
		}
	}

	// DETAIL PAGE
	if ($("form[name='BookDetailBuy']").length) {

		$("form[name='BookDetailBuy']").submit(function(){
			return CanAdopt($(this), 'detail')
		});
	}

	// RENTAL REQUIREMENTS SECTION
	if ($("#rental-requirements").length) {
		$("#modalRentalAgree").click(function(){
			if ($("#modalRentalTOS").is(':checked')) {
				closeModal(false, true);

				if ($("form[name='BookMaterialBuy']").length) {
					$("form[name='BookMaterialBuy'] input[name='rentalTOS']").attr({'value':'Y'});
					$("form[name='BookMaterialBuy']").submit();
				}
				else if ($("form[name='BookDetailBuy']").length) {
					$("form[name='BookDetailBuy'] input[name='rentalTOS']").attr({'value':'Y'});
					$("form[name='BookDetailBuy']").submit();
				}
			}
			else
				DoFail($("#modalRentalTOS")[0], "Please read and agree to the BookRenter.com Terms of Service");

			return false;
		});
	}

	// CART PAGE - update actions
	updateCartActions();

	// ADDRESSES PAGE - ship to bill options
	if ($("#shipping-address input[name='SHIPPINGS2B']").length) {
		selectShippingLocation();
		$("#shipping-address input[name='SHIPPINGS2B']").click(selectShippingLocation);
	}

	// SHIPPING PAGE
	if ($("#frmShippingMethod").length) {
		shippingSetFillOpt();
		shippingSetShiptype();
		$("#frmShippingMethod input[name='FILLOPTION']").click(shippingSetFillOpt);
		$("#frmShippingMethod input[name='SHIPTYPE'], #frmShippingMethod input[name='RENT_SHIPTYPE']").click(shippingSetShiptype);
		$("#frmShippingMethod").submit(validateShippingMethod);
	}

	// BILLING PAGE
	if ($("#frmBilling").length) {
		$("#frmBilling").submit(validateBilling);
	}

	// CONFIRMATION PAGE
	if ($(".CR_savePage").length) {
		if ($.browser.msie)
			$(".CR_savePage").parent().show();
		else
			$(".CR_savePage").parent().hide();
	}

	// Detects iOS devices
	var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
		
	// Forces submit via label in detected iOS devices
	if (agentID)
		$("label.step-button").click(function(){});

});

