/*======================================================================
	FREE PEOPLE: JavaScript Functions
	--------------------------------------------------------------------
	Author: Jon Aldinger / James Van Arsdale III
	Company: WebLinc
	Date: 03.30.09
----------------------------------------------------------------------*/
var WEBLINC = WEBLINC || {};

$(document).ready(function(){
	WEBLINC = $.extend(WEBLINC, {
		contentContainer:			$('#content-container'),
		$userModal: 				$('#user-modal'),
		$userModalLogin:			$('div.v-login-ajaxloginform', WEBLINC.$userModal),
		$userModalSignup: 			$('div.v-account-signupform',  WEBLINC.$userModal),
		$userModalForgotPassword:	$('div.v-account-forgotpassword',  WEBLINC.$userModal),
		/*
		breadcrumbCtnr: 			$('#breadcrumb-container'),
		breadcrumbWrap: 			$('#breadcrumb-container div.crumb-wrapper'),
		breadcrumbs: 				$('#breadcrumb-container div.crumb-wrapper ul.breadcrumbs'),
		breadcrumbModal: 			$('#breadcrumb-container div.modal-navigation'),
		breadcrumbActiveNavItem:	$('#breadcrumb-container div.modal-navigation div.subcategories ul li.active'),
		*/
		stuffModal:					$('#user li.stuff div.modal-stuff'),
		cartModal:					$('#user li.basket div.cart-items-modal'),
		addedToCartModal:			$('#user li.basket div.added-to-cart-modal'),
		localizedModal:				$('#user div.country div.interntational-modal'),
		isIE6:						($.browser.msie && $.browser.version == 6 ) ? true : false,
		isLoggedIn: 				$('body').hasClass('logged-in'),
		useQuickview:				true, // False in production, but left true for testing purposes on dev and staging
		fullWidth: 					1236,
		addToCartRecommendationCount: 0,
		latestDialog:				$()
	});


	$.ajaxSetup({
		beforeSend: function() {
			//TODO show a load
		},
		complete: function() {
			//TODO hide a load
		},
		error: function() {
			//WEBLINC.messages.create('error','Sorry, Something Went Terribly Wrong','We were unable to retrieve your results for some odd reason... We&rsquo;ll look into this and correct it for you.');
			WEBLINC.messages.create('error','We\'re sorry, an error occurred while processing your request','An administrator has been notified and will correct this problem as soon as possible.');
			$(document).trigger('dialog.close');
		}
	});

	///////////////////////////////////////////////////////////////
	// Authentication: Only executes its callback when logged in.
	///////////////////////////////////////////////////////////////
	WEBLINC.whenLoggedIn = function(callback, options) {
		options = options || {};

		return function () {
			if (!WEBLINC.isLoggedIn) {
				options = $.extend({
					loginUrl: $('#user a.login-link').attr('href'),
					returnUrl: $.param.querystring(
						window.location.toString(),
						$.extend($.deparam.querystring(window.location.search), options.returnParams || {})
					)
				}, options);

				window.location = $.param.querystring(options.loginUrl, { returnUrl: options.returnUrl });
				return false;
			} else {
				return callback.apply(this, Array.prototype.slice.call(arguments));
			}
		}
	};

	/////////////////////
	// Collection Liking
	/////////////////////
	$('a.like-collection').live('click', WEBLINC.whenLoggedIn(function(e) {
		e.preventDefault();

		var $this = $(this);

		$.getJSON($this.attr('href'), function(data) {
			if (data.success) {
				$this.replaceWith(data.link);
			} else {
				WEBLINC.messages.create('error', 'Error!', 'Sorry, there was an error liking this collection. Please try again later.');
			}
		});
	}));

	/////////////////////
	// Product Quickview
	/////////////////////
	var quickViewBound = false;
	WEBLINC.bindQuickview = function() {
		if (WEBLINC.isIE6 || quickViewBound) { return; }

		$('ul.products li div.image')
			.live('mouseenter', function() { $(this).addClass('image-hover'); })
			.live('mouseleave', function() { $(this).removeClass('image-hover'); })

		WEBLINC.useQuickview = true;
		WEBLINC.widgets.quickView.init(document);

		quickViewBound = true;
	}

	var quickviewCache = {};

	WEBLINC.callQuickview = function(productUrl, callback) {
		hideModal();

		if (quickviewCache[productUrl]) {
			showModal(quickviewCache[productUrl]);
			return;
		}

		if ($('div.browser').length) {
			var quickViewType = $('div.search-results').length ? 'SEARCH RESULTS ELEMENTS' : 'PRODUCT CATEGORY ELEMENTS';
			cmCreatePageElementTag('QUICK VIEW', quickViewType);
		}

		var $modal = $('<div class="modal modal-product-quickview"></div>').appendTo($('#content-container'));

		showModal($modal);

		WEBLINC.modals.thisModal($modal);
		quickviewCache[productUrl] = $modal;
		var $loading = $('<div class="loading"><h2>Loading...</h2></div>').appendTo($('div.modal-content', $modal));

		$.ajax({
			global: false,
			url: productUrl.replace('products.detail', 'products.quickView'),
			data: { '_layout': 'none' },
			success: function(response) {
				var $response = $(response);
				$response.find('noscript').remove();

				$loading.replaceWith($response);

				$modal.find('.button, .button-alt').buttonize();
				$modal.find('.button-medium').removeClass('button-medium').addClass('button-small');

				if ($.isFunction(callback)) {
					callback($modal.get(0));
				}
			},
			error: function() { $modal.remove(); }
		});

		function hideModal() {
			$('div.modal-product-quickview').hide();
		}

		function showModal($modalToShow) {
			var minimum = $('#content-container').offset().top;
			$modalToShow
				.css({ top: $(window).scrollTop() + minimum + 'px' })
				.show();
		}
	}

	//
	// Video Coremetrics
	//
	$('a.viewvideo').live('click', function() {
		cmCreatePageElementTag('VIEW PRODUCT VIDEO', 'PRODUCT DETAIL ELEMENTS');
	});

	/*======================================================================
		SITE CORSET SIZER
		--------------------------------------------------------------------
		Decides whether the site is in wide or narrow view mode.
	----------------------------------------------------------------------*/
		WEBLINC.corsetize = function()
		{
			var corsetVal = "tight";

			if( !WEBLINC.isIE6 )
			{
				if( $(window).width() < WEBLINC.fullWidth )
				{
					corsetVal = "tight";
					$('#corset').removeClass('loose').addClass(corsetVal);
					$("input.corset-size").val(corsetVal);
				}
				else if( $(window).width() >= WEBLINC.fullWidth )
				{
					corsetVal = "loose";
					$('#corset').removeClass('tight').addClass(corsetVal);
					$("input.corset-size").val(corsetVal);
				}
			}

			$.cookie('wl_corset', corsetVal, { path: '/' });
		}

	/*======================================================================
		IMAGE PRELOADER
		--------------------------------------------------------------------
		Pass in a list or an array to preload images
	----------------------------------------------------------------------*/
		WEBLINC.preloadImages = function()
		{
			var args = (typeof arguments[0] == 'object')? arguments[0] : arguments;
			for(var i = args.length -1; i > 0; i--)
			{
				$('<img>').attr("src", args[i]);
			}
		}


	/*======================================================================
		SHADOWED
		--------------------------------------------------------------------
		Inserts non-semantic markup hooks for dynamically sized transparent
		shadows around divs.
	----------------------------------------------------------------------*/
		WEBLINC.shadows =
		{
			init: function()
			{
				$('.shadowed:not(div.shadow-container > div.shadowed)').each(function(){
					var $this = $(this);

					$this
						.find('script').remove()
						.end()
						.wrap('<div class="shadow-container"></div>')
						.after('<div class="shadows"><b></b><i></i><span></span></div>')
						.parent().css('margin-bottom', $this.css('margin-bottom'))
						.end()
						.css('margin-bottom', 0);
				});
			}
		}


	/*======================================================================
		GLOBAL MESSAGING
		--------------------------------------------------------------------
		Messaging function for error, warning, or success.
		type: error, warning, success
	----------------------------------------------------------------------*/
		WEBLINC.messages =
		{
			create: function(type, title, message)
			{
				$('div.flash-message').parents('div.shadow-container').remove();
				var titleString = title.length ? '<h2>'+title+'</h2>' : '',
				    messageHtml = $('<div class="flash-message '+ type +'-message"><a class="close" href="#">close</a>'+ titleString +'<div class="message">'+ message +'</div></div>');

				if ($('body:first').hasClass('l-checkout')) {
					messageHtml.insertAfter($('div.v-checkout-checkouttemplate div.checkout-header'));
				} else {
					messageHtml.prependTo(WEBLINC.contentContainer);
				}

				WEBLINC.messages.bindClose();
			},
			bindClose: function()
			{
				WEBLINC.contentContainer.css('padding-top','5px');

				$('div.flash-message a.close', WEBLINC.contentContainer).click(function() {
					$(this).parents('div.flash-message').remove();
					WEBLINC.contentContainer.css('padding-top','0');

					return false;
				});
			}
		}


	/*======================================================================
		MODAL
		--------------------------------------------------------------------
		Inserts non-semantic markup hooks for dynamically sized transparent,
		rounded corners with shadows for modal windows.
	----------------------------------------------------------------------*/
		WEBLINC.modals =
		{
			init: function()
			{
				$('.modal').each(WEBLINC.modals.createModal);
			},
			childModal: function(obj)
			{
				obj.find('.modal').each(WEBLINC.modals.createModal);
			},
			thisModal: function(obj)
			{
				obj.each(WEBLINC.modals.createModal)
			},
			createModal: function()
			{
				var $this = $(this);
				if(!WEBLINC.modals.isModalized($this)) {
					$this
						.find('script').remove()
						.end()
						.append('<span class="shadow-tr"></span><span class="shadow-br"></span>')
						.wrapInner('<div class="modal-content shadow-bl"></div>')
						.prepend('<a class="close" href="#">close</a>')
						.append('<span class="shadow-tl"></span>')
						.find('a.close, a.cancel').live('click', function(e) {
							e.preventDefault();
							$(this).parent().hide();
							$(this).closest('div.ajaxloaded-content').removeClass('ajaxloaded-content');	// remove parent z-index hack
						});
				}
			},
			isModalized: function(el) {
				var $el = $(el);
				return !!$el.find('div.modal-content').length;
			}
		}

		/*-- Modal trigger for handling client content modals --*/
		$('a.show-modal').live('click', function() {
			var modalURL	= $(this).attr('href'),
				$modalID	= $(modalURL.substr(modalURL.search('#'), modalURL.length)),
				classes 	= $modalID.attr('class');
				offset 		= $(this).offset(),
				position 	= $(this).position();

			if( $modalID.hasClass('client-modal') )
			{
				$modalID.css({ top: offset.top - ($modalID.height()), left: offset.left - 200 }).show();
			}
			else if( $modalID.hasClass('csc-modal') )
			{
				$modalID.css({ top: 0, left: 0 }).show();
			}
			else
			{
				$modalID.css({ top: position.top, left: position.left - 200 }).show();
			}

			return false;
		});


	/*======================================================================
		BREADCRUMB NAV
		--------------------------------------------------------------------
		Hover handling for breadcrumb and main menu navigation.
	----------------------------------------------------------------------
		WEBLINC.breadcrumbNav =
		{
			init: function()
			{
				if( WEBLINC.isIE6 )
				{
					$('#category-selector').change(function() {
						window.location = $(this).val();
					});
				}
				else
				{
					if( WEBLINC.breadcrumbCtnr.length && $('div.subcategories ul li',WEBLINC.breadcrumbModal).length )
					{
						var config =
							{
								sensitivity: 1, // sensitivity threshold (must be 1 or higher)
								interval: 10,   // milliseconds for onMouseOver polling interval
								timeout: 10,    // milliseconds delay before onMouseOut
								over: function(){
									WEBLINC.breadcrumbModal.show();
									WEBLINC.breadcrumbWrap.hide();
								},
								out: function(){
									WEBLINC.breadcrumbModal.hide();
									WEBLINC.breadcrumbWrap.show();
								}
							};

						WEBLINC.breadcrumbModal.addClass('modal');			// add modal class for styling
						WEBLINC.modals.childModal(WEBLINC.breadcrumbCtnr);		// build modal

						var menuTimer = null;
						WEBLINC.breadcrumbWrap.hover(
							function() { 			// show modal nav on breadcrumb hover
								if(!menuTimer)
									menuTimer = setTimeout(function() { WEBLINC.breadcrumbModal.show(); }, 50);
							},
							function() {
								clearTimeout(menuTimer);
								menuTimer = null;
							}
						);
						WEBLINC.breadcrumbModal.hoverIntent(config);				// bind hoverIntent function for modal nav

						WEBLINC.breadcrumbModalCt = $('#breadcrumb-container div.modal-content');	// after modal is built, create global nav to modal-content
						WEBLINC.breadcrumbModalCt.prepend(WEBLINC.breadcrumbWrap.html());			// copy breadcrumbs into modal content

						$('a:eq(0)',WEBLINC.breadcrumbActiveNavItem).prepend('<i></i>');			// add arrow container element into active anchor

					}
				}
			}
		}
	*/

	/*======================================================================
		SUBCATEGORY SEPARATOR TOGGLE NAV
		--------------------------------------------------------------------
		Handle separator categories, with children, toggle open/closed.
	----------------------------------------------------------------------*/
		$('#side-container ul.subcategories a.separator').live('click',function() {
			$(this).closest('li').toggleClass('open');

			return false;
		});



	/*======================================================================
		CART DROP DOWN
		--------------------------------------------------------------------
		Bind hover events for basket to show cart items.
	----------------------------------------------------------------------*/
		WEBLINC.cartDropDown = function()
		{
			var config =
				{
					sensitivity: 1000, // sensitivity threshold (must be 1 or higher)
					interval: 100,   // milliseconds for onMouseOver polling interval
					timeout: 50,    // milliseconds delay before onMouseOut
					over: function(){
						if ($.browser.msie){
							//account for IE's inablity to fade alpha channels
							WEBLINC.cartModal.show();
						} else {
							WEBLINC.cartModal.fadeIn(150);
						}
					},
					out: function(){
						if ($.browser.msie){
							//account for IE's inablity to fade alpha channels
							WEBLINC.cartModal.hide();
						} else {
							WEBLINC.cartModal.fadeOut(150);
						}
					}
				};

			var cartTimer = null;
			$('#user li.basket:has(.modal)').hover(
				function()
				{
					if(!cartTimer)
						cartTimer = setTimeout(function() { WEBLINC.cartModal.show(); }, 150);
				},
				function()
				{
					clearTimeout(cartTimer);
					cartTimer = null;
				}
			);

			WEBLINC.cartModal.hoverIntent(config);
		}

	/*======================================================================
		STUFF DROP DOWN
		--------------------------------------------------------------------
		Bind hover events to show users' "stuff".
	----------------------------------------------------------------------*/
		WEBLINC.stuffDropDown = function()
		{
			var config =
				{
					sensitivity: 1000, // sensitivity threshold (must be 1 or higher)
					interval: 100,   // milliseconds for onMouseOver polling interval
					timeout: 50,    // milliseconds delay before onMouseOut
					over: function(){
						if( !WEBLINC.stuffModal.siblings('div.modal-wishlist').length ) {
							if ($.browser.msie){
								//account for IE's inablity to fade alpha channels
								WEBLINC.stuffModal.show();
							} else {
								WEBLINC.stuffModal.fadeIn(150);
							}
						}
					},
					out: function(){
						if ($.browser.msie){
							//account for IE's inablity to fade alpha channels
							WEBLINC.stuffModal.hide();
						} else {
							WEBLINC.stuffModal.fadeOut(200);
						}
					}
				};

			$('#user li.stuff:has(.modal)').hoverIntent(config);
		}

		WEBLINC.stuffDropDown();


	/*======================================================================
		SEARCH/EMAIL INPUT TEXT SWITCHING
		--------------------------------------------------------------------
		On focus of these fields, remove text, on blur if empty replace
		with initial field value text.
	----------------------------------------------------------------------*/
		WEBLINC.focusInputs =
		{
			init: function(obj)
			{
				var searchInitVal = obj.val();

				obj.focus(function() {
					if($(this).val() == searchInitVal)
						$(this).val("").removeClass("hint");
				})
				.blur(function() {
					if($(this).val() == "")
						$(this).val(searchInitVal).addClass("hint");
				});
			}
		}


	/*======================================================================
		Call User Modal Form
	----------------------------------------------------------------------*/
		WEBLINC.callUserForm = function() {
			WEBLINC.switchUserForm(WEBLINC.$userModalLogin);

			var em = $("form input[name='emailAddress']", WEBLINC.$userModalLogin).val();
			if (em.length) {
				$("form input[name='password']", WEBLINC.$userModalLogin).focus();
			}
			else {
				$("form input[name='emailAddress']", WEBLINC.$userModalLogin).focus();
			}

			var userPosition = $('#user').offset();
			WEBLINC.$userModal.css('left', userPosition.left + 8).css('top', userPosition.top).show();
			return false;
		}

	/*======================================================================
		Switch User Modal Form
		--------------------------------------------------------------------
		Switch between login, signup, forgot password
	----------------------------------------------------------------------*/
		WEBLINC.switchUserForm = function(formToShow) {
			WEBLINC.$userModalLogin.hide();
			WEBLINC.$userModalSignup.hide();
			WEBLINC.$userModalForgotPassword.hide();
			formToShow.show();
			return false;
		}

	/*======================================================================
		INIT INTERFACE
		--------------------------------------------------------------------
		Call all functions, and bind events on document.ready.
	----------------------------------------------------------------------*/
		WEBLINC.preloadImages('/resources/freepeople/images/buttons/button-hover.png',
							  '/resources/freepeople/images/buttons/button-alt-hover.png');
		$('.button, .button-alt').buttonize();

		//$.each([WEBLINC.shadows, WEBLINC.modals, WEBLINC.breadcrumbNav], function() { this.init(); });
		$.each([WEBLINC.shadows, WEBLINC.modals], function() { this.init(); });

		if ($('input#site-search').val() == "Enter Keywords or Style #") {
			WEBLINC.focusInputs.init($('input#site-search'));
		}
		WEBLINC.focusInputs.init($('input#email-subscribe'));
		if( !WEBLINC.isIE6 )
		{
			$.fn.jScrollPane.defaults.showArrows = true;			// set default look for jScrollPanes
			WEBLINC.cartDropDown();
		}

		/* page resizing */
		if( !WEBLINC.isIE6 )
		{
			$(window).resize(function(){
				WEBLINC.corsetize();
			});
		}

		WEBLINC.corsetize();

		///////////////////////////////////
		// This code is a hack around
		// buttonize, which messes up
		// submission of user login forms
		// by pressing enter (only in IE).
		///////////////////////////////////
		if ($.browser.msie) {
			$('#user-modal')
				.find('input[type=text],input[type=password]')
					.keypress(function(e) {
						if (e.which !== 13) { return; } // 13 is the enter keycode

						$(this).closest('form').submit();
						return false;
					});
		}


	/*======================================================================
		FP RADIO
		--------------------------------------------------------------------
		Pop-up player for playlist.com
	----------------------------------------------------------------------*/
		$('#header li.listen a').click(function(){
			window.open(($(this).attr('href')), 'fpradio', 'width=675, height=525, resizable=1, toolbar=0, status=0');
			return false;
		});


	/*======================================================================
		POP UP WINDOWS
		--------------------------------------------------------------------
		Pop-up windows for simplified layout content.
	----------------------------------------------------------------------*/
		WEBLINC.popup = function(obj, winWidth, winHeight)
		{
			var $popup = obj,
				popupLink = $popup.attr('href');

			window.open(popupLink, 'fp_popup', 'width=' +winWidth+ ', height=' +winHeight+ ', resizable=1, scrollbars=1, toolbar=0, status=0');

			return false;
		};

		$('a.pop-up').live('click',function(e) {
			e.preventDefault();
			
			var $this = $(this),
				dimensions = $this.attr('rel') || '500x400';
				$size = $.trim(dimensions.replace(/ /g, '')),		// Accepts width and height via "rel" attribute, in "100x100" format.
				xPos = $size.indexOf('x'),
				$width = $size.substr(0,xPos),
				$height = $size.substr((xPos + 1),$size.length);
			
			WEBLINC.popup($this, $width, $height);
		});


	/*======================================================================
		LOGIN FORM TOGGLE
		--------------------------------------------------------------------
		Show/hide create account form.
	----------------------------------------------------------------------*/
		function initLoginFormToggle() {
			var $signUpForm = $('.create',$loginWrap),
				$createSwap = $('.create-swap',$loginWrap),
				$loginForm = $('.login',$loginWrap);

			// Cancel signing-up
			$('div.actionlist ul.actions', $signUpForm)
				.append('<li class="action-secondary action clearfix"><a href="#">Cancel</a></li>')
					.find('li.action-secondary a')
						.click(function(e) {
							e.preventDefault();

							$signUpForm.hide();
							$loginForm.add($createSwap).show();
						});

			$('a',$createSwap).click(function(e){
				e.preventDefault();

				$createSwap.add($loginForm).hide();
				$signUpForm.show();
			});
		}

		var $loginWrap = $('.l-account .login-wrap');
		if($loginWrap.length){
			initLoginFormToggle();
		};


	/*======================================================================
	 	Modal LOGIN/PASSWORD/CREATE ACCOUNT form stuff
	 	--------------------------------------------------------------------
	 	handled separate from other ajax forms since form is always present
	 	in layout, and not loaded via ajax
	 ----------------------------------------------------------------------*/
	 	/*
		if( !WEBLINC.isIE6 )
		{
			var $stuff = $('#user li.stuff'),
				$loginLink = $('#user li.stuff a.login-link, #modal-container a.login-link');

			$loginLink.live("click", function(e){
				//only fire for left mouse button click
				if(e.button) return;

				// scroll to the top of the window
				$('html, body').animate({scrollTop:0}, 'slow');

				WEBLINC.callUserForm();
				return false;
			});

			$('p.forgot-password a', WEBLINC.$userModalLogin).click(function(){
				WEBLINC.switchUserForm(WEBLINC.$userModalForgotPassword);
				return false;
			});

			$("#account-form-link").click(function(){
				WEBLINC.switchUserForm(WEBLINC.$userModalSignup);
				return false;
			});

			$("#vlogin-forgotpasswordform-forgotpasswordsubmit").each(function(){
				$myForm = $(this).closest("form");
				$myForm.find("input[name='fuseaction']").val('login.sendPassword_ajax');

				$('input[type=submit]', $myForm).click(function(){
					$.ajax({
						url: $myForm.attr('action'),
						data: $myForm.serialize(),
						dataType: 'jsonp',
						success: function(data){
							$("#loading").hide();
							WEBLINC.$userModal.hide();

							var messageType = data.success ? 'success' : 'error';
							WEBLINC.messages.create(messageType, messageType, data.message);
						}
					});

					return false;
				});
			});
		}
		*/

	/*======================================================================
		AJAX HELPERS
		--------------------------------------------------------------------
		Bind the ajax functions for any ajaxsubmitlink form
	----------------------------------------------------------------------*/
		var $modalContainer = $('#modal-container');

		$('a.cancel', $modalContainer).live("click", function(e){
			//only fire for left mouse button click
			if(e.button) return;

			e.preventDefault();

			$modalContainer.hide();
			$modalContainer.closest('div.ajaxloaded-content').removeClass('ajaxloaded-content');	// remove parent z-index hack
		});

		$(".ajaxsubmitlink").live("click", function(e){
			//only fire for left mouse button click
			if(e.button) return;

			e.preventDefault();

			// remove ajaxloaded-content class from other containers within user profile dashboard
			$('#content-container div.v-userprofile-home div.ajaxloaded-content').removeClass('ajaxloaded-content');

			var $this = $(this),
			myLink = $this.attr("href"),
			$callingParent = $this.closest('div.ajaxloaded');
			$callingParent.addClass('ajaxloaded-content');	// add class to make the z-index the highest for that parent container.

			//if our modal container doesn't exist, create one and assign it to our query variable
			if (!$modalContainer.length){
				$("#corset").append('<div id="modal-container" class="modal modal-account"><div id="ajaxFormContent"></div></div>');
				$modalContainer = $('#modal-container');
				WEBLINC.modals.thisModal($modalContainer);
			}

			//if we found an 'ajaxloaded' parent container, insert modal here instead of at the end of the DOM for contextual placement
			if($callingParent){
				$modalContainer.appendTo($callingParent);
			}

			if ($callingParent.hasClass("ajaxloaded-modal")){
				$loadInto = $('#ajaxFormContent');
			}
			else {
				$loadInto = $callingParent
			}

			$.ajax({
				cache: false,
				url: myLink+'_ajax',
				beforeSend: function() {
		    		//hide the modal until it gets re-written if another form was still on page
		    		$modalContainer.hide();

		    		//remove the flash message
		    		$(".flash-message").parents('.shadow-container').remove();
					WEBLINC.contentContainer.css('padding-top','0');

					//show the loader
		    		//$("#loading").show();
					$("#ajaxFormContent").html("<h2>Loading...</h2>");
					$modalContainer.addClass("loading").show();

		    	},
		        error: function(XMLHttpRequest, textStatus) {
		            if(textStatus == 'timeout') {
		                WEBLINC.messages.create({ type: 'error', title: 'Timeout!', message: 'There was a timeout error! Are you connected to the internet?' });
		            }

					else {
						WEBLINC.messages.create('error','error','An error has occurred');
					}
		    	},
				complete: function(XMLHttpRequest, textStatus){

					if ( textStatus == 'success' ) {
						if( XMLHttpRequest.getResponseHeader('FP_loginRequired') == 1 ){
							$modalContainer.removeClass('loading').hide();
							//alert('1');
							WEBLINC.callUserForm();
							return false;
						}
						else {
							$modalContainer.removeClass('loading').show();

							var $response = $(XMLHttpRequest.responseText);
							$response.find("input[name='fuseaction']").each(function(){
								this.value = this.value + '_ajax';
							});


							//write the form
							$("#ajaxFormContent").html('').append($response);

							WEBLINC.widgets.init($("#ajaxFormContent"));

							//stylize the buttons
							$('.button, .button-alt').buttonize();

							//ajaxify submit in returned form
							$('.ajaxsubmit').each(function(){
								var $myForm = $(this).closest('form'),
									myFormAction = $myForm.attr('action'),
									myFormFuseaction = $myForm.find("input[name='fuseaction']").val(),

									myCircuit = myFormFuseaction.split('.')[0],
									myReloader = myFormAction + '/fuseaction/' + myCircuit + '.view_ajax';

								$myForm.ajaxForm({
									beforeSubmit: function(arr, $form) {
										if ($form.valid()) WEBLINC.changeSubmitToLoading($myForm);
										return $form.valid();
									},
									cache: false,
									complete: function(XMLHttpRequest, textStatus){
										WEBLINC.changeLoadingToSubmit($myForm);
										if ( textStatus == 'success' ) {
											if( XMLHttpRequest.getResponseHeader('FP_loginRequired') == 1 ){
												$modalContainer.removeClass('loading').hide();
												//alert('2');
												WEBLINC.callUserForm();
												return false;
											}
											else {
												if (XMLHttpRequest.responseText.length){
													var $myResponse = $.trim(XMLHttpRequest.responseText);
												}
												$.ajax({
													cache: false,
													url: myReloader,
													success: function(html){
														$loadInto.html(html);
														$('.button, .button-alt').buttonize();
														if ($loadInto.attr('id') == "ajaxFormContent"){
															$modalContainer.removeClass('loading').show();
														}
														else {
															$modalContainer.removeClass('loading').hide();
															WEBLINC.messages.create('success','success',$myResponse);
														}
														//$("#ajaxFormContent").prepend('<div id="ajaxResponse">'+responseText+'</div>');
													}
												});
												//if (XMLHttpRequest.responseText.length){
												//	WEBLINC.messages.create('success','',$.trim(XMLHttpRequest.responseText));
												//}
											}
										}
										$callingParent.closest('div.ajaxloaded-content').removeClass('ajaxloaded-content');	// remove parent z-index hack
									},

									beforeSend: function() {
										//hide the modal until it gets re-written if another form was still on page
										$modalContainer.hide();

										//remove the flash message
										$(".flash-message").parents('.shadow-container').remove();
										WEBLINC.contentContainer.css('padding-top','0');

										//show the loader
										$("#ajaxFormContent").html("<h2>Processing...</h2>");
										$modalContainer.addClass("loading").show();
									},
									error: function(XMLHttpRequest, textStatus) {
										if(textStatus == 'timeout') {
											WEBLINC.messages.create({ type: 'error', title: 'Timeout!', message: 'There was a timeout error! Are you connected to the internet?' });
										}

										else {
											WEBLINC.messages.create('error','error','An error has occurred');
										}
									}
								});
							});
						}
					}
				}
			});
		});

	WEBLINC.centerDialog = function() {
		var $dialog = WEBLINC.latestDialog;
		if ($('.ui-dialog').length) {
			$dialog.dialog({
				position: [
					~~(($(window).width() - $dialog.width()) / 2 ),
					~~(($(window).height() - $dialog.height()) / 2)
				]});
		}
	}

	///////////////////////////////////////////////////////////////
	// Currency functions
	///////////////////////////////////////////////////////////////
	WEBLINC.currencyConvert = function(value) {
			var countryCode = $.cookie('CURRENCYPREFERENCE').toLowerCase();
			var countryStruct = null;

			if (countryCode && WEBLINC.currencies)
				countryStruct = WEBLINC.currencies[countryCode];

			if (countryStruct && !isNaN(value))
				return value * countryStruct.rate;
			else
				return value;
		}

	WEBLINC.currencyFormat = function(value, negative) {
			var countryCode = $.cookie('CURRENCYPREFERENCE').toLowerCase();
			var currencySymbol;
			var negativeValue = negative ? '-' : '';

			if (countryCode && WEBLINC.currencies)
				currencySymbol = WEBLINC.currencies[countryCode].symbol;

			if(!currencySymbol)
				currencySymbol = "$";

			var result = Math.floor(value)+".";

			var cents = 100*(value-Math.floor(value))+0.5;

			result += Math.floor(cents/10);
			result += Math.floor(cents%10);

			result = currencySymbol + negativeValue + $.addCommas(result.toString());

			return result;
		}


	/**********************************
		Functions for QAS form dialogs
	***********************************/
	var QAS_CSS_CLASSES = ['qas-corrected', 'qas-user', 'qas-recommendation', 'qas-refinement', 'qas-list'];

	WEBLINC.submitCheckoutQas = function($form, $modal) {
		if (!$modal || !$modal.length) {
			$modal = $form.closest('div.modal');
		}

		var isNew = !$modal.find('.checkout-modal-content').length;
		var $modalContent = isNew ? $modal.find('.modal-content') : $modal.find('.checkout-modal-content');

		$form.ajaxSubmit({
			cache: false,
			dataType: 'json',
			success: function(data) {

				$modal.removeClass('loading');
				if (data.qasSuccess) {

					if (data.checkoutHtml.xmlQuery.messages.length > 0)
						WEBLINC.messages.create('general','a quick note...',jQuery.trim(data.checkoutHtml.xmlQuery.messages));

					if (data.checkoutHtml.xmlQuery.messagesType.length && data.xmlQuery.qasContent.length)
						WEBLINC.messages.create('general', 'address validation', jQuery.trim(data.checkoutHtml.xmlQuery.qasContent));

					if (!isNew) { $modalContent.html(''); }

					jQuery(data.checkoutHtml.xmlQuery.content.rows).each(function(rowNum, contentRowObj){
						jQuery('#' + contentRowObj.contentID).html(contentRowObj.content);
					});
					jQuery('#' + data.checkoutHtml.xmlQuery.activeStep).setActive();

					//Hide Modal if empty
					if (isNew || $modalContent.html().length == 0) {
						$modal.hide();
					}

				} else {
					$modal.show();
					if (isNew) {
						$modal.find('a.close').trigger('click');

						$modal = $('<div class="modal checkout-modal modal-qas clearfix"></div>').appendTo($('div.v-checkout-billingaddressshipmentoptiontemplate'));
						WEBLINC.modals.thisModal($modal);

						$modalContent = $modal.find('div.modal-content');
						$modalContent.html(data.html);

						$('<span class="shadow-tr"></span>').appendTo($modalContent);
						$('<span class="shadow-br"></span> ').appendTo($modalContent);

						$modal.show();
					} else {
						$modalContent.html(data.html);
					}

					// Reset qas classes for the modal
					$.each(QAS_CSS_CLASSES, function() {
						var modalCssClass = 'modal-' + this;
						$modal.removeClass(modalCssClass);
						if ($modal.find('.' + this).length) {
							$modal.addClass(modalCssClass);
						}
					});
				}
				$('.button, .button-alt').buttonize();
			},
			complete: function() { bindCheckoutStepsAjaxForm(); }
		});
	};

	WEBLINC.submitWishlistQas = function($form, $modal) {

		if (!$modal || !$modal.length) {
			$modal = $('#modal-container');
		}

		$form.ajaxSubmit({
			cache: false,
			dataType: 'json',
			beforeSend: function(){
				$modal
					.find('#ajaxFormContent')
						.html("<h2>Loading...</h2>")
						.end()
					.removeClass(QAS_CSS_CLASSES.join(' '))
					.addClass("loading")
					.show();
			},
			success: function(data) {
				if (data.qasSuccess) {
					$modal.removeClass('loading').hide();
					WEBLINC.messages.create( 'success', 'Success!', 'Your address has been saved.');
				} else {
					$modal.removeClass('loading').show();

					var $content = $("#ajaxFormContent");
					if (!$content.length) { $content = $modal.find('div.modal-content'); }

					$content.html(data.html);

					// Reset qas classes for the modal
					$.each(QAS_CSS_CLASSES, function() {
						var modalCssClass = 'modal-' + this;
						$modal.removeClass(modalCssClass);
						if ($modal.find('.' + this).length) {
							$modal.addClass(modalCssClass);
						}
					});

					$('.button, .button-alt').buttonize();
				}
			}
		});
	};

	// The third arg here was formally a qForm object,
	// but I didn't want to raise exceptions if there's some
	// obscure place still trying to pass something here
	WEBLINC.submitQasForm = function(form, modal, nil) {
		var $form = $(form),
			$modal = modal ? $(modal) : null,
			isCheckout = !!$('div.l-checkout').length,
			isWishlist = !!$('wishlist-details').length;

		if ($form.valid()) {
			if(isCheckout) {
				WEBLINC.submitCheckoutQas($form, $modal);
			} else if(isWishlist) {
				WEBLINC.submitUserProfileQas($form, $modal)
			} else {
				WEBLINC.submitWishlistQas($form, $modal)
			}
		}

		return false;
	};
	
});


