﻿//var sPageName;

function centerDeptBanner(jqObj) {
	if (jqObj.length > 0) {
		jqObj.each(function(index, elem) {
			var elemObj = $(elem),
				oldSize = elemObj.height(),
				newSize = 0;
			
			if ((oldSize != 0) && (oldSize < 300)) {
				newSize = Math.ceil((300 - oldSize) / 2);
				elemObj.css("padding-top", newSize + "px");
			} else {
				elemObj.css("padding-top", 5 + "px");
			}
		});
	}
}

var bundleSaving = {
    'B9001272': '550.00',
    'B9002776': '1100.00',
    'B9002777': '110.00',
    'B9002781': '525.00',
    'B9002783': '170.00',
    'B9002784': '280.00',
    'B9002785': '125.00',
    'B9002786': '175.00',
    'B9002664': '80.00',
    'B9002673': '50.00',
    'B9002778': '45.00',
    'B9002779': '45.00',
    'B9002780': '45.00',
    'B9002782': '148.00',
    'B9002763': '100.00',
    'B9002660': '150.00',
    'B9002409': '95.00',
    'B9002410': '95.00',
    'B9002792': '95.00',
    'B9002788': '55.00',
    'B9002789': '55.00',
    'B9002790': '55.00',
    'B9002783': '90.00',
    'B9002793': '58.00',
    'B9002794': '58.00',
    'B9002795': '58.00',
    'B9002798': '80.00',
    'B9002797': '98.00'

}

$(document).ready(function() {

    var pageFR = ($('html').attr('lang') == 'fr-CA') ? true : false;

    $('.c1, .c2, .a2, .c4, .a3, .a6').each(function() {
        var o = $(this);

        var sku = String(o.find('.prodImage img').attr('src').match(/[a-zA-Z0-9^.]+.jpg/gi)).replace(/.jpg/, '');
        if (sku && sku.charAt(0) == 'B') {
            var saving = bundleSaving[sku];
            if (saving && o.find('.details.save').length == 0) {
                o.find('.priceblock').addClass('sale').after('<p class="details save">' + (pageFR?'Épargnez : '+saving.replace('.',',')+' $':'Save: $' + saving) + '</p>');
            }
        }

    });

    Sys.Application.add_load(function() {
        $(".ta3").each(function() {
            attachtracking($(this));
        });
        $(".ta1").each(function() {
            attachtracking($(this));
        });
        $(".ta2").each(function() {
            attachtracking($(this));
        });
    });

    // GeekSquad attribute glossary
    $(".price-holder").append('<div id="glossaryPopover"></div>');
    var i = 0;
    $(".price-holder .attributes .info a").each(function() {
        var tempLink = $(this).attr("href");
        $(this).attr("href", "#");
        $(this).after('<div class="glossary"></div>');
        $(this).parent().find(".glossary").load(
            tempLink.substring(tempLink.indexOf("'") + 1,
            tempLink.lastIndexOf("'") - 4) + " .content .std-topspace");

        $(this)
            .click(function() { return false; })
            .hover(function() {

                var tempGlossary = $(this).parent().find(".glossary").html();
                if (tempGlossary != "") {
                    $("#glossaryPopover")
                    .html(tempGlossary)
                    .show();
                }
            }, function() {
                $("#glossaryPopover").hide();
            })
            .mousemove(function(e) {
                $("#glossaryPopover").css({
                    top: e.pageY - 20,
                    left: e.pageX + 20
                });
            });

    });

    // GeekSquad attribute pricing
    $(".price-holder .attributes .pricing span").each(function() {
        if ($(this).html() == "Included" || $(this).html() == "Inclus") {
            $(this).addClass("checked");
        }
        if ($(this).html() == "Not Included" || $(this).html() == "Non inclus") {
            $(this).html("");
        }
    });

    // GeekSquad Dept widgets
    $(".geeksquad-deptpromo .items ol li a").hover(function() {
        $("." + $(this).parent().attr("class") + " a").addClass("over");
    }, function() {
        $("." + $(this).parent().attr("class") + " a").removeClass("over");
    }).click(function() {
        $(".geeksquad-deptpromo .detailpanel .content").hide();
        $(".geeksquad-deptpromo .detailpanel ." + $(this).parent().attr("class") + "-content").show();
        $(".geeksquad-deptpromo .detailpanel").animate({
            top: 0
        }, 500, function() {
        });
        return false;
    });
    $(".geeksquad-deptpromo .detailpanel .btnClose").click(function() {
        $(".geeksquad-deptpromo .detailpanel").animate({
            top: 199
        }, 500, function() {
        });
        return false;
    });
    $(".geeksquad-deptpromo .tooltips li a").hover(function() {
        $("." + $(this).parent().attr("class") + " a").addClass("over");
    }, function() {
        $("." + $(this).parent().attr("class") + " a").removeClass("over");
    }).click(function() {
        $(".geeksquad-deptpromo .items ol li." + $(this).parent().attr("class") + " a").click();
        return false;
    });


    $(".ui-tabcontrol").each(function() {
        var tab = new ui.TabControl($(this), function(that, index) {
            if (that.contents.children().eq(index - 1).children("[id!='']:first-child").length > 0) {
                var id = that.contents.children().eq(index - 1).children(":first-child").attr("id");
                $("#" + id + " .prod-orient-ver").removeAttr("style");
                JsLib.UI.equaliseBoxesHeightByClassNameInsideElement('prod-orient-ver', id);
            }
            centerDeptBanner($(".prod-orient-hor", "#" + that.contents.children().eq(index - 1).attr("id")).find(".prodDetails"));
        });
    });
});

var pluginCatContent = function(labelID, boardID, container, args) {
    args = args || {};
    var sortableArray = new Array();

    var populateArray = function(json) {
        if (json.response.threads)
        $(json.response.threads.thread).each(function() {
            sortableArray.push({
                subject: this.messages.topic.subject.$,
                href: this.view_href,
                authorLink: this.messages.topic.author.view_href,
                authorID: this.messages.topic.author.login.$,
                date: this.messages.topic.post_time.view_date,
                sortDate: this.messages.topic.post_time.$
            })
        })
    }

    var SortTwoDimensional = function(a, b) {
        return ((a.sortDate < b.sortDate) ? -1 : ((a.sortDate > b.sortDate) ? 1 : 0));
    }

    $.getJSON('/projects/community/ajaxrespond.aspx?src=BBYC-group-label&id=' + labelID, function(json) {
        populateArray(json);
        $.getJSON('/projects/community/ajaxrespond.aspx?src=BBYC-group-forum&id=' + boardID, function(json2) {
            populateArray(json2)
            sortableArray.sort(SortTwoDimensional);
            if (sortableArray.length > 0) {
                var wrapper = $('<ul></ul');
                $(sortableArray).each(function() {
                    var item = "";
                    if (this.subject != "") {
                        item = "<li><a class='subject' href='" + this.href + "' title='" + this.subject + "'>" + this.subject + "</a>"
                            + "<div class='info'>" + (args.subtext ? args.subtext : "") + "</div></li>"
                    }
                    item = item.replace(/\{var1\}/i, this.authorLink).replace(/\{var2\}/i, this.authorID).replace(/\{var3\}/i, this.date);
                    wrapper.prepend(item);
                })
                wrapper.appendTo(container);
            }
        })
    })
}

function attachtracking(obj) {
    $(obj).find("a[href*=product]").each(function() {

        // Get language
        var url = $(this).attr("href");
        var lang = url.match(/(en|fr)-CA/gi)[0].replace("-CA", "");

        // Get Sku
        var sku = url.substring(url.lastIndexOf('/') + 1);
        sku = sku.substring(0, sku.lastIndexOf('.'));

        // Get Title
        var titlearr = url.split("/");
        var title = (titlearr.length > 3) ? titlearr[3].replace(/\-/g, "") : "";

        // Get homepage accordion tab
        //var homepagetab = "";
        //homepagetab = $(".acc-tabs .tab-selected a").text().replace(/\W/gi, "");
        //homepagetab = (homepagetab != "") ? "-tab:" + homepagetab : "";
        
        //sPageName = (sPageName == "home" || sPageName == "accueil") ? "home" : sPageName;
        //$(this).attr("href", url + "&lid=fp-" + sku + "-" + title + "-" + lang);
        $(this).attr("href", url + "&lid=fp-" + sku + "-" + title.slice(0, 30) + "-" + lang);

        //$(this).click(function() {        
        //    trackEvent.event('event.link', { lid: "fp-" + sku + "-" + title.slice(0, 20) + "-" + lang });
        //});
    });
}

// Param: ext - Keep file extension or not
function getPageName(ext) {
    ext = typeof (ext) != 'undefined' ? ext : false;

    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    if (!ext) {
        sPage = sPage.substring(0, sPage.lastIndexOf('.'));
    }
    return sPage;
}

/* BUBBLE */
(function($) {
    $.fn.Bubble = function(args) {
        var defaults = {
            hoverFade: true, // Fade out other bubbles on hover true/false | default: true
            opacityIn: 1,
            opacityOut: 0.5,
            speedIn: 'fast',
            speedOut: 'fast'
        };

        args = $.extend(defaults, args);
        var Bubbles = this;
		var IE = $.browser.msie;
		
		if(IE) {
			Bubbles.show();
		} else {
			Bubbles.fadeIn('slow');
		}

        return Bubbles.each(function() {
            var obj = $(this);

            obj.addClass('ui-bubble');

            obj.wrapInner('<div class="ui-bubbleInsert" />');
            obj.wrapInner('<div class="ui-bubbleContent" />');
            obj.prepend('<div class="ui-indicator"></div>');
            var allIndicators = $(Bubbles).find('.ui-indicator');

            obj.hover(function() {
				var _this = $(this);
				
				var posX = (_this.position()).left,
					posY = (_this.position()).top,
					curWidth = _this.parent().width(),
					curHeight = _this.parent().height(),
					bubbleContentObj = _this.find('.ui-bubbleContent'),
					curBubbleWidth = bubbleContentObj.width(),
					curBubbleHeight = bubbleContentObj.height(),
					padding = 50;
				
				// MOVE BUBBLE SCRIPT					
		        if ((posX + curBubbleWidth + padding) > curWidth) {
		            bubbleContentObj.css('left', (-1 * curBubbleWidth));
		        }
		        if ((posY + curBubbleHeight + padding) > curHeight - 50) {
		            bubbleContentObj.css('top', (-1 * curBubbleHeight));
		        }
				
                _this.css('z-index', '2000');
                _this.find('.ui-bubbleContent').fadeIn(args.speedIn);

                if (args.hoverFade) { // if hoverFade = false - don't bother
                    _this.find('.ui-indicator').addClass('hover');

                    allIndicators.each(function() {
                        var curInd = $(this);
                        if (!curInd.hasClass('hover')) {
                            if (IE) {
                                curInd.stop().hide();
                            } else {
                                curInd.stop().animate({ opacity: args.opacityOut }, args.speedOut);
                            }
                        }
                    });
                }
            }, function() {
                var _this = $(this);
                _this.find('.ui-bubbleContent').fadeOut(args.speedOut);
                _this.css('z-index', '170');

                if (args.hoverFade) {
                    if (IE) {
                        allIndicators.removeClass('hover').stop().show();
                    } else {
                        allIndicators.removeClass('hover').stop().animate({ opacity: args.opacityIn }, args.speedIn);
                    }
                }
            });
        });
    };
})(jQuery);
