// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// releated under the MIT license

(function($) {
    
    function fixTitle($ele) {
        if ($ele.attr('title') || typeof($ele.attr('original-title')) != 'string') {
            $ele.attr('original-title', $ele.attr('title') || '').removeAttr('title');
        }
    }
    
    function Tipsy(element, options) {
        this.$element = $(element);
        this.options = options;
        this.enabled = true;
        fixTitle(this.$element);
    }
    
    Tipsy.prototype = {
        show: function() {
            var title = this.getTitle();
            if (title && this.enabled) {
                var $tip = this.tip();
                
                $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
                $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
                $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
                
                var pos = $.extend({}, this.$element.offset(), {
                    width: this.$element[0].offsetWidth,
                    height: this.$element[0].offsetHeight
                });
                
                var actualWidth = $tip[0].offsetWidth, actualHeight = $tip[0].offsetHeight;
                var gravity = (typeof this.options.gravity == 'function')
                                ? this.options.gravity.call(this.$element[0])
                                : this.options.gravity;
                
                var tp;
                switch (gravity.charAt(0)) {
                    case 'n':
                        tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 's':
                        tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 'e':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
                        break;
                    case 'w':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
                        break;
                }
                
                if (gravity.length == 2) {
                    if (gravity.charAt(1) == 'w') {
                        tp.left = pos.left + pos.width / 2 - 15;
                    } else {
                        tp.left = pos.left + pos.width / 2 - actualWidth + 15;
                    }
                }
                
                $tip.css(tp).addClass('tipsy-' + gravity);
                
                if (this.options.fade) {
                    $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
                } else {
                    $tip.css({visibility: 'visible', opacity: this.options.opacity});
                }
            }
        },
        
        hide: function() {
            if (this.options.fade) {
                this.tip().stop().fadeOut(function() { $(this).remove(); });
            } else {
                this.tip().remove();
            }
        },
        
        getTitle: function() {
            var title, $e = this.$element, o = this.options;
            fixTitle($e);
            var title, o = this.options;
            if (typeof o.title == 'string') {
                title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
            } else if (typeof o.title == 'function') {
                title = o.title.call($e[0]);
            }
            title = ('' + title).replace(/(^\s*|\s*$)/, "");
            return title || o.fallback;
        },
        
        tip: function() {
            if (!this.$tip) {
                this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"/></div>');
            }
            return this.$tip;
        },
        
        validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide();
                this.$element = null;
                this.options = null;
            }
        },
        
        enable: function() { this.enabled = true; },
        disable: function() { this.enabled = false; },
        toggleEnabled: function() { this.enabled = !this.enabled; }
    };
    
    $.fn.tipsy = function(options) {
        
        if (options === true) {
            return this.data('tipsy');
        } else if (typeof options == 'string') {
            return this.data('tipsy')[options]();
        }
        
        options = $.extend({}, $.fn.tipsy.defaults, options);
        
        function get(ele) {
            var tipsy = $.data(ele, 'tipsy');
            if (!tipsy) {
                tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
                $.data(ele, 'tipsy', tipsy);
            }
            return tipsy;
        }
        
        function enter() {
            var tipsy = get(this);
            tipsy.hoverState = 'in';
            if (options.delayIn == 0) {
                tipsy.show();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
            }
        };
        
        function leave() {
            var tipsy = get(this);
            tipsy.hoverState = 'out';
            if (options.delayOut == 0) {
                tipsy.hide();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
            }
        };
        
        if (!options.live) this.each(function() { get(this); });
        
        if (options.trigger != 'manual') {
            var binder   = options.live ? 'live' : 'bind',
                eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus',
                eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
            this[binder](eventIn, enter)[binder](eventOut, leave);
        }
        
        return this;
        
    };
    
    $.fn.tipsy.defaults = {
        delayIn: 0,
        delayOut: 0,
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        live: false,
        offset: 0,
        opacity: 0.8,
        title: 'title',
        trigger: 'hover'
    };
    
    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };
    
    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };
    
    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };
    
})(jQuery);


// jStepper 1.2

// A jQuery plugin by EmKay usable for making a numeric textfield value easy to increase or decrease.

function AddOrSubtractTwoFloats(fltValue1, fltValue2, bAddSubtract) {

	var strNumber1 = fltValue1.toString();
	var strNumber2 = fltValue2.toString();

	var strResult = "";

	if (strNumber1.indexOf(".") > -1 || strNumber2.indexOf(".") > -1) {

		// If no decimals on one of them, then put them on!
		if (strNumber1.indexOf(".") == -1) {
			strNumber1 = strNumber1 + ".0";
		}

		if (strNumber2.indexOf(".") == -1) {
			strNumber2 = strNumber2 + ".0";
		}

		// Get only decimals
		var strDecimals1 = strNumber1.substr(strNumber1.indexOf(".") + 1);
		var strDecimals2 = strNumber2.substr(strNumber2.indexOf(".") + 1);

		// Getting the integers...
		var strInteger1 = strNumber1.substr(0, strNumber1.indexOf("."));
		var strInteger2 = strNumber2.substr(0, strNumber2.indexOf("."));

		//Make sure that the two decimals are same length (ie .02 vs .001) and append zeros as necessary.
		var bNotSameLength = true;

		while (bNotSameLength) {

			if (strDecimals1.length != strDecimals2.length) {
				if (strDecimals1.length < strDecimals2.length) {
					strDecimals1 += "0";
				} else {
					strDecimals2 += "0";
				}
			} else {
				bNotSameLength = false;
			}
		}

		var intOriginalDecimalLength = strDecimals1.length;

		for (var intCharIndex = 0; intCharIndex <= strDecimals1.length - 1; intCharIndex++) {
			strInteger1 = strInteger1 + strDecimals1.substr(intCharIndex, 1);
			strInteger2 = strInteger2 + strDecimals2.substr(intCharIndex, 1);
		}

		var intInteger1 = Number(strInteger1);
		var intInteger2 = Number(strInteger2);
		var intResult;

		if (bAddSubtract) {
			intResult = intInteger1 + intInteger2;
		} else {
			intResult = intInteger1 - intInteger2;
		}

		strResult = intResult.toString();

		for (var intZerosAdded = 0; intZerosAdded < ((intOriginalDecimalLength - strResult.length) + 1); intZerosAdded++) {
			strResult = "0" + strResult;
		}

		if (strResult.length >= intOriginalDecimalLength) {
			strResult = strResult.substring(0, strResult.length - intOriginalDecimalLength) + "." + strResult.substring(strResult.length - intOriginalDecimalLength);
		}
		
	} else {
		if (bAddSubtract) {
			strResult = Number(fltValue1) + Number(fltValue2);
		} else {
			strResult = Number(fltValue1) - Number(fltValue2);
		}
		
	}

	return Number(strResult);
}

(function(jQuery) {

	jQuery.fn.jStepper = function(options) {

		var opts = jQuery.extend({}, jQuery.fn.jStepper.defaults, options);

		return this.each(function() {
			var $this = jQuery(this);

			var o = jQuery.meta ? jQuery.extend({}, opts, $this.data()) : opts;

			if (o.disableAutocomplete) {
				$this.attr("autocomplete", "off");
			}

			if (jQuery.isFunction($this.mousewheel)) {
				$this.mousewheel(function(objEvent, intDelta){
					if (intDelta > 0){ // Up
						MakeStep(o, 1, null, this);
						return false;
					}
					else if (intDelta < 0){ // Down
						MakeStep(o, 0, null, this);
						return false;
					}
				});
			}

			$this.keydown(function(e){
				var key = e.keyCode;

				if (key == 38){ // Up
					MakeStep(o, 1, e, this);
				}

				if (key == 40){ // Down
					MakeStep(o, 0, e, this);
				}

			});
			
			$this.keyup(function(e){

				CheckValue(o, this);

			});

		});
	};

	function CheckValue(o, objElm) {
	
		var $objElm = jQuery(objElm);
	
		var strValue = $objElm.val();
	
		if (o.disableNonNumeric) {
			strValue = strValue.replace(/[^\d\.,\-]/gi,"");
		}
		
		if (o.maxValue !== null) {
			if (strValue >= o.maxValue) {
				strValue = o.maxValue;
			}
		}
		
		if (o.minValue !== null) {
			if (strValue <= o.minValue && strValue != "") {
				strValue = o.minValue;
			}
		}
		
		$objElm.val(strValue);
	
	}

	function MakeStep(o, bDirection, keydown, objElm) {
	
		var $objElm = jQuery(objElm);
		
		var stepToUse;
		if(keydown) {

			if (keydown.ctrlKey) {
				stepToUse = o.ctrlStep;
			} else if (keydown.shiftKey) {
				stepToUse = o.shiftStep;
			} else {
				stepToUse = o.normalStep;
			}

		} else {
			stepToUse = o.normalStep;
		}

		var numValue = $objElm.val();
		
		var intSelectionStart = numValue.length - objElm.selectionStart;
		var intSelectionEnd = numValue.length - objElm.selectionEnd;

		numValue = numValue.replace(/,/g,".");
		numValue = numValue.replace(o.decimalSeparator,".");
		
		numValue = numValue + '';
		if (numValue.indexOf(".") != -1) {
			numValue = numValue.match(new RegExp("-{0,1}[0-9]+[\\.][0-9]*"));
		}

		numValue = numValue + '';
		if (numValue.indexOf("-") != -1) {
			numValue = numValue.match(new RegExp("-{0,1}[0-9]+[\\.]*[0-9]*"));
		}

		numValue = numValue + '';
		numValue = numValue.match(new RegExp("-{0,1}[0-9]+[\\.]*[0-9]*"));

		if (numValue === "" || numValue == "-" || numValue === null) {
			numValue = o.defaultValue;
		}


		if (bDirection == 1) {
			numValue = AddOrSubtractTwoFloats(numValue, stepToUse, true);
		} else {
			numValue = AddOrSubtractTwoFloats(numValue, stepToUse, false);
		}

		var bLimitReached = false;

		if (o.maxValue !== null) {
			if (numValue >= o.maxValue) {
			numValue = o.maxValue;
			bLimitReached = true;
			}
		}

		if (o.minValue !== null) {
			if (numValue <= o.minValue) {
			numValue = o.minValue;
			bLimitReached = true;
			}
		}

		numValue = numValue + '';

		if (o.minLength !== null) {
			var intLengthNow = numValue.length;
			if (numValue.indexOf(".") != -1) {
				intLengthNow = numValue.indexOf(".");
			}
			var bIsNegative = false;
			if (numValue.indexOf("-") != -1) {
				bIsNegative = true;
				numValue = numValue.replace(/-/,"");
			}
			
			if (intLengthNow < o.minLength) {
				for (var i=1;i<=(o.minLength - intLengthNow);i++) {
					numValue = '0' + numValue;
				}
			}
			
			if (bIsNegative) {
				numValue =  '-' + numValue;
			}
		
		}
		
		numValue = numValue + '';
		
		var intDecimalsNow;
		
		if (o.minDecimals > 0) {
			var intDecimalsMissing; 
			if (numValue.indexOf(".") != -1) {
				intDecimalsNow = numValue.length - (numValue.indexOf(".") + 1);
				if (intDecimalsNow < o.minDecimals) {
					intDecimalsMissing = o.minDecimals - intDecimalsNow;
				}
			}	else {
				intDecimalsMissing = o.minDecimals;
				numValue = numValue + '.';
			}
			for (var intDecimalIndex=1; intDecimalIndex<=intDecimalsMissing; intDecimalIndex++) {
				numValue = numValue + '0';
			}
		} 

		if (o.maxDecimals > 0) {
			intDecimalsNow = 0; 
			if (numValue.indexOf(".") != -1) {
				intDecimalsNow = numValue.length - (numValue.indexOf(".") + 1);
				if (o.maxDecimals < intDecimalsNow) {
					numValue = numValue.substring(0,numValue.indexOf(".")) + "." + numValue.substring(numValue.indexOf(".") + 1,numValue.indexOf(".") + 1 + o.maxDecimals);
				}
			}
		}
		
		if (!o.allowDecimals) {
			numValue = numValue + '';
			numValue = numValue.replace(new RegExp("[\\.].+"),"");
		}
		
		numValue = numValue.replace(/\./,o.decimalSeparator);

		$objElm.val(numValue);
		
		objElm.selectionStart = numValue.length - intSelectionStart;
		objElm.selectionEnd = numValue.length - intSelectionEnd;
		
		CheckValue(o, this);
		
		if (o.onStep) {
			o.onStep($objElm, bDirection, bLimitReached);
		}
		
		return false;
	
	}

	jQuery.fn.jStepper.defaults = {
		maxValue : null,
		minValue : null,
		normalStep : 1,
		shiftStep : 5,
		ctrlStep : 10,
		minLength : null,
		disableAutocomplete : true,
		defaultValue : 1,
		decimalSeparator : ",",
		allowDecimals : true,
		minDecimals : 0,
		maxDecimals : null,
		disableNonNumeric : true,
		onStep : null
	};

})(jQuery);


function showModalLoadingMessage(title) {
    $('#loadingtext').text(title);
    $('#loading').show();
}

function hideModalLoadingMessage() {
    $('#loading').fadeOut('slow');
}

function HandleDeleteCartItemButton(row) {
    row.find('input:first').val('0');
    row.fadeTo('slow', 0);
}


var clothesTimeout = null;
var designersTimeout = null;
var shoesTimeout = null;
var kidsTimeout = null;
var jewelryTimeout = null;

$(function () {

	$("<img>").attr("src", "/Content/Images/Backgrounds/Loading.gif");

    $('.nojavascript').remove();

    $('.requiresjavascript').show();

    $('.quantityinput').jStepper({ minValue: 1, maxValue: 6 });

    $('<div class="loading" id="loading"><div id="loadingbar"></div><div id="loadingtext"></div></div>').appendTo('body');

    $('.photozoom').fancybox();

    $('#sizingguide').fancybox();

    $('.galleryimage').fancybox({
        'cyclic': true
    });
    
    $('.tooltip').tipsy({gravity: 'nw'});

    $('.enlargebutton').click(function (e) {
        $('.photozoom').trigger('click');
        return false;
    });

    if ($('#shippingAddressSame').attr('checked')) {
        $('#ShippingAddressDiv').before("<div class='note' id='ShippingAddressSameLabel'>Same as billing address</div>");
        $('#ShippingAddressDiv').hide();
    }

    $("#shippingAddressSame, #shippingAddressDifferent").click(function () {

        if ($("#ShippingAddressSameLabel").length == 0) {
            $('#ShippingAddressDiv').before("<div class='note' id='ShippingAddressSameLabel'>Same as billing address</div>");
        }
        if ($('#shippingAddressSame').attr('checked')) {
            $("#ShippingAddressSameLabel").stop(true, true).slideDown();
            $('#ShippingAddressDiv').stop(true, true).fadeOut(1000);
        } else {
            $("#ShippingAddressSameLabel").stop(true, true).slideUp();
            $('#ShippingAddressDiv').stop(true, true).fadeIn(1000);
        }
    });

    $('form').inputHintOverlay();



 	var menuCallbacks = new Array();
 	var menuCallbacks = new Array();
 
	var currentTouch = null;

    $.each(['clothes', 'handbags', 'accessories', 'shoes', 'filter12', 'filter13', 'designers'], function(index, value) { 

	   $('#'+value+'-hover').css({top: '31px', left: $('#'+value+'-link').position().left-1});

	   $('#'+value+'-link').mouseenter(function () {
	        $('#'+value+'-link').addClass('hover-active');
	        $('#'+value+'-link').parent().addClass('hover-active');
	        $('#'+value+'-hover').show();
	    });

    $('#'+value+'-link').bind('touchstart touchend', function(e) {

	if (currentTouch != value) {
		 e.preventDefault();
	        $('.hover-content').hide();
		$('#mainnav-contents li').removeClass('hover-active');
	        $('#'+value+'-link').addClass('hover-active');
	        $('#'+value+'-link').parent().addClass('hover-active');
		$('#'+value+'-hover').show();
		currentTouch = value;
	}
    });

	
	    $('#'+value+'-link').mouseleave(function () {
	        menuCallbacks[value] = setTimeout(function () { $('#'+value+'-hover').hide(); $('#'+value+'-link').removeClass('hover-active'); $('#'+value+'-link').parent().removeClass('hover-active'); }, 100);
	    });
	


	    $('#'+value+'-hover').mouseenter(function () {
	        if (menuCallbacks[value] != null) {
	            clearTimeout(menuCallbacks[value]);
	            menuCallbacks[value] = null;
	        }
	    });
	
	    $('#'+value+'-hover').mouseleave(function () {
	        $('#'+value+'-link').removeClass('hover-active');
	        $('#'+value+'-link').parent().removeClass('hover-active');
	        $('#'+value+'-hover').hide();
	    });
	    
	    if ($('#'+value+'-hover').width() + 22 + $('#'+value+'-link').position().left > 924) {
	    	$('#'+value+'-hover').css('left', 924 - 22 - $('#'+value+'-hover').width());
	    }
    
    });
    
    $('.hover-content a').live('touchend', function(e) {
	    var el = $(this);
	    var link = el.attr('href');
	    window.location = link;
	});


	$('.favorite').click(function (e) {
		if (typeof UserIsAuthenticated != 'undefined' && UserIsAuthenticated != null) {
	
		    if ($(this).hasClass('favorite-on')) {
		    	$(this).removeClass('favorite-on').attr('title', 'Add to My Favorites');
		    	$.get($(this).attr('href').replace("Action", "Remove"));				
		    } else {
		    	$(this).addClass('favorite-on').attr('title', 'Remove from My Favorites');
		    	$.get($(this).attr('href').replace("Action", "Add"));				
		    }
		} 
				    
	    return false;
	});

    $(Skye).bind("QuickLoginSuccess", function () {
	    $.get('/Content/PartialZone/TopNavigation', function (data) {
	        $('#cartnav').html(data);
	    });
	});	

    $('.navlist dd').has('ul').hide();
    $('.navlist dd').has('ul').has('a.active').show();
    $('.navlist dt').click(function () { $(this).next().slideToggle(); });
    $('.navlist dd.nocollapse').show();

    $('.navlist dd li').has('ul').hide();
    $('.navlist dd li').has('ul').has('a.active').show();
    $('.navlist span').click(function () { $(this).parent().next().slideToggle(); });

    /*
    $('#minicart').hide();

    $('.shoppingbag').click(function () {

        if ($('#minicart').children().size() == 0) {
            showModalLoadingMessage("Loading Cart");

            $.ajax({
                url: '/Cart/MiniCart',
                success: function (data) {
                    $('#minicart').html(data);
                    $('#minicart').slideDown();
                    hideModalLoadingMessage();
                }
            });

            return false;
        }


        if ($('#minicart').is(':visible'))
            $('#minicart').slideUp();
        else
            $('#minicart').slideDown();

        return false;
    });
    */

    $('html').removeClass('jsloading');

    $('.search-autocomplete').autocomplete({
        source: "/Search/Autocomplete",
        select: function (event, ui) {
            $(".search-autocomplete").val(ui.item.value);
            $(".search-autocomplete-form").submit();
        }
    });

    $('.mainsearch-autocomplete').autocomplete({
        source: "/Search/Autocomplete",
        select: function (event, ui) {
            $(".mainsearch-autocomplete").val(ui.item.value);
            $(".mainsearch-autocomplete-form").submit();
        }
    });




});




