var makePopup = {};

$(document).ready(function(){

	function findPosX(obj) {
	    var curleft = 0;
	    if(obj.offsetParent)
	        while(1) {
	          curleft += obj.offsetLeft;
	          if(!obj.offsetParent)
	            break;
	          obj = obj.offsetParent;
	        }
	    else if(obj.x)
	        curleft += obj.x;
	    return curleft;
	  }

	/* Make Popups */

	makePopups = function(id) {

		var nhbsLeft = findPosX(document.getElementById('nhbs_container'));

		if($.browser.msie && parseInt(jQuery.browser.version) <= 7){
			var nhbsWidth = 904;
		} else {
			var nhbsWidth = 950;
		}

		$.getJSON("/js/main_menu.json",function(data){

			$.each(data.popups,function(i,popup) {

				var html = '';
				var tableWidth = (parseInt(popup.columnWidth)*popup.columns.length);

				if($.browser.msie && parseInt(jQuery.browser.version) <= 7){
					if (popup.popupDirection != 'left') {
					html += '<div id="popup-container-'+popup.id+'" class="popup-container" style="width:'+tableWidth+'px;">\n';
					} else {
					html += '<div id="popup-container-'+popup.id+'" class="popup-container" >\n';
					}
				} else {
					html += '<div id="popup-container-'+popup.id+'" class="popup-container">\n';
				}

				html += '<table id="popup-table-'+popup.id+'" class="popup" style="width:'+tableWidth+'px;" cellspacing="0" cellpadding="0">\n';

				if (popup.headerContents.length>2) {
					html += '<tr><td colspan="'+popup.columns.length+'" class="popup-head">'+popup.headerContents+'</td></tr>\n';
				}

				html += '<tr>\n';

				$.each(popup.columns,function(i,column) {

					html += '<td valign="top" style="width:'+popup.columnWidth+'px;">\n';

						$.each(column,function(i,link) {

						if (link.htmlContent == '') {

								var new_win = (parseInt(link.openInNewWindow)==1)?' rel="external"':'';
								if((link.url == "") || (link.url == null)){
									var link_html = link.displayName;
								}else{
									var link_html = '<a href="'+link.url+'" title="'+link.displayName+'"'+new_win+'>'+link.displayName+'</a>';
								}

								if (parseInt(link.hidden) != 1) {
									if (parseInt(link.isHeading) == 1) {
										html += '<h5 class="popup_heading" style="width:'+popup.columnWidth+'px;">'+link_html+'</h5>\n';
									} else {
										html += '<p class="popup_link" style="width:'+popup.columnWidth+'px;">'+link_html+'</p>\n';
									}
								}

							} else {
								html += link.htmlContent+'\n';
							}

						});

					html += '</td>\n';

				});

				html += '</tr>\n';

				if (popup.footerContents != '') {
					html += '<tr><td colspan="'+popup.columns.length+'" class="popup-foot">'+popup.footerContents+'</td></tr>\n';
				}

				html += '</table>\n';
				html += '</div>\n';

				$('#popup_'+popup.id).append(html);

				$('#popup_'+popup.id).hover(function()


				{
					//Delay the menu popping up
		      $(this).oneTime(150, 'popup_delay', function() {
          $('#popup_'+popup.id).css('position','relative');
          $('#popup-container-'+popup.id).css('left','auto');
          $(this).stopTime("popup_timer");

					if (popup.popupDirection == 'left') {

						/* LEFT DIRECTION */

						if($.browser.msie && parseInt(jQuery.browser.version) <= 6){
							$('#popup-container-'+popup.id).css('right','-1px');
						} else {
							$('#popup-container-'+popup.id).css('right','0');
						}

						var navLeft = findPosX(document.getElementById('nav-tabs'));
						var popupLeft = findPosX(document.getElementById('popup-container-'+popup.id));

						if (popupLeft < navLeft) {

							if($.browser.msie && parseInt(jQuery.browser.version) <= 7){
								if(jQuery.browser.version=='6.0'){
									var rightOffset = (navLeft-popupLeft+1);
								} else {
									var rightOffset = (navLeft-popupLeft);
								}
							} else {
								var rightOffset = (navLeft-popupLeft);
							}

							$('#popup-container-'+popup.id).css('right','-'+rightOffset+'px');
						}

					} else {

						/* RIGHT DIRECTION */

						$('#popup-container-'+popup.id).css('zoom',1);

						var popupLeft = findPosX(document.getElementById('popup-container-'+popup.id));

						var popupDiff = (popupLeft-nhbsLeft);
						var containerWidthArray = $('#popup-container-'+popup.id).css('width').split('px');

						var containerWidth = parseInt(containerWidthArray[0]);
						var popupTotal = (popupDiff+containerWidth);

						if (popupTotal > nhbsWidth) {
							var popupOffset = (popupTotal-nhbsWidth);
							$('#popup-container-'+popup.id).css('left','-'+popupOffset+'px');
						}

					}

					$('div.popup-container:not(#popup-container-'+popup.id+')').css('left','-9999px');


				});},function()
				{
					$(this).stopTime("popup_delay");
					$(this).oneTime(parseInt(popup.stickyness),"popup_timer",function() {
						$('#popup-container-'+popup.id).css('left','-9999px');
						$('#popup-container-'+popup.id).css('right','auto');
					});
				});

				$("a[rel=external]").attr('target','_blank');

			});

		});

	};

	/* Load Popups */
	makePopups(null);

});

$(window).load(function(){

	if($.browser.msie && parseInt(jQuery.browser.version) <= 6){
		$('ul#nav-tabs li.tab').hover(function(){
		$(this).find('a.tab:not(.current)').css('background-position','0 -43px');
		$(this).find('a:not(.current) span').css('background-position','100% -43px');
		$(this).find('a.popup.current span').css('padding-bottom','2px');
		$(this).find('a.tab:not(.current) span').css('background-position','100% -43px');
	}
	,function(){
		$(this).find('a.tab:not(.current) span').css('background-position','100% 2px');
		$(this).find('a.tab:not(.current)').css('background-position','0 2px');
		$(this).find('a:not(.current) span').css('background-position','100% 2px');
		$(this).find('a.popup.current span').css('padding-bottom','7px');
	});
	}
});

//Addding a function for checking if an element exists
jQuery.fn.exists = function() { return (this.length > 0); };

/* Flash Message JS */
$(".FLASH_MESSAGE_OUTER").ready(function(){

	$(".FLASH_MESSAGE_OUTER").fadeOut(200).fadeIn(200);

	$(".flash_message_close-fade").click(function(){
		$(".FLASH_MESSAGE_OUTER").fadeOut("slow");
		return false;
	});
});

// Make scrollable function for the carasoules
$("div.sc_menu_wrapper").ready(function() {
	function makeScrollable(wrapper, scrollable){
		// Get jQuery elements
		var wrapper = $(wrapper), scrollable = $(scrollable), moveRight = 70;

		// Hide images until they are not loaded
		scrollable.hide();
		var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);

		// Set function that will check if all images are loaded
		var interval = setInterval(function(){
			var images = scrollable.find('img');
			var completed = 0;

			// Counts number of images that are succesfully loaded
			images.each(function(){
				if (this.complete) completed++;
			});

			if (completed == images.length){
				clearInterval(interval);
				// Timeout added to fix problem with Chrome
				setTimeout(function(){

					loading.hide();
					// Remove scrollbars
					wrapper.css({overflow: 'hidden'});

					//scrollable.slideDown('slow', function(){
						scrollable.show();
						enable();
					//});
				}, 1000);
			}
		}, 100);

		function enable(){

			var inactiveMargin = 99;

			var wrapperWidth = wrapper.width();
			var wrapperHeight = wrapper.height();


			var tooltip = $('<div class="sc_menu_tooltip"></div>')
				.css('opacity', 0)
				.appendTo(".carrawrapper");

			scrollable.find('a').each(function(){
				$(this).data('tooltipText', this.title);
			});

			// Remove default tooltip
			scrollable.find('a').removeAttr('title');
			// Remove default tooltip in IE
			scrollable.find('img').removeAttr('alt');

			var lastTarget;
			//When user move mouse over menu
			wrapper.mousemove(function(e){
				lastTarget = e.target;

				var wrapperOffset = wrapper.offset();
				var divWidth = wrapper.width();

				var ul = $('ul.sc_menu'), ulPadding = 15;
				var lastLi = ul.find('li:last-child');
				var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

				var tooltipLeft = e.pageX - wrapperOffset.left;
				var tooltipTop = e.pageY - wrapperOffset.top + 30;


				tooltip.css({top: tooltipTop, left: tooltipLeft, maxWidth: "150px"});

				wrapper.css({overflow: 'hidden'});

				var left = (e.pageX - wrapperOffset.left) * (ulWidth-divWidth) / divWidth + 10;
				wrapper.scrollLeft(left);
			});



		    $(".menutooltipImage").mouseout(function(){
				lastTarget = false;
				tooltip.stop(true).css('opacity', 0).text('');
		      }).mouseover(function(e){
					lastTarget = e.target;
					if (!lastTarget) return;

					var currentText = tooltip.text();

					if (lastTarget.nodeName == 'IMG'){
						// We've attached data to a link, not image
						var newText = $(lastTarget).parent().data('tooltipText');

						// Show tooltip with the new text
						if (currentText != newText) {
							tooltip
								.stop(true)
								.css('opacity', 1)
								.text(newText)

								//.animate({opacity: 1}, 1000);
						}
					}
		      });
		}

		$(".shiftBookShelfLeftRight").click(function(e){

			var ul = $('ul.sc_menu'), ulPadding = 15;
			var lastLi = ul.find('li:last-child');
			var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

			var wrapperOffset = wrapper.offset();
			var divWidth = wrapper.width();

			var left = (e.pageX - wrapperOffset.left) * (ulWidth-divWidth) / divWidth + 10;
			wrapper.scrollLeft(left);
		});

	}

	makeScrollable("div.sc_menu_wrapper", "ul.sc_menu");


});

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
