/**
 * Wedding boutique global JavaScript
 * @author Lee Daffen lee.daffen@net-a-porter.com
 */

var WeddingBoutique = {
    landingPage: {
		$carouselLi: {},			// container object for the carousel list items collection
		currentIndex: 1,			// current position of the carousel
		firstVisit: true,			// TODO: put this value in a cookie
		cycleInterval: {},
		navOpen: true,				// state of the collapsible nav container

		displayPage: function(data) {
			$("#landing-page-content").fadeOut(function() {
				$("#landing-page-content").html(data);
			});

			$("#landing-page-content").fadeIn(function() {
				if(data) {
					data;
				}
			});
		},

		pageError: function(errorData) {
			//
		},

		getPage: function(currentIndex) {
            WeddingLandingPageService.getContentForPage(currentIndex, {
				callback: WeddingBoutique.landingPage.displayPage,
				timeout: 5000,
				errorHandler: WeddingBoutique.landingPage.pageError
			});
		},

        displayNav: function(data) {
            $("#nav-carousel").html(data);
        },

        getNav: function(callback) {
            WeddingLandingPageService.getNavigation({
                callback: function(data) {
                    WeddingBoutique.landingPage.displayNav(data);
                    callback();
                },
                timeout: 10000,
                errorHandler: WeddingBoutique.landingPage.pageError
            });
        },

		closeNav: function() {
			$("#nav-carousel-wrapper").animate({
				height: "17px",
				opacity: 0.75
			}, function() {
				$("#nav-close-button").html('<a href=""><img src="/nap/build_8.13.1/images/wedding_boutique/bottom_menu_open.gif" /></a>');
				WeddingBoutique.landingPage.navOpen = false;
			}).addClass("closed");
			$("#nav-carousel").fadeOut();
			$(".nav-carousel-nav-button").fadeOut();
		},

		openNav: function() {
			$("#nav-carousel-wrapper").animate({
				height: "106px",
				opacity: 1
			}, function() {
				$("#nav-close-button").html('<a href=""><img src="/nap/build_8.13.1/images/wedding_boutique/bottom_menu_close.gif" /></a>');
				WeddingBoutique.landingPage.navOpen = true;
			}).removeClass("closed");
			$("#nav-carousel").fadeIn();
			$(".nav-carousel-nav-button").fadeIn();
		},

		cyclePages: {
			loadFirstPage: function() {
				WeddingBoutique.landingPage.currentIndex = 1;
				WeddingBoutique.landingPage.getPage(WeddingBoutique.landingPage.currentIndex);
				WeddingBoutique.landingPage.hiLiteCarousel(WeddingBoutique.landingPage.currentIndex);
			},

			go: function() {
				var carouselLength = $("#nav-carousel li").length;

				WeddingBoutique.landingPage.cycleInterval = window.setInterval(function() {
					if(WeddingBoutique.landingPage.currentIndex < carouselLength) {
						WeddingBoutique.landingPage.currentIndex++;
						WeddingBoutique.landingPage.getPage(WeddingBoutique.landingPage.currentIndex);
						WeddingBoutique.landingPage.hiLiteCarousel(WeddingBoutique.landingPage.currentIndex);
					} else {
						WeddingBoutique.landingPage.cyclePages.stop();
						WeddingBoutique.landingPage.firstVisit = false;
						window.setTimeout(WeddingBoutique.landingPage.closeNav, 3000);
						WeddingBoutique.landingPage.cyclePages.loadFirstPage();
					}
				}, 8000);
			},

			stop: function() {
				window.clearInterval(WeddingBoutique.landingPage.cycleInterval);
			}
		},

		hiLiteCarousel: function(item) {
			if(typeof item === "number") {
				WeddingBoutique.landingPage.$carouselLi.removeClass("current");
				$("#i"+item).addClass("current");
				WeddingBoutique.landingPage.currentIndex = item;
			} else {
				WeddingBoutique.landingPage.$carouselLi.removeClass("current");
				$(item).parent().addClass("current");
				WeddingBoutique.landingPage.currentIndex = item.parentNode.id.match(/[0-9]+/)[0];
			}
		},

		init: function() {
			WeddingBoutique.landingPage.$carouselLi = $("#nav-carousel li");

			if(WeddingBoutique.landingPage.firstVisit) {
				WeddingBoutique.landingPage.getPage(WeddingBoutique.landingPage.currentIndex);
                WeddingBoutique.landingPage.cyclePages.go();
			} else {
				WeddingBoutique.landingPage.getPage(WeddingBoutique.landingPage.currentIndex);
			}

			WeddingBoutique.landingPage.$carouselLi.find("a").click(function(e) {
				e.preventDefault();
				WeddingBoutique.landingPage.cyclePages.stop();

				if(!$(this).parent().hasClass("current")) {
					WeddingBoutique.landingPage.currentIndex = this.parentNode.id.match(/[0-9]+/)[0];
					$("#landing-page-content").html('<div class="ajax-loader"><img src="/nap/build_8.13.1/images/wedding_boutique/ajax-loader.gif" /><span>Loading...</span></div>');
					WeddingBoutique.landingPage.getPage(WeddingBoutique.landingPage.currentIndex);
				}

				WeddingBoutique.landingPage.hiLiteCarousel(this);
			});

			$("#nav-close-button").click(function(e) {
                e.preventDefault();
				if(!$("#nav-carousel-wrapper").hasClass("closed")) {
					WeddingBoutique.landingPage.closeNav();
				} else {
					WeddingBoutique.landingPage.openNav();
				}
			});
		}
	},

	gowns: {
        $carouselLi: [],			// container object for the carousel list items collection
        currentIndex: 1,			// current position of the carousel
		currentVisible: [],			// container for the collection returned by the carousel's afterEnd callback data
		navInterface: {},			// container for the carousel's exposed interface methods
		cycleInterval: {},

        getPidFromId: function(id) {
            var regEx = /[0-9]{5}/g,
                regExMatch = id.match(regEx);

            if(regExMatch) { return regExMatch[0]; }

            return false;
        },

        displayProductInfo: function(productData) {
            if(productData) {

                var productDetails = productData.details,
                    productDetailsSplit = productDetails.split("$$"),
                    pdSplit1 = '<span id="en-first-desc">' + productDetailsSplit[0] + '</span>',
                    ellipsis = '<span id="en-ellipsis">...</span>',
                    pdSplit2 = '<span id="en-last-desc">' + productDetailsSplit[1] + '</span>',
                    productDetailsHTML,
                    productDetail;

                if(productDetailsSplit[1]) {
                    productDetail = pdSplit1+ellipsis;
                } else {
                    productDetail = pdSplit1;
                }

                productDetailsHTML = [
                    '<div id="product-info-inner" style="display:none;">',
                        '<div id="product-designer-name">',productData.designer,'</div>',
                        '<div id="product-name">',productData.title,'</div>',
                        '<div id="product-price">',productData.price,'</div>',
                        '<div id="product-details">',productDetail,'</div>',
                        '<div id="product-shop-now"><a href="/product/',productData.productId,'"><img src="/nap/build_8.13.1/images/wedding_boutique/view_details.gif" alt="View Details" /></a></div>',
                    '</div>'
                ].join(""),

                productImageHTML = [
                    '<div id="product-image-container"><a href="/product/',productData.productId,'"><img style="display:none;" class="product-image" src="http://cache.net-a-porter.com/images/products/',productData.productId,'/',productData.productId,'_fr_ml.jpg" alt="',productData.designer,' ',productData.title,'" /></a></div>'
                ].join("");

                $("#current-index").text(WeddingBoutique.gowns.currentIndex);
                $("#product-info-container").html(productDetailsHTML);
                $("#product-lhs").html(productImageHTML);

                $("#product-info-inner").fadeIn(500);
                $("#product-lhs img").fadeIn(500);
            }
        },

        productInfoError: function(errorData) {
            //
        },

		slideShow: {
			playing: false,
			go: function() {
				if(!this.playing) {
					this.playing = true;

					var carouselLength = $("#nav-carousel li").length,
						itemVisible;

					WeddingBoutique.gowns.cycleInterval = window.setInterval(function() {
						if(WeddingBoutique.gowns.currentIndex < carouselLength) {
							// if the slideshow hasn't reached the end of the carousel
                            WeddingBoutique.gowns.captureClick($(WeddingBoutique.gowns.$carouselLi[WeddingBoutique.gowns.currentIndex]).find("a"));
                        } else {
							WeddingBoutique.gowns.currentIndex = 1;
                            WeddingBoutique.gowns.captureClick($(WeddingBoutique.gowns.$carouselLi[WeddingBoutique.gowns.currentIndex-1]).find("a"));
                        }

						itemVisible = false;

						for(var i=0; i<WeddingBoutique.gowns.currentVisible.length; i++) {
							if($(WeddingBoutique.gowns.currentVisible[i]).attr("id") === "i"+WeddingBoutique.gowns.currentIndex) {
								// is the current carousel item visible in the currently displayed collection?
								itemVisible = true;
							}
						}
						if(!itemVisible) {
							// if the current item isn't visible, move the carousel to the appropriate position
							WeddingBoutique.gowns.navInterface.go(Math.min(Math.abs(WeddingBoutique.gowns.currentIndex-WeddingBoutique.gowns.currentVisible.length),WeddingBoutique.gowns.currentIndex-1), false);
						}
					}, 8000);
				}
			},
			stop: function() {
				this.playing = false;
				window.clearInterval(WeddingBoutique.gowns.cycleInterval);
			}
		},

		checkPosition: function(currentItems) {
			//
		},

		getProductInfo: function(pid) {
            ProductService.getSearchableProductInformation(pid, {
                callback: WeddingBoutique.gowns.displayProductInfo,
                timeout: 5000,
                errorHandler: WeddingBoutique.gowns.productInfoError
            });
		},

        stopSlideshow: function() {
            WeddingBoutique.gowns.slideShow.stop();
            $("#play-button").html("<img src='/nap/build_8.13.1/images/wedding_boutique/play.gif' alt='Play' title='Play' /><span class='play-pause-text' id='play-text'>Play slide show</span>");
        },

        startSlideshow: function() {
            WeddingBoutique.gowns.slideShow.go();
            $("#play-button").html("<img src='/nap/build_8.13.1/images/wedding_boutique/pause.gif' alt='Pause' title='Pause' /><span class='play-pause-text' id='pause-text'>Pause slide show</span>");
        },

        captureClick: function(el, e) {
            if(e) {
                e.preventDefault();

                // if the click event was user-generated, it will have a clientX property. Triggered events don't contain this property.
                // this prevents the slideshow from cancelling itself
                if(e.clientX) {
                    if(WeddingBoutique.gowns.slideShow.playing) { WeddingBoutique.gowns.stopSlideshow(); }
                }
            }

            var $elParent = $(el).parent();

            // check if the user has clicked the currently active product link in the carousel
            if(!$elParent.hasClass("current")) {
                $("#product-info-container").html('<div class="ajax-loader"><img src="/nap/build_8.13.1/images/wedding_boutique/ajax-loader.gif" />Loading...</div>');
                $("#product-lhs").html('<div id="product-image-container"><div class="ajax-loader"><img src="/nap/build_8.13.1/images/wedding_boutique/ajax-loader.gif" />Loading...</div></div>');

                WeddingBoutique.gowns.$carouselLi.removeClass("current");
                $elParent.addClass("current");
                WeddingBoutique.gowns.currentIndex = $elParent.attr('id').match(/[0-9]+/)[0];

                WeddingBoutique.gowns.getProductInfo(WeddingBoutique.gowns.getPidFromId($(el).attr('id')));
            }
        },

        init: function() {
            WeddingBoutique.gowns.$carouselLi = $("#nav-carousel li");
            WeddingBoutique.gowns.currentVisible = WeddingBoutique.gowns.navInterface.vis();

            WeddingBoutique.gowns.getProductInfo(WeddingBoutique.gowns.getPidFromId($("#nav-carousel li:first a").attr("id")));

            WeddingBoutique.gowns.$carouselLi.find("a").click(function(e) {
                WeddingBoutique.gowns.captureClick(this, e);
            });

            $(".nav-carousel-nav-button, #nav-carousel-scrollbar").click(function() {
                if(WeddingBoutique.gowns.slideShow.playing) {
                    WeddingBoutique.gowns.stopSlideshow();
                }
            });

            $("#play-button").click(function(e) {
                if(WeddingBoutique.gowns.slideShow.playing) {
                    WeddingBoutique.gowns.stopSlideshow();
                } else {
                    WeddingBoutique.gowns.startSlideshow();
                }
            });

            WeddingBoutique.gowns.startSlideshow();
        }
    }
};
