//Bookstore search
$(document).ajaxSend(function(event, request, settings) {
	if (typeof(AUTH_TOKEN) == "undefined") return;
	// settings.data is a serialized string like "foo=bar&baz=boink" (or null)
	settings.data = settings.data || "";
	settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

function categoryDropdown() {
	$("#search_cat dl").hover(function() {
		$("#search_cat dd").show();
	}, function() {
		$("#search_cat dd").hide();
	});
}

function displayResults(type, value) {
	$.ajax({
		type: "POST",
		async: false,
		url: "/bookstore/filter",
		data: "content_type=" + type + "&value=" + value,
		success: function(msg){
			eval(msg);
		}
	});
	$("div.book_details").remove();
}
function loadCategoryFilter() {
	$("#search_cat dl dd a").click( function() {
		var value = encodeURIComponent($(this).html());
		displayResults("category", value);
		return false;
	});
	$("#store_search form ul a").click( function() {
		var value = encodeURIComponent($(this).html());
		displayResults($(this).attr("name"), value);
		return false;
	});
}

function keywordSearch() {
	$('#searchterm').liveUpdate('#store_search form ul');
}

// The famous Mr. John Resig's jQuery LiveSearch with Quicksilver http://ejohn.org/blog/jquery-livesearch/
// Used for searching on the video page
jQuery.fn.liveUpdate = function(list){
	list = jQuery(list);
	if ( list.length ) {
		var rows = list.children('li'),
		cache = rows.map(function(){
			return $(this).find("a").html().toLowerCase();
		});
	this
		.keyup(filter).keyup()
		.focus(filter)
		.parents('form').submit(function(){
			return false;
		});
	}

	return this;

	function filter(){
		var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];

		if ( !term ) {
			rows.hide();
			$("#store_search form ul").hide();
		} else {
			rows.hide();
			$("#store_search form ul").show();
			cache.each(function(i){
				var score = this.score(term);
				if (score > 0) { scores.push([score, i]); }
			});
			jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
				jQuery(rows[ this[1] ]).show();
			});
			if ( scores.length == 0 ) {
				$("#store_search form ul").hide();
			}
		}
	
	}
};
//End bookstore search

//Start Coverflow
function flipImages(newIndex, oldIndex, newPos) {
	//Flip the original main book cover
	var oldMainImg = $("#cover_frame ul li img").eq(oldIndex).attr("src");
	if(oldIndex < newIndex) {
		oldMainImg = oldMainImg.replace(/center_/, "left_");
		
	} else if(oldIndex > newIndex) {
		oldMainImg = oldMainImg.replace(/center_/, "right_");
	}
	
	//Flip the new main book cover
	var newMainImg = $("#cover_frame ul li img").eq(newIndex).attr("src");
	if(newMainImg.match("left_") != null) {
		newMainImg = newMainImg.replace(/left_/, "center_");
	} else if(newMainImg.match("right_") != null) {
		newMainImg = newMainImg.replace(/right_/, "center_");		
	}
	
	//Flip all images to the left and right of the new main cover
	var totalImgs = $("#coverflow ul li").size();
	for (i = 0; i < totalImgs; i++) {
		var sideImages = $("#cover_frame ul li img").eq(i).attr("src");
		if(i < newIndex) {
			sideImages = sideImages.replace(/right_/, "left_");
		} else if(i > newIndex) {
			sideImages = sideImages.replace(/left_/, "right_");
		}
		$("#cover_frame ul li img").eq(i).attr("src", sideImages);
	}
	
	$("#cover_frame ul li img").eq(oldIndex).attr("src", oldMainImg);
	$("#cover_frame ul li img").eq(newIndex).attr("src", newMainImg);
	
}
function loadBookInfo() {
	//Loads basic book info into blurb area on the coverflow
	var title = $("#coverflow ul li.current img").attr("alt");
	var desc = $("#coverflow ul li.current a").attr("title");
	var url = $("#coverflow ul li.current a").attr("href");
	$("#book_info h2").html(title);
	$("#book_info p").html(desc);
	$("#coverflow_desc a.btn_red").attr("href", url);
}
//Global function to move to a new book cover
var displacement = 0;
var arrowOff = false;
var jsLoaded = false;
function animateCoverflow(newIndex, oldIndex, initial) {
	if(newIndex != oldIndex) {
		arrowOff = true;
		var change = (oldIndex - newIndex)*136;
		var oldPos = stripPx($("#cover_frame ul").css("left"));
		var undisplaced = oldPos - displacement;
		
		var newPos = undisplaced + change;
		
		var oldMainSrc = $("#cover_frame ul li img").eq(oldIndex).attr("src");
		var newMainSrc = $("#cover_frame ul li img").eq(newIndex).attr("src");
		
		flipImages(newIndex, oldIndex, newPos);
		
		$("#cover_frame ul li").eq(oldIndex).removeClass();
		$("#cover_frame ul li").eq(newIndex).addClass("current");
		
		var acutalWidth = $("#cover_frame ul li.current img").width();
		displacement = (214 - acutalWidth) / 2;
		
		if(initial == true) {
			//centers the first book with 2 books left and right
			newPos = newPos + displacement + (136*2);
		} else {
			newPos = newPos + displacement;
		}
		$("#cover_frame ul").animate({
			left: newPos
		}, "normal", function() {
			arrowOff = false;
			if(jsLoaded == false) {
				jsLoaded = true;
				console.log(jsLoaded);
			}	
			if(jsLoaded == true) {
				$("#cover_frame").css({
					position: "relative",
					top: "auto"
				});
				$("#coverflow_preloader").hide();
			}
		});
		loadBookInfo();
	} else {
		return;
	}
	return false;
}
//Places full book details in main area of bookstore page
function getBookDetails(ele) {
	$.ajax({
		type: "GET",
		async: true,
		url: $(ele).attr("href"),
		//data: "&",
		success: function(msg){
			eval(msg);
		}
	});
	$("#store_results").removeClass();
}
//Searches the coverflow for matching url
function scanCoverflow(ele) {
	if(arrowOff == false) {
		var oldMainIndex = $("#cover_frame ul li").index($("#cover_frame ul li.current"));
		var url = $(ele).attr("href");
		var bookList = $("#cover_frame ul li").size();
		for(i = 0; i < bookList; i++) {
			var compare = $("#cover_frame ul li a").eq(i).attr("href");
			if(url == compare) {
				animateCoverflow(i, oldMainIndex);
			}
		}
		getBookDetails(ele);
	}
}

//First set up of coverflow
function initiateCoverflow() {
	//If there are more than 3159 width of images, set a new width
	
	var totalWidth = 50;
	var coverflowSize = $("#coverflow ul img").size();
	for(i = 0; i < coverflowSize; i++) {
		totalWidth += $("#coverflow ul img").eq(i).width();
	}
	if(totalWidth != 0) {
		$("#cover_frame ul").width(totalWidth);
	}
	
	//Animate to the first book
	var newIndex = $("#cover_frame ul li").index($("#cover_frame ul li.current"));
	animateCoverflow(newIndex, 0, true);
}
//Arrow clicks only change coverflow, does not change book details content
function arrowClick() {
	$("#coverflow a.arrow").eq(0).click(function() {
		if(arrowOff == false) {
			var oldMainIndex = $("#cover_frame ul li").index($("#cover_frame ul li.current"));
			if(oldMainIndex != 0) {
				var newMainIndex = oldMainIndex - 1;
				animateCoverflow(newMainIndex, oldMainIndex);
			}
		}
		return false;
	});
	$("#coverflow a.arrow").eq(1).click(function() {
		if(arrowOff == false) {
			var oldMainIndex = $("#cover_frame ul li").index($("#cover_frame ul li.current"));
			if(oldMainIndex < ($("#coverflow ul li").size() - 1)) {
				var newMainIndex = oldMainIndex + 1;
				animateCoverflow(newMainIndex, oldMainIndex);
			}
		}
		return false;
	});
}
function resultsClick() {
	//When user clicks on a book within the coverflow
	$("#cover_frame a").click(function() {
		scanCoverflow(this);
		return false;
	});
	
	//When user clicks on the thumbnail to change the coverflow center image
	$("#store_results a.thumb").click(function() {
		scanCoverflow(this);
		return false;
	});
	
	//This is when you click on the "read more" button within the search results
	$("#store_results a.btn_brown").click(function() {
		scanCoverflow(this);
		return false;
	});

	//This is when you click on the "see more" button on the coverflow
	$("#coverflow_desc a.btn_red").click(function() {
		getBookDetails(this);
		var targetOffset = $("#store_results").offset().top;
        $('html,body').animate({scrollTop: targetOffset}, 500);
		return false;
	});
}
$(document).ready(function() {
	formFocusBlur("#store_search form input.input", "Search Here");
	categoryDropdown();
	loadCategoryFilter();
	keywordSearch();
	setTimeout("initiateCoverflow()", 2500);
	arrowClick();
	resultsClick();
});