/**
* @author Aaron.Lisman
* Updated by Amit Gaur
*/

if (!window.console) {
    window.console = { log: function() { } };
}


// Custom Void
var Void = function() { }; $.fn.VoidLink = function() { return $(this).attr('href', 'javascript:Void()') };

function getCookie(tabIndex) {//alert("from get cookie length : " + document.cookie.length);
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(tabIndex + "=");
        //alert("from get c_start : " + c_start);
        if (c_start != -1) {
            c_start = c_start + tabIndex.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return ""
}

function setCookie(tabIndex, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = tabIndex + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString());
    var cookieVal = tabIndex + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString());
    //alert("I am called from setcooke : " + cookieVal);
}

function checkCookie() {
    tabIndex = getCookie('tabIndex');
    //alert("initial value : " + tabIndex);
    if (tabIndex != null && tabIndex != "") {
        //alert('Welcome again '+tabIndex+'!');
    }
    else {
        tabIndex = 0;
        if (tabIndex != null && tabIndex != "") {
            setCookie('tabIndex', tabIndex, 365);
        }
    }
}

$(function() { Site.Init(); });

var Site = {

    // runs on page load
    Init: function() {

        // call Page object PreInit if exists
        if (this.Page && typeof this.Page.PreInit == 'function') {
            this.Page.PreInit();
        }

        this.CreateNav();
        this.CorrectCSS();
        this.InitGlobalModules();
        this.SetModuleLinkPosition.Init();
        this.Navigation.Init();
        this.SideNav.Init();
        Site.FixMenuBackgrounds.Init();
        this.WorlwideLinkModal.Init();
        this.qcTabSetter.Init();
        this.localizationSelector.Init();
        this.alphaSelectSetter.Init();
        this.prodListPanes.Init();
        this.MediaPlayer.Init()

        setInterval(Site.qcTabSetter.SetAppearance, ((jQuery.browser.msie && jQuery.browser.version.charAt(0) == '6') ? 1500 : 250));
        this.SetSiteSearch();
        this.AudioOverlay.Init();
        Site.Print.Init();
        Site.Share.Init(); // added for share on 10/06

        // call Page object PreInit if exists
        if (this.Page && typeof this.Page.Init == 'function') {
            this.Page.Init();
        }

    },
    Page: null,
    TextResizer: null,
    // create navigation
    CreateNav: function() {
        $(".drop").singleDropMenu({ parentMO: "drop-hover", childMO: "ddchildhover" });
    },
    // function to ctreate flash for home page
    CreateFlashHero: function() {
        swfobject.embedSWF("/_layouts/images/Japan/includes/audio-video/swf/merck_homepagehero_pureas3.swf", "hero", "975", "461", "9.0.0", null, { videoPlayerSkinURL: "/_layouts/images/Japan/includes/audio-video/swf/assets/swfs/homevideoskin.swf", dataXMLURL: "/_layouts/images/Japan/includes/audio-video/swf/assets/xml/homepagehero.xml" }, { wmode: "opaque" }, { id: "hero" });
    },
    // function to correct CSS
    CorrectCSS: function() {

        $(".moduleContainer-center-threeAccross div:last").css("margin-right", "0px");
    },
    // function to correct module height
    CorrectModuleHeights: function() {
        var modeGroups = $(".moduleContainer-center-threeAccross").each(function() {
            var greatestHeight = 0;
            var divs = $(this).children("div");
            divs.each(function() {
                var height = $(this).height();
                // if height exceeds prior greatest height, the reset greatestHeight
                if (height > greatestHeight) { greatestHeight = height; }
            });
            divs.css("height", greatestHeight);
        });
    },
    // function to initialize global modules
    InitGlobalModules: function() {
        $(".module-merckAccordian").each(function() { $(this).merckAccordian(); });
        this.TextResizer.Init();
    },
    // function to configure navigation
    Navigation: {
        TopNavSelector: 'ul.topNav li a',
        MainNavSelector: 'ul.drop > li > a',
        SideNavSelector: 'div.sideNav ul li a',
        DefaultPages: ["home.aspx"],
        Init: function() {
            //   debugger;

            var arr = location.pathname.replace("#nojs", "").split("/");
            if (Site.Navigation.__OVERRIDE_PAGE) { arr = Site.Navigation.__OVERRIDE_PAGE.split("/"); }

            Site.Navigation.__CURRENT_PAGE = arr.pop();
            Site.Navigation.__CURRENT_PATH = arr;

            if (Site.Navigation.__CURRENT_PAGE.length > 0) {

                Site.Navigation.Highlight.TopNav();
                Site.Navigation.Highlight.MainNav();
                Site.Navigation.Highlight.SideNav();
            }
        },
        // function to set link on active page
        Highlight: {
            ElementsByPath: function(selector) {
                // duplicate the array with slice
                var arr = Site.Navigation.__CURRENT_PATH.slice();

                // keep a blank array of elements in case there are no links to set active
                var eles = $([]);

                // makes ure there's only 1 slash in the begining, when splitting, its an empty string
                while (arr[1] == "") { arr.shift(); };

                // if we don't find any elements on this level, then go 1 level up and keep trying.
                while (arr.length > 1 && eles.length == 0) {
                    eles = $(selector + '[href^="' + arr.join("/") + '"]');
                    arr.pop();
                }

                return eles;
            },
            // function to highlight link by page
            ElementsByPage: function(selector) {
                var path = Site.Navigation.__CURRENT_PATH.join("/");
                path += "/";
                selector += "[href^=" + path + Site.Navigation.__CURRENT_PAGE + "]";
                var elements = $(selector)
					.addClass("active");

                return elements;
            },
            // function to set active class for top navigation
            TopNav: function() { Site.Navigation.Highlight.ElementsByPath(Site.Navigation.TopNavSelector).addClass('active'); },
            MainNav: function() {
                var eles = Site.Navigation.Highlight.ElementsByPage(Site.Navigation.MainNavSelector).addClass("active");

                if (eles.length == 0) {
                    var eles = Site.Navigation.Highlight.ElementsByPath(Site.Navigation.MainNavSelector).addClass("active");
                }

                eles.next().remove();
            },
            // function to configure side navigation
            SideNav: function() {
                var eles = Site.Navigation.Highlight.ElementsByPage(Site.Navigation.SideNavSelector);

                if (eles.length > 0) {
                    eles.parents('li:last').find('a:first').mouseover();
                    eles.VoidLink();
                }
            }
        }
    },
    // function to configure search
    SetSiteSearch: function() {
        $("form.search input").focus(function() {
            var dat = $(this).data("label");
            if (typeof dat == 'undefined') {
                $(this).data("label", $(this).val());
            }
            $(this).val("");
        });
        $("form.search input").blur(function() {
            if ($(this).val().length == 0) {
                $(this).val($(this).data("label"));
            }
        });
    }
}

Site.AudioOverlay = {
    Init: function() {
        $(".audioPlayer")
			.VoidLink()
			.click(Site.AudioOverlay.Show);
    },
    Show: function() {
        var html = $('#audioPlayerOverlay').html();
        modal.enter(html);
    }
}

Site.Print = {
    TemplateUrl: "/includes/print-friendly.html",
    ShowTemplate: function() {
        Site.Print.__CONTENT = $("#columnCenter, #columnCenterNoLeftNav, #NoLeftNavWorldWideContacts").html();
        var popWin = window.open(Site.Print.TemplateUrl, '_printMerck', 'status=no,toolbar=no,width=600,height=700,scrollbars=yes,menubar=no');
    },
    // this fires on the print friendly page itself
    PageInit: function() {
        $('.close a')
			.VoidLink()
			.click(function() {
			    window.close();
			});

        $('.printPage a')
			.VoidLink()
			.click(function() {
			    window.print();
			});
    },
    Init: function() {
        $('.utility-buttons .printButton a')
			.VoidLink()
			.click(Site.Print.ShowTemplate);
    },
    SetContent: function(popWin) {
        if (popWin.opener && popWin.opener.Site.Print.__CONTENT) {
            popWin.$("#columnCenter, #columnCenterNoLeftNav, #NoLeftNavWorldWideContacts").html(popWin.opener.Site.Print.__CONTENT);
        }
    }
}

// added for share on 10/06
Site.Share = {

    ShowTemplate: function() {
        var popWin = window.open("/share/share-site.html", "_shareSite",
                                 "status=no,toolbar=no,width=500,height=450,top=100,left=250,scrollbars=no,menubar=no");
        try { popWin.focus(); } catch (e) { }
    },

    Init: function() {
        $('.utility-buttons .shareButton a')
           .VoidLink()
           .click(Site.Share.ShowTemplate);
    }

}

// handles the resizing of text on the page
Site.TextResizer = {
    CssClass: "alternativeSize",
    Init: function() {
        Site.TextResizer.__ELEMENT = $(document.body);
        $(".textSizeButton a").VoidLink().click(Site.TextResizer.ChangeFontSize);
        if ($.cookie('alternativeSize') && $.cookie('alternativeSize') != 'false') {
            Site.TextResizer.ChangeFontSize();
        }
    },
    ChangeFontSize: function() {
        Site.TextResizer.__ELEMENT
			.toggleClass(Site.TextResizer.CssClass);
        $.cookie('alternativeSize', Site.TextResizer.__ELEMENT.hasClass(Site.TextResizer.CssClass).toString());
    }
}

// handles positioning of middle module footer links
Site.SetModuleLinkPosition = {
    LinkSelector: 'div[class^=module-bucket-container-]<div.module-bucket-container-inner',
    Init: function() {
        $(Site.SetModuleLinkPosition.LinkSelector).each(function() {
            // for some reason immediate child selector doesn't work for more than one nesting ... jquery bug?
            // need this logic to compensate to detect immediate child-parent relationship
            var isSingleCol = (/\-oneCol\-/.test(this.parentNode.className));
            $(this).find('div.module-bucket>a.baseArrow').each(function() {
                var leftOffset = ($($('html')[0]).hasClass('ie6')) ? ((isSingleCol) ? 0 : this.parentNode.offsetLeft) : this.offsetLeft;
                var linkHref = this.getAttribute('href') || '#';
                var linkLabel = this.innerHTML;
                this.style.display = 'none'// TODO: jquery.
                $(this.parentNode.parentNode).append('<a href="' + linkHref + '" class="arrow-moved" style="left: ' + leftOffset + 'px;">' + linkLabel + '</a>').addClass('module-contain-moved-arrows');
            });
        });
    }
};

Site.WorlwideLinkModal = {
    Markup: null,
    LinkSelector: '.globalWrapper .headerTop a.btn-worldwide',
    Show: function() {
        modal.enter(Site.WorlwideLinkModal.Markup);
        $('#modalPositioner a.closeBtn').click(function() { modal.exit(); return false; });
        Site.qcTabSetter.Init();
        $('body').applyCssQuadBg();
        return false;
    },
    SetMarkup: function(content) {
        Site.WorlwideLinkModal.Markup = content.split(/\<body\>/)[1].split(/\<\/body\>/)[0]; // TODO: refine.
    },
    Init: function() {
        if ($(Site.WorlwideLinkModal.LinkSelector).length) {
            Site.WorlwideLinkModal.baseMarkup = jQuery.get($(Site.WorlwideLinkModal.LinkSelector).attr('href'), null, Site.WorlwideLinkModal.SetMarkup)
        }
        $(Site.WorlwideLinkModal.LinkSelector)
			.VoidLink()
			.click(Site.WorlwideLinkModal.Show);
    }
}

Site.SideNav = {
    Init: function() {
        //$(".sideNav > ul > li > a").mouseover(Site.SideNav.AnimationHandler); // STRUCK 10/6/09 BY AARON ISMAN
        $(".sideNav > ul > li > ul").css('display', 'none'); // hide all 
        var activeLink = $(".sideNav a.active");

        if (activeLink.length > 0) {
            /* THIS WAS STRUCK 10/6/09 BY AARON LISMAN
            $(".sideNav > ul").mouseleave( function() { 
            window.activeLink = activeLink;
            var parentLinkEle = activeLink.parents('li:last').find('a:first').mouseover();
            if( parentLinkEle.next().length == 0 ) {
            $("div.sideNav > ul > li > ul").slideUp(500, function() {});
            $(".sideNav > ul > li > a").removeClass('on');
            }
            });
            */
            var $link = activeLink.parents('li:last').find('a:first');
            if ($link.siblings("ul").length > 0) {
                $link.addClass("on")
						 .next("ul").show();
            }
        }

    },
    AnimationHandler: function() {
        if ($(this).next("ul").length != 0) {
            $("div.sideNav > ul > li > ul").not($(this).next("ul")).slideUp(500, function() { });
            $(".sideNav > ul > li > a").removeClass('on');
            $(this).addClass('on');
            $(this).next("ul").slideDown(400);
        }
    }
}

//// javascript trick to fix background images
Site.FixMenuBackgrounds = {
    MenuSelector: '.globalNav>ul.drop>li>ul',
    Init: function() {
        $(Site.FixMenuBackgrounds.MenuSelector).each(Site.FixMenuBackgrounds.SetBackgroundProps);
    },
    SetBackgroundProps: function() {
        var menuTargetId = 'cacheImgOrig-' + this.parentNode.className.split(' ').join('');
        var menuTarget = $(this);
        menuTarget.attr('id', menuTargetId);
        var bgImgUrl = menuTarget.css('background-image');
        bgImgUrl = bgImgUrl.split('url(')[1].split(')')[0]; //strip url bracing
        bgImgUrl = (bgImgUrl.charAt(0) == '\'' || bgImgUrl.charAt(0) == '"') ? bgImgUrl.substring(1, bgImgUrl.length - 1) : bgImgUrl;
        window[menuTargetId] = document.getElementsByTagName('body')[0].appendChild(document.createElement('img'));
        window[menuTargetId].className = 'cacheImg';
        window[menuTargetId].onload = function() {
            var srcImgUrl = this.src;
            document.getElementById(menuTargetId).style.backgroundColor = 'transparent';
            document.getElementById(menuTargetId).style.backgroundImage = 'url(' + srcImgUrl + ')';
        };
        window[menuTargetId].src = bgImgUrl;
    }
}

//// experiments in tab styling
Site.qcTabSetter = {
    // applies tab widths to max out available space evenly.
    SetAppearance: function() {
        $('.tabbed-navigation>li, .tabbed-navigation-js>li').each(function() {
            var thisTab = $(this)
            var tabCount = thisTab.siblings().length + 1;
            var tabSpace = Math.round((this.parentNode.offsetWidth - 20) / tabCount);
            if (tabSpace > 0) {
                thisTab.css({ width: tabSpace + 'px' });
            }
        });
    },
    // classify child elements.
    SetClassification: function() {
        $('.tabbed-content-js').children().addClass('tabbed-content-passive');
        $('.tabbed-navigation-js').children().addClass('tabbed-content-passive');
    },
    // sets initial default content for tabs if no default is set manually.
    SetInitial: function() {
        $('.tabbed-navigation-js').each(function() {
            var tabSet = $(this);
            var activeTabIsSet = (tabSet.children('li.tabbed-navigation-active').length > 0);
            if (activeTabIsSet) {

            } else {
                //var tabIndex = 0
                checkCookie();
            }
            tabSet.children('li').eq(tabIndex).addClass('tabbed-navigation-active').removeClass('tabbed-navigation-passive');
            tabSet.nextAll('.tabbed-content-js').eq(0).children().eq(tabIndex).addClass('tabbed-content-active').removeClass('tabbed-content-passive');
        });
    },
    // sets tab behaviours for JS tabs.
    SetBehaviour: function() {
        $('.tabbed-navigation-js>li a').click(
			function() {
			    // preparatory traversing and fact finding
			    var clickedTab = this.parentNode.parentNode;                                    //<-- clicked element (raw) used for acquiring tabindex.
			    var tabsParent = $(this).parents().eq(2);                                       //<-- container for tabs.
			    var contParent = tabsParent.nextAll('.tabbed-content-js').eq(0);                //<-- container for content elements.
			    var tabs = tabsParent.children();                                         //<-- all tab LI elements.
			    var conts = contParent.children();                                         //<-- all contents DOM elements.
			    var tabIndex = 0;                                                             //<-- tab index, to be incremented by next line.
			    tabs.each(function() { if (this == clickedTab) { return false; } tabIndex++; }); //<-- get the real tabIndex of the clicked tab.
			    setCookie('tabIndex', tabIndex, 365);
			    // set classes for tab states
			    tabs.removeClass('tabbed-navigation-active').addClass('tabbed-navigation-passive');
			    tabs.eq(tabIndex).addClass('tabbed-navigation-active').removeClass('tabbed-navigation-passive');
			    // special handling for media player playback - stop playback of any players within all (relevant) tabs when switching. This is only really needed for challeneged microsoft browsers. Other browsers automatically suspend swf activity when player is hidden.
			    conts.each(function() {
			        var thisTab = $(this);
			        var mediaPlayers = thisTab.find('object[id^=mediaplayerrandomidgen-], embed[name^=mediaplayerrandomidgen-]');
			        var playerID = mediaPlayers.eq(0).attr('id') || mediaPlayers.eq(0).attr('name')
			        var playerObj = (typeof (ActiveXObject) != 'undefined' && document.embeds) ? window[playerID] : document[playerID];
			        try { playerObj.stopPlayback(); } catch (e) { } // NOTE: must catch errors because some browsers temporarily delete movie when it is not visible, resulting in errors.
			    });
			    // set classes for content states
			    conts.removeClass('tabbed-content-active').addClass('tabbed-content-passive');
			    conts.eq(tabIndex).addClass('tabbed-content-active').removeClass('tabbed-content-passive');
			    return false
			}
		);
    },
    // initialize tabbing system.
    Init: function() {
        Site.qcTabSetter.SetClassification();
        Site.qcTabSetter.SetInitial();
        Site.qcTabSetter.SetAppearance();
        Site.qcTabSetter.SetBehaviour();
    }
}

Site.alphaSelectSetter = {
    Init: function() {
        $('.alphabetic-selector li a').each(function() {
            var letter = $(this).attr('href').charAt(1);
            var hasSection = ($('a.alpha-anchor[id=' + letter + ']').length);
            if (!hasSection) { $(this.parentNode).addClass('disabled'); }
        });
    }
}

Site.localizationSelector = {
    Init: function() {
        $('#localization-nav li').click(function() {
            var currentLang = $(this.parentNode).find('li.active a').attr('href').substring(1);
            var thisLang = $(this).find('a').attr('href').substring(1);
            if (currentLang != thisLang) {
                $('body#countryBridge div.globalWrapper').addClass(thisLang).removeClass(currentLang);
                $('body#countryBridge div.globalWrapper li.active').removeClass('active');
                $(this).addClass('active');
            }
            return false;
        });
    }
}


Site.prodListPanes = {
    Toggle: function() {
        var drug = $(this.parentNode);
        drug.toggleClass('open');
    },
    Init: function() {
        $('ul.products-list li h5').click(Site.prodListPanes.Toggle);
    }
}


Site.MediaPlayer = {
    // minimum required flash version
    FlashVersionRequired: '9.0.0.0',
    // url of the main flash movie
    PlayerSwfURL: '/_layouts/images/japan/includes/audio-video/mediaPlayer/Main.swf',
    flashSupported: false,
    // default flashvars params
    ParamObjDefaults: {
        fontsURL: '/_layouts/images/japan/includes/audio-video/mediaPlayer/swf/fonts.swf',
        stylesURL: '/_layouts/images/japan/includes/audio-video/mediaPlayer/css/mpstyles.css',
        playlistURL: '',
        skinURL: '',
        mediaURL: '',
        mediaType: '',
        audio: '',
        videoimg: '',
        overlay: ''
    },
    // basic movie loading/creation function
    Load: function(paramObj, targetElement) {
        // merge defaults with override value.
        var playerParams = {};
        for (var i in Site.MediaPlayer.ParamObjDefaults) {
            var defaultName = i;
            var defaultValue = Site.MediaPlayer.ParamObjDefaults[i];
            var setValue = paramObj[defaultName];
            var mergedValue = (setValue != undefined) ? setValue : defaultValue;
            playerParams[i] = mergedValue;
        }
        // set default skin if override not present
        if (playerParams.skinURL == '') {
            playerParams.skinURL = Site.MediaPlayer.Skins[playerParams.mediaType.toLowerCase()];
        }
        // find media features, if included. This could probably be refined but it works for now.
        if (playerParams.mediaType == 'video' && playerParams.playlistURL != '') { var mediaFeature = 'gallery'; }
        else if (playerParams.mediaType == 'image' && playerParams.audio == 'true') { var mediaFeature = 'audio'; }
        // get dimensions for media type, or mediaType + mediaFeature
        var dimensions = Site.MediaPlayer.Dimensions[playerParams.mediaType];
        dimensions = (mediaFeature && dimensions[mediaFeature]) ? dimensions[mediaFeature] : dimensions;
        // general swf params for the player
        var swfParams = {
            allowFullScreen: 'true',
            menu: 'false',
            wmode: 'transparent'
        };
        var swfAttrs = {};
        // show some handy logging info for debug purposes
        if (typeof (console.log) == 'function') {
            /*			console.log('PLAYER URL', Site.MediaPlayer.PlayerSwfURL);
            console.log('TARGET ELEMENT', targetElement || 'MODAL');
            console.log('PLAYERPARAMS', playerParams);*/
        }
        // NOTE: the following chunk of code is a workaround for a swfObject design issue.
        // swfObject expects an id string to represent the target element ... which is not
        // ideal to say the least for general-purpose embedding in raw elements. to make
        // up for this problem we look at the target element, and check it for an ID. If
        // it has one, we use it. If not, we assign it a random ID and then use that.
        if (targetElement && typeof (targetElement) != 'string') {
            var targetID = $(targetElement).attr('id');
            if (!targetID) {
                var targetID = 'mediaplayerrandomidgen-' + (Math.round(Math.random() * 100000));
                while (document.getElementById(targetID)) {
                    var targetID = 'mediaplayerrandomidgen-' + (Math.round(Math.random() * 100000));
                }
                $(targetElement).attr('id', targetID);
                playerParams.overlay = '';
            }
        } else if (!targetElement) {
            modal.enter('<div id="ModalMediaPlayerParent"></div>')
            var targetID = 'ModalMediaPlayerParent';
            playerParams.overlay = 'true';
        }
        // go ahead and embed the swf with swfobject.
        if (Site.MediaPlayer.flashSupported) {
            swfobject.embedSWF(
				Site.MediaPlayer.PlayerSwfURL,
				targetID,
				dimensions.width,
				dimensions.height,
				Site.MediaPlayer.FlashVersionRequired,
				'expressInstall.swf',
				playerParams,
				swfParams,
				swfAttrs
			);
        } else if (!Site.MediaPlayer.flashSupported && targetID == 'ModalMediaPlayerParent') {
            modal.enter('<div id="ModalMediaPlayerParent"><h1>To view this content, you need the flash player</h1><h1><a href="http://adobe.com/getflash/" target="_blank">download the flash player here.</a></h1></div>');
        }
    },
    // media-specific load functions
    loadVideo: function(paramObj, targetElement) {
        paramObj.mediaType = 'video';
        //		playlistURL
        //		mediaURL
        //		audio   
        //		videoimg
        Site.MediaPlayer.Load(paramObj, targetElement);
    },
    loadAudio: function(paramObj, targetElement) {
        paramObj.mediaType = 'audio';
        //		playlistURL
        //		mediaURL
        //		audio   
        //		videoimg
        Site.MediaPlayer.Load(paramObj, targetElement);
    },
    loadImage: function(paramObj, targetElement) {
        paramObj.mediaType = 'image';
        //		playlistURL
        //		mediaURL
        //		audio   
        //		videoimg
        Site.MediaPlayer.Load(paramObj, targetElement);
    },
    // initialization of link-scheme items
    Init: function() {
        // detect support
        Site.MediaPlayer.flashSupported = (swfobject.getFlashPlayerVersion().major >= parseInt(Site.MediaPlayer.FlashVersionRequired.charAt(0)));
        // audioLinkage
        $('a[href^=http://get.adobe.com/flashplayer/#mediaPlayer/loadAudio:]').each(function() {
            var playerWrap = $(this);
            playerWrap.click(function() { if (Site.MediaPlayer.flashSupported) { return false; } })
            var audioPath = playerWrap.attr('href').split('loadAudio:')[1].split('&')[0];
            Site.MediaPlayer.loadAudio({
                mediaURL: audioPath
            }, playerWrap.get(0));
        });
        //imageLinkage
        $('a[href^=http://get.adobe.com/flashplayer/#mediaPlayer/loadImage:]').each(function() {
            var playerWrap = $(this);
            var playlistURL = playerWrap.attr('href').split('loadImage:')[1];
            var audioSTR = ((/\&audio\:true/).test(playerWrap.attr('href'))) ? 'true' : '';
            var inline = ((/\&inline\:true/).test(playerWrap.attr('href'))) ? playerWrap.get(0) : null;
            var makeMovie = function() {
                Site.MediaPlayer.loadImage({
                    playlistURL: playlistURL,
                    audio: audioSTR
                }, inline);
            }
            if (inline) {
                makeMovie();
                playerWrap.click(function() {
                    if (Site.MediaPlayer.flashSupported) { return false; }
                });
            } else {
                playerWrap.click(function() {
                    makeMovie();
                    return false;
                });
            }
        });
        //videoLinkage
        $('a[href^=http://get.adobe.com/flashplayer/#mediaPlayer/loadVideo:]').each(function() {
            var playerWrap = $(this);
            var playlistURL = playerWrap.attr('href').split('&playlist:')[1].split('&')[0];
            var mediaURL = playerWrap.attr('href').split('loadVideo:')[1].split('&')[0];
            var videoimg = playerWrap.attr('href').split('&loadImage:')[1].split('&')[0];
            var inline = ((/\&inline\:true/).test(playerWrap.attr('href'))) ? playerWrap.get(0) : null;
            var makeMovie = function() {
                Site.MediaPlayer.loadVideo({
                    playlistURL: playlistURL,
                    mediaURL: mediaURL,
                    videoimg: videoimg
                }, inline);
            }
            if (inline) {
                makeMovie();
                playerWrap.click(function() {
                    if (Site.MediaPlayer.flashSupported) { return false; }
                });
            } else {
                playerWrap.click(function() {
                    makeMovie();
                    return false;
                });
            }
        });
    },
    // Default Skins
    Skins: {
        video: '/_layouts/images/japan/includes/audio-video/mediaPlayer/swf/videoskin.swf',
        audio: '/_layouts/images/japan/includes/audio-video/mediaPlayer/swf/audioskin.swf',
        image: '/_layouts/images/japan/includes/audio-video/mediaPlayer/swf/imageskin.swf'
    },
    // stores dimensions for various states of the mediaPlayer
    Dimensions: {
        video: {
            width: 530,
            height: 336,
            gallery: {
                width: 530,
                height: 423
            }
        },
        image: {
            width: 530,
            height: 340,
            audio: {
                width: 530,
                height: 360
            }
        },
        audio: {
            width: 180,
            height: 21
        }
    }
};

// Douglas Crockford's supplant method
String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};
