// JavaScript Document
if($.browser != 'msie' && $.browser.version != 8) {
	DD_roundies.addRule('.button, .button2', '6px', true);
}

$(document).ready(function() {
	var myHeight = 171;
	
	function moveContent(value) {
		var maxScroll =  $(".scroll-content").height() - $(".scroll-pane").height();
		var scrollAmount = value * maxScroll / myHeight;
		$(".scroll-pane").scrollTop(scrollAmount);
	}
	
	$("#slider-vertical").slider({
		orientation: "vertical",
		min: -myHeight,
		max: 0,
		value: 0,
		slide: function(event, ui) {
			moveContent(ui.value * -1);
		}
	});
	$("#slider-vertical").height(myHeight + "px");
	
	$('a.ajaxvideo').click(function() {
		var url = this.href;
		var skinUrl = "/video/video_player.php";
		var mytitle = this.title;
		var dialog;
		
		if ($("#dialog").length < 1) {
			dialog = $('<div style="display:hidden;" id="dialog"></div>').appendTo('body');
			
			// load remote content
			dialog.load(skinUrl, {url: url}, function (responseText, textStatus, XMLHttpRequest) {
				dialog.dialog({
					modal: true,
					width: 480,
					height: 295,
					dialogClass: 'videoplayer',
					title: mytitle
				});
			});
		}
		else {
			dialog = $("#dialog");
			dialog.dialog("open");
		}
		
		//prevent the browser to follow the link
		return false;
	});
	
	// make update column the correct height
	/*
	if($("#content-section .col_left").height() < $("#content-section .col_right").height()){
		var diff = $("#content-section .col_right").height() - $("#content-section .col_left").height();
		$(".scroll-pane").height( $(".scroll-pane").height() + diff );
		$("#slider-vertical").height( $("#slider-vertical").height() + diff );
	}
	*/
	
	$(".signin-content input[name:signin-type]:radio").click(function(element){
		var myval = $(".signin-content input[name:signin-type]:checked").val();
		
		if(myval == 'new') {
			$(".form-signup").show();
			$(".form-signin").hide();
		}
		else {
			$(".form-signup").hide();
			$(".form-signin").show();
		}
	});
	
	$(".login a").click(function(element){
		$("#form-login").submit();
		return false;
	});
	
	$("#signin-submit").click(function(element){
		$("#form-signin").submit();
		return false;
	});
	
	$("#billing-submit").click(function(element){
		$("#form-billing").submit();
		return false;
	});
	
	$("#delivery-submit").click(function(element){
		$("#form-delivery").submit();
		return false;
	});
	
	$("#pay-submit").click(function(element){
		if ($("#postage-type").val() == "") {
			alert("Please select a valid postage type before continuing.");
		}
		else {
			if ($("#total-post").length > 0) {
				if ($("#total-post").val() > 0) {
					$("#form-pay").submit();
				}
				else if ($("#total-post").val() == "ignore") {
					$("#form-pay").submit();
				}
				else {
					alert("Please select a valid postage type before continuing.");
				}
			}
			else {
				$("#form-pay").submit();
			}
		}
		return false;
	});
	
	$("#signup-submit").click(function(element){
		if ($("#signup-email").val() != $("#signup-email2").val()) {
			alert("The email addresses don't match.");
		}
		else {
			$("#form-signup").submit();
		}
		return false;
	});
	
	$("#enews-submit").click(function(element){
		if ($("#enews-email").val() != $("#enews-email2").val()) {
			alert("The email addresses don't match.");
		}
		else {
			$("#form-enews").submit();
		}
		return false;
	});
	
	$("#forgotten-submit").click(function(element){
		$("#form-forgotten").submit();
		return false;
	});
	
	$("#contribute-submit").click(function(element){
		$("#form-contribute").submit();
		return false;
	});
	
	$(".logout").click(function(element){
		$("#form-logout").submit();
		return false;
	});
	
	$(".page-book .add, .page-paper .add").click(function(element){
		var option = $('input[name:purchase_options]:checked').val();
		
		if(typeof option !== 'undefined') {
			// handle institutional access purchase
			if(option == "ia") {
				//console.log("do institutional access handling...");
			}
			else {
				var href = $(element.target).attr("href");
				href = href + "&option=" + option;
				
				//console.log(href);
				window.location = href;
			}
		}
		else {
			alert("Please select a purchase option before adding to cart.");
		}
		
		return false;
	});
	
	$(".page-books .add, .page-papers .add, .page-publications .add").click(function(element){
		var nid = $(this).attr("href").replace("/cart/add?nid=", "");
		nid = nid.replace("/cart/purchase?nid=", "");
		
		element.preventDefault();
		var option = $('#purchase_options_' + nid).val();
		
		if(typeof option !== 'undefined' && option != "") {
			// handle institutional access purchase
			if(option == "Institutional Access") {
				//console.log("do institutional access handling...");
			}
			else {
				var href = $(element.target).attr("href");
				href = href + "&option=" + option;
				
				//console.log(href);
				window.location = href;
			}
		}
		else {
			alert("Please select a purchase option before adding to cart.");
		}
		
		return false;
	});
	
	$(".events_upcoming .add").click(function(element){
		var option = $('input[name:ticket_type]:checked').val();
		var quantity;
		
		if(typeof option !== 'undefined') {
			
			if (option === "single") {
				quantity = $("#single_tickets").val();
			}
			else {
				quantity = 1;
			}
			
			if (quantity > 0) {
				var href = $(element.target).attr("href");
				href = href + "&option=" + option + "&quantity=" + quantity;
				
				//console.log(href);
				window.location = href;
			}
		}
		
		return false;
	});
	
	$(".select-quantity").change(function(){
		var removeHref = $(this).siblings("a")[0].href;
		var myUrl = removeHref.replace("remove", "change");
		myUrl = myUrl + "&quantity=" + $(this).val();
		window.location = myUrl;
	});
	
	$("#single_tickets").change(function(){
		var numTickets = $(this).val();
		var ticketPrice = $("#tickets-single").val();
		var total = parseFloat(numTickets * ticketPrice, 10);
		$("#tickets-single-total").html('<span>$</span>' + total.toFixed(2));
		$("#tickets-single-total-hidden").val(total);
		updateTotal();
	});
	
	$("input[name:ticket_type]:radio").change(function(){
		updateTotal();
	});
	
	function updateTotal() {
		var radio = $("input[name:ticket_type]:checked").val();
		var total, GST;
		
		if(radio == "single") {
			total = parseFloat($("#tickets-single-total-hidden").val(), 10);
			$("#tickets-grandtotal").html('<span>$</span>' + total.toFixed(2));
		}
		else if(radio == "table") {
			total = parseFloat($("#tickets-table-total-hidden").val(), 10);
			$("#tickets-grandtotal").html('<span>$</span>' + total.toFixed(2));
		}
		else {
			total = 0;
		}
		
		GST = total/10;
		$("#gst").html('<span>$</span>' + GST.toFixed(2));
	}
	
	// fix firefox not using selected attribute for shopping cart
	$(".select-quantity, .select-country, .select-states, .select-contribute").each(function (index, domEle) {
		var selectedOption = $("option", $(domEle)).filter(function() {
			if (typeof this.attributes['selected'] !== "undefined") {
				return $(this);
			}
		});
		
		$(domEle).val(selectedOption.val());
	});
	
	// pager
	$(".pager").each(function (index, elem) {
		var $pager = $(this);
		var $pages = $('<div class="page-info" />');
		var numPages = $pager.find(".pager-current").length + $pager.find(".pager-item").length;
		var current = $pager.find(".pager-current").text();
		
		$pages.html('<strong>Page ' + current + ' of ' + numPages + '</strong>');
		$pager.parent().append($pages);
		$pager.wrap('<div class="pager-wrap" />');
	});
	
	if ($("#banner-section").length > 0 && $("#banner-section").find("div").length > 1) {
		var banners = $("#banner-section").find("div"),
			active = 0, banLen = banners.length, dur = 10000, effDur = 500;
		
		var intervalID = setInterval(function () {
			$(banners[active]).fadeOut(effDur, function () {
				active = (active === (banLen - 1)) ? 0: active + 1;
				$(banners[active]).fadeIn(effDur);
			});
		},
		dur);
	}
	
	// contribute form
	$(".select-contribute").change(function(){
		var value = $(".select-contribute").val();
		
		$(".hideshow").hide();
		if (value != "") {
			$("#" + value).show();
		}
	});
	
	$("input[name:contribute_papers]:radio").change(function(){
		var value = $("input[name:contribute_papers]:checked").val();
		
		if (value == "yes") {
			$("#contribute_name").addClass("required");
		}
		else {
			$("#contribute_name").removeClass("required");
		}
	});
	
	// forms
	$("#form-signup").validate();
	$("#form-enews").validate();
	$("#form-signin").validate();
	$("#form-billing").validate();
	$("#form-pay").validate();
	$("#form-forgotten").validate();
	$("#form-contribute").validate();
	
	// bad browser fix
	$(".col_right").css({
	    "overflow": "auto"
	});
	
	/* click here js */
	var $popup = $(".options-clicked");
	var popShow = 0;
	var titlePatt = /title=.*/;
	var optPatt = /option=.*/;
	$(".button-options").click(function(e) {
		e.preventDefault();
		
		var html = $(this).parent().next(".item-options-content").html(),
			href = $(this).attr("href"),
			content = $(".options-clicked .options-content"),
			pos = $(this).position(),
			title = titlePatt.exec(href),
			title = title[0].replace("title=", "");
		
		$(".options-confirm").hide();
		if (popShow) {
			$popup.hide();
			popShow = 0;
		}
		else {
			content.empty();
			content.append(html);
			
			$(".options-clicked").css({
				"top" : pos.top + 28.4,
				"left" : pos.left - 137.2
			});
			
			$popup.show();
			popShow = 1;
			
			content.find("tr").hover(function(e) {
				$(this).css("background-color", "#e6d5c9");
			},
			function(e) {
				$(this).css("background-color", "");
			});
			
			content.find("td a").click(function(e) {
				e.preventDefault();
				
				var href2 = $(this).attr("href"),
					confirm = $(".options-confirm"),
					pos2 = $(this).position(),
					content = "",
					myopt = optPatt.exec(href2),
					myopt = myopt[0].replace("option=", "");
				
				switch(myopt){
					case "ebook":
						myopt = "permanent ebook access";
						break;
					case "ebook_1m":
						myopt = "1 month ebook access";
						break;
					case "ebook_1w":
						myopt = "1 week ebook access";
						break;
					case "hardcopy":
						myopt = "hard copy (hard cover)";
						break;
					case "hardcopy_soft":
						myopt = "hard copy (soft cover)";
						break;
					case "sub1y":
						myopt = "1 year subscription";
						break;
					case "sub2y":
						myopt = "2 year subscription";
						break;
				}
				
				content += "<p>Please confirm you want to add " + myopt + " for <span class='title'>" + title + "</span> to your shopping cart.</p>";
				content += '<p align="center" style="margin:0;" class="buttons"><span><a href="/cancel" class="button2 cancel">CANCEL</a><a href="' + href2 + '&quantity=1" class="button2 add">ADD TO CART</a></span></p>';
				
				confirm.empty();
				confirm.append(content);
				
				confirm.css("top", pos2.top).show();
				
				confirm.find(".cancel").click(function(e) {
					e.preventDefault();
					confirm.hide();
				});
			});
		}
	});
	
	$(".options-top").click(function(e) {
		var html;
		
		e.preventDefault();
		$(".options-confirm").hide();
		if (popShow) {
			$popup.hide();
			popShow = 0;
		}
		else {
			$popup.show();
			popShow = 1;
		}
	});
	
	// postage calculation
	$("#postage-type").change(function (e) {
		var value = this.value,
			$queryStrings = $('.qs'),
			numQs = $queryStrings.length,
			count = 0,
			total = 0,
			itemsTotal = $("#sub-total").text(),
			grandTotal = 0;
		
		//console.log(value, $queryStrings);
		
		e.preventDefault();
		if (value != "") {
			$queryStrings.each(function (index, elem) {
				var qs = elem.value + "&Service_Type=" + value;
				
				if (qs == "ignore&Service_Type=" + value) {
					$("#total-post").val("ignore");
				} else {
					$.ajax({
						type: "GET",
						dataType: "json",
						data: qs,
						url: "/post_estimate.php",
						success: function(json){
							if (json.error == "1") {
								alert(json.response);
							}
							else {
								total = total + json.response;
							}
							count++;
							
							if (count == numQs) {
								$(".total-post").text(total.toFixed(2));
								$("#total-post").val(total.toFixed(2));
								grandTotal = parseFloat(total) + parseFloat(itemsTotal);
								$("#grand-total").text(grandTotal.toFixed(2));
								$("#grandTotalCart").val(grandTotal.toFixed(2));
								$("#grandTotal").val(grandTotal.toFixed(2));
							}
						}
					});
				}
			});
		}
	});
});
