﻿
$(function () {
    // show ribbon bar
    if ($('#siteactiontd').text().trim().length != 0) {
        $('.ribbonbackground').show();
    }

    HandleExternalLinks();

    InitSocialBar();

    //AttachLeftNavEvents();

    //SwitchHeroSlider(1);
});

/* Begin Lightbox */
ShowVideoLightbox = function (uuid, isFullScreen) {
    var reg = new RegExp('^https?://([^/]+)((/[^/]+){2}).*$', 'i');
    var match = reg.exec(location.href);
    if (match != null) {
        var url = match[2] + '/_layouts/Canviz/Showcase.aspx?v=' + uuid + '&f=' + (isFullScreen ? '1' : '0');
        ShowLightbox(url, null, 863, 539);
    }
}

ShowLightbox = function (url, title, width, height) {
    _ensureLightboxDOM();

    var bodyHeight = height - 32;
    $('#lightboxTitle').html(title);
    /*    $('.bpio-lightbox-framewrapper').css('width', width + 'px');
    $('.bpio-lightbox-framewrapper').css('height', bodyHeight + 'px');*/
    $('#lightboxFrame').attr('src', url);
    $('#lightboxFrame').css('width', width + 'px');
    $('#lightboxFrame').css('height', bodyHeight + 'px');

    $.blockUI({
        message: $('#bpioLightbox'),
        css: {
            top: ($(window).height() - height) / 2 + 'px',
            left: ($(window).width() - width) / 2 + 'px',
            width: width + 'px',
            height: height + 'px',
            border: 'none'
        }
    });
}

_ensureLightboxDOM = function () {
    if ($('#bpioLightbox').length == 0) {
        var html = '<div style="display:none">';
        html += '<div id="bpioLightbox">';
        html += '<div class="bpio-lightbox-header">';
        html += '<span id="lightboxTitle"></span>';
        html += '<img id="lightboxCloseBtn" border="0" src="/businessproductivity/PublishingImages/CloseDialog.png"/>';
        html += '</div>';
        html += '<div class="bpio-lightbox-framewrapper"><IFRAME id="lightboxFrame" frameBorder="0"></IFRAME></div>';
        html += '</div>';
        html += '</div>';

        $('body').append(html);

        $('#lightboxCloseBtn').click($.unblockUI);
    }
}
/* End Lightbox <<< */


/* Begin Home Hero */
var currentIndex = -1;
var expandedSlideIndex = -1;
var headerWidth = 27;
var frameCount = 50;
var frameDuration = 1;
var autoSlidesDuration = 5000;
var fadeInDuration = 1000;
var headerBgColorArray = ['#EAA000', '#E57700', '#E36200'];

var autoSlidesTimeout;
var expandSlideByPieceTimeout;

var bodyWidth;
var frameWidth;
var inprogress = false;

InitSlides = function (defaultIndex) {
    InitShowcaseVideos();

    SwitchHeroSlider(defaultIndex);

    if ($('#WhyMSHero,#GoogleHero').length > 0) {
        autoSlidesTimeout = setTimeout(AutoSwitch, autoSlidesDuration);
    }

    $('#WhyMSHero,#GoogleHero').hover(
		function (e) {
		    if (autoSlidesTimeout != null) clearTimeout(autoSlidesTimeout);
		},
		function (e) {
		    autoSlidesTimeout = setTimeout(AutoSwitch, autoSlidesDuration);
		}
	);
}

AutoSwitch = function () {
    if (expandedSlideIndex == -1 || expandedSlideIndex == $('#WhyMSHero li,#GoogleHero li').length - 1) {
        SwitchHeroSlider(0);
    }
    else {
        SwitchHeroSlider(expandedSlideIndex + 1);
    }

    autoSlidesTimeout = setTimeout(AutoSwitch, autoSlidesDuration);
}

SwitchHeroSlider = function (index, cancelSwitch) {
    if (cancelSwitch) {
        if (expandSlideByPieceTimeout) clearTimeout(expandSlideByPieceTimeout);

        // Ensure the variable index reflects the correct slide.
        index = expandedSlideIndex;
        // 
        expandedSlideIndex = currentIndex;
    }
    else if (inprogress) {
        return;
    }

    inprogress = true;
    bodyWidth = Math.ceil($('#HomeHero ul,#WhyMSHero ul,#GoogleHero ul').width() - ($('#HomeHero li,#WhyMSHero li,#GoogleHero li').length - 1) * headerWidth);
    frameWidth = Math.ceil(bodyWidth / frameCount);

    currentIndex = index;

    if (expandedSlideIndex == -1) {
        $('#HomeHero li,#WhyMSHero li,#GoogleHero li').width(headerWidth);

        $('.bpio-heroslides-itemHeader').eq(currentIndex).hide();

        $('#HomeHero li,#WhyMSHero li,#GoogleHero li').eq(currentIndex).width(bodyWidth);
        $('.bpio-heroslides-itemBody').eq(currentIndex).width(bodyWidth);

        expandedSlideIndex = currentIndex;

        SetSlideHeaderArrow();
        SetSlideHeaderBg();
        inprogress = false;
    }
    else {
        if (expandedSlideIndex < currentIndex) {
            $('.bpio-heroslides-itemHeader').eq(currentIndex).css('float', 'left');
            $('.bpio-heroslides-itemBody').eq(currentIndex).css('float', 'left');
        }
        else if (expandedSlideIndex > currentIndex) {
            $('.bpio-heroslides-itemHeader').eq(currentIndex).css('float', 'right');
            $('.bpio-heroslides-itemBody').eq(currentIndex).css('float', 'right');
        }

        expandSlideByPieceTimeout = setTimeout(ExpandSlideByPiece, frameDuration);
    }

    if (!cancelSwitch) {
        $('.bpio-heroslides-itemBody').eq(currentIndex).find('img').hide();
        $('.bpio-heroslides-itemBody').eq(currentIndex).find('img').fadeIn(fadeInDuration);
    }
}

ExpandSlideByPiece = function () {
    var expandedItem = $('#HomeHero li,#WhyMSHero li,#GoogleHero li').eq(expandedSlideIndex);
    var currentItem = $('#HomeHero li,#WhyMSHero li,#GoogleHero li').eq(currentIndex);
   
    var expandedHeaderWidth = expandedItem.children('.bpio-heroslides-itemHeader').css('display') == 'none' ? 0 : headerWidth;
    var currentHeaderWidth = currentItem.children('.bpio-heroslides-itemHeader').css('display') == 'none' ? 0 : headerWidth;
   
    var expandedBodyWidth = expandedItem.children('.bpio-heroslides-itemBody').width();
    var newExpandedBodyWidth = Math.max(0, expandedBodyWidth - frameWidth);
    var newCurrentBodyWidth = bodyWidth - newExpandedBodyWidth;

    if (expandedBodyWidth > 0) {
        expandedItem.children('.bpio-heroslides-itemBody').width(newExpandedBodyWidth);
        expandedItem.width(newExpandedBodyWidth + expandedHeaderWidth);

        currentItem.children('.bpio-heroslides-itemBody').width(newCurrentBodyWidth);
        currentItem.width(newCurrentBodyWidth + currentHeaderWidth);

        expandSlideByPieceTimeout = setTimeout(ExpandSlideByPiece, frameDuration);
    }
    else {
        expandedItem.children('.bpio-heroslides-itemHeader').show();
        expandedItem.width(headerWidth);

        currentItem.children('.bpio-heroslides-itemHeader').hide();
        currentItem.width(newCurrentBodyWidth);

        expandedSlideIndex = currentIndex;

        SetSlideHeaderArrow();
        SetSlideHeaderBg();

        ResetShowcaseVideo(expandedItem);

        inprogress = false;
    }
}

SetSlideHeaderArrow = function () {
    var leftArrows = $('.bpio-heroslides-leftArrow');
    var rightArrows = $('.bpio-heroslides-rightArrow');

    for (var i = 0; i < leftArrows.length; i++) {
        if (i < expandedSlideIndex) {
            leftArrows.eq(i).hide();
            rightArrows.eq(i).show();
        }
        else if (i > expandedSlideIndex) {
            leftArrows.eq(i).show();
            rightArrows.eq(i).hide();
        }
    }
}

SetSlideHeaderBg = function () {
    var visibleHeaders = $('.bpio-heroslides-itemHeader:visible');
    for (var i = 0; i < visibleHeaders.length; i++) {
        if (i < headerBgColorArray.length) {
            visibleHeaders.eq(i).css('background', headerBgColorArray[i]);
        }
    }
}


InitShowcaseVideos = function () {
    $('#HomeHero li .bpio-heroslides-itemBody:has(".bpio-heroslides-video")').click(function () {
        var slideItem = $(this).parentsUntil('ul').last();
        var playerArea = slideItem.find('.bpio-heroslides-video');
        var showcaseUrl = playerArea.attr('showcaseurl');
        var uuid = showcaseUrl.substring(showcaseUrl.lastIndexOf('/') + 1);
        loadVideoPlayer(playerArea.find('.player'), uuid, playerArea.width(), playerArea.height());

        playerArea.find('.preview').hide();
        playerArea.find('.player').show();

        // cancle sliding
        var slideIndex = slideItem.prevAll().length;
        if (inprogress && slideIndex == expandedSlideIndex) {
            SwitchHeroSlider(expandedSlideIndex, true);
        }
    });
}

ResetShowcaseVideo = function (slide) {
    slide.find('.player').html('');
    slide.find('.player').hide();
    slide.find('.preview').show();
}

loadVideoPlayer = function (playerContainer, uuid, width, height) {
    var html = '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="' + width + 'px" height="' + height + 'px">'
        + '<param name="source" value="http://www.microsoft.com/showcase/silverlight/player/1/player-en.xap" />'
        + '<param name="enableHtmlAccess" value="true" />'
        + '<param name="background" value="#000000" />'
        + '<param name="windowless" value="true" />'
        + '<param name="allowHtmlPopupwindow" value="true" />'
        + '<param name="minRuntimeVersion" value="4.0.50401.0" />'
        + '<param name="autoUpgrade" value="true" />'
        + '<param name="initParams" value="Culture=en-US,Uuid=' + uuid + ',Autoplay=true,ShowMarketingOverlay=false,MiscControls=FullScreen;Detached,ShowMenu=false,Tabs=Embed;Email;Share;Info,VideoUrl=http://microsoft.com/showcase/en/us/details/' + uuid + ',Mode=Player" />'
        + '<a href="http://go.microsoft.com/fwlink/?LinkID=149156" style="text-decoration: none;">'
        + '<img src="http://img.microsoft.com/showcase/Content/img/resx/en-US/installSL.gif" alt="Get Microsoft Silverlight" style="border-style: none; width: ' + width + 'px; height: ' + height + 'px" />'
        + '</a>'
        + '<noscript>'
        + '<div><img alt="DCSIMG" id="DCSIMG" width="1" height="1" src="http://m.webtrends.com/dcsygm2gb10000kf9xm7kfvub_9p1t/njs.gif?dcsuri=/nojavascript&WT.js=No" /></div>'
        + '</noscript>'
        + '</object>';

    playerContainer.html(html);

    playerContainer.find('A').bind({ mousedown: function () {
        new Image().src = 'http://m.webtrends.com/dcsygm2gb10000kf9xm7kfvub_9p1t/dcs.gif?dcsdat=' + new Date().getTime() + '&dcssip=www.microsoft.com&dcsuri=' + window.location.href + '&WT.tz=-8&WT.bh=16&WT.ul=en-US&WT.cd=32&WT.jo=Yes&WT.ti=&WT.js=Yes&WT.jv=1.5&WT.fi=Yes&WT.fv=10.0&WT.sli=Not%20Installed&WT.slv=Version%20Unavailable&WT.dl=1&WT.seg_1=Not%20Logged%20In&WT.vt_f_a=2&WT.vt_f=2&WT.vt_nvr1=2&WT.vt_nvr2=2&WT.vt_nvr3=2&WT.vt_nvr4=2&vp_site=Embedded&wtEvtSrc=' + window.location.href + '&vp_sli=Embedded';
    }
    });
}


/* End Home Hero <<< */


/* Begin Common */
function HandleExternalLinks() {
    var hostName = window.location.hostname;
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        if (links[i].href.indexOf("http") == 0 && links[i].hostname != hostName) {
            links[i].setAttribute("target", "_blank");
        }
    }
}

function bookmarkClick(link, url, title) {
    if ($.browser.msie) {
        window.external.AddFavorite(url, title);
    }
    else if ($.browser.mozilla) {
        window.sidebar.addPanel(title, url, '');
    }
    else if ($.browser.opera && window.print) {
        link.setAttribute('href', url);
        link.setAttribute('title', title);
        link.setAttribute('rel', 'sidebar');
    }
    else {
        // bookmark not supported
    }
}
/* End Common <<< */


/* Begin Social Bar */

var headerShareBtnTimeout;
var headerSocialBarTimeout;
var shareBtnTimeout;
var socialBarTimeout;
var shortenedUrlMappings;
InitSocialBar = function () {
    // workaround to make sure the social bar always shows horizontally.
    $('#HeaderSocialBar').width(123);
    $('#SocialBar').width(116);

    AttachShareButtonToBorderAreas();

    AttachWebTrendsEvents();

    LoadShortenedUrlMappings();

    $('#HeaderShareButton').hover(
		function (e) {
		    if (headerShareBtnTimeout != null) clearTimeout(headerShareBtnTimeout);
		    if (headerSocialBarTimeout != null) clearTimeout(headerSocialBarTimeout);

		    ParseSocialLinksTokens($(this), $('#HeaderSocialBar'));

		    $('#HeaderSocialBar').css('left', $(this).offset().left - $('#HeaderSocialBar').outerWidth());
		    $('#HeaderSocialBar').css('top', $(this).offset().top + $(this).outerHeight() / 2 - $('#HeaderSocialBar').outerHeight() / 2);
		    $('#HeaderSocialBar').show();
		},
		function (e) {
		    headerShareBtnTimeout = setTimeout(function () { $('#HeaderSocialBar').hide(); }, 300);
		}
	);

    $('#HeaderSocialBar').hover(
		function (e) {
		    if (headerShareBtnTimeout != null) clearTimeout(headerShareBtnTimeout);
		    if (headerSocialBarTimeout != null) clearTimeout(headerSocialBarTimeout);
		},
		function (e) {
		    headerSocialBarTimeout = setTimeout(function () { $('#HeaderSocialBar').hide(); }, 300);
		}
	);


    $('img[name="ShareButton"]').hover(
		function (e) {
		    if (shareBtnTimeout != null) clearTimeout(shareBtnTimeout);
		    if (socialBarTimeout != null) clearTimeout(socialBarTimeout);

		    ParseSocialLinksTokens($(this), $('#SocialBar'));

		    $('#SocialBar').css('left', $(this).offset().left + $(this).width() / 2 - $('#SocialBar').outerWidth() / 2);
		    $('#SocialBar').css('top', $(this).offset().top - $('#SocialBar').outerHeight());
		    $('#SocialBar').show();
		},
		function (e) {
		    shareBtnTimeout = setTimeout(function () { $('#SocialBar').hide(); }, 300);
		}
	);

    $('#SocialBar').hover(
		function (e) {
		    if (shareBtnTimeout != null) clearTimeout(shareBtnTimeout);
		    if (socialBarTimeout != null) clearTimeout(socialBarTimeout);
		},
		function (e) {
		    socialBarTimeout = setTimeout(function () { $('#SocialBar').hide(); }, 300);
		}
	);
}

AttachShareButtonToBorderAreas = function () {
    //var borderAreas = $("td.ms-WPBorderBorderOnly, td.ms-WPBorder");
    var borderAreas = $("td.ms-WPBorderBorderOnly:has(.bpio-sociallinkurl)");

    var area;
    var html;
    var linkUrl;
    var linkTitle;
    for (var i = 0; i < borderAreas.length; i++) {
        area = borderAreas.eq(i);

        if (area.find('a.bpio-sociallinkurl').attr('href')) {
            linkUrl = area.find('a.bpio-sociallinkurl').attr('href');
            linkTitle = area.find('.bpio-sociallinktitle').text() ? area.find('.bpio-sociallinktitle').text() : '';
        }
        else {
            linkUrl = location.href;
            linkTitle = document.title;
        }

        html = '<img name="ShareButton" style="float:right; margin-right:-1px; margin-bottom:-1px;" src="/businessproductivity/PublishingImages/ShareButton.png" border="0" alt=""';
        html += ' sociallinkurl="' + linkUrl + '" sociallinktitle="' + linkTitle + '" />';

        area.append(html);

        // remove the padding bottom since the share button will add the gap automatically.
        area.find('.ms-WPBody').css('padding-bottom', '0px');
    }
}

ParseSocialLinksTokens = function (shareButton, socialBar) {
    var socialLinkUrl;
    var socialLinkTitle;
    if (shareButton.attr('sociallinkurl')) {
        socialLinkUrl = shareButton.attr('sociallinkurl');
        socialLinkTitle = shareButton.attr('sociallinktitle') ? shareButton.attr('sociallinktitle') : '';
    }
    else {
        socialLinkUrl = location.href;
        socialLinkTitle = document.title;
    }

    // Replace the url with the shortened one if exists
    //var reg = new RegExp('^(https?://.+?\.aspx)([?#].*)?$', 'i');
    var shortenedUrl = shortenedUrlMappings[socialLinkUrl.toLowerCase()];
    if (shortenedUrl) {
        socialLinkUrl = shortenedUrl;
    }

    var refinedSocialLinkTitle;
    var links = socialBar.find('a');
    for (var i = 0; i < links.length; i++) {
        refinedSocialLinkTitle = links.eq(i).attr('urltoken').indexOf('javascript:') == 0 ? socialLinkTitle.replace('\'', '\\\'').replace('"', '\\"') : socialLinkTitle;
        if (links.eq(i).attr('socialname') == 'Bookmark') {
            // Try to get the title inside the orange bar
            var bookmarkTitle = $('.bpio-secondaryright-top').text() ? $('.bpio-secondaryright-top').text() : socialLinkTitle;
            links.eq(i).attr('href', links.eq(i).attr('urltoken').replace('*', encodeURIComponent(socialLinkUrl)).replace('$', encodeURIComponent(bookmarkTitle)));
        }
        else {
            links.eq(i).attr('href', links.eq(i).attr('urltoken').replace('*', encodeURIComponent(socialLinkUrl)).replace('$', encodeURIComponent(refinedSocialLinkTitle)));
        }


    }
}

var _websitePathNameMap = { 'BusinessChallenges': 'Business Challenges', 'solutions': 'Our Solutions', 'Why-Microsoft': 'Why Microsoft', 'GetStarted': 'Get Started', 'Resources': 'Resources' };
AttachWebTrendsEvents = function () {
    $('#HeaderSocialBar li a,#SocialBar li a').click(function () {
        var z_app;
        var z_name = $(this).attr('socialname');

        var reg = new RegExp('^https?://([^/]+/){3}([^/]+)/.*$', 'i');
        var match = reg.exec(parent.location.href);
        if (match != null && _websitePathNameMap[match[2]]) {
            z_app = _websitePathNameMap[match[2]]
        }
        else {
            z_app = 'Home';
        }

        dcsSetVar('WT.z_app', z_app, 'WT.z_type', 'Sharing', 'WT.z_name', z_name, 'WT.z_action', 'Referral');
    });
}

LoadShortenedUrlMappings = function () {
    shortenedUrlMappings = [];
    var items = $('#shortenedUrlMappingsProvider li');
    for (var i = 0; i < items.length; i++) {
        shortenedUrlMappings[items.eq(i).attr('pageurl').toLowerCase()] = items.eq(i).attr('shortenedurl');
    }
}

/* End Social Bar <<< */

/* Begin Resource */
webTrendForResourceSelect = function () {
    var selectItems = $(".ts-filterCategories").find("input:checked").next().map(function () {
        return this.innerHTML;
    }).get().join(';');

    dcsMultiTrack('DCS.dcsuri', '/webtrendstag/resource/sort', 'WT.ti', 'Resource Library Sort', 'WT.z_app', 'Resources', 'WT.z_sort', selectItems, 'WT.dl', '1');
}
/* End Resorce */


/* Left Nav */

AttachLeftNavEvents = function () {
    $('.bpio-leftNav-buttons li').hover(
		function () {
		    $(this).addClass('hover');
		},
		function () {
		    $(this).removeClass('hover');
		}
	);

    $('.bpio-leftNav-buttons li').click(function () {
        var url = $(this).attr('url');
        if (url) {
            location.href = url;
        }
    });
}

/* End Left Nav */

