//Modal mask
var Modal = {
    width: 0,
    onOpen: function () { },
    onClose: function () { },
    onResize: function () { },
    open: function (options) {
        options = options || {};
        var title = options.title || "";
        var url = options.url || "";
        var trackUrl = options.trackUrl == null ? url : options.trackUrl;
        var params = options.params || {};
        var contentEl = options.contentEl || "";
        var iframe = options.iframe || "";
        var iheight = options.iheight || 300;
        var iwidth = options.iwidth || 640;
        var externalHref = options.externalHref || "";
        var onComplete = params.onComplete || function () { };
        //if (trackUrl != "")
        //pageTracker._trackPageview(trackUrl);
        Modal.onOpen = options.onOpen || function () { };
        Modal.onClose = options.onClose || function () { };
        Modal.onResize = options.onResize || function () { };
        Modal.onTransferContent = options.onTransferContent || function () { };
        Modal.modalStyle = options.modalStyle || "";
        Modal.top = options.top || 100;
        Modal.width = options.width || 500;
        if (iframe != "") Modal.width = iwidth;
        Modal.cleanUp(); //clean up old modal
        params.onComplete = function () {
            $("#modalloader").remove(); //in case of error, don't show loading animation forever
            onComplete.apply(null, arguments);
        }; 

        if (url != "") {
            $("#modalcontent").html("<div id='modalloader' class='modalloader'></div>"); //show loading animation
            Modal.updater = $("#modalcontent").load(url, params.onComplete);
        }
        else if (contentEl != "") {//make sure moving contentEl into the modal doesn't duplicate id's
            Modal.contentOrigin = $(contentEl);
            Modal.transferContent(Modal.contentOrigin, "#modalcontent");
        }
        else if (iframe != "") {
            Modal.updater = $("#modalcontent").html('<iframe src="' + iframe + '" width="' + iwidth + '" height="' + iheight + '" frameborder="0" allowtransparency="true"><p>Your browser does not support iframes.</p></iframe>');
        }
        $("#modalcontainer").addClass(Modal.modalStyle).removeClass("hidden");
        $("#modaltitle").html(title);

        Modal.resize();

        if (Modal.modalStyle.match("graphmodal") != null) {
            imgH = $("#modalcontent img").height();
            imgW = $("#modalcontent img").width();
            $("#modalcloser").css({ 'display': 'none' }).delay(800).fadeIn();
            $("#modalcontent h2").css({ 'opacity': '0' }).delay(800).animate({ 'opacity': '1' });
            $("#modalcontent img").css({ 'height': 0, 'width': 0 }).animate({ 'height': imgH + 'px', 'width': imgW + 'px' }, "slow");
        } else if (Modal.modalStyle.match("leaving") != null) {
            externalLink = externalHref;
        }

        Modal.onOpen(); //use params.onComplete if you want something to run after the AJAX finishes        
    },
    close: function () {
        //pageTracker._trackEvent('Modal', 'Close');
        if ($('.pdufaModal').is('*')) {
            $('.pdufamodalcontent').jScrollPaneRemove();
        }
        Modal.onClose();
        Modal.cleanUp();
        $("#modalcontainer").removeClass(Modal.modalStyle);
        $("#modalcontent").html('');
    },
    cleanUp: function () {
        if (Modal.contentOrigin) {//make sure restoring contentEl doesn't duplicate id's
            Modal.transferContent("#modalcontent", Modal.contentOrigin);
            Modal.contentOrigin = null;
        }
        $("#modalcontainer").removeClass(Modal.modalStyle).addClass("hidden");
        $("#modalcontent").html('');
    },
    resize: function () {

        // find mobile user agents
        var agent = navigator.userAgent.toLowerCase();
        var is_iphone = ((agent.indexOf('iphone') != -1));
        var is_ipad = ((agent.indexOf('ipad') != -1));
        var is_android = ((agent.indexOf('android') != -1));
        var is_blackberry = ((agent.indexOf('blackberry') != -1));

        var is_mobile = (is_ipad || is_iphone || is_android || is_blackberry); // combine all mobile user agents into a variable for all mobiles


        var height = $("#modalbody").height();
        // set left position to zero if mobile
        if (is_mobile) {
            var left = (0);
        } else {
            var left = (document.documentElement.offsetWidth / 2) - (Modal.width / 2);
        }
        // set top position to zero if mobile
        if (is_mobile) {
            var top = (0);
        } else {
            var top = ($(window).height() > height + Modal.top) ? Modal.top : ($(window).height() - height) / 2;
        }
        var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
        var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
        left = (left > 0) ? left : 0;
        top = (top > 0) ? top : 0;
        if (Modal.modalStyle) {
            // set left and top position to zero if mobile
            if (is_mobile) {
                $("#modalbody").css({
                    left: (0) + "px",
                    top: (0) + "px"
                });
            } else {
                $("#modalbody").css({
                    left: (Modal.modalStyle.match(/regModal/i) != null) ? 200 + "px" : (scrollLeft + left) + "px",
                    top: (Modal.modalStyle.match(/regModal/i) != null) ? 10 + "px" : (scrollTop + top) + "px"
                });
            }
        } else {
            // set left and top position to zero if mobile with no scrollLeft or scrollTop
            if (is_mobile) {
                $("#modalbody").css({
                    left: (0) + "px",
                    top: (0) + "px"
                });
            } else {
                $("#modalbody").css({
                    left: (scrollLeft + left) + "px",
                    top: (scrollTop + top) + "px"
                });
            }
        }
        $("#modalbody").width(Modal.width + "px");
        //only calculate scroll dimensions after modal body has been repositioned
        $("#modalmask").hide(); //hide mask temporarily to measure document size
        var scrollHeight = Math.max(document.body.scrollHeight, $(window).height());
        var scrollWidth = Math.max(document.body.scrollWidth, $(window).width());
        $("#modalmask").css({
            height: scrollHeight + "px",
            width: scrollWidth + "px"
        });
        $("#modalmask").show();
        Modal.onResize();
    },
    transferContent: function (source, dest) {
        $(dest).html($(source)[0].innerHTML);
        $(source)[0].innerHTML = "";
        Modal.onTransferContent();
    }
}

var stopcarousel = false;

var runcarousel = function () {

    var getcurrent = jQuery('#gallery-box .active').removeClass('active').css('display', 'none');
    var getcurrentbtn = jQuery('#switcher li.active').removeClass('active');
    var next = getcurrent.parent().next('div').find('div:first');

    if (next.length) {
        getcurrentbtn.next('li').addClass('active');
        next.addClass('active').fadeIn('slow');
        jQuery('#switcher-next').html(jQuery('#switcher li.active .switcher-next-hidden').html());


    } else {
        getcurrentbtn;
        jQuery('#switcher > li:first').addClass('active');
        jQuery('#switcher-next').html(jQuery('#switcher li.active .switcher-next-hidden').html());
        getcurrent;
        jQuery('#gallery-box > div:first > div:first').addClass('active').fadeIn('slow');
    }

}

var showgallery = function (gallery) {
    jQuery('#switcher li').each(function (s, value) {
        jQuery(this).removeClass('active');
        if ((gallery - 1) == s) {
            jQuery(this).addClass('active');
            jQuery('#switcher-next').html(jQuery('#switcher li.active .switcher-next-hidden').html());
        }
    });
    jQuery('#gallery-box .active').removeClass('active');
    jQuery('#gallery-box .gallery').each(function (s, value) {
        if (s + 1 == gallery) {
            jQuery(this).addClass('active');
        }
    });
    jQuery('#gallery-box > div > div:nth-child(1)').css('display', 'none');
    jQuery('#gallery' + gallery).fadeIn('slow');
    stopcarousel = true;
}

var TOOLTIPS = (function(){
	
	var tooltips = {};
	
	tooltips.init = function() {
		var that = this;
		var carousel = jQuery('#carousel');
		
		jQuery('#switcher li').hover(
			function() {
				var index = jQuery(this).find('a').text();
				var tooltip = "#gallery" + index + '-wrapper .tooltip';
				var element = carousel.find(tooltip);
				that.position(element, index-1, {start: 22, interval: 21});
				
				
		},
			function() {
				var index = jQuery(this).find('a').text();
				var tooltip = "#gallery" + index + '-wrapper .tooltip';
				carousel.find(tooltip).addClass('hidden');
			}
		);
		
	};
	
	tooltips.position = function(elem, index, options){
		var start = options.start;
		var interval = options.interval;
		var location = start + (interval * index);
		elem.css({'left': location+"px"}).removeClass("hidden");
		
		
	};
	
	return tooltips;

})();

//get position of element
var isScrolledIntoView = function(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    if ($(elem).offset() == null) return;
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    //return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    return elemTop - docViewTop;
}

var expandISI = function () {
    var navHeight = 150;
    var expandHeight = 125 + isScrolledIntoView('#bottom-isi') - navHeight;
    var expandBarHeight = 75 + isScrolledIntoView('#bottom-isi') - navHeight;
    $('#expandISI').toggle(function () {
        $('#bottom-isi').animate({ height: expandHeight }).find('#bottom-isi-content').css({ height: expandBarHeight }).prev().find('a').addClass('collapse');
        $('#bottom-isi-content').jScrollPane({ showArrows: true });
    }, function () {
        $('#bottom-isi').animate({ height: '125' }).find('#bottom-isi-content').css({ height: '75' }).prev().find('a').removeClass('collapse');
        $('#bottom-isi-content').jScrollPane({ showArrows: true });
    });
}

var setBottomISI = function () {
    $('#bottom-isi-content').html($('#isicontainer').html());
    $('#bottom-isi-content').jScrollPane({ showArrows: true });
    $('#bottom-isi-content #isitext h2').remove();
    $('#bottom-isi-content #isitext ul li:first').remove();
}

var fontsizing = function () {
    var fontcount = 0;
    // Increase Font Size
    $(".util-links .incr").click(function () {
        if (fontcount <= 5) {
			
			// remove any previous font class from the body
			var oldClass = "fontsize" + fontcount;
			$("body").removeClass(oldClass);
			
            fontcount++;
			
			// add the current font class to the body
			var newClass = "fontsize" + fontcount;
			$("body").addClass(newClass);
			
            $('.pdufa #container #middle').find('*').each(function () {
                var currentFontSize = $(this).css('font-size');
                var currentFontSizeNum = parseInt(currentFontSize);
                var newFontSize = currentFontSizeNum + 1;
                $(this).css('font-size', newFontSize + 'px');
            });
        }
        return false;
    });
    // Decrease Font Size
    $(".util-links .decr").click(function () {
        if (fontcount > 0) {
            
			// remove any previous font class from the body
			var oldClass = "fontsize" + fontcount;
			$("body").removeClass(oldClass);
			
            fontcount--;
			
			// add the current font class to the body
			var newClass = "fontsize" + fontcount;
			$("body").addClass(newClass);

            $('.pdufa #container #middle').find('*').each(function () {
                var currentFontSize = $(this).css('font-size');
                var currentFontSizeNum = parseInt(currentFontSize);
                var newFontSize = currentFontSizeNum - 1;
                $(this).css('font-size', newFontSize + 'px');
            });
        }
        return false;
    });
}

var closeModalIFrame = function () {
    if (SSLPage && (SSLPage.DoRedirect && SSLPage.isSecure())) {
        // closing iframe, but we don't need ssl anymore, redirect to normal url
        var ary = SSLPage.getQueryString2Hash();
        delete ary["register"];
        var qs = SSLPage.getHash2QueryString(ary);
        var url = SSLPage.getNormalURL();
        if (qs != "")
            url += "?" + qs;
        location.href = url;
    }
    else {
        Modal.close();
        if (GAPage) {
            GAPage.closeModal();
        }
    }
}


$(function () {
    fontsizing();
    setBottomISI();
    expandISI();


    //target mobile phones
    if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
        $('.topbg').css({ 'width': '1003px' });
    }

    /*menu selected*/
    $('.pdufa #primaryNavigation a').each(function () {
        var urlpath = new RegExp($(this).attr('href'), "i");
        if (document.location.href.match(urlpath) != null) {
            $(this).parent().addClass('selected')
        }
    });

    if (document.location.href.match(/previously-untreated-multiple-myeloma/i) != null) {
        $('.pumm').parent().addClass('selected');
    } else if (document.location.href.match(/relapsed-multiple-myeloma/i) != null) {
        $('.rmm').parent().addClass('selected');
    } else if (document.location.href.match(/relapsed-mantle-cell-lymphoma/i) != null) {
        $('.rmcl').parent().addClass('selected');
    } else if (document.location.href.match(/reimbursement-program/i) != null) {
        $('.ri').parent().addClass('selected');
    } else if (document.location.href.match(/app/i) != null) {
        $('.vpa').parent().addClass('selected');
    }

    /*carousel*/
    TOOLTIPS.init();
    setInterval(function () {
        if (stopcarousel == false) {
            runcarousel();
        }
    }, 5000);

    $('.gallery-holder').mouseover(function (e) {
        stopcarousel = true;
    }).mouseout(function (e) {
        stopcarousel = false;
    });

    /*end carousel*/

    $('.view_larger_image').click(function (e) {
        var gallery = $(this).closest('.gallery').attr('id');
        var galleryNumber = gallery.match(/gallery(\d)/)[1];
        var modalGraph = $('#modal-graph' + galleryNumber)[0];
        Modal.open({ contentEl: modalGraph, width: 630, modalStyle: 'graphmodal', onOpen: function () { setTimeout(function () { stopcarousel = true; }, 1000); }, onClose: function () { stopcarousel = false; } });
    });



    $(window).resize(Modal.resize);
    $("#modalcloser").click(Modal.close);


    /*pdufa contact modal*/
    /*$('.pdufa #globalUtility .header-links li:last a,.pdufa #globalLinks a:first, .learnmoreContact').click(function (e) {
        showmodaltext(e, '#ContactText', '/Global/ContactUs.aspx');
    });*/
    $('.pdufaModal #ctl00_ContactUs_A1').live('click', function (e) {
        Modal.close();
        showmodaltext(e, '#PrivacyText', '/Global/PrivacyPolicy.aspx');
    });

    /*pdufa privacy modal*/
    $('.pdufa #globalLinks a:nth-child(3)').click(function (e) {
        showmodaltext(e, '#PrivacyText', '/Global/PrivacyPolicy.aspx');
    });
    $('.pdufaModal #ctl00_PrivacyText1_A1').live('click', function (e) {
        Modal.close();
        showmodaltext(e, '#TermsText', '/Global/TermsOfUse.aspx');
    });

    /*pdufa terms modal*/
    $('.pdufa #globalLinks a:nth-child(2)').click(function (e) {
        showmodaltext(e, '#TermsText', '/Global/TermsOfUse.aspx');
    });
    $('.pdufaModal #ctl00_TermsText1_A1').live('click', function (e) {
        Modal.close();
        showmodaltext(e, '#PrivacyText', '/Global/PrivacyPolicy.aspx');
    });

    /*leaving modal*/
    $('.pdufa .leaving').click(function (e) {
        showmodaltext(e, '#LeavingText', '/Global/TermsOfUse.aspx');
    });
})

var showmodaltext = function (event, id, track) {
    event.preventDefault();
	Modal.open({ contentEl: id, modalStyle: 'pdufaModal' });
    TrackPopupModal(track);
    $('.pdufamodalcontent').jScrollPane({ showArrows: true });
}

var registPopup = function() {

    if (SSLPage && (!SSLPage.DoRedirect || SSLPage.isSecure())) {
        // don't redirect page because registration is in SSL already
        Modal.open({ iframe: '/registration.aspx', modalStyle: 'iframe regModal', width: '590', iheight: '780' });
        TrackPopupModal('registration.aspx');
    } else {
        var ary = SSLPage.getQueryString2Hash();
        ary["register"] = "true";
        var qs = SSLPage.getHash2QueryString(ary);
        var url = SSLPage.getSecureURL();
        if (qs != "")
            url += "?" + qs;
        location.href = url;
    }
}

var contactusPop = function () {
    Modal.open({ iframe: '/ContactUs.aspx', modalStyle: 'sharemodal', top: '10', iheight: '730' }); 
    TrackPopupModal('/contactus.aspx');
}

// unsubscribe dropdown
$("#options div").live("mouseover", function(){$(this).addClass("hover")})
				.live("mouseout", function(){$(this).removeClass("hover")})
				.live("click", function(){
					$("#specialty,#reason").val($(this).html())
				})

$("#specialty,#selector,#reason").live("click", function(){
	$("#options").removeClass("hidden");
})

$("html").click(function(e){
	if(e.target.id != "specialty" && e.target.id != "selector")
		$("#options").addClass("hidden");
})
// end unsubscribe pulldown



