/*
Client: Samsca										
Author: Michael Lyons : michael.lyons@rosetta.com, Ryan Suleski : ryan.suleski@rosetta.com
Description: Main Javascript page
*/

/**** Main JS Class ****/
var Sam = Sam || {};

/**** Samasca.UI Definition ****/
Sam.UI = Sam.UI || {};

Sam.UI = {

    // global variables
    isMobile: false,

    clickEvent: 'click',


    // Init - Runs on DOM load : BEGIN
    init: function () {

        // browser check
        var browser = navigator.userAgent.toLowerCase();

        if (browser.indexOf('ipad') != -1 || browser.indexOf('iphone') != -1 || browser.indexOf('ipod') != -1) {
            Sam.UI.isMobile = true;
            Sam.UI.clickEvent = 'touchstart';
        } else if (browser.indexOf('android') != -1) {
            Sam.UI.isMobile = true;
        }


        // run methods
        Sam.UI.pdfBox();
        Sam.UI.emailBox();
        Sam.UI.vidPlayer.init();
        Sam.UI.nav();
        Sam.UI.interstitial();

        // had to fix the field names so that the text could be cleared ... 
        $("#VitalData_firstName, #VitalData_lastName").focus(function () {
            $('.pre').text("")
        });

        //form fields
        $('#RegistrationData_healthCareIdentifier').change(function () {
            Sam.UI.toggleHealthCareIdentifier(this);
        });

        $('a[href*=prescribing-information-samsca.pdf]').click(function () {
            _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'Prescribing Information']);
        });
        $('a[href*=medication-guide-samsca.pdf]').click(function () {
            _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'Medication Guide']);
        });

        $('a[href*=patient-asssistance-brochure-pi.pdf]').click(function () {
            _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'Patient Brochure with PI']);
        });
        $('a[href*=patient-asssistance-application-form-pi.pdf]').click(function () {
            _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'Application Form with PI']);
        });

    },
    // Init : END

    // fixes a bug where lightbox greyed  out bg might not be large enough
    growOverlay: function () {
        $('#fancybox-overlay').css({ 'width': $(document).width() });
    },

    openInterBox: function (link) {

        // set the href of the continue button to the href of what you clicked on
        $('#interstitialContinue').attr('href', link);

        // show the fanybox using the interstital popup html
        $.fancybox(
                $('#interstitial').parent().html(),
                {
                    'padding': 2,
                    'overlayColor': '#000',
                    'autoDimensions': true,
                    'onComplete': function () {
                        Sam.UI.growOverlay();
                    }
                }
         );

    },

    // interstitial lightbox : BEGIN
    interstitial: function () {

        // set vars
        var eventType = 'onClick';
        var closeFancy = '$.fancybox.close();';

        $('#interstitialContinue').attr(eventType, closeFancy);
        $('#interstitialGoBack').attr(eventType, closeFancy);

        $('a.interstitial').click(function () {



            Sam.UI.openInterBox(this.href);

            return false;

        });

        /*
        // set all intersitals click event
        $('a.interstitial').each(function () {
        var link = this.href;
        $(this).attr('href', 'javascript:void(0);').attr(eventType, 'Sam.UI.openInterBox("' + link + '");');
        $(this).attr('href', 'javascript:void(0);').attr(eventType, 'Sam.UI.openInterBox("' + link + '");');
        });
        */


    },
    // interstitial lightbox : END


    // Nav : BEGIN
    nav: function () {

        // store variables
        var origLeft = $('#header .left'),
            origRight = $('#header .right'),
            origCurrent = $('#header .current'),
            oldLeft = origLeft,
            oldRight = origRight,
            oldCurrent = origCurrent;


        /*
        When you mouse over a navigation item you make it blue by adding the class current
        Next you make the navigation itmes next to them 'left' and 'right'
        */
        $('#header .navBar a').mouseenter(function () {

            var $current = $(this);

            var leftID = $current.parent().attr('id') - 1;
            var rightID = leftID + 2;

            leftID = '#' + leftID + ' a';
            rightID = '#' + rightID + ' a';

            origLeft.removeClass('left');
            origRight.removeClass('right');
            origCurrent.removeClass('current');

            oldLeft.removeClass('left');
            oldRight.removeClass('right');
            oldCurrent.removeClass('current');

            oldLeft = $(leftID).addClass('left');
            oldRight = $(rightID).addClass('right');
            oldCurrent = $current.addClass('current');
        });

        /*
        When your mouse leaves the nav bar you reset it back to the way it was originally.
        */
        $('#header .navBar').mouseleave(function () {

            oldLeft.removeClass('left');
            oldRight.removeClass('right');
            oldCurrent.removeClass('current');

            origLeft.addClass('left');
            origRight.addClass('right');
            origCurrent.addClass('current');
        });


    },
    // Nav : END

    // logic for the pdf lightbox : BEGIN
    pdfBox: function () {

        // fanybox for click
        $('#hcpLetter').fancybox({
            'padding': 2,
            'overlayColor': '#000',
            'autoDimensions': true,
            'onComplete': function () {
                Sam.UI.growOverlay();
            }
        });

        // store the last checked radio button
        var lastChecked = $('#brochurePopup .checked');


        /*
        When you click a radio button first check if its already on. If yes do nothing
        If its a new button then set it to checked and turn off the last one
        */
        $('#brochurePopup .radio').bind(Sam.UI.clickEvent, function () {
            $this = $(this);
            if ($this.hasClass('checked')) { }
            else {
                lastChecked.removeClass('checked');
                $this.addClass('checked');
                lastChecked = $this;
            }
        });

        // store all the radio buttons
        var radioButtons = [$('#radio_0'), $('#radio_1'), $('#radio_2'), $('#radio_3')];

        // when you click cancedl the fancybox closes
        $('#cancelPDF').bind(Sam.UI.clickEvent, function () {
            $.fancybox.close();
        });

        // when you click download, load the correct pdf and close the fancybox
        $('#downloadPDF').bind(Sam.UI.clickEvent, function () {
            if (radioButtons[0].hasClass('checked')) {
                _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'HCP Letter']);
                window.open("/pdf/hcp-letter-samsca.pdf", "_blank");
            }
            else if (radioButtons[1].hasClass('checked')) {
                _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'HCP Letter with PI']);
                window.open("/pdf/hcp-letter-pi-samsca.pdf", "_blank");
            }
            else if (radioButtons[2].hasClass('checked')) {
                _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'Prescriber Brochure']);
                window.open("/pdf/prescriber-brochure-samsca.pdf", "_blank");
            }
            else if (radioButtons[3].hasClass('checked')) {
                _gaq.push(['_trackEvent', 'PDF Download', 'Download', 'Prescriber Brochure with PI']);
                window.open("/pdf/prescriber-brochure-pi-samsca.pdf", "_blank");
            }
            $.fancybox.close();
        });

    },
    // logic for the pdf lightbox : END

    // logic for the email a college lightbox : BEGIN
    emailBox: function () {

        // fanybox for click
        $('#emailColleague').fancybox({
            'padding': 2,
            'overlayColor': '#000',
            'autoDimensions': true,
            'onComplete': function () {
                Sam.UI.growOverlay();
            },
            'onClosed': function () {
                // when the fancy box is closed clear and hide thank you & show the form
                $('#emailForm_confirmation').hide();
                $('#emailForm').show();
            }
        });


        if (window.location.hash.indexOf('emailPopup') > -1) {
            $('#emailColleague').click();
        }
    },
    // logic for the email a college lightbox : END

    // logic for email a Colleague submit : BEGIN
    emailColleague_Callback: function () {

        // google analytics
        _gaq.push(['_trackEvent', 'EmailColleague', 'Success', 'EmailColleague']); // ga tag

        // clear inputs
        $('#emailForm .inputs input').val('');

        // hide the form and show the thank you
        $('#emailForm').hide();
        $('#emailForm_confirmation').show();
    },
    // logic for email a Colleague submit : END

    toggle: function (id) {
        var state = document.getElementById(id).style.display;
        if (state == 'block') {
            document.getElementById(id).style.display = 'none';
        } else {
            document.getElementById(id).style.display = 'block';
        }
    },

    toggleHealthCareIdentifier: function (select) {

        var selectedValue = $(select).attr('value');

        if (selectedValue == 'npi') {
            $('#health_care_identifier_npi').show();
            $('#health_care_identifier_state').hide();
        }
        else if (selectedValue == 'state') {
            $('#health_care_identifier_npi').hide();
            $('#health_care_identifier_state').show();
        }
    }

},

Sam.UI.vidPlayer = Sam.UI.vidPlayer || {};

Sam.UI.vidPlayer = {

    timer: -1,
    duration: -1,
    position: -1,
    percent: -1,
    current: null,
    video_default: 'includes/videos/Champion', // This is the featured video on the homepage callout
    video_specified: null,
    p_25: false,
    p_50: false,
    p_75: false,
    p_100: false,

    init: function () {
        if ($('#videoFileUrl').length > 0) {

            Sam.UI.vidPlayer.video_specified = $('#videoFileUrl').html();

            if (Sam.UI.vidPlayer.video_specified) {
                Sam.UI.vidPlayer.setup(Sam.UI.vidPlayer.video_specified, $('a[rel=' + Sam.UI.vidPlayer.video_specified + ']').attr('rev'), true);
            } else {
                Sam.UI.vidPlayer.setup(Sam.UI.vidPlayer.video_default, $('a[rel=' + Sam.UI.vidPlayer.video_default + ']').attr('rev'), !Sam.UI.isMobile);
            }

            $('.vidbox').click(function () {
                if (Sam.UI.vidPlayer.current != $(this).attr('rel')) {
                    Sam.UI.vidPlayer.setup($(this).attr('rel'), $(this).attr('rev'), true);

                    var sportlightSrc = '2828321';
                    var spotlightType = 'brand010';
                    var swfID = '/' + $(this).attr("rel");
                    var swfDATE = $(this).attr("title");
                    var swfCAT = $(this).attr("id");
                    var swfPAGEID = $(this).attr("dir");

                    var axel = Math.random() + "";
                    var axel2 = Math.random() + "";
                    var a = axel * 10000000000000;
                    var b = axel2 * 10000000000000;

                    var doPing_Datran = new Image();
                    doPing_Datran.src = 'http://aperture.displaymarketplace.com/audmeasure.gif?liveconclientID=4183299094980&PageID=' + swfPAGEID + '&EventType=view&rand=' + b;
                    var doPing = new Image();
                    doPing.src = 'http://ad.doubleclick.net/activity;src=' + sportlightSrc + ';type=' + spotlightType + ';cat=' + swfCAT + ';ord=' + a;
                }
            });

        }
    },

    reset: function () {
        clearInterval(Sam.UI.vidPlayer.timer);
        Sam.UI.vidPlayer.duration = Sam.UI.vidPlayer.position = Sam.UI.vidPlayer.percent = Sam.UI.vidPlayer.timer = -1;
        Sam.UI.vidPlayer.current = null;
        Sam.UI.vidPlayer.p_25 = Sam.UI.vidPlayer.p_50 = Sam.UI.vidPlayer.p_75 = Sam.UI.vidPlayer.p_100 = false;
    },

    status: function () {
        if (Sam.UI.vidPlayer.duration < 0) {
            Sam.UI.vidPlayer.duration = jwplayer().getDuration();
        } else {
            Sam.UI.vidPlayer.position = jwplayer().getPosition();
            Sam.UI.vidPlayer.percent = (Sam.UI.vidPlayer.position / Sam.UI.vidPlayer.duration) * 100;
            //console.log("Duration: " + Sam.UI.vidPlayer.duration + "\t\tPosition: " + Sam.UI.vidPlayer.position + "\t\tPercent: " + Sam.UI.vidPlayer.percent + "%");

            if (Sam.UI.vidPlayer.percent >= 25 && !Sam.UI.vidPlayer.p_25) {
                //console.log("25% watched");
                pageTracker._trackEvent("videos", Sam.UI.vidPlayer.current, "25% video playback");
                Sam.UI.vidPlayer.p_25 = true;
            } else if (Sam.UI.vidPlayer.percent >= 50 && !Sam.UI.vidPlayer.p_50) {
                //console.log("50% watched");
                pageTracker._trackEvent("videos", Sam.UI.vidPlayer.current, "50% video playback");
                Sam.UI.vidPlayer.p_50 = true;
            } else if (Sam.UI.vidPlayer.percent >= 75 && !Sam.UI.vidPlayer.p_75) {
                //console.log("75% watched");
                pageTracker._trackEvent("videos", Sam.UI.vidPlayer.current, "75% video playback");
                Sam.UI.vidPlayer.p_75 = true;
            } else if (Sam.UI.vidPlayer.percent >= 98 && !Sam.UI.vidPlayer.p_100) {
                //console.log("100% watched");
                pageTracker._trackEvent("videos", Sam.UI.vidPlayer.current, "100% video playback");
                Sam.UI.vidPlayer.p_100 = true;
                clearInterval(Sam.UI.vidPlayer.timer);
            }
        }
    },

    setup: function (source, width, autostart) {

        Sam.UI.vidPlayer.reset();

        Sam.UI.vidPlayer.current = source;

        jwplayer('vidPlayer').setup({
            autostart: autostart,
            width: width,
            height: '360',
            file: '/' + source + '.mp4',
            events: {
                onPlay:
                    function () {
                        if (Sam.UI.vidPlayer.timer < 0) {
                            //console.log('Video Playback Started');
                            Sam.UI.vidPlayer.timer = setInterval(function () { Sam.UI.vidPlayer.status(); }, 1000);
                        }
                    }
            },
            modes: [{ type: "html5" }, { type: "flash", src: "/includes/jwplayer/player.swf"}]
        });

        pageTracker._trackEvent("videos", Sam.UI.vidPlayer.current, "Playback Started");

    }

}

$(document).ready(function () {
    Sam.UI.init();
});
