// Modify taoshop object
(function(taoshop){

	// Update user registration information
	var isRegistrationFormValid = taoshop.user.isRegistrationFormValid;
	taoshop.user.isRegistrationFormValid = function(data){
		var isValid = isRegistrationFormValid();
		if ($F('register_telephone') != "") {
			isValid &= tao.form.validateElement($('register_telephone'), 'phoneNumber', 'Please enter a valid telephone number');
		}
		return isValid;
	};
	var getRegistrationData = taoshop.user.getRegistrationData;
	taoshop.user.getRegistrationData = function(data){
		var data = getRegistrationData();
		data.set('telephone_number', $F('register_telephone'))
		if ($('register_favourite_store')) data.set('favourite_store_id', $F('register_favourite_store'));
		
		var storeOptIn = $$('input:checked[name=SignedUpForStoreEmail]').pluck('value').first();
		data.set('opted_in_subsite', storeOptIn);
		
		return data;
	};

	// Profile saving
	taoshop.user.saveProfile = function() {
		var validName = tao.form.validateElement($('profile_first_name'), 'required', 'Please enter a first name');
		validName &= tao.form.validateElement($('profile_last_name'), 'required', 'Please enter a surname');
		// Usernames are optional for taoshop instances
		var validUserName = true;
		var userName = "";

		if ($('profile_user_name')) {
			validUserName = tao.form.validateElement($('profile_user_name'), 'required', 'Please enter a user name');
			userName = $F('profile_user_name');
		}

		var validEmailAddress = tao.form.validateElement($('profile_email_address'), 'emailAddress', 'Please enter a valid email address');
		
		var validForm = (validName && validUserName && validEmailAddress);
		if (validForm) {
			xajax_saveUserProfile(xajax.getFormValues('edit-details'));
		} else {
			shop.display.validationWarn();
		}
	};
	
	// Autocomplete
	taoshop.search.useAutocomplete = true;
	taoshop.search.defaultText = "Keyword, title, author, ISBN";
    taoshop.search.init = function() {
            if (!$('main_search_input')) return;
            if ($F('main_search_input') == '') $('main_search_input').setValue(shop.search.defaultText);
            $('main_search_input').observe('blur', shop.search.ensureDefaultTextIsPresent);
            $('main_search_input').observe('click', shop.search.removeDefaultText);
            if (shop.search.useAutocomplete) {
            	function eventCallBack(element, entry) {
            		return entry + "&mediatype=" + $('select-filter').value;
            		}
	            var autocompleter = new Ajax.Autocompleter(
	                'main_search_input',
	                'main_search_suggestions',
	                '/autocomplete/search.tao',
	                {
	                    updateElement:   shop.search.handleSelect,
	                    frequency:       0.4,
                        callback: eventCallBack
	                }
	            );
            }
    };

	// Growler
	jQuery.jGrowl.defaults.position = 'center';
	taoshop.display.info = function(message) {
		jQuery.jGrowl(message, {position: 'center', theme: 'growl-info', header: ''});
	};
	taoshop.display.error = function(message) {
		jQuery.jGrowl(message, {position: 'center', theme: 'growl-error', header: '', sticky: true});
	};
	taoshop.display.warn = function(message) {
		jQuery.jGrowl(message, {position: 'center', theme: 'growl-warn', header: ''});
	};
	taoshop.display.special = function(message) {
		jQuery.jGrowl(message, {position: 'center', theme: 'growl-special', header: ''});
	};

	// Checkout modifications
	taoshop.checkout.updateBillingOptions = function(){};
	taoshop.checkout.isPaymentRequired = function() {
		return true;
	};
	getDispatchOption = function() {
		return 'ItemsSeparately';
	};
	var getSubmissionData = taoshop.checkout.getOrderDataForSubmission;
	taoshop.checkout.getOrderDataForSubmission = function() {
		var data = getSubmissionData();
		data.set('dispatchOption', getDispatchOption());
		if (data.get('deliveryMethod') == "UkStorePickUp") {
			data.set('storeId', parseInt($F('store-id'), 10));
		}
		return data;
	};
	var isDeliveryDataValid = taoshop.checkout.getOrderDataForSubmission;
	taoshop.checkout.isDeliveryDataValid = function() {
		if (taoshop.checkout.getDeliveryMethod() == "UkStorePickUp") {
			return $F('store-id') > 0;
		} else {
			return isDeliveryDataValid();
		}
	};
	taoshop.checkout.updateDeliveryMethod = function() {
		var dispatchOption = getDispatchOption();
		var deliveryMethod = taoshop.checkout.getDeliveryMethod();
		var country = $j('#da_country').val();
		if (!country) {
			country = 'GB';
		}
		if (country != 'GB') {
			deliveryMethod = 'EuStandard';
		}
		if (country == 'GB' && deliveryMethod == 'EuStandard') {
			deliveryMethod = 'UkStandard';
		}
		xajax_updateDeliveryMethod(deliveryMethod, dispatchOption, country);
	}
	
	var updateProductQuantity = function(event) {
		var newQuantity = event.element().getValue();
		var productId = event.element().next('input').getValue();
		var request = {};
		request[productId] = newQuantity;
		xajax_updateBasketLineQuantities(JSON.stringify(request));
	};
	var checkoutInit = taoshop.checkout.init;
	taoshop.checkout.init = function() {
		checkoutInit();
		$$('input[name=DeliveryOption]').invoke('observe', 'click', taoshop.checkout.updateDeliveryMethod);
		$$('select[id=da_country]').invoke('observe', 'change', taoshop.checkout.updateDeliveryMethod);
		$$('.checkout-quantity').invoke('observe', 'blur', updateProductQuantity);
	};
	taoshop.checkout.handleThreeDSecure = function() {
		hive.modalBox.init('<div id="modalBoxContainer">Loading...</div>', 550, 500);
		var iframe = $('threeDSecureDiv').remove();
		$('modalBoxContainer').insert(iframe);
		document.downloadForm.target = "ACSframe"; document.downloadForm.submit();
	};
	taoshop.checkout.submitOrder = function(){
		var totalAmount = $j('#totalAmount').html();
		var nbtAmount = $j('#tokenAmount').val();
		
		tao.form.flushErrorMessages();
		// Checks for anonymous checkouts and exit to populate data from ui_Response
		// Same function will be called again by ui_Response after save
		var deliveryAddressAnonymFormId = 'delivery-address-form-anonymous';
		if (!tao.form.validateElement($('delivery_address'), 'nonzero') && $(deliveryAddressAnonymFormId)) {
			taoshop.user.saveDeliveryAddress(deliveryAddressAnonymFormId);
			return;
		}
		var billingAddressAnonymFormId = 'billing-address-form-anonymous';
		if (!tao.form.validateElement($('billing_address'), 'nonzero') && $(billingAddressAnonymFormId)) {
			taoshop.user.saveBillingAddress(billingAddressAnonymFormId);
			return;
		}
		var cardAnonymousFormId = 'card_form_anonymous';
		if ($(cardAnonymousFormId)) {
			if (totalAmount > nbtAmount && !taoshop.checkout.saveBankcard()) {
				taoshop.display.error("Bank card details incomplete");
				return;
			}
		}
	    if (!taoshop.checkout.isCheckoutComplete()) {
	    	if (tao.form.errorMessages.length > 0) {
	    		taoshop.display.error(tao.form.errorMessages.join('<br/>'));
	    	} else {
	    		taoshop.display.error("Checkout data is incomplete");
	    	}
	    	return;
	    }
	    taoshop.checkout.disableSubmitButton();
	    taoshop.display.notify('Processing order...');
	    taoshop.checkout.registerGuestEmailAddress();
	    var orderData = taoshop.checkout.getOrderDataForSubmission();
	    xajax_submitOrder(orderData.toJSON());
	    tao.analytics.track('/checkout/completed/');
	};
	taoshop.user.signinAnonymous = function(errorMessageClass) {
		var validEmailAddress = tao.form.validateElement($('anonymous_sign_in_email_address'), 'emailAddress', 'Please enter a valid email address', errorMessageClass);
		validEmailAddress &= tao.form.validateElement($('anonymous_sign_in_confirm_email_address'), function(){return $F('anonymous_sign_in_email_address') == $F('anonymous_sign_in_confirm_email_address');}, 'Please ensure your confirmation email address matches your main address', errorMessageClass);
        if (validEmailAddress) {
            xajax_userRegisterAnonymous($F('anonymous_sign_in_email_address'));
        } else {
        	return false;
        }
	};
	taoshop.user.signinFacebookAnonymous = function(errorMessageClass) {
		var validEmailAddress = tao.form.validateElement($('fb_anonymous_sign_in_email_address'), 'emailAddress', 'Please enter a valid email address', errorMessageClass);
		validEmailAddress &= tao.form.validateElement($('fb_anonymous_sign_in_confirm_email_address'), function(){return $F('fb_anonymous_sign_in_email_address') == $F('fb_anonymous_sign_in_confirm_email_address');}, 'Please ensure your confirmation email address matches your main address', errorMessageClass);
        if (validEmailAddress) {
            xajax_userRegisterAnonymous($F('fb_anonymous_sign_in_email_address'));
        } else {
        	return false;
        }
	};
    taoshop.user.saveDeliveryAddress = function(formId) {
		if (!formId) formId = 'delivery_address_form';
		var isFormValid = true;
		isFormValid &= tao.form.validateElement($('da_first_name'), 'required', 'Please enter a first name');
		isFormValid &= tao.form.validateElement($('da_last_name'), 'required', 'Please enter a last name');
		isFormValid &= tao.form.validateElement($('da_line1'), 'required', 'Please enter the first line of your address');
		isFormValid &= shop.user.isValidSuburb($('da_line3'));
        if ($('da_line4')) {
            // City isn't always present but is required when it is
        	isFormValid &= tao.form.validateElement($('da_line4'), 'required', 'Please enter your city');
        }
        isFormValid &= tao.form.validateElement($('da_postcode'), $('da_country').value == 'GB' ? 'postcode' : 'required', 'Please enter a valid post/zip code');
        if (isFormValid) {
            xajax_saveDeliveryAddress(xajax.getFormValues(formId))
        } else {
        	shop.display.validationWarn();
        }
    };
    taoshop.user.saveBillingAddress = function(formId) {
    	if (!formId) formId = 'billing_address_form';
    	var isFormValid = true;
    	isFormValid &= tao.form.validateElement($('ba_first_name'), 'required', 'Please enter a first name');
    	isFormValid &= tao.form.validateElement($('ba_last_name'), 'required', 'Please enter a last name');
    	isFormValid &= tao.form.validateElement($('ba_line1'), 'required', 'Please enter the first line of your address');
    	isFormValid &= shop.user.isValidSuburb($('ba_line3'));
        if ($('ba_line4')) {
            // City isn't always present but is required when it is
        	isFormValid &= tao.form.validateElement($('ba_line4'), 'required', 'Please enter your city');
        }
        isFormValid &= tao.form.validateElement($('ba_postcode'), $('ba_country').value == 'GB' ? 'postcode' : 'required', 'Please enter a valid post/zip code');
        if (isFormValid) {
            xajax_saveBillingAddress(xajax.getFormValues(formId));
        } else {
        	shop.display.validationWarn();
        }
    };
    taoshop.user.copyDeliveryAddressToBilling = function() {
    	try{
    		if ($("copy-delivery-address-to-billing").checked) {
    	    	$('ba_first_name').setAttribute('value', $('da_first_name').getValue());
    	    	$('ba_last_name').setAttribute('value', $('da_last_name').getValue());
    	    	$('ba_line1').setAttribute('value', $('da_line1').getValue());
    	    	$('ba_line2').setAttribute('value', $('da_line2').getValue());
    	    	$('ba_line3').setAttribute('value', $('da_line3').getValue());
    	    	$('ba_postcode').setAttribute('value', $('da_postcode').getValue());
    	    	$('ba_country').setAttribute('value', $('da_country').getValue());
    		} else {
    	    	$('ba_first_name').setAttribute('value', '');
    	    	$('ba_last_name').setAttribute('value', '');
    	    	$('ba_line1').setAttribute('value', '');
    	    	$('ba_line2').setAttribute('value', '');
    	    	$('ba_line3').setAttribute('value', '');
    	    	$('ba_postcode').setAttribute('value', '');
    	    	$('ba_country').setAttribute('value', '');
    		}
    	} catch (err) {}
    }
})(shop);

// Modify tao object
(function(t){
	// Alter validation message display
	t.form.errorClass = 'error';
	t.form.displayError = function(ele, message, className) {
		if (tao.form.isErrorElementCreated(ele)) {
			ele.next().update(message);
		} else {
			ele.insert({after: new Element('p', {'class': t.form.errorClass}).update(message)});
			var holderDiv = ele.up('div.field');
			if (holderDiv) holderDiv.addClassName(t.form.errorClass);
		}
	};
	var parentRemoveError = t.form.removeError;
	t.form.removeError = function(ele) {
		parentRemoveError(ele);
		var holderDiv = ele.up('div.field');
		if (holderDiv) holderDiv.removeClassName(t.form.errorClass);
	};
})(tao);

/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-default" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);


/* Hive object */
var hive = {
	user: {
		signUpForNewsletter: function() {
			var isEmailValid = tao.form.validateElement('newsletter_email', 'emailAddress', 'Please enter a valid email address');
			if (isEmailValid) {
				xajax_signUpForNewsletterAnonymously($F('newsletter_email'));
			}
		},
		sendVatInvoiceEmail: function() {
			var isEmailValid = tao.form.validateElement('user-email-vat-invoice', 'emailAddress', 'Please enter a valid email address');
			if (isEmailValid) {
				xajax_sendVatInvoiceEmail($F('user-email-vat-invoice'));
			}
		},
                sendSalesReceiptEmail: function() {
			var isEmailValid = tao.form.validateElement('user-email-vat-invoice', 'emailAddress', 'Please enter a valid email address');
			if (isEmailValid) {
				xajax_sendSalesReceiptEmail($F('user-email-vat-invoice'));
			}
		}
	},
	search: {
		handleNumItemsChange: function() {
			var numItems = $F('products-per-page');
			var queryParams = document.location.search.substr(1).split('&');
			var newNumItemsParam = 'num-results='+numItems;
			var newParams = [];
			var pushed = false;
			
			queryParams.each(function(pair) {
			    if (pair.search('num-results') == 0) {
			    	newParams.push(newNumItemsParam);
			    	pushed = true;
			    } else if (pair.length != 0) {
			    	newParams.push(pair);
			    }
			});
		    if (pushed == false) {
		    	newParams.push(newNumItemsParam);
		    }
			document.location.search = '?'+newParams.join('&');
		},
		handleSortOptionsChange: function() {
			var sortBy = $F('sort');
			var queryParams = document.location.search.substr(1).split('&');
			var newSortParam = 'sort='+sortBy;
			var newParams = [];
			var pushed = false;
			queryParams.each(function(pair) {
			    if (pair.search('sort') == 0) {
			    	newParams.push(newSortParam);
			    	pushed = true;
			    } else if (pair.length != 0) {
			    	newParams.push(pair);
			    }
			});
		    if (pushed == false) {
		    	newParams.push(newSortParam);
		    }
		    document.location.search = '?'+newParams.join('&');
		}
	}
};


if (typeof Object.create !== 'function') {
	function F() {}
	Object.create = function(o) {
		F.prototype = o;
		return new F();
	};
}

(function($) {
	// product carousel
	hive.productCarousel = {
	itemIndex: 0,
		itemsPerPage: 4,
		itemsPerTransition: 4,
		speed: 750,
		posOffset: 6, // posOffset is only used in IE as it uses absolute positioning to move items (not scrollLeft) meaning padding used to compensate badge needs to be added
		init: function($el) {
			if (!$el.length) {return false;}
			this.$container = $el;
			this.setUp();
		},
		setUp: function() {
		
			this.$runner = this.$container.find('ul');
			this.$items = this.$runner.children();
			this.noOfItems = this.$items.length;
			this.noOfPages = Math.ceil((this.noOfItems - this.itemsPerPage) / this.itemsPerTransition) + 1;
			
			this.setUpMask();
			
			if (this.noOfItems <= this.itemsPerPage) {return false;}
			
			this.insertNumberedLinks();
			this.buttonStatus();
			
			this.$noLinksContainer.find('a').click($.proxy(this, 'numberedLinksHandler')).click(function() {return false;});
		
		},
		setUpMask: function() {
			
			var maskHeight;
			
			maskHeight = this.$runner.outerHeight(true);
			this.$mask = this.$container.find('div.products');
			//this.$mask.height(maskHeight); // IE8 had fit over jQuery .height() when in SWC...fine on local flats...
			this.$mask[0].style.height = maskHeight + 'px';
		},
		insertNumberedLinks: function() {

			// insert numbered links
			var i, links = [];
			this.$noLinksContainer = $('<ol class="numbered-links" />').appendTo(this.$container);
			for (i = 0; i < this.noOfPages; i++) {

				if (i === this.noOfPages - 1) {
					links[i] = '<li class="last-child"><a href="#item--' + i + '">' + (i + 1) + '</a></li>';
				}
				else {
					links[i] = '<li><a href="#item--' + i + '">' + (i + 1) + '</a></li>'; // using double hyphen as IE sticks full URL in place so error can occur if href is split by single '-', prob should use a somthing better than double hyphen
				}
			}
			this.$noLinksContainer.append(links.join('')).wrap('<div class="pagination">');
		
		},
		numberedLinksHandler: function(e) {
			this.itemIndex = $(e.target).attr('href').split('--')[1] * this.itemsPerTransition;
			this.animate();
			return false;
		},
		buttonStatus: function() {
			this.$noLinksContainer
				.children().removeClass('current')
					.eq(Math.ceil(this.itemIndex / this.itemsPerTransition)).addClass('current');
		},
		animate: function() {
		
			var $nextItem, pos;
		
			// check whether there are enough items to animate to
			if (this.itemIndex > (this.noOfItems - this.itemsPerPage)) {
				// go to last panel - items per transition
				this.itemIndex = this.noOfItems - this.itemsPerPage;
			}
			else if (this.itemIndex < 0) {
				// go to first
				this.itemIndex = 0;
			}
			
			$nextItem = this.$items.eq(this.itemIndex);
			pos = $nextItem.position();

			// IE performs better with positon being animated not scrollPos
			if ($.browser.msie) {
				this.$runner.stop().animate({left: -pos.left + this.posOffset}, this.speed);
			}
			else {
				this.$mask.stop().animate({scrollLeft: pos.left}, this.speed);
			}
			
			//this.$mask.scrollLeft(pos.left);
			
			this.buttonStatus();
		}
	}

	// offers carousel [extends hive.productCarousel]
	hive.offersCarousel = Object.create(hive.productCarousel);
	$.extend(hive.offersCarousel, {

		itemsPerPage: 1,
		itemsPerTransition: 1,
		speed: 500,
		pause: 6000,
		setUp: function() {
		
			this.$runner = this.$container.find('ul');
			this.$items = this.$runner.children().eq(0).addClass('current').end();
			this.noOfItems = this.$items.length;
			this.noOfPages = Math.ceil((this.noOfItems - this.itemsPerPage) / this.itemsPerTransition) + 1;

			if (this.noOfItems <= this.itemsPerPage) {return false;}
			
			this.insertNumberedLinks();
			this.buttonStatus();
			
			this.startInterval();
			this.$container.hover($.proxy(this, 'stopInterval'), $.proxy(this, 'startInterval'));
			this.$noLinksContainer.find('a').click($.proxy(this, 'numberedLinksHandler'));
		
		},
		animate: function() {
		
			var $currentItem, $nextItem;
		
			$currentItem = $('.current', this.$container).addClass('previous').removeClass('current');
			$nextItem = this.$items.eq(this.itemIndex);
			
			$nextItem.css({'opacity': 0}).addClass('current').animate({'opacity': 1}, this.speed, function() {
				$currentItem.removeClass('previous');
			});
			
			this.buttonStatus();
		
		},
		intervalHandler: function() {
			this.itemIndex = this.itemIndex + this.itemsPerTransition;
			if (this.itemIndex > (this.noOfItems - this.itemsPerPage)) {
				this.itemIndex = 0;
			}
			this.animate();
		},
		startInterval: function() {
			this.interval = setInterval($.proxy(this, 'intervalHandler'), this.pause);
		},
		stopInterval: function() {
			clearInterval(this.interval);
		}

	});

	// review tabs - uses Ben Almans hashchange plugin for back button support
	hive.reviewTabs = {
		init: function() {
			this.$container = $('#reviews');
			if (!this.$container.length) {return false;}
			this.setUp();
		},
		setUp: function() {
			this.$panels = this.$container.find('#customer-reviews, #bookseller-reviews').eq(1).hide().end();
			this.$tabs = this.$container.find('ul.nav li a');
			
			$(window).hashchange($.proxy(this, 'switchTab'));
			$(window).trigger('hashchange');
			
		},
		switchTab: function() {
			var hash = window.location.hash || '#customer-reviews';
			this.$panels.hide().filter(hash).show();
			
			this.$currentTab = $('ul.nav a[hash=' + hash + ']', this.$container);
			this.tabStatus();
		},
		tabStatus: function() {
			this.$tabs.parent().removeClass('current');
			this.$currentTab.parent().addClass('current');
		}
	};

	function parseURL(url) {
			var a =  document.createElement('a');
			a.href = url;
			return {
				source: url,
				protocol: a.protocol.replace(':',''),
				host: a.hostname,
				port: a.port,
				query: a.search,
				params: (function(){
					var ret = {},
					seg = a.search.replace(/^\?/,'').split('&'),
					len = seg.length, i = 0, s;
					for (;i<len;i++) {
						if (!seg[i]) { continue; }
						s = seg[i].split('=');
						ret[s[0]] = s[1];
					}
					return ret;
				})(),
				file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
				hash: a.hash.replace('#',''),
				path: a.pathname.replace(/^([^\/])/,'/$1'),
				relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
				segments: a.pathname.replace(/^\//,'').split('/')
			};
		}

	hive.modalBox = {
		speed: 250,
		initiated: false,
		init: function(content, width, height) {
			if (!content) {return false;}
			this.content = content;
			this.width = width;
			this.height = height;

			if (this.initiated) {
				this.update(this.content);
				return;
			}

			this.setUp();
			this.initiated = true;
		},
		setUp: function() {

			this.insertModal();
			this.insertCloseBtn().click($.proxy(this, 'close'));
			this.positionModal();

			// hide select boxes in IE6 and below
			if($.browser.msie && $.browser.version === '6.0') {
				$('select').css({'opacity': 0});
				$(window).scrollTop(0);
			}
			this.show();
		},
		insertModal: function() {
			this.$modal = $('<div id="modal" />').hide().html($('<div class="content" />').html(this.content)).appendTo('body');
			this.$overlay = $('<div id="overlay" />').css({'opacity': 0.25}).hide().appendTo('body');
		},
		insertCloseBtn: function() {
			return $('<p class="close-modal"><a href="#">x</a></p>').appendTo(this.$modal);
		},
		positionModal: function() {

			if (this.height) {
				this.$modal.height(this.height);
			}
			else {
				this.height = this.$modal.height();
			}
			
			if (this.width) {
				this.$modal.width(this.width);
			}
			else {
				this.width = this.$modal.height();
			}

			this.$modal.css({
				'height': this.height,
				'width': this.width,
				'margin-top': -this.height / 2,
				'margin-left': -this.width / 2
			});

		},
		show: function() {
			this.$modal.add(this.$overlay).fadeIn(this.speed);
		},
		close: function() {

			// hide select boxes in IE6 and below
			if($.browser.msie && $.browser.version === '6.0') {
				$('select').show();
			}
			this.$modal.add(this.$overlay).fadeOut(this.speed, function() {
				$(this).remove();
			});
			this.initiated = false;
			return false;
		},
		update: function(content) {
			this.$modal.find('div.content').html(content);
		}
	};
	
	hive.bookTokenToggle = {
		init: function() {
			this.bookTokenRadios = $('#token-true, #token-false').change($.proxy(this, 'changeHandler'));
			this.hiddenContent = $('#credit-cards, #payment_card_container, #billing_block');
		},
		changeHandler: function(e) {
			var elem = e.target;
			if (elem.checked) {
				if (elem.id === 'token-false') {
					this.hiddenContent.show();
				}
				else {
					this.hiddenContent.hide();
				}
			}
		}
	};
	
})(jQuery);

/*
 * @Dan Motzenbecker May 2011
 * (c) NationalField, LLC
 * Dynamically swap out browser default select menus
 */

(function($){
	$.fn.nfSelect = function(){
		if(!(this.length > 0)){
			return this;
		}
		if(!isInit){
			init();
		}
		for(var i = 0, len = this.length; i < len; i++){
			(function($t){
				if(!$t.is('select')){
					return;
				}
				var elId = $t.attr('id'),
					options = $t.find('option');
				if($('#nfSelect-' + elId).length > 0){
					return;
				}
				$t.hide();
				var newSelect = $('<div/>', { 'id' : 'nfSelect-' + elId, 'class' : 'nfSelect' }),
					head = $('<div/>', { 'class' : 'selectHead' })
						.appendTo(newSelect);
				$('<div/>', { 'class' : 'togArrow' }).appendTo(head);
				var list = $('<ul/>'),
					preset = false;
				for(var i = 0, len = options.length; i < len; i++){
					var option = options.eq(i),
						item = $('<li/>', { 'data-val' : option.val() || false, text : option.text() }),
						attr = option.attr('selected');
					if(attr === 'selected' || (typeof attr !== 'undefined' && attr !== false)){
						preset = option.text();
					}
					list.append(item);
				}
				var title = $('<div/>', { 'class' : 'selectHeadTitle', text : preset || options.first().text() })
					.prependTo(head);
				newSelect.append(list);
				newSelect.after("<br class='clear'/>");
				$('<span/>', { 'class' : 'nfSelectWrap' }).html(newSelect).insertAfter($t);
				head.bind('click', function(){
					list.toggle();
					$('.nfSelect .open').hide();
					list.toggleClass('open');
					list.offset({ left : newSelect.offset().left });
				});
				var select = $t;
				list.delegate('li', 'click', function(){
					var $this = $(this);
					select.val($this.attr('data-val') || '');
					title.text($this.text());
					list.hide();
					select.change();
				});
			})($(this[i]));
		}
		return this;
	};
	var isInit = false;
	function init(){
		isInit = true;
		$('body').delegate('*', 'click.nfSelect', function(e){
			e.stopPropagation();
			var $et = $(e.target);
			if(!($et.hasClass('selectHead') || $et.parents('.selectHead').length > 0)){
				$('.nfSelect .open').removeClass('open').hide();
			}
		});
	}
})(jQuery);

function init_facet_browsing() {
    var facetContainers = new Array (
        "mediatype-facets-container",
        "category-facets-container",
        "price-facets-container",
        "format-facets-container",
        "stock-facets-container"
        );

    $j.each(facetContainers, function() {
        var visibleFacets = $j("#"+this +' .facet');
        var hiddenFacets = $j("#"+this +' .facet_extended');
        var showAllHtml = '<li><a href="javascript:void(0);">Show All</a></li>';
        hiddenFacets.hide();
        $j("#"+this).find('ul').has('.facet_extended').append(showAllHtml);
        $j("#"+this+" ul").has('.facet_extended').children().last().addClass('show_all');
        $j("#"+this+' ul li.show_all').wrapInner('<a href="javascript:void(0);" />');
        $j("#"+this+' ul li.show_all a').click(function() {
            $j(this).parent().remove();
            hiddenFacets.show();
        });
    });
}

jQuery(document).ready(function($) {

	$('body').addClass('js-enabled');
	
	$('#select-filter').nfSelect();

	init_facet_browsing();
	
	// 4 item carousel
	$('div.products-carousel').not('.no-sidebar div.products-carousel, .no-sub-nav .products-carousel').each(function() {
		var obj = Object.create(hive.productCarousel);
		obj.init($(this));
	});
	
	// 5 item carousels
	$('.no-sidebar div.products-carousel, .no-sub-nav div.products-carousel').each(function() {
		var obj = Object.create(hive.productCarousel);
		obj.itemsPerPage = 5;
		obj.itemsPerTransition = 5;
		obj.init($(this));
	});


	hive.offersCarousel.init($('#offers.carousel'));
	hive.reviewTabs.init();

	
	// dummy modal box call
	$('.popup-link').live('click', function() {
		var modalContent = false;
		if ($(this).attr('rel') !== "")
			modalContent = $($(this).attr('rel'));
		else
			modalContent = $(this).next('.popup-content');

		if (modalContent !== undefined) hive.modalBox.init(modalContent.html(), 500, 250);
		return false;
	});

	// store locator back to top link
	$('.back-to-top a').bind('click', function() {
		$(window).scrollTop(0);
		return false;
	});
	
	if (typeof $.fn.expander !== 'undefined') {
		// show more / less general
		$('#main-content .expand').expander({
			slicePoint: 100,
			widow: 7,
			userCollapseText: 'Hide'
		});
		
		// show more / less product description expander
		$('#product-details').find('div.description').expander({
			slicePoint: 200,
			widow: 30,
			userCollapseText: 'Hide'
		});
		
		// show more / less user review expander
		$('#customer-reviews').find('li .body').expander({
			slicePoint: 200,
			widow: 30,
			userCollapseText: 'Hide'
		});
	}
	
	// show / hide biling info based on book token selection
	hive.bookTokenToggle.init();

	// add target="_blank"
	$j("a.new-window").attr("target", "_blank");

	// Overwrite growler plugin markup
	$j.fn.jGrowl.prototype.render=function(_19)
	{var _1a=this;var _1b=_19.message;var o=_19.options;var _19=$("<div class=\"jGrowl-notification"+((o.group!=undefined&&o.group!="")?" "+o.group:"")+"\">"+"<div class=\"close\">"+o.closeTemplate+"</div>"+"<div class=\"header\">"+o.header+"</div>"+"<div class=\"message\">"+_1b+"</div></div>").data("jGrowl",o).addClass(o.theme).children("div.close").bind("click.jGrowl",function()
	{$(this).parent().trigger("jGrowl.close");}).parent();$(_19).bind("mouseover.jGrowl",function()
	{$("div.jGrowl-notification",_1a.element).data("jGrowl.pause",true);}).bind("mouseout.jGrowl",function()
	{$("div.jGrowl-notification",_1a.element).data("jGrowl.pause",false);}).bind("jGrowl.beforeOpen",function()
	{if(o.beforeOpen.apply(_19,[_19,_1b,o,_1a.element])!=false)
	{$(this).trigger("jGrowl.open");}}).bind("jGrowl.open",function()
	{if(o.open.apply(_19,[_19,_1b,o,_1a.element])!=false)
	{if(o.glue=="after")
	{$("div.jGrowl-notification:last",_1a.element).after(_19);}
	else
	{$("div.jGrowl-notification:first",_1a.element).before(_19);}
	$(this).animate(o.animateOpen,o.speed,o.easing,function()
	{if($.browser.msie&&(parseInt($(this).css("opacity"),10)===1||parseInt($(this).css("opacity"),10)===0))
	{this.style.removeAttribute("filter");}
	$(this).data("jGrowl").created=new Date();});}}).bind("jGrowl.beforeClose",function()
	{if(o.beforeClose.apply(_19,[_19,_1b,o,_1a.element])!=false)
	{$(this).trigger("jGrowl.close");}}).bind("jGrowl.close",function()
	{$(this).data("jGrowl.pause",true);$(this).animate(o.animateClose,o.speed,o.easing,function()
	{$(this).remove();var _1d=o.close.apply(_19,[_19,_1b,o,_1a.element]);if($.isFunction(_1d))
	{_1d.apply(_19,[_19,_1b,o,_1a.element]);}});}).trigger("jGrowl.beforeOpen");if($.fn.corner!=undefined)
	{$(_19).corner(o.corners);}
	if($("div.jGrowl-notification:parent",_1a.element).size()>1&&$("div.jGrowl-closer",_1a.element).size()==0&&this.defaults.closer!=false)
	{$(this.defaults.closerTemplate).addClass("jGrowl-closer").addClass(this.defaults.theme).appendTo(_1a.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function()
	{$(this).siblings().children("div.close").trigger("click.jGrowl");if($.isFunction(_1a.defaults.closer))
	{_1a.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);}});}}

});

