

$.namespace('hello');
$.fn.hello.breadcrumbCarousel = function(opts){
    return $(this).each(function(){
        try {
            if($(this).data('carouseled')) return;
            $(this).data('carouseled', true);
            var $el = $(this);
            $el.find('ul').each(function(){
                var afterEnd = function(){
                    var args = arguments;
                    var vis = args[0];
                    $(vis[0]).prevAll('li').length ? $(hash.btnPrev).removeClass('disabled') : $(hash.btnPrev).addClass('disabled');
                    $(vis[vis.length-1]).nextAll('li').length ? $(hash.btnNext).removeClass('disabled') : $(hash.btnNext).addClass('disabled');

                    // manually trigger the mouseup events on invisible elements
                    hash.btnPrev.not(':not(.disabled)').trigger('mouseup');
                    hash.btnNext.not(':not(.disabled)').trigger('mouseup');

                    return false;
                };

                var hash = $.extend({
                    btnNext: $el.find('a.downArrow')
                    ,btnPrev: $el.find('a.upArrow')
                    ,vertical: true
                    ,visible: 14
                    ,circular: false
                    ,afterEnd: afterEnd
                    ,speed: 400
                    ,easing: 'easeOutQuad'
                    ,scroll: 4
                    //,mouseWheel: true
                }, opts || {});

                if($(this).find('li').length <= hash.visible){
                    hash.visible = $(this).find('li').length;
                    hash.btnPrev.hide();
                    hash.btnNext.hide();
                }

                var scroller = function(opts){
                    opts = opts || {};
                    var self = this;

                    self.mousedown = false;
                    self.forward = false;
                    self.timeout = false;

                    // user config options to be overridden
                    self.debugging = opts.debugging || false;
                    self.interval = opts.interval || 500;
                    self.fnNext = opts.fnNext || function(){self.debug('default fnNext function');};
                    self.fnPrev = opts.fnPrev || function(){self.debug('default fnPrev function');};

                    self.debug = function(msg){
                        if(!self.debugging) return;
                        try {
                            console.log(msg);
                        } catch(e) {
                            alert(msg);
                        }
                    };
                    self.startNext = function(){
                        self.mousedown = true;
                        self.forward = true;
                        self.scroll();
                    };
                    self.stopNext = function(){
                        self.mousedown = false;
                        self.timeout = false;
                        self.debug('stopNext');
                    };
                    self.startPrev = function(){
                        self.mousedown = true;
                        self.forward = false;
                        self.scroll();
                    };
                    self.stopPrev = function(){
                        self.mousedown = false;
                        self.timeout = false;
                        self.debug('stopPrev');
                    };
                    self.scroll = function(){
                        if(!self.mousedown) {
                            self.timeout = false;
                            return false;
                        }
                        self.debug('scroll()');
                        try {
                            if(self.forward){
                                self.fnNext();
                            } else {
                                self.fnPrev();
                            }
                        } catch(e) {
                            self.debug(e);
                        }
                        self.timeout = setTimeout(self.scroll, self.interval);
                    };

                };

                /*
                var myScroller = new scroller({
                    interval: 50,
                    fnNext: function(){
                        hash.btnNext.trigger('click');
                    },
                    fnPrev: function(){
                        hash.btnPrev.trigger('click');
                    }
                });

                hash.btnNext.mousedown(myScroller.startNext);
                hash.btnPrev.mousedown(myScroller.startPrev);
                hash.btnNext.mouseup(myScroller.stopNext);
                hash.btnPrev.mouseup(myScroller.stopPrev);
                */
                hash.btnNext.click(function(){return false;}).addClass('disabled');
                hash.btnPrev.click(function(){return false;}).addClass('disabled');

                var div = $(this).closest('div').jCarouselLite(hash);
                $(this).find('li:hidden').show();
                hash.btnPrev.trigger('click'); //click();

            });
        } catch(e) {
            //console.log(e);
        }
    });
};

// override style function to fix msie stuff

$.fn.hello.relatedProductsCarousel = function(opts){
    return $(this).each(function(){
        var hash = $.merge({
            btnPrev: $(this).find('a.leftArrow')
            ,btnNext: $(this).find('a.rightArrow')
            ,visible: 5
            ,speed: 200
        }, opts || {});
        var div = $(this).find('ul.carousel').each(function(){
            var heights = $(this).find('li').map(function(){
                return $(this).height();
            });
            $(this).find('li').height(heights.sort()[heights.length-1]);

            if($(this).find('li').length <= hash.visible){
                hash.btnPrev.css('visibility','hidden');
                hash.btnNext.css('visibility','hidden');
            }
        }).closest('div').jCarouselLite(hash).show();
        setTimeout(function(){div.hide().show();}, 0);
    });
};

$.fn.hello.sidebarCarousel = function(opts){
    return $(this).each(function(){
        var hash = $.merge({
            btnPrev: $(this).find('a.upArrow')
            ,btnNext: $(this).find('a.downArrow')
            ,vertical: true
            ,visible: 3
            ,speed: 200
        }, opts || {});
        var div = $(this).find('ul.carousel').each(function(){
            if($(this).find('li').length <= hash.visible){
                hash.btnPrev.css('visibility','hidden');
                hash.btnNext.css('visibility','hidden');
            }
        }).closest('div').jCarouselLite(hash);
    });
};

$.extend({
    hello: {
        getEventTarget: function(e) {
            e = e || window.event;
            return e.target || e.srcElement;
        },
        fnHandleFieldBlur: function(){
            var $el = $(this);
            $el.attr('value', $el.attr('title')).focus(function(){
                if($el.attr('value') == $el.attr('title')) {
                    $el.attr('value', '');
                }
            }).blur(function(){
                if($el.attr('value') == '') {
                    $el.attr('value', $el.attr('title'));
                }
            });
        }
    }
});

//stuff added for nuskin js library integration
var logInPopup = null;

/**
 * NON CAS Implementation of displaying the login screen
 */
var showLoginPopup = function(anchor){
    var taiwanLogin = false;

    if (document.URL.indexof("zh_TW") !=-1) {
        taiwanLogin = true;
    }

    if (typeof(useCAS) != "undefined" && useCAS) {
        showCASLogin(anchor);
    } else if (taiwanLogin) {
        var loginUrl = "http://test.nuskin.com.tw/tengah/CMS/login.do?furl=http://dev.nuskin.com/zh_TW/home.html";
        window.open(loginUrl, '', '')
    } else {
       // old school login
       if(window.nuskin && window.nuskin.account) {
            if(anchor) {
                nuskin.account.AccountManager.setAfterLoginUrl(anchor.href, ((anchor.target && anchor.target == '_blank') || (anchor.rel && anchor.rel == 'external')));
            } else {
                nuskin.account.AccountManager.setAfterLoginUrl(null);
            }
        }
        resetLoginForm();
        $('#logInFormErrors').css('display', 'none');
        $('#username').val('');
        $('#password').val('');
        logInPopup = $('#domWindow').jqm({
            closeClass: 'close'
        });
        logInPopup.jqmShow();
        $('#username').focus();
    }
};

/**
 * CAS Implementation of displaying the login screen
 */
var showCASLogin = function(anchor){
    var newWindow = false;
    if (anchor) {
        if ((anchor.target && anchor.target == '_blank') || (anchor.rel && anchor.rel == 'external')) {
            newWindow = true;
        }
    }

	if(window.nuskin && window.nuskin.account) {
		if(anchor) {
            nuskin.account.AccountManager.setAfterLoginUrl(anchor.href, newWindow);
		} else {
            nuskin.account.AccountManager.setAfterLoginUrl(null);
		}
	}

    var loginUrl = nuskin.util.authenticationHost+"/index.jsp";

    if (newWindow) {
        window.open(loginUrl, '', '')
    } else {
        window.location = loginUrl;
    }
};

/* DOM Ready Functions */
$(function(){

	// Open Links in New Window via rel="external"
	$('a[rel="external"]').click(function(){this.target = "_blank";});

	// Main Nav - Set Content Shade
	var currentSubNav = null;
	var cleanupCurrentSubNav = function(){
		if(currentSubNav) {
			$(currentSubNav).removeClass('active');
            var span = $(currentSubNav).children('a').children('span');
            if (useVerlagImage) {
                var navImg = span.children('img');
			    navImg.attr('src', navImg.attr('src').replace('.blue.png', '.png'));
            } else {
                span.css('border','1px solid white');
            }
			$('#mainNav li .subNav').css('left', '-999.9em');
			//$(this).siblings('a').removeClass('active');
			currentSubNav = null;
		}
	};

	$('#mainNav').hoverIntent({
		timeout: 200,
		interval: 100,
		over: function(){
			if ($('#setMainNavBg').length > 0) {
				var headerHt = $('#header').height();
				var contentHt = $(document).height() - 128;
				if ($.browser.msie && $.browser.version < 7) {
					var contentHt = $(document).height() - 132;
				}
				$('#headerDivider').after('<div class="contentShade"></div>');
				$('#setMainNavBg').show();
				$('div.contentShade').css('height', contentHt);
			}
		},
		out: function(){
			cleanupCurrentSubNav();
			$('div.contentShade').remove();
			$('#setMainNavBg').hide();
		}}
	);

	// Main Nav - Show Sub-Nav
	$('#mainNav li').not('#mainNav .subNav li').hoverIntent({
		timeout: 200,
		interval: 100,
		sensitivity: 3,
		over: function(){
			cleanupCurrentSubNav();
			currentSubNav = this;
			var topLi = $(this);
			topLi.addClass('active');
			//$(this).siblings('a').addClass('active');
			var topLiAnchor = topLi.children('a');
			var hoveredAnchorId = topLiAnchor.attr('id');
            var span = topLiAnchor.children('span');
            if (useVerlagImage) {
			    var navImg = span.children('img');
			    navImg.attr('src', navImg.attr('src').replace('.png', '.blue.png'));
            } else {
                // do a mouseover effect
                span.css('border','1px solid #7FC4D7');
            }
			var add = false;
			var offset = 0;

			$('#mainNav li a').not('#mainNav .subNav li a').each(function(i) {
				if(add) {
					offset = offset + $(this).parent().outerWidth(true);
				}
				if(!add && $(this).attr('id') == hoveredAnchorId) {
					add = true;
					offset = ($(this).parent().outerWidth() / 2);
				}
			});
			var mainNavWidth = $('#mainNav').outerWidth(true);
            var adjustment = arrowAdjustment;
			$('#mainNav li.active .subNav').css('left', '-'+(786 - mainNavWidth)+'px'); // positions the images/text on the subnav
            var arrowX = adjustment - offset;
            //console.log("arrowX:"+arrowX+" offset:"+offset+" adjustment:"+adjustment);
			$('#mainNav .subNav ul').css('background-position', arrowX+'px 0'); // positions the arrow
		},
		out: function(){}}
	);

	$('a.call-link').hover(function(){
		width = $(this).outerWidth(true);
		height = $(this).outerHeight(true);
		$(this).find('span.overeffect').css({
			width:width+'px',
			height:height+'px',
            position:'absolute',
            top:'0',
			left:'0',
			background: 'url("/apps/hello/services/backgroundHover.'+width+'.'+height+'.png") 0 0 no-repeat',
			display:'block'}
		);
	},
	function(){
		$(this).find('span.overeffect').css({
			display:'none'}
		);
	});

	// Choose Language & My Office List Menus Hover
    $('.listMenu li.top').hover(function () {
		$(this).addClass('active');
		$(this).find('a:first-child').addClass('active');
	},
	function () {
		$(this).removeClass('active');
		$('.listMenu a:first-child').removeClass('active');
	});


	// Choose Language & My Office List Menu Click
	$('.listMenu li a:first-child').click(function() {
		$(this).siblings('ul').toggleClass('opened');
	    return false;
	});

	$('.listMenu li ul a').click(function() {
		if($.inArray('requiresAuthentication', $(this).attr('class').split(' ')) > -1 && !nuskin.account.AccountManager.currentData) {
            showLoginPopup(this);
		} else {
			if((this.target && this.target == '_blank') || (this.rel && this.rel == 'external')) {
				window.open(this.href, '', '');
			} else {
				window.location = this.href;
			}
		}
		$(this).parents('ul.opened').toggleClass('opened');
		return false;
	});

    $('a.authenticate').click(function() {
		if(!nuskin.account.AccountManager.currentData) {
            showLoginPopup(this);
            return false;
		}
	});

	// Custom Breadcrumb Menu
	$('.customMenu a.openClose').click(function(){
        $('.customMenu a.openClose').removeClass('opened').siblings('.menu').hide();
		$(this).toggleClass('opened');
	    if ($(this).hasClass('opened')){
	    	$(this).siblings('.menu').slideDown('fast').hello().breadcrumbCarousel();
	    } else {
	        $(this).siblings('.menu').hide();
	    }
	    return false;
	});

	// Focus changes on input fields (like search)
	var preFocusHandler = function(inputElement){
		$(inputElement).val('');
		$(inputElement).removeClass('preFocus');
	};
	$('input.preFocus').focus(function(){
		preFocusHandler(this);
	});

	$('form.requireNoPreFocus').submit(function(){
		var submit = true;
		$(this).find('input.preFocus').each(function(){
			if(submit) {
				preFocusHandler(this);
				this.focus();
			}
			submit = false;
		});
		return submit;
	});

	var signInHandler = function(formId){
		//only allow signin if no logged in user
		if (!nuskin.account.AccountManager.currentData) {
			var username = $('#'+formId+'-username').val();
		    var password = $('#'+formId+'-password').val();
		    $('#'+formId+'-logInFormErrors').css('display', 'none');
			nuskin.account.AccountManager.authenticate(username, password);
		}
	};
	// Log In Form Pop Up
	$('a.pop').click(function(){
	    showLoginPopup();
        return false;
    });
	$('a.logout').click(function(){
		nuskin.account.AccountManager.logout();
        return false;
    });
	$('a.signIn').click(function(){
		signInHandler($(this).attr('id'));
	});
	$('input.logInForm-password').keypress(function(e){
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			signInHandler($(this).attr('id').replace('-password', ''));
		}
	});
	if(window.location.hash == "#showLogin") {
		showLoginPopup();
	}
	if(window._nuskinPopupLogin) {
		showLoginPopup();
	}

	$('a.addToCart').click(function(){
		var sku = $(this).attr('id').split("-")[1];
		var qtyInput = $('#qty-'+sku);
		var qty = 1;
		if(qtyInput && qtyInput.val()) {
			qty = qtyInput.val();
		}
		nuskin.shop.addToCart(sku, qty);
        return false;
	});

	$('a.addToAdrCart').click(function(){
		var sku = $(this).attr('id').split("-")[1];
		var qtyInput = $('#qty-'+sku);
		var qty = 1;
		if(qtyInput && qtyInput.val()) {
			qty = qtyInput.val();
		}
		nuskin.shop.addToAdrCart(sku, qty);
        return false;
	});

    $('a.addToAdrCartWithCoupon').click(function(){
        var coupon = $('#coupon').val();
        if (coupon == '' || coupon == 'Enter Coupon Code') {
            alert("You must enter a valid coupon to add this product");
            return false;
        }

        // modify this.href to include the coupon
        // add the coupon and the quantity
        var vitalitySku = $(this).attr('id').split("-")[1];
        var qtyInput = $('#qty-'+vitalitySku);
        var qty = 1;
        if(qtyInput && qtyInput.val()) {
            qty = qtyInput.val();
        }
        if (qty > 1) {
           vitalitySku += ":"+qty;
        }

        var redirectUrl = window.location;
        // now strip out any extra query parameters

        var urlArray = redirectUrl.toString().split("?");
        if (urlArray.length > 1) {
            redirectUrl = urlArray[0];
        }

        this.href = this.href+"?vitalitySku="+vitalitySku+"&vitalityCouponCode="+coupon;
        if (!nuskin.account.AccountManager.currentData) {
            showLoginPopup(this);
        } else {
            window.location = this.href;
        }
        return false;
    });

    $('#coupon').click(function() {
        if ($(this).val() == 'Enter Coupon Code') {
            $(this).val("");
        }

        var fadeArgs = {
            node: "couponError",
            duration: 1000
        };
        dojo.fadeOut(fadeArgs).play();
    });

    $('a#continueShopping').click(function() {
        dojo.fadeOut({node: "checkoutPanel"}).play();
        // note that fadeOut just set the opacity to 0,
        // people can still click on the button (and it covers other button)
        // set the css display:none for the panel to make sure people cannot click on it
        $('#checkoutPanel').css('display', 'none');
    });

    $('a#closeCheckout').click(function() {
        dojo.fadeOut({node: "checkoutPanel"}).play();
        $('#checkoutPanel').css('display', 'none');
    });

    $('.menu').click(function(ev){
        if(getEventTarget(ev).tagName == 'A'){
            return true;
        }
        return false;
    });

	// Document Click Handler
	$(document).click(function() {
        // Close Choose Language
		$('.listMenu li ul').removeClass('opened');

		// Close Custom Menu
	    $('.customMenu').children('.menu').hide();
	    $(".customMenu a.openClose").removeClass('opened');

	});


	// Module Hover
	//if ($('body').is('#category,#subCategory')) {
		$('.category .module, .subCategory .module').hover(
			function () {
				$(this).find('.shade').addClass('active');
			},
			function () {
				$(this).find('.shade').removeClass('active');
			}
		);
	//}


	// Product Details Show/Hide
	if ($('#productInfo #details')[0]) {
		$('#details li a').not('#details li .contentSectionContainer a').click(function(){
			$(this).siblings('div').slideToggle();
			$(this).toggleClass('selected');
		    return false;
		});

		$('#details li a.default').siblings('div').slideToggle();
		$('#details li a.default').toggleClass('selected');
	}

	// Question Mark Tooltip
	$('a.questionMark').hover(function(e){
		$('.tooltip')
			.css('top','-135px')
			.css('left','43px')
			.show();
		},
		function(){
			$('.tooltip').css('display','none');
	});

	// Cart Add Product Input
	var fnHandleFieldBlur = function(){
        var $el = $(this);
        $el.attr('value', $el.attr('title')).focus(function(){
            if($el.attr('value') == $el.attr('title')) {
                $el.attr('value', '');
            }
        }).blur(function(){
            if($el.attr('value') == '') {
                $el.attr('value', $el.attr('title'));
            }
        });
    };

    $('#addProduct input').each(fnHandleFieldBlur);


    // other products carousel
    $('#otherProducts .carouselWrap').each(function(){
        var hash = {
            btnPrev: $(this).find('a.leftArrow')
            ,btnNext: $(this).find('a.rightArrow')
            ,visible: 5
        };
        var div = $(this).find('ul.carousel').each(function(){
            var heights = $(this).find('li').map(function(){
                return $(this).height();
            });
            $(this).find('li').height(heights.sort()[heights.length-1]);

            if($(this).find('li').length <= hash.visible){
				hash.circular = false;
                hash.btnPrev.css('visibility','hidden');
                hash.btnNext.css('visibility','hidden');
            }
        }).closest('div').jCarouselLite(hash).show();
        setTimeout(function(){div.hide().show();}, 0);
    });

    // hello-slideshow
    $('div.hello-slideshow-container').each(function(){
        var hash = {
            btnPrev: $(this).find('a.leftArrow'),
            btnNext: $(this).find('a.rightArrow'),
            visible: 1
        };
        $(this).find('div.hello-slideshow').jCarouselLite(hash).show();
    });


    $('#sideBar .carouselWrap').each(function(){
        var hash = {
            btnPrev: $(this).find('a.upArrow')
            ,btnNext: $(this).find('a.downArrow')
            ,vertical: true
            ,visible: 3
        };
        var div = $(this).find('ul.carousel').each(function(){
            if($(this).find('li').length <= hash.visible){
				hash.circular = false;
                hash.btnPrev.css('visibility','hidden');
                hash.btnNext.css('visibility','hidden');
            }
        }).closest('div').jCarouselLite(hash);
    });

	$('#globalLanding .links a').click(function() {
		if($('#rememberLocation:checked').length > 0) {
			dojo.cookie('nuskin.hello.savedLocation', this.href, {path:'/', expires: 365});
		}
	});

	$('#cart a').click(function() {
		if(window.nuskin && window.nuskin.shop) {
			var shopMode = nuskin.shop.getShopMode();
			if(shopMode && "cart" != shopMode) {
				this.href = this.href + "/" + shopMode;
			}
		}
	});

	// IE6 FIxes
	if ($.browser.msie && $.browser.version <7) {

		// Fixes Hover for Homepage and Header Promos
		$('#header #promo a, .carousel li a, #hero a').hover(
			function () {
				if ($(this).is('#hero a'))
					$(this).addClass('active');
				else{
					$(this).find('span').addClass('active');
				}
			},
			function () {
				if ($(this).is('#hero a'))
					$(this).removeClass('active');
				else{
					$(this).find('span').removeClass('active');
				}
			}
		);

		// Adds iframe for Tooltip
		$('.tooltip').bgiframe();

	}


});

// For the popup component sharing with the rte popupDialog widget
var showPopup = function(divName) {
    var e = $('#' + divName);
    if (e) {
        var aPopup = e.jqm({
            closeClass: 'close'
        });
        aPopup.jqmShow();
    }
    return false;
};


