$(document).ready(function() {

	dynamItScript({
		xout: {
			image: '/img/xout.png',
			width: 21,
			height: 21,
			right: 24,
			top: 24 },
		dialogTop:	'<div id="dialog"><div class="dialogbody"><div class="exp_container"><div class="exp_head"><h3>%s</h3><div class="clear"></div></div><div class="exp_body">',
		dialogBottom: '</div></div></div> <div class="dialogbottom"></div></div>',
		dialogWidth: 478,
		dialogHeight: 'auto'
	});

	/** nav : dropdown **/
	$("ul#nav").dynamItDrop(); 

	/** nav : dropdown (books) : switch tab **/ 
	$("ul.tabs li").not(".notab").click(function() {

		var rel = $(this).parent().attr('rel');

		$("ul.tabs").filter("[rel='"+rel+"']").children('li').removeClass('on');
		$(this).addClass('on');

		$('ul.tabcontent').filter("[rel='"+rel+"']").children('li').removeClass('on');
		$('ul.tabcontent').filter("[rel='"+rel+"']").children('li').eq($(this).index()).addClass('on');
		location.hash = $(this).attr('title');
		return false;
	});

	if( location.hash.length ) {
		$('ul.tabs li').filter("[title='" + location.hash.substring(1) + "']").click();
	}

	/** loginbox **/
	$("#loginbox a.close").click(function() {
		$("#loginbox").fadeOut('slow');
		return false;
	});

	/** home : banner **/
	$("#carousel ul").dynamItCarousel({
		next: '#carouselbox .next',
		prev: '#carouselbox .prev',
		width: 884,
		wraparound: true,
		slideshow: true,
		slideshowtimeout: 6000
	}); 

	/** home : current books **/
	$("#bookcarousel ul").dynamItCarousel({
		next: '#bookcontrols .next',
		prev: '#bookcontrols .prev',
		width: 584,
		wraparound: false,
		slideshow: false,
		inview: 4
	}); 

    /** general : cms : popup testimonials **/
	$('a.bubble').click( function() {
		// if on member benefits page, event track the testimonial view
		if( location.href.indexOf('membership-benefits') != -1 ) analyticsEvent('TestimonialView', '', '');

		var dialogTitle = $(this).attr('title');
		var url = 'pages/' + $(this).attr('href') + '.php';
		dynamItLoadData( url, '', function(data) {
			dynamItConfDialog(data, false, dialogTitle);
		});
		return false;
	});

	/** track events on case studies anchors **/
	$("a[href*='#']").click( function() {
		if( location.href.indexOf('case-studies') != -1 ) 
			analyticsEvent('CaseStudyView', $(this).attr('href'), '');
	});
	
	/** track events on news downloads **/
	$("a.download").click( function() {
		analyticsEvent('NewsDownload', $(this).attr('href'), '');
	});
	

    /** general : forms : blank labels on focus **/
    $('input, textarea').live('focus', function() {
	    if( $(this).val() == $(this).attr('title') ) {
		    $(this).val('');
	    }
    }).live('blur', function() {
	    if( $(this).val() == '' ) {
		    $(this).val( $(this).attr('title') );
	    }
    });

	/** general : expanding tables **/
	$('div.exp_container div.exp_head span.ctl a').click(function() {
		if ( $(this).hasClass('exp') ) {
			$(this).closest('div.exp_container').find('.exp_body').slideDown('normal');
			$(this).closest('div.exp_container').find('.exp_head').removeClass('collapsed');
		} else {
			$(this).closest('div.exp_container').find('.exp_body').slideUp('normal',function() {
				$(this).closest('div.exp_container').find('.exp_head').addClass('collapsed');
			});
		}
		$(this).toggleClass('exp');
		return false;
	});
	
	/** Message/Alerts : Close **/
	$('div.message a.close, div.alert a.close').click(function() { 
		$(this).parent().fadeOut();
		return false;
	});
	
	
	/** books : cover art zoom **/
	$('.coverthumb').hover( function() {
		$(this).siblings('.coverart').show();
	}, function() {
		$(this).siblings('.coverart').hide();
	});	

	/** book ratings **/
	$('.dynamitRate').each(function() {

		// Set Star Hover
		$(this).find('.star').hover(function() {
			$(this).addClass('hover');
			$(this).prevAll().addClass('hover');
		},function() {
			$(this).removeClass('hover');
			$(this).prevAll().removeClass('hover');			
		});
		
		// Set Star Click
		$(this).find('.star').click(function() {
			var book = $(this).parent().attr('id').split('_')[1];
			var rating = parseInt($(this).attr('class').replace('star s','').replace('hover',''));
			var width = 0;
			switch (rating) {
				case 1: width = 21; break;
				case 2: width = 42; break;
				case 3: width = 60; break;
				case 4: width = 78; break;
				case 5: width = 100; break;
			}
			$(this).closest('.dynamitRate').find('.init').addClass('user');
			$(this).closest('.dynamitRate').find('.init').css('width',width+'%');

//			$(this).parent().siblings('.dialog').load('/books/rate/', '&book=' + book + '&rating=' + rating).show();
			var lft = $(this).parent().offset().left + 'px';
			var tp =  ($(this).parent().offset().top + 33) + 'px';
			$("#rateinfo").load('/books/rate/', '&book=' + book + '&rating=' + rating).css({ left: lft , top: tp }).show();
            
            analyticsEvent('Rate Book', book, rating);

			// check height, we can't have this dipping below the hills.
/*			var vLimit =  $('#footer-top').offset().top;
			var vCalc = $(this).parent().siblings('.dialog').offset().top + $(this).parent().siblings('.dialog').height();

			if( vCalc > vLimit) $(this).parent().siblings('.dialog').css('top', 'auto').css('bottom', '33px');
*/
			return false;
		});
		
		// Set Main Hover
		$(this).find('.rate').hover(function() {
			$(this).siblings('.init').css('display','none');
		},function() {
			$(this).siblings('.init').css('display','block');			
		});
		
	});

	$("#rateinfo .close").live('click', function() { 
		$(this).parent().hide();
		return false;
	});
	$("#rateinfo .nothanks").live('click', function() { 
		$(this).closest('.loginbox').hide();
		return false;
	});



	/** wishlists **/
	$("a.newwishlist").click( function() {
		dynamItLoad('/account/wishlist/add', null, 478, 'auto', null);
		return false;
	});
	$("a.editwishlist").click( function() {
		dynamItLoad('/account/wishlist/edit?list=' + $(this).attr('title'), null, 478, 'auto', null);
		return false;
	});

	$("#wishlists input.wlcheck").live('click', function() {

		dynamItSend('/account/wishlist/default?list=' + $(this).val());
		$("input.wlcheck").not(this).removeAttr('checked');

	});

	$('.selectlist').click(function() { 
		if( $(this).siblings('.wishlistoptions').filter(':visible').length ) {
			$(this).siblings('.wishlistoptions').slideUp('slow');
		} else {
			$(this).siblings('.wishlistoptions').slideDown('slow');
		}
	});


	/** lightbox **/
	$('a.lightbox').lightBox();


	/** IE6 **/
	if ($.browser.msie && $.browser.version <= 6 ) {
		
		// Move Quick Cart
		$(window).scroll(function () {
			var top = $(window).scrollTop();
			var h = $(window).height();
			var move_to = top + (h*0.4);
			$('#quickcart').css('top',move_to);
		});	
		
		// Kill bottom sep borders for sub nav
		//$('#int-content #sec_nav ul#sec_nav_account li a').css('border','none');
	
	}

	/** pagination style hack **/	
	$("ul.tabcontent .table_control").eq(0).addClass("table_control_top");
	$("ul.tabcontent .table_control").eq(1).addClass("table_control_bot");

	/** link the logo **/
	$('h1#logo').css('cursor', 'pointer').click( function() { location.href = '/'; });


	$('a.print').click( function() {
		window.print();
		return false;
	});

	/* marc logic button */
	$(".marclogic").hover(function() { $(this).children('span').show(); }, function() { $(this).children('span').hide(); });
	
	/* News + events: jlg mag: view more */
	$('div.more_news a.more').click(function() {
		$('div.newspost.hidden').each(function() { 
			$(this).slideDown();
		});
		$(this).parent().fadeOut();
	});
	
	
	
});


var globalTimeout = null;
function queue(fcn, interval) {

    if(globalTimeout) clearTimeout(globalTimeout);
    globalTimeout = setTimeout(fcn, interval);
}

function dequeue(hide) {

    if(globalTimeout) clearTimeout(globalTimeout);
    $(hide).hide();
}


function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}


function marcRecord(isbn, filename, placeholder) {
    var args = 'isbn='+isbn+'&filename='+filename+'&placeholder='+(placeholder?1:0);

    if ( getCookie('marc')=='1' ) {
        if ( placeholder ) {
            // Log the event with google
            analyticsEvent('MARC Record', 'Download Placeholder', filename);
            window.open('/books/downloadmarcplace.dT?'+args, 'marcdownload');
        } else {
            // Log the event with google
            analyticsEvent('MARC Record', 'Download Standard', filename);
            window.open('/books/downloadmarcstd.dT?'+args, 'marcdownload');
        }
    } else {
        dynamItLoad('/books/marc_warning.dT?'+args,null,478,275,null);
    }
}

function jlgGuideDownload(itemcode, type) {
    if ( type == 1 ) {
        analyticsEvent('JLG Guide', 'Download', 'Student:'+itemcode);
    } else if ( type == 2 ) {
        analyticsEvent('JLG Guide', 'Download', 'Teacher:'+itemcode);
    } else {
        analyticsEvent('JLG Guide', 'Download', 'Default:'+itemcode);
    }
}

function memberPriceWarning(isbn) {
    var args = "isbn="+isbn;
    
    if ( getCookie('memberpricewarning')=='1' ) {
        return true;
    } else {
        dynamItLoad('/cart/member_price_warning.dT?'+args,null,478,'auto',null);
        return false;
    }
    
}


function adminRemovePackage(id) {
    dynamItSendOnConfirm('/admin/removepkg.dT?pid=' + id, 'Are you sure you wish to delete this package?');
}

function adminAwardsDeleteList(list) {
    dynamItSendOnConfirm('/admin/awards/delete.dT?lid=' + list, 'Are you sure you wish to delete this book list?');

}
function adminAwardsDeleteCategory(cat) {
    dynamItSendOnConfirm('/admin/awards/category/delete.dT?cid=' + cat, 'Are you sure you wish to delete this category?');

}
function adminAwardsRemBook(list, book) {
    dynamItSend('/admin/awards/rembook.dT?lid=' + list + '&book=' + book);
}


function deleteFromWeb(id) {
    dynamItSendOnConfirm('/admin/doDeleteFromWeb.dT?isbn=' + id, 'Would you like to delete ISBN <b>'+id+'</b> from the website?<br/><br/>NOTE: Future SAP synchronizations may re-enable this item unless the master record is hidden or deleted.');
}


function noticeCouponLoad(notice, coupon) {
    dynamItLoad('/news/load.dT?cid=' + coupon, 'noticeBody', null, null, function() {

        if(lastNotice) $('#notice_' + lastNotice).removeClass();
        $('#notice_' + notice).addClass('selectedrow');
        lastNotice = notice;
    });
}


/*** CART AND WISHLIST FUNCTIONS ***/
function addLevelToCart(levels) {
    var url = '/cart/addlevel.dT';
    if(typeof(levels) == 'object') {
        url += '?level[]=' + levels.join('&level[]=');
        analyticsEvent('AddLevelToCart', customerid, levels.join(','));
    } else {
        url += '?level=' + levels;
        analyticsEvent('AddLevelToCart', customerid, levels);
    }
    url += '&cart=1';
    dynamItSend(url);
}

function addLevelToWishlist(levels, list, pkg) {

    var url = '/cart/wishlist/additems.dT';
    if(typeof(levels) == 'object') {
        url += '?level[]=' + levels.join('&level[]=');
        analyticsEvent('AddLevelToWish', customerid, levels.join(','));
    } else {
        url += '?level=' + levels;
        analyticsEvent('AddLevelToWish', customerid, levels);
    }
	if(list != null) url += '&list=' + list;
	if(pkg != null) url += '&package=' + pkg;
    dynamItSend(url);

}



function addBookToWishlist(book) {
    var url = '/cart/addguide.dT';
    if(typeof(book) == 'object') {
        url += '?book[]=' + book.join('&book[]=');
        analyticsEvent('AddBookToWish', customerid, book.join(','));
    } else {
        url += '?book=' + book;
        analyticsEvent('AddBookToWish', customerid, book);
    }
    url += '&cart=Wishlist';
    dynamItSend(url);
}

function doAddBookToCart(book) {
    var url = '/cart/add.dT';
    if(typeof(book) == 'object') {
        url += '?book[]=' + book.join('&book[]=');
        analyticsEvent('AddBookToCart', customerid, book.join(','));
    } else {
        url += '?book=' + book;
        analyticsEvent('AddBookToCart', customerid, book);
    }
    dynamItSend(url);
    dynamItCloseDialog();
}

function doAddBookToWishlist(book, list) {
    var url = '/cart/wishlist/additems';
    if(typeof(book) == 'object') {
        url += '?book[]=' + book.join('&book[]=');
        analyticsEvent('AddBookToWish', customerid, book.join(','));
    } else {
        url += '?book=' + book;
        analyticsEvent('AddBookToWish', customerid, book);
    }
	if(list != null) url += '&list=' + list;

    dynamItSend(url);
    dynamItCloseDialog();
}

function moveBatchToCart(f) {
    f.action = '/wishlist/move.dT';
    dynamItPublish(f);
}

function moveBookToCart(book) {
    dynamItSend('/wishlist/move.dT?book[]=' + book);
}

function moveLevelToCart(level) {
    dynamItSend('/wishlist/move.dT?level[]=' + level);
}

function removeBatchFromWishlist(f) {
    f.action = '/wishlist/remove.dT';
    dynamItPublish(f);
}


function removeBatchFromCart(f) {
    f.action = '/cart/remove.dT';
    dynamItPublish(f);
}

function removeFromCart(type, item) {
	var url = '/cart/remove?' + type + '=' + item;
	dynamItSend(url);
}

function removeFromWishlist(type, item, list) {
	var url = '/cart/wishlist/remitems?' + type + '=' + item;
	if( list != null ) url += '&list=' + list;
	dynamItSend(url);
}


function addBatchToCart(f) {
    var booklist = new Array();
    $(f).find("input[name='book[]']").each(function() {
        if(this.checked) {
            booklist.push($(this).val());
        }
    });

    doAddBookToCart(booklist);
}

function addBatchToWishlist(f) {
    var booklist = new Array();
    $(f).find("input[name='book[]']").each(function() {
        if(this.checked) {
            booklist.push($(this).val());
        }
    });

    addBookToWishlist(booklist);
}

function applyCoupon(coupon) {
    var url = '/cart/addcoupon.dT?coupon='+escape(coupon);
    dynamItSend(url);
}

function removeCoupon(coupon) {
    var url = '/cart/removecoupon.dT?coupon='+escape(coupon);
    dynamItSend(url);
}

function renewLevel(levels) {

    var url = '/cart/addlevel.dT?lengthopt=3';
    if(typeof(levels) == 'object') {
        url += '&level[]=' + levels.join('&level[]=');
    } else {
        url += '&level=' + levels;
    }

    dynamItSend(url);

}

function renewBatchLevels(f) {
    f.action = '/cart/addlevel.dT';
    dynamItPublish(f);
}

function addLevelBatchToCart(f) {
    f.action = '/cart/addlevel.dT';
    dynamItPublish(f);
}

/*** END CART AND WISHLIST ***/



function changeQty(level, book, qtyf, unit, proc, months) {

    if(qtyf.value == '') return;

    var qty = parseInt(qtyf.value, 10);
    qtyf.value = qty;

    var q = '';
    if(qty <= 0) {
        if(book != '') q = 'book[]=' + book;
        if(level != '') q = 'level[]=' + level;

        dynamItSendOnConfirm('/cart/remove.dT?' + q, 'Remove this item from your cart?');
    } else {
        if(book != '') q = 'book=' + book;
        if(level != '') q = 'level=' + level;
        q += '&qty=' + qty;
        q += '&unit=' + unit;
        q += '&proc=' + proc;
        q += '&months=' + months;

        dynamItSend('/cart/quantity.dT?' + q);
    }
}

function couponsNeedRefesh() {
    // TODO: Possibly refresh panel with new data
    $("tr.coupondata").each(function() {
        $(this).hide();
    });

    $("tr.couponrefresh").fadeIn();
}


function changeOpt(level, opt) {
    var url = '/cart/updatelevel.dT';
    url += '?level=' + level;
    url += '&lengthopt=' + opt;

    location.href = url;
}

function findBook(q) {
    if(q == '') {
        $("#swapOrigList").show();
        $("#swapSearchList").html('').hide();
        return;
    }

    var url = '/account/findbook.dT?q=' + urlencode(q);
    dynamItLoad(url, 'swapSearchList', null, null, function() {
        $("#swapOrigList").hide();
        $("#swapSearchList").show();
        activateSwappers();
    });

}

function doClearFormHelperValues(id) {
    $('#'+id+' :input').each( function() {
                                if( $(this).val() == $(this).attr('title') ) {
                                    $(this).val(''); 
                                }
                              } );
    return true;
}


function jlgRateBook( item, rating ) {
    alert('todo:');	
}

function cartProcessingOptChange( addon, setup ) {
    if ( addon == 1 && setup == 1 ) {
        var select = dynamItElem("processing");
        select.value='0';
        dynamItLinkOnConfirm('/cart/processing.dT?addon='+addon, 'Your processing profile options have not been defined.<br/><br/>Would you like set them up now?');
    } else {
        location.href='/cart/processing.dT?addon='+addon;
    }
}

function base_convert (number, frombase, tobase) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +   improved by: Rafal Kukawski (http://blog.kukawski.pl)
    // *     example 1: base_convert('A37334', 16, 2);
    // *     returns 1: '101000110111001100110100'

    return parseInt(number + '', frombase | 0).toString(tobase | 0);
}

function time () {
    // http://kevin.vanzonneveld.net
    // +   original by: GeekFG (http://geekfg.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: metjay
    // +   improved by: HKM
    // *     example 1: timeStamp = time();
    // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000
    
    return Math.floor(new Date().getTime()/1000);
}


function toggleRadio(c) {
    var radiogroup = c.form.elements[c.name];

    // Uninitialized? set previous to default state
    if ( null == c.getAttribute('previousstate') ) {
        c.setAttribute( 'previousstate', c.defaultChecked?'true':'false' );
    }

    // Toggle control if previous state and current state match
    if ( c.checked && c.getAttribute('previousstate')=='true' ) {
        c.checked = false;
    }

    // Remember the previous state for all radios in this group
    for(var i = 0; i < radiogroup.length; i++) {
        radiogroup[i].setAttribute( 'previousstate', radiogroup[i].checked?'true':'false' );
    }
}


/** SWAP **/
    var selectedBook = null;
    var swapLevel = null;
    var swapDate = null;

    function swapBook(level, date) {
        dynamItLoad('/account/swap.dT?level=' + level  + '&date=' + date, null, 478, 500, function() {
            initSwapDialog(level, date);
            activateSwappers();
        });
    }

    function initSwapDialog(level, date) {
        swapLevel = level;
        swapDate = date;
    }

    function activateSwappers() {
        $('.availableBook').click(function() {

            if(selectedBook) $('#' + selectedBook).css('backgroundColor', '#ffffff');

            var val = $(this).attr('id');
            selectedBook = val;
            $(this).css('backgroundColor', '#BEF3F7');
        });
    }

    function makeTheSwap() {

        if(selectedBook) {
            var url = '/account/makeswap.dT';
            url += '?level=' + swapLevel;
            url += '&date=' + swapDate;
            url += '&book=' + selectedBook;

            analyticsEvent( 'SwapBook', swapLevel+':'+swapDate, selectedBook );
            
            dynamItSend(url);
        }

    }
/*********/


function changePassword() {
    dynamItLoad('/account/password.dT', null, 478, 'auto', null);
}


/**
* ajaxCall will make a synchronous AJAX call and return the result
* the called URL must return the result in the format:
* return: <yourdatahere>
*/
function ajaxCall(url) {
    var ret = null;
    
    $.ajax({ async:   false,
             url:     url,
             success: function(data) {
                 var rx = /^result:\s*(.*?)\s*$/m;
                 if ( ret = data.match(rx) ) {
                     ret =  ret[1];
                 }
             }
           });
    
    return ret;
}


function bookartSwap(dir) {
	var count = $('#bookart').children('a').length;
	var i = $('#bookart').children('a').filter('.on').index();

	if(dir == 0) {
		$('#bookart').children('a').eq(i).click(); //init lightbox
	} else {
		$('#bookart').children('a').removeClass('on');
		var next = i+dir;
		if( next < 0 ) next = count - 1;
		else if( next == count ) next = 0;

		var thumb = $('#bookart').children('a').eq(next).children('img').attr('src');
		var zoom = $('#bookart').children('a').eq(next).attr('href');

		$('#bookart').children('a').eq(next).addClass('on');
		$('#coverthumb').attr('src', thumb);
		$('#coverzoom').attr('src', zoom);
	}
}

function levelQuickView(lvl) {
    analyticsEvent("QuickView", 'Level', lvl);
	dynamItLoad('/books/quicklevel?level='+lvl, null, 680, 'auto', null);
}


function accountMessageDelete(m) {
	dynamItSendOnConfirm('/account/delmessage?message=' + m, 'Really delete this message?');
}

function accountMessageView(m) {
	dynamItLoad('/account/readmessage?message=' + m, null, 478, 'auto', null);	
}

function wishlistPrice() {
	var total = 0;
	$('td.price').each( function() {
		if( $(this).text().substring(0,1) == '$' ) {
			var dollars = parseFloat( $(this).text().substring(1) );
			if( !isNaN(dollars) ) total += dollars;
		}
	});

	$("span#wlprice").html(total.toFixed(2));
		
}

function changeBilling() {
	dynamItLoad('/cart/checkout/billing', null, 478, 'auto', null);
}
function changeShipping() {
	dynamItLoad('/cart/checkout/shipping', null, 478, 'auto', null);
}

function showLoader(o) { 
	$(o).append('<div style="clear:both;font-size:12px;line-height:16px;"><img src="/img/ajax-loader.gif" alt="" /> &nbsp; Sending...</div>');
}

function showLogin() {
	$('#loginbox').fadeIn('slow');
}
