bb.page.mpp = {};

var franchiseCategories = ["CATEGORY22793","CATEGORY22957","CATEGORY22760","CATEGORY21935","CATEGORY21925","CATEGORY21923","CATEGORY21926","CATEGORY21939","CATEGORY21922","CATEGORY21938","CATEGORY21941","CATEGORY21937","CATEGORY22757","CATEGORY21964","CATEGORY21936", "CATEGORY21968", "CATEGORY22009","CATEGORY22082","CATEGORY22081","CATEGORY22118","CATEGORY22131","CATEGORY22761","CATEGORY22147","CATEGORY22212","CATEGORY22247","CATEGORY22625","CATEGORY22626","CATEGORY22670","CATEGORY22671","CATEGORY20618","CATEGORY22822","CATEGORY22801","CATEGORY22869","CATEGORY22866","CATEGORY23960"];
bb.page.mpp.headerImageLinks = {
	CATEGORY22761: [{
		top   :	273,
		left  : 691,
		width : 211,
		height: 32,
		href  : "/learn/video.tmpl?video=G09_foundation"
	}, {
		top   :	203,
		left  : 49,
		width : 199,
		height: 26,
		href  : "/learn/perfect_skin.tmpl"
	}],
	CATEGORY22670: [{
		top   :	190,
		left  : 200,
		width : 171,
		height: 22,
		href  : "/learn/video.tmpl?video=G09_chrome"
	}],
	CATEGORY23960: [{
		top   :	275,
		left  : 235,
		width : 111,
		height: 22,
		href  : "/learn/video.tmpl?video=S10_brightening"
	}]
};

// Test to see if mpp page is Sample Category
bb.page.mpp.isSampleCat = function() {
	var samplePage = false;
	if (bb.page.categoryID == 'CATEGORY20618')
		samplePage = true;
		
	return samplePage;
}

document.observe("dom:loaded", function() {
    bb.page.mpp.init();
});

bb.page.mpp.init = function() {
    var rawProductData = bb.page.mpp.categoryData[0];
    var mergedProductData = bb.productData.mergeSkusIntoProducts(rawProductData.product, rawProductData.sku);
	
	// sets the proper category in global nav to on
	bb.page.setGlobalCat(bb.page.global_cat);
	
	var isFranchise = false;
	
	//runs through franchise array to check if cat is a franchise cat
	franchiseCategories.each(function(i) {
  		if (bb.page.categoryID == i) {
			isFranchise = true;	
		} 
	});
	
	//if it is a franchise page, display franchise format.  if not, display regular format
	if (isFranchise) {
		bb.page.mpp.franchise(mergedProductData);
	} else {
		bb.page.mpp.renderPage(mergedProductData);
	}
};

bb.page.mpp.renderPage = function(mergedProductData) {
    
	var productDataArray = bb.page.mpp.sortProducts(mergedProductData);
	
	$$(".franchise_area")[0].setStyle({display:"none"});
    var containerNode = $$(".whatsnew-area")[0];
    var rowOuterContainer = $$(".products_block")[0];
    var rowInnerContainer = new Element ("div", {"class":"content products"});
    rowOuterContainer.insert(rowInnerContainer);
     productDataArray = productDataArray.findAll(function(productData) {
         return bb.productData.isProductShoppable(productData);
     });

    // iterate through the products in the category
    productDataArray.each(function(productData, idx) {
        if (idx > 2) {
            if ( (idx + 1) % 4 === 0 ) {
//                rowInnerContainer.style.visibility = "visible";
                rowOuterContainer = new Element ("div", {"class":"whatsnew-block", style:"visibility:hidden"});
                rowInnerContainer = new Element ("div", {"class":"content products"});
                rowOuterContainer.insert(rowInnerContainer);
                containerNode.insert(rowOuterContainer);
            }
        }

        bb.page.mpp.loadProducts (productData,rowInnerContainer);   
    }); // end iterating through products 
    //
    // display category-specific Quote image
    if (bb.page.categoryID && bb.page.categoryID.length > 0) {
        var quoteContainerNode = $$("div.products_area div.quote")[0];
        if (quoteContainerNode) {
            var categoryIDnumber = bb.page.categoryID.substring(8, bb.page.categoryID.length);
            var imgSrc = "/images/products/quotes/" + categoryIDnumber + ".gif";
            var img = new Element("img", {src: imgSrc} );
            quoteContainerNode.update(img);
        }
    }
	
	bb.page.mpp.displayProducts();
};


bb.page.mpp.franchise = function(mergedProductData) {
    
	var productDataArray = bb.page.mpp.sortProducts(mergedProductData);
    
	var containerNode = $$(".whatsnew-area")[0];
	var rowOuterContainer = null;
	var rowInnerContainer = null;
	
    productDataArray = productDataArray.findAll(function(productData) {
        return bb.productData.isProductShoppable(productData);
    });
	
    // iterate through the products in the category
    productDataArray.each(function(productData, idx) {
            if (idx % 4 === 0) {
//                rowInnerContainer.style.visibility = "visible";
                rowOuterContainer = new Element ("div", {"class":"whatsnew-block", style:"visibility:hidden"});
				
                rowInnerContainer = new Element ("div", {"class":"content products"});
				
				// on first pass, insert the header container
				if (idx < 4) {
					headerContainer = new Element ("div", {"class":"header-block"});
					rowInnerContainer.insert(headerContainer);
				}
				
                rowOuterContainer.insert(rowInnerContainer);
                containerNode.insert(rowOuterContainer);
            }

        bb.page.mpp.loadProducts (productData,rowInnerContainer);
    }); // end iterating through products 
    //
    // display category-specific Quote and header image
    if (bb.page.categoryID && bb.page.categoryID.length > 0) {
		$$("div.products_area div.quote")[0].setStyle({display:"none"});
		$$(".products_area")[0].setStyle({background:"none",margin:"0",padding:"0"});
        var franchiseContainerNode = $$(".franchise_area")[0];
        if (franchiseContainerNode) {
            var categoryIDnumber = bb.page.categoryID.substring(8, bb.page.categoryID.length);
            var imgSrc = "/images/products/collections/imgs/" + categoryIDnumber + ".jpg";
            var img = new Element("img", {src: imgSrc, "class": "franchise-image"} );
            franchiseContainerNode.update(img);

			var linksArray = bb.page.mpp.headerImageLinks[bb.page.categoryID];
			if (linksArray) {
				linksArray.each( function(linkObj) {
					var styleString = "top:" + linkObj.top + "px; left:" + linkObj.left + "px;";
					var linkEle = new Element("a", {
						href   : linkObj.href,
						"style": styleString,
						"class": "franchise-image-link"
					});
					styleString = "width:" + linkObj.width + "px; height:" + linkObj.height + "px;";
					var imgEle = new Element("img", {
						src    : "/images/global/transparent.gif",
						"style": styleString
					});
		            franchiseContainerNode.insert(linkEle);
		            linkEle.update(imgEle);
				});
			}
        }
		
		var franchiseHeaderNode = $$(".header-block")[0];
		if (franchiseHeaderNode && !bb.page.mpp.isSampleCat()) {
			var categoryIDnumber = bb.page.categoryID.substring(8, bb.page.categoryID.length);
			var categoryDisplayName = bb.page.categoryName;
            var imgSrc = "/images/products/collections/headers/" + categoryIDnumber + ".gif";
            var img = new Element("img", {src: imgSrc} );
            franchiseHeaderNode.update(img);
		}
    }
	
	bb.page.mpp.displayProducts();
};

bb.page.mpp.sortProducts = function(mergedProductData) {
	var productDataArray = mergedProductData;
    // sort the products
    productDataArray = productDataArray.sortBy(function(productData){
//		console.log(productData.DISPLAY_ORDER)
        return productData.DISPLAY_ORDER;
    });
    /*Commented out since Display Order will only determine the order
	productDataArray = productDataArray.sortBy(function(productData){
        return bb.productData.isNew(productData);
    });
    productDataArray = productDataArray.sortBy(function(productData){
        return bb.productData.isAwardWinning(productData);
    });*/
	
	return productDataArray;
}

bb.page.mpp.loadProducts = function(productData,rowInnerContainer) {
	productData.priceString = bb.productData.formatPriceRange(productData);

//        productData.url = "/templates/products/spp/index.tmpl?PRODUCT_ID=" + productData.PRODUCT_ID;
//        if (bb.page.categoryID.length > 0) {
//            productData.url += "&CATEGORY_ID=" + bb.page.categoryID;
//        }

        productData.url = bb.productData.convertProductURL(productData.url);
        productData.description = bb.productData.truncateDescription(productData.DESCRIPTION, productData.url);
        
        productData.imagePath = bb.page.PRODUCT_IMG_PATH + productData.IMAGE_NAME + "_m.jpg";
        var average_rating = productData.AVERAGE_RATING;
        var review_count = productData.TOTAL_REVIEW_COUNT;
	 var recommended_percent = productData.RECOMMENDED_PERCENT;
        var ratings = productData.ONLY_RATINGS_COUNT;
        var prodattributes = average_rating + "-_-" +review_count+ "-_-" +recommended_percent+ "-_-" +ratings;
        //console.log(bb.page.categoryID);
        addMppTag(productData.PRODUCT_ID,productData.PRODUCT_NAME,bb.page.categoryID,prodattributes);
		  
        var templt_args = { url_domain : window.URL_DOMAIN };
        
        templt_args.ratingReviewString = productData.TOTAL_REVIEW_COUNT > 1 ? 'Reviews' : 'Review';
        templt_args.ratingDisplay = typeof productData.AVERAGE_RATING == 'number' && isFinite(productData.AVERAGE_RATING) ? 'block' : 'none';
        templt_args.ratingRounded = Math.round(productData.AVERAGE_RATING*10)/10;
		  
        Object.extend(productData, templt_args);
		
        bb.templateFactory.get("product-thumb").evaluateCallback({
            object: productData,
            callback: function(container, productData, html) {
                var wrapperNode = new Element("div");
                container.insert(wrapperNode);
                wrapperNode.insert(html);

                var callOutNode = wrapperNode.select(".callout")[0];
				
				bb.productData.setCallOut(callOutNode,productData);
				
				var quickshopLinkNode = wrapperNode.select("a.open-product-1")[0];
				var infoNode = wrapperNode.select("div.info")[0];
				// Checks to see if this is sample category.  If so, remove quickshop, price and shop now.
				if (bb.page.mpp.isSampleCat()) {
					var linkNode = quickshopLinkNode.select('span')[0];
                	linkNode.setStyle({'display':'none'});
                	var priceNode = infoNode.select('.price')[0];
                	priceNode.setStyle({'display':'none'});
                	var shopNowNode = infoNode.select('.shopnow')[0];
                	shopNowNode.setStyle({'display':'none'});
                } else {
                	bb.page.productView.initQuickshopLink(quickshopLinkNode, productData);
                }
                
                var parentContainerNode = container.parentNode;
                $(parentContainerNode).setStyle({visibility :"visible"});
			
            }.curry(rowInnerContainer, productData)
        });
};

bb.page.mpp.displayProducts = function() {
	//once products are loaded, the following divs are showing
	$$(".loading-container")[0].style.display = "none";
    var productAreaArray = [$$(".products_area")[0], $$(".whatsnew-area")[0], $$(".sec_content")[0], $$(".products_container")[0]];
	productAreaArray.each(function(s) {
		s.setStyle({display :"block"});
	});
}
