$(function () {
    
    var mcoffl, mcofft;
    
    $('a.ro').mbRollover();
    
    if ($("#signup-open").length > 0) {
        $("#signup-open").click(function () {
            //toggleMCSignup();
            if(typeof norilskTrigger == 'function') {
                norilskTrigger(462,1);
            }
        });

        /*$(window).bind('resize', function () {
            adjMCSignup();
        });*/

    }

    if (scripts_isIE6) {
        $(window).load(function () {
            $(document).pngFix();
        });
    }

/*     
	$('#topNav').superfish({
            delay:       700,                            // one second delay on mouseout 
            animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
            speed:       'fast',                          // faster animation speed 
            autoArrows:  false,                           // disable generation of arrow mark-up 
            dropShadows: false                            // disable drop shadows
	});
*/

    $("a[rel^='lightbox']").prettyPhoto({
        animationSpeed: 'slow',
        padding: 40,
        opacity: 0.85,
        showTitle: false,
        allowresize: true,
        counter_separator_label: '/',
        theme: 'light_square'
    });

    if($('div#home-marquee marquee').length > 0 ) {
	    $('div#home-marquee marquee').marquee('pointer').mouseover(function () {
	        $(this).trigger('stop');
	    }).mouseout(function () {
	        $(this).trigger('start');
	    }).mousemove(function (event) {
	        if ($(this).data('drag') == true) {
	            this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
	        }
	    }).mousedown(function (event) {
	        $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
	    }).mouseup(function () {
	        $(this).data('drag', false);
	    });
	    $('div#home-marquee div.pointer').append('<div class="clearLeft"></div>');
    }


    if ($(".lbook").length >= 2) {
        setInterval(function () {
            rotateBooks($(".lbook").length);
        }, 10000);
    }

    if ($.fn.mbBookShowcase) {
        if ($("#first-ed-books").length > 0) {
            $("#tray-wrapper").mbBookShowcase({
                targetTray: 'firstEdTrays',
                //div id of tray in your php fetch file trays.php
                scrollTrayClass: "bookTray",
                trayOffset: 20,
                descriptionMode: 'detail',
                tooltip: true,
                tooltipFileDiv: "home-book-desc-content",
                itemClass: 'book',
                imgClass: 'bookImg',
                loadTrayFromExternalFile: true,
                followLink: true,
                phpFetchUrlValue: "firstEd"
            }, function () {});
        } else if ($("#rare-books").length > 0) {
            $("#tray-wrapper").mbBookShowcase({
                targetTray: 'rareTrays',
                //div id of tray in your php fetch file trays.php
                scrollTrayClass: "bookTray",
                trayOffset: 20,
                descriptionMode: 'detail',
                tooltip: true,
                tooltipFileDiv: "home-book-desc-content",
                itemClass: 'book',
                imgClass: 'bookImg',
                loadTrayFromExternalFile: true,
                followLink: true,
                phpFetchUrlValue: "rare"
            }, function () {});

        } else if ($("#signed-books").length > 0) {
            $("#tray-wrapper").mbBookShowcase({
                targetTray: 'signedTrays',
                //div id of tray in your php fetch file trays.php
                scrollTrayClass: "bookTray",
                trayOffset: 20,
                descriptionMode: 'detail',
                tooltip: true,
                tooltipFileDiv: "home-book-desc-content",
                itemClass: 'book',
                imgClass: 'bookImg',
                loadTrayFromExternalFile: true,
                followLink: true,
                phpFetchUrlValue: "signed"
            }, function () {});

        }
    }
    
    $("#social-close a").click(function(){
    	$("#social-bar-center").fadeOut("fast");
    	$("#social-bar").animate({
		bottom: '-=20px'
    	},1000);
    	
	$("#social-close").fadeOut(function(){
	$("#social-open").fadeIn();
    	$("#social-open").animate({
    		bottom: '+=20px'
    		}, 500);
	});
	//$("#social-bar").load("setSocialBar.php", {status: "closed"}, function(response, status, xhr){});
	$.ajax({
   		type: "POST",
 		url: 'setSocialBar.php',
  		data: "status=closed",
 		success: function(data) {//alert(data);
 		}
	});
    });
    
    $("#social-open a").click(function(){
    	$("#social-bar-center").fadeIn();
    	$("#social-bar").animate({
		bottom: '+=20px'
    	},1000);
    	
    	$("#social-open").animate({ bottom: '-=20px'}, 500);
	$("#social-open").fadeOut("fast");
	
	$("#social-close").fadeIn();
	$.ajax({
   		type: "POST",
 		url: 'setSocialBar.php',
  		data: "status=open",
 		success: function(data) {//alert(data);
 		}
	});
	//$("#social-bar").load("setSocialBar.php", {status: "open"}, function(response, status, xhr){});
    
    });
    
    if($("#search_free_shipping").length > 0 )
    {
    	$("#search_free_shipping a").click(function(){
    	
    		_gaq.push(['_trackEvent', 'FrShip', 'Link']);
    		
		var pos = $(this).parent().offset();
		var w = $("#main_free_shipping_lyr").width() / 1.5;
		$("#main_free_shipping_lyr").css("left", pos.left-w+'px');
		$("#main_free_shipping_lyr").css("top", pos.top+'px');
		$("#main_free_shipping_lyr").show();
		
		$("#main_free_shipping_close a").click(function(){
			$("#main_free_shipping_lyr").hide();
			
		});
	});
    }
    
    if($("#glossary-layer").length > 0)
    {
    	//Required fields necessary for submission
    	var reqFlds = $('.req-fld');
    	
   	$("#glossary-open").click(function(){
   		
   		//Reset required fields on new layer open
   		reqFlds.each(function(){
   			$(this).val("");
   		});
	   	$("#phoneNumber-fld").val("");
	   	$('#modalGlossary').mbModal({
			openDivID: 'glossary-layer',
			buttonClose: 'glossary-close',
			centerOffsetLeft: -2,
			clickToClose: true,
			zIndexStart: 2000
		});
	});
	
	//Error checking
    	var errorWrap = $("#error-wrap");
	$("#formGlossary").submit(function(){
		var errors = "";
		errorWrap.children("ul.error").remove();
		reqFlds.each(function(){
			if($(this).val() == "") {
				$(this).addClass('error-fld');
				errors = "<li>Please enter all required information</li>"; 
			} else $(this).removeClass('error-fld');
		});
		
		var emailaddr = $("#email-fld").val();
		var efilter = "^[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+@[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+";
		if( !emailaddr.match(efilter)) {
			errors += "<li>Please enter a valid email</li>";
		}
		
		if(errors != ""){
			errorWrap.append('<ul class="error">'+errors+'</ul>');
		} else {
			var request = $.ajax({
			  url: "glossary-layer-send.php",
			  type: "POST",
			  data: {'emailaddr': $("#email-fld").val(), 'firstname': $("#firstname-fld").val(), 'phoneNumber': $("#phoneNumber-fld").val(), 'country': $("#country-fld").val(), 'term': $("#question-fld").val()},
			  dataType: "html"
			});
			
			request.done(function(msg) {
				$("#glossary-layer-div").fadeOut(function(){
					$("#glossary-layer-thankyou").fadeIn();
				});
			});
			
			request.fail(function(jqXHR, textStatus) {
				errorWrap.html('<ul class="error"><li>The request failed. Please try again in a few seconds.</ul>');
			});				
		}
		
		return false;
	});
    }
});

function toggleMCSignup() {
    var thisHeight = $("#social-link-newsletter").height();
    var thisObj = $("#signup-open");
    if ($("#social-link-newsletter").is(":visible")) {
        /*$(thisObj).text("Newsletter Signup");
        $("#social-link-newsletter").animate({
            top: '+=' + thisHeight
        }, 1000);
        $("#social-link-newsletter").fadeOut("fast");
        */
        if(typeof nrlskSlideUpClose == 'function') {
            $(thisObj).text("Close Signup");
            nrlskSlideUpClose();
        }

    } else {
        /*
        $("#social-link-newsletter").css('left', $(thisObj).offset().left);
        $("#social-link-newsletter").css('top', $(thisObj).offset().top);
        $(thisObj).text("Close Signup");
        $("#social-link-newsletter").fadeIn("fast", function () {
            $("#social-link-newsletter").animate({
                top: '-=' + thisHeight
            }, 1000);
        }); */
        if(typeof norilskTrigger == 'function') {
            $(thisObj).text("Close Signup");
            norilskTrigger(462,1);
        }
    }
}

/*
function adjMCSignup() {
    var thisHeight = $("#social-link-newsletter").height();
    var thisObj = $("#signup-open");
    if ($("#social-link-newsletter").is(":visible")) {
        $("#social-link-newsletter").css('left', $(thisObj).offset().left);
        $("#social-link-newsletter").css('top', $(thisObj).offset().top - thisHeight);
    }
}
*/

var currRotate = 1;
function rotateBooks(numBooks) {
    //alert(currRotate);
    $("div#lbook" + currRotate).fadeOut(2500, function () {
        if (++currRotate > numBooks) {
            currRotate = 1;
        }
        $("div#lbook" + currRotate).fadeIn(2500);
    });
}

