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

/**
 * initalization for SPP page. Makes initial AJAX request for Product & SKU data,
 * then uses that data to render elements on the page.
 */
bb.page.spp.init = function() {
    if (bb.page.productID.length > 0) {
        var callbackFn = function(mergedProductData, rawProductData) {
            bb.page.spp.renderPage(mergedProductData, rawProductData);
        };
        var fetchDataArgs = {
            productID  : bb.page.productID,
            callback   : callbackFn
        };
        if (bb.page.categoryID && bb.page.categoryID.length > 0) {
                fetchDataArgs.categoryID = bb.page.categoryID;
        }
        bb.page.productView.fetchData(fetchDataArgs);
    }
};

bb.page.spp.renderBreadcrumb = function(categoryData, containerNode) {
    var mppLink = new Element("a", {href: "#", "class":"return"});
    mppLink.setStyle({display:"block",marginBottom:"25px"});
   var sp_name = ''; 
	if (categoryData.breadcrumb_url) {
       mppLink.update(categoryData.DISPLAY_NAME + " 제품리스트로 가기");
			mppLink.href = categoryData.breadcrumb_url;
			// see coremetrics note below
			mppLink.id = 'cm_breadcrumb';
		  var catDisName = categoryData.DISPLAY_NAME;
		  sp_name = catDisName.replace(/\s+/g,'');
    }
    containerNode.insert({"top" : mppLink});
	// kfr: coremetrics needs to throw a tag, this was the only way i could figure
	//	found in ( ~js/coremetricvs/coremetrics.js ) 
	// add an 'id' (above) and call a function to manually toss the tag
	bc_load(sp_name);
};

bb.page.spp.renderPage = function(mergedProductData, rawProductData) {
    var hiddenDivs = [ $$(".info-block")[0], $$(".reviews-area")[0], $$(".product-description")[0] ];
    var productData = mergedProductData[0];
    var callbackFn = function() {
		
		// sets the proper category in global nav to on
		bb.page.setGlobalCat(bb.page.global_cat);
	
        hiddenDivs.each(function(ele){
            if (ele) {
                ele.style.visibility = "visible";
            }
        });
        bb.page.replaceSelects();
        
		var callOutContainerNode = $$(".callout")[0];		
		
		bb.productData.setCallOut(callOutContainerNode,productData);
		
		// sets call out for works well with items
//		var calloutNode = wwwItemWrapperNode.select(".callout")[0];
//        if (bb.productData.isAwardWinning(productData)) {
//            calloutNode.update("Award Winning");
//        } else if (bb.productData.isNew(productData)) {
//            calloutNode.update("New");
//        } else if (bb.productData.isNewShades(productData)) {
//            calloutNode.update("New Shades");
//        } else {
//            calloutNode.hide();
//        }
        var leftColumnNode = productViewContainerNode.select(".product-info")[0];
        var categoryData = null;
        if (rawProductData.category && bb.page.categoryID.length > 1) {
            categoryData = rawProductData.category[bb.page.categoryID];
        }       
        if (categoryData && leftColumnNode) {
            bb.page.spp.renderBreadcrumb(categoryData, leftColumnNode);
        }
        productReviewArgs = {
            containerNode : productViewContainerNode,
            productData              : productData
        };
        bb.page.productView.initReviews(productReviewArgs);

    };
    var productViewContainerNode = $$("div.prod-details")[0];
    var productViewArgs = {
        descriptionContainerNode : productViewContainerNode,
        productData              : productData,
        postRenderCallback       : callbackFn
    };
    bb.page.productView.initDescription(productViewArgs);
    bb.page.spp.initWorksWellWith(productData);

	

	bb.page.spp.initFeatureContent(productData);

	$$(".loading-container")[0].style.display = "none";

};

bb.page.spp.initFeatureContent = function(productData) {
    switch (productData.SPP_FEATURE_TEMPLATE) {
        case "tips":
            bb.page.spp.renderTipsPane(productData);
            break;
        case "video":
            bb.page.spp.renderVideoPane(productData);
            break;
        default:
            break;
    }
};

bb.page.spp.renderTipsPane = function(productData) {
    var containerNode = $$(".feature-content-container")[0];
    var hasTip = function(id) {
        var tipFound = true;
        var fieldPrefix = "TIP" + id + "_";
        var checkFields = function(fieldNameSuffixArray) {
            var hasValue = false
            for (var i=0, len=fieldNameSuffixArray.length; i<len; i++) {
                var fieldValue = productData[fieldPrefix + fieldNameSuffixArray[i]];
                hasValue = hasValue || (fieldValue && fieldValue.length && fieldValue.length > 0);
            }
            return hasValue;
        }
        tipFound = checkFields(["LINK", "IMAGE", "HEADLINE", "DESCRIPTION"]);
        return tipFound;
    }

    bb.templateFactory.get("spp-feature-tips").evaluateCallback({
        object: productData,
        callback: function(html) {
            containerNode.update(html);
            if (hasTip(1)) {
                var hdr = containerNode.select("#tips-headline-1")[0];
                if (hdr) {
                    if (productData.TIP1_LINK) {
                        var lnk = new Element("a", {href:productData.TIP1_LINK});
                        lnk.update(productData.TIP1_HEADLINE);
                        hdr.update(lnk);
                    } else {
                        hdr.update(productData.TIP1_HEADLINE);
                    }
                }
                bb.sIFR.replaceAll();
            } else {
                var tipContainerNode = containerNode.select("#tip-container-1")[0];
                if (tipContainerNode) {
                    tipContainerNode.style.visibility = "hidden";
                }
            }
            if (hasTip(2)) {
                var hdr = containerNode.select("#tips-headline-2")[0];
                if (hdr) {
                    if (productData.TIP2_LINK) {
                        var lnk = new Element("a", {href:productData.TIP2_LINK});
                        lnk.update(productData.TIP2_HEADLINE);
                        hdr.update(lnk);
                    } else {
                        hdr.update(productData.TIP2_HEADLINE);
                    }
                }
            } else {
                var tipContainerNode = containerNode.select("#tip-container-2")[0];
                if (tipContainerNode) {
                    tipContainerNode.style.visibility = "hidden";
                }
            }
            
        }
    });
};

bb.page.spp.renderVideoPane = function(productData) {
    console.log(productData);
    var containerNode = $$(".feature-content-container")[0];
    bb.templateFactory.get("spp-feature-video",false,"tmpl").evaluateCallback({
        object: productData,
        callback: function(html) {
            containerNode.update(html);
            // load SWF
            var swfParams = {
                allowFullScreen : "true",
//                 menu  : "false",
                wmode : "opaque"
//                 scale : "noscale"
            };
            var swfVars = {
                width  : "467",
                height : "310",
                productName : productData.PRODUCT_NAME,
                xmlPath : productData.VIDEO_FILE
            };
            swfobject.embedSWF(
                "/media/flash/videoplayer/BobbiBrownVideoPlayerSPP.swf",
                "spp-video-container",
                "467",
                "310", 
                "9.0.124",
                "expressInstall.swf",
                swfVars,
                swfParams );
       }
    });
};


bb.page.spp.initWorksWellWith = function(productData) {
    var wwwIDs = [];
    [ productData.WORKS_WITH_1, productData.WORKS_WITH_2 ].each( function(wwwID) {
        if (wwwID) {
            wwwIDs.push(wwwID);
        }
    });
    var jsonrpcArgs = {
        method : "prodcat.byid",
        params : [{
            "product": wwwIDs,
            "product_fields": bb.page.productView.productFields,
            "sku_fields": bb.page.productView.skuFields
        }],
        onSuccess: function(response) {
            var responseObj = response.responseText.evalJSON(true);
            if (responseObj[0].error === null) {
                var rawProductData = responseObj[0].result;
                if (typeof rawProductData === "object") {
                    var mergedProductData = bb.productData.mergeSkusIntoProducts(rawProductData.product, rawProductData.sku);
					if (mergedProductData == "") {
						var relatedNode = $$(".related")[0];
						relatedNode.style.display="none";
					} else {
                    	bb.page.spp.renderWorksWellWith(mergedProductData);
					}
                }
            } else {
                console.log(responseObj[0].error);
            }
        }
    };
    bb.JSONRPC.fetch(jsonrpcArgs);
};

bb.page.spp.renderWorksWellWith = function(productDataArray) {
    var wwwContainerNode = $$("div.related ul")[0];
    if (wwwContainerNode) {
        productDataArray.each(function(productData) {
            //console.log(productData);
                                //CoreMetrics QV and VC override for url because it is being used as a WW
				addMppTag(productData.PRODUCT_ID,productData.PRODUCT_NAME,productData.PARENT_CAT_ID,"ww");
                                productData.url = productData.url;

				productData.priceString = bb.productData.formatPriceRange(productData);
            var wwwItemWrapperNode = new Element("div", {"class":"related-item-wrapper"});
            productData.imagePath = bb.page.PRODUCT_IMG_PATH + productData.IMAGE_NAME + "_s.jpg";
            bb.templateFactory.get("works-well-thumb").evaluateCallback({
                object: productData,
                callback: function(html) {
                    wwwItemWrapperNode.insert(html);
                    wwwContainerNode.insert(wwwItemWrapperNode);
                    var quickshopLink = wwwItemWrapperNode.select(".quickshop-link")[0];
					
					// sets call out for works well with items
					var callOutNode = wwwItemWrapperNode.select(".works-well-callout")[0];
					
					bb.productData.setCallOut(callOutNode,productData);
					
                	// if (bb.productData.isAwardWinning(productData)) {
//                     	calloutNode.update("Award Winning");
//                 	} else if (bb.productData.isNew(productData)) {
//                     	calloutNode.update("New");
//                 	} else if (bb.productData.isNewShades(productData)) {
//                     	calloutNode.update("New Shades");
//                 	} else {
//                     	calloutNode.hide();
//                 	}
					
                    bb.page.productView.initQuickshopLink(quickshopLink, productData);
                }
            });
        });
    }
};


//bb.page.productView.initBazaarVoice = function(productData) {
bb.page.productView.initReviews = function(args) {
    
    bb.templateFactory.get("ratings").evaluateCallback({
        object   : args.productData,
        callback : function(html) {
            var rvwContainer = args.containerNode.select(".reviews-dynamic")[0];
            rvwContainer.insert(html);

            var bvstaging = window.URL_DOMAIN.match(/dev/) || window.URL_DOMAIN.match(/stage/) ? 'bvstaging/' : '';

            var iframeSrc = "http://reviews.bobbibrown.co.kr/" + bvstaging + "3816-ko_kr/" +
                    args.productData.PRODUCT_ID +
                    "/reviews.htm?format=embedded";
            var bvIframe = new Element("iframe", {
                id   : "BVFrame",
                name : "BVFrame",
                src	 : iframeSrc
            });
            bvIframe.setStyle({
                visibility : "hidden",
                width      : "1px",
                height     : "1px",
                position   : "absolute",
                left       : "-999px",
                top        : "-999px"
            });
            $(document.body).insert(bvIframe);
        	//
        	// confirm that BV reviews loaded into the iFrame
        	// if not, redirect the iframe to the logging URL
            window.BVisLoaded = false;
            bvIframe.observe('load', function() {
                if (!window.BVisLoaded) {
                    var ele = document.getElementById("BVFrame");
                    if (ele) {
                        var page = ele.src;
                        ele.src='http://reviews.bobbibrown.co.kr/logging?page=' + escape(page);
                    }
                }
        	});
        }
    });
 

};


