$.ajaxSetup({
	type: "POST",
	contentType: "application/json; charset=utf-8",
	data: "{}",
	dataType: "json"
});

$(document).ready(function () {
	/* Button Hover Effects */
	$(".home_buttons a.with_hover").hover(ReplaceImage, ReplaceImage);

	/* Slide Show */
	$('.slidecontainer .slideshow').cycle({
		fx: 'scrollHorz',
		speed: 300,
		next: '.next',
		prev: '.prev',
		pager: '.pages',
		pagerAnchorBuilder: pagerFactory,
		//pagerEvent: 'mouseover',
		pauseOnPagerHover: true,
		timeout: 7000,
		delay: 50,
		before: beforeImageChanged,
		after: afterImageChanged
	});

	$('.slidecontainer .slideshow a').hover(function () {
		$('.slidecontainer .slideshow').cycle("pause");
	}, function () {
		$('.slidecontainer .slideshow').cycle("resume");
	});

	function pagerFactory(idx, slide) {
		var i = idx + 1;
		var c = $('.slidecontainer .slideshow a').length;
		var m = 5;
		m = c > m ? m : c;
		var s = i > m ? ' style="display:none"' : '';
		var t = i > (m - 1) ? '' : '|';
		return '<li' + s + '><a href="#">' + (i) + '</a>' + t + '</li>';
	};

	function beforeImageChanged() {
		$('.slidecontainer .slidetitle').html("");
		$('.slidecontainer .slidedescription').html("");
	}

	function afterImageChanged() {
		$('.slidecontainer .slidetitle').html("<a href=\"" + $("img", this).parent().attr("href") + "\">" + $("img", this).attr("title") + "</a>");
		$('.slidecontainer .slidedescription').html($("img", this).attr("desc"));
	}

	$('.slidecontainer .slideshow').removeClass("unloaded");

	/* Employee Directory Search */
	$('input#sq,.staffdir_deptbox').live("keydown", function (e) {
		/* ENTER PRESSED*/
		if (e.which == 13) {
			window.location = $(".staff_searchbutton").attr("href");
			return false;
		}
	});

	$("input#sq").live("keyup", function (e) {
		var qev = $("input#sq").val();
		var qe = encodeURIComponent(qev);

		$(".staff_searchbutton").attr("href", "index.aspx?page=" + $("input#hdnStaffPage").val()
			+ "&search=" + encodeURIComponent(qe) + "&dept="
			+ encodeURIComponent($(".staffdir_deptbox option:selected").val()));
	});

	$(".staffdir_deptbox").change(function () {
		var qev = $("input#sq").val().replace($("input#sq").attr("title"), "");
		var qe = encodeURIComponent(qev);

		$(".staff_searchbutton").attr("href", "index.aspx?page=" + $("input#hdnStaffPage").val()
			+ "&search=" + encodeURIComponent(qe) + "&dept="
			+ encodeURIComponent($(".staffdir_deptbox option:selected").val()));
	});

	/* Recently Reviewed Items*/
	if ($(".recently_reviewed_items").length > 0) {
		GetRecentlyReviewedItems();
		$("#ddlFilterRecentlyReviewedItems").change(GetRecentlyReviewedItems);
	}

	/* Quicklinks */
	$(".quicklink").change(function (e) {
		if ($(this).val().length > 2) {
			var v = $(this).val().split("|");
			redirectToUrl(v[0], v[1], v[2]);
		}
	});
});

function ReplaceImage(imgSrc) {
	var oldsrc = $("img", this).attr("src");
	var isHover = oldsrc.indexOf('_over') > -1;
	var from = !isHover ? "" : "_over";
	var to = !isHover ? "_over" : "";
	if (oldsrc.match(/.jpg$/))
		$("img", this).attr("src", oldsrc.replace(from + ".jpg", to + ".jpg"));
	else if (oldsrc.match(/.png$/))
		$("img", this).attr("src", oldsrc.replace(from + ".png", to + ".png"));
	else if (oldsrc.match(/.gif$/))
		$("img", this).attr("src", oldsrc.replace(from + ".gif", to + ".gif"));
}

function GetRecentlyReviewedItems() {
	var biblio_url = $("#hdnRcntlyRvwdURL").val() + $("#ddlFilterRecentlyReviewedItems option:selected").val()

	$(".recently_reviewed_items").html("").append("<div class='loading'><img src='Scripts/feedback/loadingAnimation.gif'/><span>Loading...</span></div>");
	$(".recently_reviewed_items_info").html("");

	$.ajax({
		type: "GET",
		url: biblio_url,
		success: GetRecentlyReviewedItemsCompleted, 
		dataType: 'jsonp'
	});
}

var jc = null;

var current_carousel_item = 1;
var current_carousel_length = 0;

function GetRecentlyReviewedItemsCompleted(r) {
	try {
		current_carousel_item = 5;

		var ul = $(".carousel .container", r.html).addClass("jcarousel-skin-custom");
		var div = $(".carousel .bibInfoBlock .info", r.html);

		//	while ($(ul).children().length != 4) $(ul).children().last().remove();

		current_carousel_length = $(ul).children().length;
		var li_count = current_carousel_length;

		if (li_count >= 3) current_carousel_item = 4;
		else if (li_count < 3) current_carousel_item = 3;

		$("img", ul).each(function (i, j) {
			var url = $("#hdnBibliocommonsURL").val();
			var err = $(this).attr("onerror").replace("this.src='", /*"this.src='" + */url).replace("';", "");
			$(this).attr("errimg", err);
			$(this).removeAttr("onerror");
		});

		div.each(function (i, j) {
			$("li", ul).eq(i).append(j);
		});

		$(ul).prepend("<li><div class='dummy_image'></div></li>")
		.prepend("<li><div class='dummy_image'></div></li>")
		.append("<li><div class='dummy_image'></div></li>")
		.append("<li><div class='dummy_image'></div></li>");

		$(".recently_reviewed_items").html(ul);

		if ($('.recently_reviewed_items ul').length > 0) {
			jc = $('.recently_reviewed_items ul').jcarousel({
				wrap: 'both',
				scroll: 1,
				visible: 3,
				start: 3,
				itemLoadCallback: itemLoadCallback,
				initCallback: initCallback,
				buttonNextHTML: null,
				buttonPrevHTML: null,
				animation: 'fast',
				itemFallbackDimension: 176
			});
		}

		if ($(ul).length == 0) {
			$(".recently_reviewed_items_info").html("<p class='no_items'>No one has reviewed a " + $("#ddlFilterRecentlyReviewedItems option:selected").attr("title") + " recently.</p>");
		}
	}
	catch (ex) {
		var err =
			"Number: " + ex.ErrorNumber + "\n" +
			"Description: " + ex.Description + "\n" + 
			"Stack Trace: " + ex.StackTrace;
		alert(err);
	}
}

var item_loaded = false;
var item_size = 0;

function itemLoadCallback(i, j, k) {
	$(".jcarousel-list li").find("img").removeClass("current").css("opacity", "0.5");
	//console.log(current_carousel_item + " " + i.size());
	var current_item = $(".jcarousel-list li[jcarouselindex=" + current_carousel_item + "]");
	$(current_item).find("img").addClass("current").css("opacity", "1.0");	
	var info = $(current_item).find(".info").html();
	$(".recently_reviewed_items_info").html(info);
	item_loaded = true;
	if (current_carousel_length <= 2)
		i.scroll(current_carousel_item - 1);
}

function initCallback(carousel) {
	$('.jcarousel-next').unbind('click');
	$('.jcarousel-next').bind('click', function () {
		if (item_loaded) {
			item_loaded = false;
			if (current_carousel_item < carousel.size() - 2) current_carousel_item++;
			else { current_carousel_item = 3; }
			carousel.scroll(current_carousel_item - 1);
		}
		return false;
	});

	$('.jcarousel-prev').unbind('click');
	$('.jcarousel-prev').bind('click', function () {
		if (item_loaded) {
			item_loaded = false;
			if (current_carousel_item > 3) current_carousel_item--;
			else { current_carousel_item = carousel.size() - 2; }
			carousel.scroll(current_carousel_item - 1);
		}
		return false;
	});

	setTimeout(function () {
		$(".jcarousel-list li img").each(function () {
			if (($(this).width()) && $(this).width() == 1) {
				$(this).attr("src", $(this).attr("errimg"));
				$(this).removeAttr("errimg");
			}
		});
	}, 500);
};


function redirectToUrl(url, target, id) {
	var objWin = window;
	if (target == "_blank") {
		objWin = window.open(url, id);
		return;
	}
	else if (target == "_parent") {
		if (window.parent != null) {
			objWin = window.parent;
		}
	}
	else if (target == "_top") {
		if (window.top != null) {
			objWin = window.top;
		}
	}
	if (objWin != null) {
		objWin.location = url;
		objWin.focus();
	}
}
