﻿var origPageHeight = null;
var siteBasePath = null;
var currentSelected = "";

function openReferences(page, height) {
    openChromelessWindow(siteBasePath + "/popups/references.aspx?q=" + page, 450, height);
}

function openChromelessWindow(url, width, height) {
    if (width == null)
        width = 800;
    if (height == null)
        height = 600;

    var x = screen.availWidth / 2 - (width / 2);
    var y = screen.availHeight / 2 - (height / 2);

    if (typeof (winHost) == "object")
        if (!winHost.closed)
            winHost.close();

    var strFeatures = "directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,height=" + height + ",width=" + width + ",top=" + y + ",left=" + x;
    winHost = window.open(url, "winHost", strFeatures, true);
    //winHost = window.open(url, "winHost", "", true);
}

function openHistoryVideo() {
    openChromelessWindow('../flash/flashhost.aspx?module=history', 640, 524);
}

function openAHAVideo() {
    openChromelessWindow('../flash/flashhost.aspx?module=aha', 480, 290);
}

function openTzdsVideo() {
    openChromelessWindow('../flash/flashhost.aspx?module=tzds', 640, 504);
}

function openHowItWorksBranded() {
    trackEvent('Video', 'How Actos Works', '');
    openChromelessWindow('flash/flashhost.aspx?module=moab', 720, 405);
}

function openExternalLink(linkUrl) {
    if (confirm('You are leaving ACTOS.com and connecting to a website that is not under the control of Takeda Pharmaceuticals North America, Inc. (Takeda). Takeda is not responsible for the contents of any such Website or any further links from such Website. Takeda is providing these links only as a convenience, and the inclusion of any link does not imply the endorsement by Takeda of the linked Website. Takeda Pharmaceuticals North America, Inc. cannot assume the accuracy or timeliness of the information available at this site.\n\nPlease click "OK" if you wish to be taken to this non-Takeda website.')) {
        //window.location = linkUrl;
        var newWindow = window.open(linkUrl, '_blank');
        newWindow.focus(); 

    }
}

function setModals(isHCP) {
    var duetactURL;
    var actoplusmetURL;

    if (/\/hcp\//.test(window.location.toString().toLowerCase())) {
        duetactURL = siteBasePath + "HCP/Duetact/Duetact.aspx"
        actoplusmetURL = siteBasePath + "HCP/ActoPlusMetXR/ActoPlusMetXR.aspx";
    }
    else {
        duetactURL = siteBasePath + "Duetact/Duetact.aspx"
        actoplusmetURL = siteBasePath + "ActoPlusMetXR/ActoPlusMetXR.aspx";
    }

    if ($(".modalButtonActoPlusMet").length) {
        $('.modalButtonActoPlusMet').click(function (e) {
            var src = actoplusmetURL;
            loadModal(src, 'simplemodal-closeActoPlusMet');
            return false;
        });
    }

    if ($(".modalButtonDuetact").length) {
        $('.modalButtonDuetact').click(function (e) {
            var src = duetactURL;
            loadModal(src, 'simplemodal-closeDuetact');
            return false;
        });
    }
}

function loadModal(src, closeClass) {
    $.modal('<iframe src="' + src + '" width="875" height="2600" style="background-color: transparent; border: 0px;" allowTransparency="true" frameborder="0" id="childframe">', {
        closeClass: closeClass,
        containerCss: {
            height: 2800,
            width: 875
        },
        overlayClose: true,
        opacity: 25,
        position: [90],
        onShow: function (dialog) {
            //                    var theFrame = $("#childframe", parent.document.body);
            //                    alert(theFrame);
            //                    alert(theFrame.height());
            //                    theFrame.height($(document.body).height() + 30);
            //                    alert(theFrame.height());

            var theFrame = $("#childframe", parent.document.body);
            theFrame.load(function () {
                var iFrame = document.getElementById('childframe');

                resizeModal();

                // check to make sure the height was modified
                // if not resize it again
                // only run 5 times
                var count = 0;
                while (iFrame.style.height == '') {
                    count++;
                    if (count == 5)
                        break;
                    resizeModal();
                    //alert(iFrame.style.height);
                }

            });
        },
        onClose: function (dialog) {
            window.location.hash = "";
            var page = $('.page');
            page.height(origPageHeight);
            origPageHeight = null;
            $.modal.close();
        }
    });
}

function resizeModal() {
    var iFrame = document.getElementById('childframe');
    
    var iFrameBody;
    var height;
    if (iFrame.contentDocument) { // FF
        height = iFrame.contentDocument.body.offsetHeight;
    }
    else if (iFrame.contentWindow) { // IE
        height = iFrame.contentWindow.document.body.scrollHeight;
        //iFrameBody = iFrame.contentWindow.document.body;
    }

    //var height = iFrameBody.scrollHeight;
    iFrame.style.height = (height + 25) + "px";
    
    $('#simplemodal-overlay').css('height', '100%');
    $('.simplemodal-container').css('height', 'auto');

    var page = $('.page');
    if (origPageHeight == null)
        origPageHeight = page.height();

    if (page.height() < height)
        page.height(height);
    else if (height < origPageHeight)
        page.height(origPageHeight);
    else if (height > origPageHeight)
        page.height(height);
}

function closeModalFromChild() {
    window.parent.jQuery.modal.close(true); // true means it's an external close call
}


var api;
function jScrollPaneInit() {
    $(function () {
        if ($('.scroll-pane').length != 0) {
            api = $('.scroll-pane').jScrollPane(
            {
                showArrows: true
            }).data('jsp');
        }
    });
}

function accordionInit() {
    $('#accordion .accordionHeader').click(function () {
        var button = $(this).children().eq(1);
        if (button.hasClass('buttonClose')) {
            button.removeClass('buttonClose');
            $(this).removeClass('itemSelected');
        }
        else {
            button.addClass('buttonClose');
            $(this).addClass('itemSelected');
        }
        $(this).next().toggle(0);
        return false;
    }).next().hide();

    var defaultOpen = $('#accordion .default');
    if (defaultOpen.length) {
        defaultOpen.find('.accordionHeader').click();
    }
}

function instantPollUpdate(poll, option) {
    var myData = { 'InstantPollID':poll, 'OptionID':option };
    var json = JSON2.stringify(myData);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: siteBasePath + "Services.svc/UpdateInstantPoll",
        data: json,
        dataType: "text",
        processData: false,
        success: function (msg) {
            // Do interesting things here.
            var result = JSON2.parse(msg);
            //alert(result.d.ResponseText);
            animatePollResult(result.d.ResponseCorrect, result.d.ResponseValue, result.d.ResponseText);
        },
        error: function (request, status, errorThrown) {
            alert(request.responseText);
            alert(status);
            alert(errorThrown);
        }
    });

}

function animatePollResult(correct, value, responseText) {
    $('.pollResponse').show();
    $('.pollResponse .pollBar .pollFill').css('width', '0px').animate(
        {
        width: value.toString() + '%'
        },
        {
            duration: 1000,
            step: function (now, fx) {
                $('.pollResponse .pollPercentage').text(Math.round(now) + "%");
            },
            specialEasing: {
                width: 'linear'
            }
        }
    ).children().text(correct);

        $('.pollResponse .pollResponseDescription').text(responseText);
//        var clicker = $('.pollOption .extender_checkbox');
//        clicker.each(function (index) {
//            alert(this.onclick);
//            this.onclick = undefined;
//            alert(this.onclick);
//        });
        $('.pollOption .extender_checkbox').removeAttr('onclick');
        // click(function () { alert('test'); return false; });

        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            var background = $('.instantPoll .instantPollBackground');
            if (background) {
                var content = $('.instantPoll .pollContent');
                var response = $('.pollResponse');
                var h = content.parent().height() + response.height();
                background.css("height", (h) + 130);
                content.css("margin-top", -(background.height()));
            }
        }
}

function overlaySetHash() {
    var path = window.location.pathname;
    //var fileName = path.substring(path.lastIndexOf('/') + 1).toLowerCase();
    var fileName = path.substring(1);
    
    parent.window.location.hash = fileName;

    // log the page for google analytics
    parent.window.trackEvent('Overlay', 'Page Requested', fileName);
}

function trackEvent(category, action, other) {
    // log the event to google analytics
    _gaq.push(['_trackEvent', category, action, other]);
}

function glimmer() {
    var glimmer = $(".glimmer");
    if (glimmer.length) {
        glimmer.each(function (index) {
            $(this).spanize('anim', 5);
            var color = $(this).css('color');
            if (color == null)
                color == '#6c6c6c';

            $(this).find('.anim').each(function (index) {
                var item = $(this);
                window.setTimeout(function () {
                    item.animate({ color: '#ffffff' }, 500).animate({ color: color }, 500);
                }, 50 * index);

                //        timer = window.setInterval(function () {
                //            item.animate({ color: 'red' }, 1000).animate({ color: '#6c6c6c' }, 1000);
                //            window.clearInterval(timer); timer = null;
                //        }, 50);
            });
        });
    }
}

function cycleImages() {
    if ($('.rotateImage').length) {
        $('.rotateImage img').show();
        $('.rotateImage').cycle({
            delay: 3000,
            speed: 1500,
            timeout: 5000
        });
    }
}

function expandInit() {
    if ($('.buttonExpand')) {
        $('.buttonExpand').click(function () {
            var div = $('.ISIfixedOuter');
            //alert(div.height());
            //            alert($('.scroll-pane').height());
            if (div.hasClass('ISIfixedExpand')) {
                div.removeClass('ISIfixedExpand');
                $(this).removeClass('buttonExpandCollapse');
                if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
                    var theWindow = $(window);
                    var windowHeight = theWindow.height();
                    var scrollTop = theWindow.scrollTop();

                    $('.scroll-pane').height(27);
                    div.height(147);

                }
                $('.scroll-pane').height(div.height() - 27);
            }
            else {
                div.addClass('ISIfixedExpand');
                $(this).addClass('buttonExpandCollapse');
                if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
                    var theWindow = $(window);
                    var elementHeight = div.height();
                    var windowHeight = theWindow.height();
                    var scrollTop = theWindow.scrollTop();

                    div.height(windowHeight - 90);

                }
                $('.scroll-pane').height(div.height() - 147);

            }
            //alert($('.scroll-pane').height());
            api.reinitialise();
        });
    }
}

function menuInit() {
    $('.menu .item a').hover(
    function () {
        var parent = $(this).parent();
        if (!parent.hasClass('selectedChild')) {
            $(this).next().slideDown();
        }
        if (!parent.hasClass('itemChild'))
            parent.addClass('hover');
    },
    function () { })
    .parent('.item').hover(function () { },
    function () {
        if (!$(this).hasClass('selectedChild')) {
            $(this).children('ul').slideUp();
        }
        $(this).removeClass('hover');
    });
}

function rolloverInit() {
    if ($('.rolloverContent').length) {
        $('.rolloverContent').hide();
        var d = $('#homeDefault');
        if (d.length) {
            d.show();
        }

        $('#rollovers .safetyRollover').hover(function () { $('.rolloverContent').hide(); $('#homeSafety').show(); });
        $('#rollovers .whatisitRollover').hover(function () { $('.rolloverContent').hide(); $('#homeWhatIsIt').show(); });
        $('#rollovers .signupRollover').hover(function () { $('.rolloverContent').hide(); $('#homeSignup').show(); });
        $('#rollovers .howitworksRollover').hover(function () { $('.rolloverContent').hide(); $('#homeHowItWorks').show(); });
    }
}

function clearText(item, defaultText) {
    if (item.value == defaultText)
        item.value = "";
}

function resetText(item, defaultText) {
    if (item.value == "")
        item.value = defaultText;
}

// registration
function registrationPrescribed(value) {
    var panel = $("#divPrescribed");
    if (value) {
        panel.show();
        checkTherapySatisfy();
    }
    else {
        panel.hide();
        $('#divTherapySatisfied').show();
    }

}

function checkPrescribed(itemClass, divItem) {
    // check if checkbox is checked
    var item = $('.' + itemClass + ' input:hidden');
    var show = item.val() === '1';

    if (show) {
        switch (itemClass) {
            case "actosReg":
                if (currentSelected !== "actoplusmetReg" && currentSelected !== "duetactReg") {
                    $('div.actoplusmetReg').css('color', '#cccccc');
                    $('div.duetactReg').css('color', '#cccccc');

                    currentSelected = "actosReg";
                    $('#' + divItem).show();
                }
                else {
                    $(item).val('0');
                    $('div.actosReg').find('.extender_checkbox').attr('src', siteBasePath + 'Styles/images/checkbox.png');
                }
                break;
            case "actoplusmetReg":
                if (currentSelected !== "actosReg" && currentSelected !== "duetactReg") {
                    $('div.actosReg').css('color', '#cccccc');
                    $('div.duetactReg').css('color', '#cccccc');

                    currentSelected = "actoplusmetReg";
                    $('#' + divItem).show();
                }
                else {
                    $(item).val('0');
                    $('div.actoplusmetReg').find('.extender_checkbox').attr('src', siteBasePath + 'Styles/images/checkbox.png');
                }
                break;
            case "duetactReg":
                if (currentSelected !== "actoplusmetReg" && currentSelected !== "actosReg") {
                    $('div.actosReg').css('color', '#cccccc');
                    $('div.actoplusmetReg').css('color', '#cccccc');

                    currentSelected = "duetactReg";
                    $('#' + divItem).show();
                }
                else {
                    $(item).val('0');
                    $('div.duetactReg').find('.extender_checkbox').attr('src', siteBasePath + 'Styles/images/checkbox.png');
                }
                break;
            default:
                $('#' + divItem).show();
                break;
        }
    }
    else {
        switch (currentSelected) {
            case "actosReg":
                $('div.actoplusmetReg').css('color', '#000000');
                $('div.duetactReg').css('color', '#000000');
                break;
            case "actoplusmetReg":
                $('div.actosReg').css('color', '#000000');
                $('div.duetactReg').css('color', '#000000');
                break;
            case "duetactReg":
                $('div.actosReg').css('color', '#000000');
                $('div.actoplusmetReg').css('color', '#000000');
                break;
            default:
                break;
        }

        currentSelected = "";
        $('#' + divItem).hide();
    }

    checkTherapySatisfy();    
}

function toggleQuestions(itemClass, showValue, divOne, divTwo, childIndex) {
    var item;
    if (typeof childIndex !== 'undefined') {
        $('.' + itemClass).each(function (index) {
            if (index === childIndex) {
                item = $(this).find('input:hidden');
            }
        });

        if (item === null) {
            item = $('.' + itemClass + ' input:hidden');
        }
    }
    else {
        item = $('.' + itemClass + ' input:hidden');
    }

    var show = item.val() === showValue;

    if (show) {
        $('#' + divOne).show();
        $('#' + divTwo).hide();
    }
    else {
        $('#' + divOne).hide();
        $('#' + divTwo).hide();
    }
}

function checkTherapySatisfy() {
    // if actos, actoplus met, or duetact selected, dont show question
    if ($('#divActosSpecific').is(':visible') || $('#divActoplusmetSpecific').is(':visible') || $('#divDuetactSpecific').is(':visible')) {
        $('#divTherapySatisfied').hide();
    }
    else {
        $('#divTherapySatisfied').show();
    }
}

function checkCaregiver() {
    var item = $('.caregiver input:hidden');
    if (item.val() == '1') {
        // checked, hide the rest
        $('#patientQuestionBlock').hide();
    }
    else {
        // not checked, show the rest
        $('#patientQuestionBlock').show();
    }
}

function validateRegistration(sender, args, item) {
    args.IsValid = false;
    $('.' + item + ' input:hidden').each(function (index) {
        var item = $(this);
        if (item.val() != '0') {
            //checked
            args.IsValid = true;
        }
    });
}

function validateRegistrationGender(sender, args) {
    validateRegistration(sender, args, 'gender');
}

function validateRegistrationDescription(sender, args) {
    validateRegistration(sender, args, 'describe');
}

function validateRegistrationDiagnosis(sender, args) {
    var item = $('.describe input:hidden').last();
    if (item.val() == '1') {
        // caregiver is checked, continue process
        args.IsValid = true;
    }
    else {
        // patient is checked, continue process
        validateRegistration(sender, args, 'diagnosisTime');
    }
}

function validateRegistrationA1C(sender, args) {
    var item = $('.describe input:hidden').last();
    if (item.val() == '1') {
        // caregiver is checked, continue process
        args.IsValid = true;
    }
    else {
        // patient is checked, continue process
        validateRegistration(sender, args, 'a1c');
    }
}

function validateRegistrationPrescribe(sender, args) {
    var item = $('.describe input:hidden').last();
    if (item.val() == '1') {
        // caregiver is checked, continue process
        args.IsValid = true;
    }
    else {
        // patient is checked, continue process
        validateRegistration(sender, args, 'prescribe');
    }
}

function validateRegistrationAdditionalPrescribe(sender, args) {
    var itemDescribe = $('.describe input:hidden').last();
    if (itemDescribe.val() == '1') {
        // caregiver is checked, continue process
        args.IsValid = true;
    }
    else {
        // patient is checked, continue process
        var item = $('.prescribe input:hidden').first();
        if (item.val() == '1') {
            validateRegistration(sender, args, 'currentPrescription');
        }
        else {
            args.IsValid = true;
        }
    }
}

function validateRegistrationActosCurrentlyTaking(sender, args) {
    if ($('#divActosSpecific').is(":visible")) {
        validateRegistration(sender, args, 'currentlyTakingActos');
    }
    else
        args.IsValid = true;
}

function validateRegistrationActosPrescription(sender, args) {
    if ($('#divActosSpecificPrescription').is(":visible")) {
        validateRegistration(sender, args, 'prescriptionFilledActos');
    }
    else
        args.IsValid = true;
}

function validateRegistrationActosBegan(sender, args) {
    if ($('#divActosSpecificBegan').is(":visible")) {
        validateRegistration(sender, args, 'beganActos');
    }
    else
        args.IsValid = true;
}


function validateRegistrationActoplusmetCurrentlyTaking(sender, args) {
    if ($('#divActoplusmetSpecific').is(":visible")) {
        validateRegistration(sender, args, 'currentlyTakingActoplusmet');
    }
    else
        args.IsValid = true;
}

function validateRegistrationActoplusmetPrescription(sender, args) {
    if ($('#divActoplusmetSpecificPrescription').is(":visible")) {
        validateRegistration(sender, args, 'prescriptionFilledActoplusmet');
    }
    else
        args.IsValid = true;
}

function validateRegistrationActoplusmetBegan(sender, args) {
    if ($('#divActoplusmetSpecificBegan').is(":visible")) {
        validateRegistration(sender, args, 'beganActoplusmet');
    }
    else
        args.IsValid = true;
}


function validateRegistrationDuetactCurrentlyTaking(sender, args) {
    if ($('#divDuetactSpecific').is(":visible")) {
        validateRegistration(sender, args, 'currentlyTakingDuetact');
    }
    else
        args.IsValid = true;
}

function validateRegistrationDuetactPrescription(sender, args) {
    if ($('#divDuetactSpecificPrescription').is(":visible")) {
        validateRegistration(sender, args, 'prescriptionFilledDuetact');
    }
    else
        args.IsValid = true;
}

function validateRegistrationDuetactBegan(sender, args) {
    if ($('#divDuetactSpecificBegan').is(":visible")) {
        validateRegistration(sender, args, 'beganDuetact');
    }
    else
        args.IsValid = true;
}

function validateRegistrationSatisfied(sender, args) {
    var item = $('.describe input:hidden').last();
    if (item.val() == '1') {
        // caregiver is checked, continue process
        args.IsValid = true;
    }
    else {
        // patient is checked, continue process
        if ($('#divTherapySatisfied').is(':visible')) {
            validateRegistration(sender, args, 'satisfied');
        }
        else {
            args.IsValid = true;
        }
    }
    
}

function validateRegistrationTherapy(sender, args) {
    validateRegistration(sender, args, 'therapy');
}

function validationRegistrationAgree(sender, args) {
    validateRegistration(sender, args, 'agree');
}

//function validateRegistrationMail(sender, args) {
//    validateRegistration(sender, args, 'mailType');
//}

$(document).ready(function () {
    $(document).pngFix();
    setModals();
    jScrollPaneInit();
    accordionInit();
    setTimeout('glimmer()', 1000);
    cycleImages();
    expandInit();
    menuInit();
    rolloverInit();

    //    if ($(".datepicker").length)
    //        $(".datepicker").datepicker();

    //instantPollUpdate();

    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        var background = $('.instantPoll .instantPollBackground');
        if (background) {
            var content = $('.instantPoll .pollContent');
            var h = content.parent().height();
            background.css("height", (h / 2) + 30);
            content.css("margin-top", -(background.height()));
        } 
    }

    //alert(window.location.hash);
    if (window.location.hash.length > 1) {
        var src = siteBasePath + window.location.hash.substring(1);
        if (/duetact\//.test(window.location.toString().toLowerCase())) {
            loadModal(src, 'simplemodal-closeDuetact');
        }
        else if (/actoplusmetxr\//.test(window.location.toString().toLowerCase())) {
            loadModal(src, 'simplemodal-closeActoPlusMet');
        }
    }

});


//http://neganov.blogspot.com/2010/01/dynamic-text-highlighting-with-jquery.html
//http://usefulthink.com/2010-12/animating-text-shadow-using-jquery/
//http://buildinternet.com/2009/09/its-a-rainbow-color-changing-text-and-backgrounds/
//http://www.si-les-idees-suffisaient.net/jquery/textgrad.html
//http://jquery.offput.ca/highlightFade/old.php
//http://onehackoranother.com/projects/jquery/jquery-grab-bag/text-effects.html


