/*
	Floating Shopping Cart v2.1.0 (store).
	All Web Promotion, Inc. 2008-2009.
*/

var awpFloatingCartT = null;

;(function($){

	$.awpFloatingCart = function (opts) {

		var defaults = {					  
			'storeId'						: 'yhst-11111111111111',
			'storeDomainName'				: 'storedomain.com',
			'pageContainerId'				: 'body',
			'currency'						: '$',
			'isModal'						:  false,
			'isSummaryOnly'					:  false,
			'isFloater'						:  true,
			'isHideWhenNone'				:  true,
			'floaterLocationDefault'		: 'e',
			'floaterContainerSel'			:  null,
			'addingItemMessage'				: 'Adding item...',
			'itemFormIds'					: '.addtocart-form',
			'itemFormButtonIds'				: '.ys_primary, .addtocartImg',
			'addtocartLinkSel'				: '.addtocart-link',
			'cartSel'						: '.cart-info',
			'cartRemoteReplaceSel'			: '.cart-info .cart-remote-replace',
			'cartInfoViewcartLinkId'		: '.cart-info .viewcart',
			'cartInfoCheckoutLinkId'		: '.cart-info .checkout',
			'cartMessageUnderId'			: '.cart-info .shipping-under-limit',
			'cartMessageUnderDisplay'		: 'inline',
			'cartMessageOverId'				: '.cart-info .shipping-over-limit',
			'cartMessageOverDisplay'		: 'inline',
			'cartNoneMessageId'				: '.cart-info .nocart',
			'cartNoneMessageDisplay'		: 'inline',
			'cartLimitAmountId'				: '.cart-info .shipping-limit-amount',
			'cartLimitRemainderId'			: '.cart-info .shipping-limit-difference',
			'cartNumitemsId'				: '.cart-info .numitems',
			'cartQuantityId'				: '.cart-info .quantity',
			'cartSubtotalId'				: '.cart-info .subtotal',
			'cartTotalId'					: '.cart-info .total',
			'cartViewcartLinkContainerId'	: '.cart-info .viewcart-info',
			'cartCloseInfoSel'				: '.cart-info .cart-close-info',
			'cartFloatInfoSel'				: '.cart-info .cart-float-info',
			'cartFloatLocationInfoSel'		: '.cart-info .cart-float-location-info',
			'cartRemoteContainerId'			: 'cart-remote',
			'cartRemoteFrameName'			: 'cartRemoteIframe',
			'cartRemoteFadeIn'				:  700,
			'cartRemoteIframeDefaultHeight'	: '110',
			'cookieName'					: 'awpcart',
			'statusCookieName'				: 'awpcartstatus',
			'checkCloseInterval'			:  200,
			'cartProgressInterval'			:  500,
			'cartProgressCount'				:  100, //50,
			'cartUpdateFxTime'				:  2000,
			'viewcartUrl'					: 'http://order.store.yahoo.net/cgi-bin/wg-order?catalog=storeid',
			'checkoutUrl'					: 'https://order.store.yahoo.net/ymix/MetaController.html?ysco_key_event_id=1&ysco_key_store_id=storeid&sectionId=ysco.ship-bill'
		};

		var settings = $.extend({}, defaults, opts);

		// CONSTANTS
		var DATA_QUANTITY = 0;
		var DATA_NUM_ITEMS = 1;
		var DATA_SUBTOTAL = 2;
		var DATA_TOTAL = 3;
		var DATA_LIMIT = 4;
		var DATA_LIMIT_REMAINDER = 5;
		var DATA_HEIGHT = 6;
		var DATA_MODE = 7;
		var DATA_TIMESTAMP = 8;

		var delimiter = '|';
		var cartRemoteContainer;
		var data = null;
		var updateTimer = [];
		var cartCookieTimestamp = null;
		var progressModalDialog;
		var iframeCounter = 0;

		//----------------------------------------------------------------------------------------------------
		// for showing remote cart
		var progressSubmit = function (init, button) {
			if (init) {
				// set timestamp mark
				cartCookieTimestamp = getCurrentTime();
				//debugPrintLine(getCurrentTime() + ' progressSubmit() init. saved timestamp: ' + cartCookieTimestamp);
				// start progress display
				progressSubmitDisplay(true, button);
				// init and start
				var max = settings.cartProgressInterval * settings.cartProgressCount;
				progressTimer('start', progressSubmit, max, 1);
			} else {
				//debugPrintLine(getCurrentTime() + ' progressSubmit() check for new cookie.');
				// get cookie
				getCartCookie();
				// stop if cookie found
				//if (data) {  // doesn't work in IE6
				//if ((typeof data !== 'undefined') && (data !== null)) {  // doesn't work in IE6
				//if ((typeof data !== 'object') && (typeof (data[0] * 1) === 'number') && (typeof (data[DATA_HEIGHT] * 1) === 'number')) { // doesn't work at all
				//if ((data) && (data[0]) && (data[DATA_HEIGHT])) { // sometimes data[DATA_HEIGHT] isn't sent
				//if ((data) && (data[DATA_QUANTITY])) {
				//if ((data) && (data[DATA_TIMESTAMP] !== cartTimestamp))
				if (statusCartCookie()) {
					if (!progressTimer('min')) {
						progressTimer('restart');
						cartCookieTimestamp = null;							// statusCartCookie() returns true the next time through
						return;
					}
					//debugPrintLine(getCurrentTime() + ' progressSubmit() found new cookie. timestamp: ' + data[DATA_TIMESTAMP]);
					progressTimer();										// stop timer
					progressSubmitDisplay();								// stop progress display
					cartDisplay((isie6()));									// show remote cart
					updateCartInfo();										// update cart summary info
					if ($(settings.cartSel).data('isFloater') === true) {	// update position for more or less items
						floatIt();
					}
					return;													// done
				} else if (progressTimer('max')) {
					// timed out
					progressTimer();										// stop timer
					progressSubmitDisplay();								// stop modal progress display
					cartHide();												// hide cart
					return;													// done
				}
				// else restart timer
				progressTimer('restart');
			}
		};

		//----------------------------------------------------------------------------------------------------
		// for showing remote cart
		var progressNormal = function (init) {
			if (init) {
				// set timestamp mark
				cartCookieTimestamp = getCurrentTime();
				//debugPrintLine(getCurrentTime() + ' progressNormal() init. saved timestamp: ' + cartCookieTimestamp);
				// start non-modal progress display
				progressNormalDisplay(true);
				// initialize progress timer
				var max = settings.cartProgressInterval * settings.cartProgressCount;
				progressTimer('start', progressNormal, max);
			} else {
				//debugPrintLine(getCurrentTime() + ' progressNormal() check for new cookie.');
				// check cookie
				getCartCookie();
				// stop if good cookie found or timed out
				if (statusCartCookie()) {
					//debugPrintLine(getCurrentTime() + ' progressNormal() found new cookie.');
					//debug
					//alert('progress done, cookie timestamp / saved timestamp: ' + data[DATA_TIMESTAMP] + ' ' + cartCookieTimestamp);
					progressTimer();			// stop timer
					progressNormalDisplay();	// stop non-modal progress display
					updateCartInfo();			// update cart info
					cartDisplay();				// show remote cart
					return;						// done
				} else if (progressTimer('max')) {
					// timed out
					//debug
					//alert('timed out');
					progressTimer();			// stop timer
					progressNormalDisplay();	// stop non-modal progress display
					return;						// done
				}
				// else restart timer
				progressTimer('restart');
			}
		};

		//----------------------------------------------------------------------------------------------------
		function pauseMS (ms) {
			var dt = new Date();
			var curDt = null;
			do {
				curDt = new Date();
			} while (curDt - dt < ms);
		} 

		//----------------------------------------------------------------------------------------------------
		function isie () {
			return ($.browser.msie);
			/*return ($.browser.msie 
        				&& /MSIE 6\.0/i.test(window.navigator.userAgent) 
        				&& !/MSIE 7\.0/i.test(window.navigator.userAgent));*/
		}

		//----------------------------------------------------------------------------------------------------
		function isie6 () {
			return $.browser.msie && (parseInt($.browser.version, 10) == 6);
			/*return ($.browser.msie 
        				&& /MSIE 6\.0/i.test(window.navigator.userAgent) 
        				&& !/MSIE 7\.0/i.test(window.navigator.userAgent));*/
		}

		//----------------------------------------------------------------------------------------------------
		function isie7 () {
			return $.browser.msie && (parseInt($.browser.version, 10) == 7);
		}

		//----------------------------------------------------------------------------------------------------
		function getCurrentTime () {
			dt = new Date;
			return dt.getTime();
		}

		//----------------------------------------------------------------------------------------------------
		// convert string to float at two decimal places.
		function toFloat (w) {
			var digitsStr = '0123456789';
			var pos;
			for (var i=0;i<w.length;i++) {
				pos = digitsStr.indexOf(w.substr(i, 1));
				if (pos != -1) {
					return parseFloat(w.substr(i)).toFixed(2);
				}
			}
			// else return 'NaN'
			return parseFloat('x');
		}

		//----------------------------------------------------------------------------------------------------
		function makePx (dimension) {
			if (!dimension) { return null; }
			dimension += '';
			var units = 'px';
			if (!(dimension.substr(dimension.length - units.length - 1) == units)) {
				dimension = dimension + units;
			}
			return dimension;
		}

		//----------------------------------------------------------------------------------------------------
		function getCartCookie () {
			data = $.cookie(settings.cookieName);
			data = (typeof data == 'string') && (data != '') ? data.replace('{plus}', '+').split(delimiter) : null;
			if (data === null) { cartCookieTimestamp = null; }
		}

		//----------------------------------------------------------------------------------------------------
		// return true: have new cookie
		function statusCartCookie () {
			if (data === null) {
				// no cookie found
				return false;
			} else if ((data[DATA_MODE] == 'remote') && ((data[DATA_TIMESTAMP] * 1) > (cartCookieTimestamp * 1))) {
				
				// debug
				//if (cartCookieTimestamp) {
				//	alert('data timestamp / saved timestamp / height: ' + data[DATA_TIMESTAMP] +' / '+ cartCookieTimestamp +' / '+ data[DATA_HEIGHT]);
				//}
				
				// new cookie found
				cartCookieTimestamp = data[DATA_TIMESTAMP];
				return true;
			} else {
				// old cookie
				return false;
			}
		}

		//----------------------------------------------------------------------------------------------------
		function viewcartUrl () {
			return settings.viewcartUrl.replace('storeid', settings.storeId);
		}

		//----------------------------------------------------------------------------------------------------
		function checkoutUrl () {
			return settings.checkoutUrl.replace('storeid', settings.storeId);
		}

		//----------------------------------------------------------------------------------------------------
		function cartIframeNameNew () {
			iframeCounter++;
		}
		//----------------------------------------------------------------------------------------------------
		function cartIframeName () {
			return settings.cartRemoteFrameName + iframeCounter;
			//return settings.cartRemoteFrameName;
		}

		//----------------------------------------------------------------------------------------------------
		function cartIframeSelector () {
			return '#' + cartIframeName();
		}

		//----------------------------------------------------------------------------------------------------
		function cartIframeClose () {
			cartRemoteContainer
				.css('height', makePx(cartRemoteContainer.height()))
				.find(cartIframeSelector())
					.empty()
					.removeAttr('src')
					.removeAttr('id')
					.removeAttr('name')
					.css('display', 'none')
					.remove();
		}

		//----------------------------------------------------------------------------------------------------
		var author = 'All Web Promotion, Inc. 2008-2009';

		//----------------------------------------------------------------------------------------------------
		function cartIframeNew (isSubmit, addtocartUrl) {
			addtocartUrl = (typeof addtocartUrl == 'string') ? addtocartUrl : '';
			cartIframeNameNew();
			var iframeName = cartIframeName();
			var iframe = $('<iframe></iframe>')
					.attr({	'id'			: iframeName,
							'name'			: iframeName,
							'scrolling'		: 'no',
							'frameborder'	: '0',
							'src'			: isSubmit ? addtocartUrl : viewcartUrl()
						  })
					.css({
						'zIndex'		: '1',
						'overflow'		: 'hidden',
						'visibility'	: 'visible',
						'border'		: '0',
						'frameBorder'	: '0'
					});
			// append iframe to container
			cartRemoteContainer
				.css({'height':'auto'})
				.append(iframe);
			//if (isie6() || isie7()) {
			// just testing for IE assumes the IE6 or IE7 compatibiliby META tag is used in IE8
			if (isie()) {
				window.frames[iframeName].name = iframeName;
			}
		}

		//----------------------------------------------------------------------------------------------------
		// remove current iframe, create new iframe and insert into container
		function cartIframe (isSubmit, addtocartUrl) {
			cartIframeClose();
			cartIframeNew(isSubmit, addtocartUrl);
		}

		//----------------------------------------------------------------------------------------------------
		function cartInit () {
			cartHideSet();
			// create container for remote cart iframe
			cartRemoteContainer = $('<div></div>')
									.attr('id', settings.cartRemoteContainerId)
									.css({	'position'			: 'relative',
											'overflow'			: 'hidden',
											'zIndex'			: '0'
									});
			$(settings.cartRemoteReplaceSel).replaceWith(cartRemoteContainer);
		}

		//----------------------------------------------------------------------------------------------------
		function cartHideSet () {
			$(settings.cartSel).css({	'display'		: 'none',
										'visibility'	: 'hidden'});
		}

		//----------------------------------------------------------------------------------------------------
		function cartHide () {
			if ($(settings.cartSel).is(':visible')) {
				$(settings.cartSel)
					.slideUp(settings.cartRemoteFadeIn, function(){
						cartHideSet();
					});
			}
		}

		//----------------------------------------------------------------------------------------------------
		function cartIsShown () {
			return $(settings.cartSel).css('display') == 'block';					
		}

		//----------------------------------------------------------------------------------------------------
		function cartDisplay (isForceDisplay) {
			if (!isForceDisplay && settings.isHideWhenNone && !((data) && (data[DATA_QUANTITY] > 0))) {
				cartHide();
				return;
			}
			// debug
			//alert('data height: ' + (((data) && (data[DATA_HEIGHT])) ? data[DATA_HEIGHT] : 'not set') + ' ['+ getCurrentTime() +']');
			// get iframe
			var iframe = cartRemoteContainer.find(cartIframeSelector());
			// get iframe height
			var h;
			if ((data) && (data[DATA_HEIGHT]) && (data[DATA_HEIGHT] > 0)) {
				h = data[DATA_HEIGHT];
			} else {
				h = settings.cartRemoteIframeDefaultHeight;
			}
			// set iframe height
			iframe.attr('height', h).css('height', makePx(h));
			// make iframe visible
			iframe.css('visibility', 'visible');
			// show cart
			$(settings.cartSel)
				.slideDown(settings.cartRemoteFadeIn)
				.css('visibility', 'visible');			
		}

		//----------------------------------------------------------------------------------------------------
		function progressTimer (mode, func, max, min) {
			if (mode == 'start') {
				// setup
				awpFloatingCartT = func;
				data = null;
				updateTimer['timer']	= null
				updateTimer['started']	= getCurrentTime();
				updateTimer['max']		= max ? max : null;
				updateTimer['min']		= min ? min : null;
			} else if (mode == 'max') {
				return getCurrentTime() > (updateTimer['started'] + updateTimer['max']);
			} else if (mode == 'min') {
				if (updateTimer['min']) {
					return getCurrentTime() > (updateTimer['started'] + updateTimer['min']);
				}
				return false;
			} else if (!mode || mode == 'stop') {
				clearTimeout(updateTimer['timer']);
				awpFloatingCartT = null;
			}
			if (mode == 'start' || mode == 'restart') {
				updateTimer['timer'] = setTimeout('awpFloatingCartT()', settings.cartProgressInterval);
			}
		}

		/*//----------------------------------------------------------------------------------------------------
		function progressLink (init) {
			if (init) {
				$(settings.cartViewcartLinkContainerId).addClass('loading');
			} else {
				$(settings.cartViewcartLinkContainerId).removeClass('loading');		
			}
		}*/

		//----------------------------------------------------------------------------------------------------
		function progressNormalDisplay (init) {
			progressCart(init);
		}

		//----------------------------------------------------------------------------------------------------
		function progressCart (init, button) {
			if (init) {
				// this remove() fixes a bug for the progress message text appearing twice overlapping itself,
				// only on the very first add item, don't know what it is.
				$('.cart-loading', '#' + settings.cartRemoteContainerId).remove();
				var jCart = $('#' + settings.cartRemoteContainerId);
				$('<div class="cart-loading"></div')
					.css({	'height'	: (jCart.height() + parseInt(jCart.css('paddingTop'), 10) + parseInt(jCart.css('paddingBottom'), 10)) + 'px',
						 	'width'		: (jCart.width()  + parseInt(jCart.css('paddingLeft'), 10) + parseInt(jCart.css('paddingRight'), 10)) + 'px',
							'position'	: 'absolute',
							'top'		: '0',
							'left'		: '0'
					})
					.append($('<div></div>')
						.text(settings.addingItemMessage))
					.prependTo(jCart);
			} else {
				$('.cart-loading', '#' + settings.cartRemoteContainerId).remove();	
			}
		}

		//----------------------------------------------------------------------------------------------------
		// for adding item to cart
		function progressSubmitDisplay (init, button) {
			(settings.isModal ? progressModal : progressCart)(init, button);
		}

		//----------------------------------------------------------------------------------------------------
		function formatCurrency (val) {
			if (val === '0' || val === 0 || val === '') {
				return '0';
			} else {
				return settings.currency + val;
			}
		}

		//----------------------------------------------------------------------------------------------------
		function updateCartInfo () {

			//$(settings.cartSel).css('display', 'block');
			$(settings.cartMessageUnderId
			  + ',' + settings.cartMessageOverId
			  + ',' + settings.cartNoneMessageId).css('display', 'none');

			if (data) {
				
				if (settings.cartQuantityId) {
					$(settings.cartQuantityId).html((data[DATA_QUANTITY]) ? data[DATA_QUANTITY] : '&nbsp;');
				}
				if (settings.cartNumitemsId) {
					$(settings.cartNumitemsId).html((data[DATA_NUM_ITEMS]) ? data[DATA_NUM_ITEMS] : '&nbsp;');
				}
				if (settings.cartSubtotalId) {
					$(settings.cartSubtotalId).html((data[DATA_SUBTOTAL]) ? formatCurrency(data[DATA_SUBTOTAL]) : '&nbsp;');
				}
				if (settings.cartTotalId) {
					$(settings.cartTotalId).html((data[DATA_TOTAL]) ? formatCurrency(data[DATA_TOTAL]) : '&nbsp;');
				}
				var shipLimit = parseFloat(data[DATA_LIMIT]).toFixed(2)
				var shipRemainder = parseFloat(data[DATA_LIMIT_REMAINDER]).toFixed(2);
				if (shipLimit > 0) {			
					$(settings.cartLimitAmountId).text(shipLimit);
					$(settings.cartLimitRemainderId).text(shipRemainder);
					if (shipRemainder > 0) {
						$(settings.cartMessageUnderId).css('display', settings.cartMessageUnderDisplay);
					} else {
						$(settings.cartMessageOverId).css('display', settings.cartMessageOverDisplay);
					}
				}
			} else {
				$(settings.cartNoneMessageId).css('display', settings.cartNoneMessageDisplay)
			}

		}

		//----------------------------------------------------------------------------------------------------
		function progressModal (startit) {
			if (startit) {
				var settings = {
					'containerId'			: 'cart-progress-modal',
					'containerFadeIn'		: 300,
					'containerHorizontal'	: 'center',
					'containerVertical'		: 'center',
					'overlayFadeIn'			: 300,
					'overlayOpacity'		: 25,
					'overlayClose'			: false,
					'closeIds'				: '.close',
					'onClose'				: null,
					'message'				: 'Updating your cart ...'
				};
				progressModalDialog = $.modal(settings);
				progressModalDialog.initWindow('<div><div class="content"><div class="message"></div></div></div>');
				progressModalDialog.container.attr('id', settings.containerId);
				progressModalDialog.container.find('.message').text(settings.message);
				progressModalDialog.show();
			} else {
				progressModalDialog.close();
				progressModalDialog = null;
				//$(addtocartButtonids).css('visibility', 'visible');
			}
		}

		//----------------------------------------------------------------------------------------------------
		function dockIt () {
			if (!settings.isFloater) { return; }
			$(settings.cartCloseInfoSel).hide();
			$(settings.cartFloatLocationInfoSel).hide();
			$(settings.cartSel)
				.floater('remove')
				.data('isFloater', false);
			$(settings.cartFloatInfoSel).show();
		}

		//----------------------------------------------------------------------------------------------------
		function floatIt (loc) {
			if (!settings.isFloater) { return; }
			// if no location arg then use last location or default location
			if (!loc) {
				loc = $(settings.cartSel).data('floatLocation') ? $(settings.cartSel).data('floatLocation') : settings.floaterLocationDefault;
			}
			$(settings.cartFloatInfoSel).hide();
			$(settings.cartSel)
				.data('floatLocation', loc)
				.data('isFloater', true)
				.floater({	'attach'		:  loc,
							'offsetX'		:  5,
							'offsetY'		:  5,
							'duration'		:  50,
							'opacity'		:  1, //'.95',
							'zIndex'		: '9000',
							'containerSel'	:  settings.floaterContainerSel
				});
			$(settings.cartCloseInfoSel).show();
			$(settings.cartFloatLocationInfoSel).show();
		}

		//----------------------------------------------------------------------------------------------------
		function debugPrintLine (w) {
			$('<div></div>')
				.html(w)
				.css({	'padding'	: '2px',
					 	'margin'	: '4px 0',
					 	'border'	: '1px solid blue'
				})
				.appendTo('#container');
		}

		//----------------------------------------------------------------------------------------------------
		// setup

		// start if cookies enabled and cart info html exists
		// else exit

		if (!($.cookie() && ($(settings.cartSel).size() > 0))) {
			$(settings.cartSel).css('display', 'none');
			return false;
		}

		// viewcart link
		$(settings.cartInfoViewcartLinkId).click(function(){
			//cartShow();
			return false;
		});

		// checkout link
		$(settings.cartInfoCheckoutLinkId).attr('href', checkoutUrl());

		// FORM submit behavior
		$(settings.itemFormIds).each(function(){
			var button = $(settings.itemFormButtonIds, this).eq(0);
			$(this).submit(function(){
				//debugPrintLine(getCurrentTime() + ' submit');
				cartIframe(true);
				$(this).attr('target', cartIframeName());
				if (!cartIsShown()) {	// show cart if not shown
					cartDisplay(true);
				}
				floatIt();
				progressSubmit(true, button);
				return true; // do submit
			});
		});

		// addtocart link
		$(settings.addtocartLinkSel).each(function(){
			var button = null;
			$(this).click(function(){
				cartIframe(true, $(this).attr('href'));
				if (!cartIsShown()) {	// show cart if not shown
					cartDisplay(true);
				}
				floatIt();
				progressSubmit(true, button);
				return false; // no default click behaviour
			});
		});

		if (settings.isFloater) {
			// close control
			$(settings.cartCloseInfoSel).hide();
			$(settings.cartCloseInfoSel).click(function(){
				dockIt();
				return false;
			});
			// float control
			$(settings.cartFloatInfoSel).show();
			$(settings.cartFloatInfoSel).click(function(){
				floatIt();
				return false;
			});
			// float location control
			$(settings.cartFloatLocationInfoSel).hide();
			$(settings.cartFloatLocationInfoSel).find('a').click(function(){
				floatIt($(this).attr('rel'));
				return false;
			});
		}

		//----------------------------------------------------------------------------------------------------
		// GO

		cartInit();				// hide cart container, create cart remote div, add to cart container
		progressNormal(true);	// start timer and progress display
		cartIframe(false);		// new remote iframe

		//----------------------------------------------------------------------------------------------------
		return true;

	}; // end $.awpFloatingCart

})(jQuery);
