var exitURL;
var didYouKnowQuestionSize = 0;

$(document).ready(function () {

    /********* Scroll to location *********/
    $('.scrollToLocation').click(function (e) {
        var getHref = $(this).attr('href');
        var correctAnchor = getHref.replace(/#/, '');

        processScrollTo(correctAnchor);

        return false;
    });

    /********* Print ISI - Right Hand Callout *********/
    $(".printRightISI").click(function () {
        $("body").addClass("printISI");
        $("body", top.document).addClass("printISI");
        parent.window.focus();
        parent.window.print();
        setTimeout(function () {
            $("body").removeClass("printISI");
            $("body", parent.document).removeClass("printISI");
        }, 5000);
    });
    /*
    $('.printRightISI').click(function() {
    var isiText = $('#isiContent').html();
    var $frame = $("<iframe id='printRightISIiFrame' style='width:0; height:0;'></iframe>");

    $('body').append($frame);

    setTimeout(function() {
    var doc = $frame[0].contentWindow.document;
    var $body = $('body', doc);
    $body.html(isiText);
    $frame[0].contentWindow.window.print();
    $('#isiContent', doc).css('width', '100%');
    var page = window.location.pathname;
    if (page == "/")
    page = "";

    // if inside modal, call parent's ga functions
    if (parent.GAPage) {
    parent.GAPage.trackEvent("Print Links", "Print", parent.GAPage.normalizeURL(page + "/Important_Safety_Information/"));
    } else if (GAPage) {
    // otherwise, not inside a modal, just call regualar ga functions
    GAPage.trackEvent("Print Links", "Print", GAPage.normalizeURL(page + "/Important_Safety_Information/"));
    }
    }, 1);

    return false;
    });
    */

    /***********************************************************************
    Font Resize (only in content area)
    ***********************************************************************/
    var lb = $('#content, .contextualGlossaryToolTipContent p');
    $("a.globalFontSizePlus").click(function () {
        var size = $(lb).css("font-size");
        var newSize = parseInt(size.replace(/px/, "")) + 1;
        $(lb).css("font-size", newSize + "px");
    });
    $("a.globalFontSizeMinus").click(function () {
        var size = $(lb).css("font-size");
        var newSize = parseInt(size.replace(/px/, "")) - 1;
        $(lb).css("font-size", newSize + "px");
    });

    /***********************************************************************
    Did You Know - Callout
    ***********************************************************************/
    didYouKnowQuestionSize = $('#calloutDidYouKnow .didYouKnowQuestion').size();
    var currentIndex;

    $('#calloutDidYouKnow .didYouKnowQuestion').eq(0).show();

    $('#nextBtn').click(function () {
        var questions = $('#calloutDidYouKnow .didYouKnowQuestion');
        $.each(questions, function (index, val) {
            var questionVisible = $('.didYouKnowQuestion').eq(index).css('display');
            if (questionVisible == 'block') {
                currentIndex = index;
            }
        });

        currentIndex++;
        updateDidYouKnow(currentIndex, "Next");

        return false;
    });

    $('#previousBtn').click(function () {
        var questions = $('#calloutDidYouKnow .didYouKnowQuestion');
        $.each(questions, function (index, val) {
            var questionVisible = $('.didYouKnowQuestion').eq(index).css('display');
            if (questionVisible == 'block') {
                currentIndex = index;
            }
        });

        currentIndex--;
        updateDidYouKnow(currentIndex, "Previous");

        return false;
    });
    /***********************************************************************
    Modal Popup
    ***********************************************************************/
    //Load Interstitial 
    var interstitialModal = new ModalPopup({
        dynamic: false,
        popupSelector: "#interstitialModal",
        triggerSelector: ".leavingSite",
        closeSelector: ".closeModal, #modalBackground, .modalCancelBtn"
    });

    //On click of link, pull interstitial information
    $('.leavingSite').click(function () {
        exitURL = $(this).attr('href');
        //$('#modalAction span').html('<a href="' + exitURL + '" target="_blank" class="modalContinueBtn">Continue</a>');
    });

    $('.modalContinueBtn').click(function () {
        $('#interstitialModal').hide();
        $('#modalBackground').remove();

        var newWindow = window.open(exitURL, '_blank');
        newWindow.focus();
        if (GAPage) {
            GAPage.trackEvent("Exit Links", "Exit", exitURL);
        }
        return false;
    });

    /***********************************************************************
    Exit Links
    ***********************************************************************/
    //On click of link, throw google page track
    $('.leavingSiteNoPopup').live("click", function () {
        if (GAPage) {
            var exitURL = $(this).get(0).href;
            GAPage.trackEvent("Exit Links", "Exit", exitURL);
        }
    });

    //load register modal
    /*var registerModal = new ModalPopup({
    dynamic: false,
    popupSelector: "#registerModal",
    triggerSelector: ".fiveyearUpdates",
    closeSelector: ".closeModal, #modalBackground, .modalCancelBtn"
    });*/

    //load share page modal
    /*var sharepageModal = new ModalPopup({
    dynamic: false,
    center: false,
    popupSelector: "#sharepageModal",
    triggerSelector: ".fiveyearSharePage",
    closeSelector: ".closeModal, #modalBackground, .modalCancelBtn"
    });*/

    //load unsub modal
    /*
    var unsubModal = new ModalPopup({
    dynamic: false,
    popupSelector: "#unsubModal",
    triggerSelector: ".fiveyearPatientLetter",
    closeSelector: ".closeModal, #modalBackground, .modalCancelBtn"
    });
    */

    /***********************************************************************
    Side Effects :: Tabs
    **********************************************************************
    var sideEffectsCurrentTabIndex = $('#sideEffectsTabNav li').index('.active');
    $('.sideEffectsTabContent:eq(' + sideEffectsCurrentTabIndex + ')').show();

    $('.sideEffectsTab').click(function()
    {
    $('.sideEffectsTabContent').hide();

    var sideEffectsTabIndex = $('a.sideEffectsTab').index($(this));

    $('.sideEffectsTabContent:eq(' + sideEffectsTabIndex + ')').show();

    $('#sideEffectsTabNav li').removeClass('active');
    $(this).parent('li').addClass('active');
    });*/

    /***********************************************************************
    Insurance Coverage :: Tabs
    **********************************************************************
    var insuranceCoverageCurrentTabIndex = $('#insuranceCoverageTabNav li').index('.active');
    $('.insuranceCoverageTabContent:eq(' + insuranceCoverageCurrentTabIndex + ')').show();

    $('.insuranceCoverageTab').click(function()
    {
    $('.insuranceCoverageTabContent').hide();

    var insuranceCoverageTabIndex = $('a.insuranceCoverageTab').index($(this));

    $('.insuranceCoverageTabContent:eq(' + insuranceCoverageTabIndex + ')').show();

    $('#insuranceCoverageTabNav li').removeClass('active');
    $(this).parent('li').addClass('active');
    });
    */

    /***********************************************************************
    Operate Tab :: Functions
    ***********************************************************************/
    // Show Current Active Tab
    var currentTabIndex = $('.tabNav li').index('.active');
    $('.tabContent:eq(' + currentTabIndex + ')').show();

    // Show Tab from URL
    var tabSectionID = getURLParam("tabShow");
    if (tabSectionID.length > 0) {
        $('.tabContent').hide();
        var content = $('.tabContent:eq(' + tabSectionID + ')');

        if (content.css("display") == "none") {
            content.show();
        }

        $('.tabNav li').removeClass('active');
        $('.tabNav li:eq(' + tabSectionID + ')').addClass('active');
    }


    $('.tab').click(function () {
        $('.tabContent').hide();

        var tabIndex = $('a.tab').index($(this));

        $('.tabContent:eq(' + tabIndex + ')').show();

        $('.tabNav li').removeClass('active');
        $(this).parent('li').addClass('active');

        if (GAPage) {
            var gaTitle = $(this).attr("gaTitle");
            GAPage.trackSectionView("Tab/" + gaTitle)
        }
    });




    /***********************************************************************
    Accordian
    ***********************************************************************/
    var sectionID = getURLParam("accShow");

    if (sectionID.length > 0) {
        operateAccordian(sectionID);
        processScrollTo(sectionID);
    }

    $('.accordian').click(function () {
        var index = $('.accordian').index(this);
        var content = jQuery('.accordianContent:eq(' + index + ')');

        var gaTitle = $(this).attr("gaTitle");
        var gaSection = $(this).parent("[gaSection]").attr("gaSection");
        if (typeof (gaSection) == "undefined") {
            var docTitle = $(document).find("title").html();
            var index = docTitle.indexOf(":")
            if (index >= 0)
                gaSection = docTitle.substring(index + 1);
            else
                gaSection = docTitle
            gaSection = jQuery.trim(gaSection);
        }

        var action = "";
        if (content.css("display") == "block") {
            content.slideUp("fast", function () {
                content.attr('style', '');
            });
            $('.accordian:eq(' + index + ') span.plusDefault').addClass('minusDefault');
            $('.accordian:eq(' + index + ') span.plusDefault').removeClass('plusDefault');
            action = "Collapse";
        }
        else {
            content.slideDown("fast");
            $('.accordian:eq(' + index + ') span.minusDefault').addClass('plusDefault');
            $('.accordian:eq(' + index + ') span.minusDefault').removeClass('minusDefault');
            action = "Expand";
        }
        if (GAPage) {
            GAPage.trackEvent(gaSection, action, gaTitle)
        }
    });

    /***********************************************************************
    Glossary
    ***********************************************************************/
    $("#glossaryNavigation #navA-D a").addClass("navOn");
    $("#glossaryContent #contentA-D").css("display", "block");

    /* Glossary Click */
    $('#glossaryNavigation li').click(function () {

        var clickedNav = this.id;
        var navLetters = clickedNav.substr(3, 3);
        var navClickedTab = "#glossaryNavigation #" + clickedNav + " a";


        $('#glossaryNavigation a').removeClass("navOn");

        $(navClickedTab).addClass("navOn");


        $('#contentA-D, #contentE-H, #contentI-L, #contentM-P, #contentQ-U, #contentV-Z').css("display", "none");
        $('#glossaryContent #content' + navLetters).css("display", "block");
    });

    /***********************************************************************
    Homepage - NON Flash
    ***********************************************************************/
    $('#flashContent .nonFlashSwitchToMM').live('click', function () {
        $("#nonFlashHomepageDefault").hide();
        $("#nonFlashMantleCellLymphoma").hide();
        $("#nonFlashMultipleMyeloma").show();

        return false;
    });

    $('#flashContent .nonFlashSwitchToMCL').live('click', function () {
        $("#nonFlashHomepageDefault").hide();
        $("#nonFlashMultipleMyeloma").hide();
        $("#nonFlashMantleCellLymphoma").show();

        return false;
    });

    /***********************************************************************
    Max Character  Functions
    ***********************************************************************/
    $('#commentsText textarea').keyup(function () {
        var len = this.value.length;

        if (len >= 200) {
            this.value = this.value.substring(0, 200);
        }

        $('#commentCharLeft').text(200 - len);


        if ($('#commentCharLeft').text() == "-1") {
            $('#commentCharLeft').text("0");
        }
    });

    $('#registrationButton').click(function () {
        var rt = $("input[@name=registration_type]:checked").val();
        var it = $('#registerModal #interest').val();

        if (rt == undefined) rt = "not specified";

        if (it == "Select one")
            it = "not specified";
        else if (it == "Previously Untreated Multiple Myeloma")
            it = "Untreated MM";
        else if (it == "Relapsed Multiple Myeloma")
            it = "Relapsed MM";
        else if (it == "Relapsed Mantle Cell Lymphoma")
            it = "MCL";
        else
            it = "not specified";

        if (parent.GAPage) {
            parent._gaq.push(['_setCustomVar', 2, "Segment", rt, 1]);
            parent.GAPage.trackEvent('Patient Updates Signup', 'What info are you interested in', it);
        }

        $.post("/handler/registrationHandler.aspx",
            {
                email: $('#registerModal #email').val(),
                confirm_email: $('#registerModal #confirm_email').val(),
                fname: $('#registerModal #fname').val(),
                lname: $('#registerModal #lname').val(),
                zipcode: $('#registerModal #zipcode').val(),
                registration_type: $("input[@name=registration_type]:checked").val(),
                interest: $('#registerModal #interest').val()
            },
            function (data) {
                var o = eval('(' + data + ')');
                if (o.Succeed == "True") {
                    $('#registerModal .initial').hide();
                    $('#registerModal .confirmation').show();
                    parent.resizeIframe(590, 313);
                    if (parent.GAPage) {
                        parent.GAPage.trackModal("registration/complete");
                    }
                    setTimeout("closeRegistionForm(9)", 1000);
                }
                else {
                    $('#registerModal .errors').show();
                    $('#registerModal .errors').html(o.errMsg);

                    if (o.validateEmail == "False" || o.validateConfirmEmail == "False") {
                        $('#registerModal #email').addClass('errorInput');
                        $('#registerModal #confirm_email').addClass('errorInput');
                    }
                    else {
                        $('#registerModal #email').removeClass('errorInput');
                        $('#registerModal #confirm_email').removeClass('errorInput');
                    }

                    if (o.validateFirstname == "False") {
                        $('#registerModal #fname').addClass('errorInput');
                    }
                    else {
                        $('#registerModal #fname').removeClass('errorInput');
                    }

                    if (o.validateLastname == "False") {
                        $('#registerModal #lname').addClass('errorInput');
                    }
                    else {
                        $('#registerModal #lname').removeClass('errorInput');
                    }
                    
                    if (o.validateZipcode == "False") {
                        $('#registerModal #zipcode').addClass('errorInput');
                    }
                    else {
                        $('#registerModal #zipcode').removeClass('errorInput');
                    }

                    if (parent.GAPage) {
                        parent.GAPage.trackModal("registration/tryagain");
                    }
                }
            }
         );
    });



});

/***********************************************************************
    Scroll Pane Functions
***********************************************************************/
$(function() {
    $('.scroll-pane').jScrollPane();
});


/***********************************************************************
	Contextual Glossary Functions
***********************************************************************/
var toolTipContainerOffsetLeft = 77; /* Adjust this to move it left/right :: the higher the number more to the left the tool tip container will move */
var toolTipContainerOffsetTop = 10; /* Adjust this to move it up/down :: the higher the number more upward the tool tip container will move */

$(function() {

    $('.toolTipContextualGlossary').live('mouseout', function() {
        $('#contextualGlossaryToolTipContainer').hide();
    });

    $('.toolTipContextualGlossary').live('mousemove', function(e) {
        if (!$('#contextualGlossaryToolTipContainer').length) {
            createToolTipPopUpContainer();
        }

        var contextualGlossaryTerm = $(this).attr("term");
        contextualGlossaryTerm = contextualGlossaryTerm.replace(/ /g, "");
        contextualGlossaryTerm = contextualGlossaryTerm.toLowerCase();

        var contextualGlossaryID = "glossaryTerm" + contextualGlossaryTerm;
        contextualGlossaryID = contextualGlossaryID.replace(/'/g, "");

        var contextualGlossaryContent = $('#' + contextualGlossaryID).html();

        $('#contextualGlossaryToolTipContainer #bodyContainer').html(contextualGlossaryContent);

        $('#contextualGlossaryToolTipContainer').show();

        var containerHeight = $('#contextualGlossaryToolTipContainer').height();

        $('#contextualGlossaryToolTipContainer').css(
        {
            left: e.pageX - toolTipContainerOffsetLeft,
            top: e.pageY - containerHeight - toolTipContainerOffsetTop
        });

        if ($('#contextualGlossaryToolTipContainer').css('display') == 'block') {
            var containerHeight = $('#contextualGlossaryToolTipContainer').height();

            $('#contextualGlossaryToolTipContainer').css(
			{
			    left: e.pageX - toolTipContainerOffsetLeft,
			    top: e.pageY - containerHeight - toolTipContainerOffsetTop
			});
        }
    });
});

function createToolTipPopUpContainer()
{
    $('<div id="contextualGlossaryToolTipContainer"><div id="topCapper"></div><div id="bodyContainer"></div><div id="btmCapper"></div></div>').appendTo('body');
    $('#contextualGlossaryToolTipContainer').hide();
}

/***********************************************************************
    Generic ToolTip Functions
***********************************************************************/
var toolTipOffsetLeft = 16; /* Adjust this to move it left/right :: the higher the number more to the left the tool tip container will move */
var toolTipOffsetTop = 50; /* Adjust this to move it up/down :: the higher the number more upward the tool tip container will move */


$(function() {
    $('.toolTip').hover(function(eStart) {
        if (!$('#toolTipContainer').length) {
            createToolTip();
        }

        $('#toolTipContainer').show();

        $('#toolTipContainer').css(
		{
		    left: eStart.pageX - toolTipOffsetLeft,
		    top: eStart.pageY - toolTipOffsetTop
		});

    }, function() {
        $('#toolTipContainer').hide();
    });

    $('.toolTip').mousemove(function(e) {
        if ($('#toolTipContainer').css('display') == 'block') {
            $('#toolTipContainer').css(
			{
			    left: e.pageX - toolTipOffsetLeft,
			    top: e.pageY - toolTipOffsetTop
			});
        }
    }); 
});

function createToolTip() {
    $('<div id="toolTipContainer"></div>').appendTo('body');
    $('#toolTipContainer').hide();
}

/***********************************************************************
    Did You Know :: Callout :: Functions
***********************************************************************/
function updateDidYouKnow(index, action)
{
    $('#calloutDidYouKnow .didYouKnowQuestion').hide();

    if(index < didYouKnowQuestionSize) {
		// do nothing
    } else if(index < 0) {
		index = didYouKnowQuestionSize-1
    } else if(index >= didYouKnowQuestionSize) {
		index = 0;
    }
	var ele = $('#calloutDidYouKnow .didYouKnowQuestion').eq(index);
	ele.show();
	if (GAPage) {
		var gaTitle = ele.attr("gaTitle");
		GAPage.trackEvent("Did You Know", action, gaTitle);
	}
}

/***********************************************************************
    Operate Accordian :: Functions
***********************************************************************/
function operateAccordian(id) {
    var contentIndex = $('a.accordian').index($('#'+id));
    var content = $('.accordianContent:eq('+contentIndex+')');

    if (content.css("display") == "block")
    {
        content.slideUp("fast");
        $('#'+id+' span.minusDefault').css({ 'background': 'url(../Images/Common/btnPlus.png) no-repeat 0 0', 'padding-left': '20px' });
    }
    else
    {
        content.slideDown("fast");
        $('#' + id + ' span.minusDefault').css({ 'background': 'url(../Images/Common/btnMinus.png) no-repeat 0 0', 'padding-left': '20px' });
    }
}




/***********************************************************************
    Get URL Param : variables (paramater name) :: Functions
***********************************************************************/
function getURLParam(strParamName)
{
    var strReturn = "";
    var strHref = window.location.href;
    
    if (strHref.indexOf("?") > -1)
    {
        //var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var strQueryString = strHref.substr(strHref.indexOf("?"));
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++)
        {
            //if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1)
            if (aQueryString[iParam].indexOf(strParamName + "=") > -1)
            {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

/***********************************************************************
    processScrollTo :: Functions
***********************************************************************/
function processScrollTo(id)
{
    var targetOffset = $('#' + id).offset().top;
    $('html, body').animate({ scrollTop: targetOffset }, 500);
}

/***********************************************************************
    SwfObject : OutPut Status :: Functions
***********************************************************************/
function swfObjectOutputStatus(e)
{
    if (!e.success)
    {
        loadAlternateFlash();
    }
    //alert("e.success = " + e.success + "\ne.id = " + e.id + "\ne.ref = " + e.ref);
}

/***********************************************************************
    loadAlternateFlash :: Functions
***********************************************************************/
function loadAlternateFlash()
{
	$.get('HomePageAlternateFlash.aspx', function(data)
	{
		$('#flashContent').html(data);
	});
}


function printPage() {
	window.print();
	if (GAPage) {
		var page = window.location.pathname;
		GAPage.trackEvent("Print Links", "Print", GAPage.normalizeURL(page));
	}
}

function closeRegistionForm(t) {
    if (t <= 0) {
        parent.closeModalIFrame();
    }
    else {
        t--;
        $('#timer').html(t);
        setTimeout("closeRegistionForm(" + t + ")", 1000);
    }
}


