// Interstitial Pluggin

// v .808 fixed hiehght issues in ie. jquery returned odd values for window v document height in ie

// v .807 added positioned-from-top, instead of centering.

// v .806 msgkill when exiting to adobe website.

// v .805 qi_dialogue'd new windows opening more qi_dialogs, fixed nameing convention. No need to update a tag's id name.

// v .804 fully jquery'd

// v .803 added support for newer versions of safari and chrome. instead of switching the contents of window -> now opens popup.

// v .802 added internal value for internal linking without having url launch in window
// use parameter {internal: true} when calling pluggin.

// v .801 Placed iframe for ie6 form elements.

// v .8

// Notes on using this plugin

// DOES NOT PLAY WELL WITH FULL SCREEN FLASH!
// Do not use anim time when dealing with flash objects
(function ($) {
    $.fn.qi_dialog = function (settings) {
        settings = $.extend({
            url: null,
            flash: false, // a div with flash in it. usefull for ie8 features

            // false : Normal click on link launches interstitial
            // true : Launches interstitial immediately (probably through flashInterfaceCall)
            // now : Launches url immediately without interstitial (probably through flashInterfaceCall)
            // click: Launches url on click, without interstitial. Usefull for just opening links in new window.
            call: false,
            type: 'pdf', // what kind of dialog? 'ext', 'pdf', 'msg', 'image'

            top: false, //distance from top of center option
            pos: false, // if false, then centered, if 'top' then positioned from top

            //markup of mask
            mask_opacity: .8,
            mask_color: false,
            mask_anim: null,

            siteurl: '',
            sitename: '',

            // Tracking Function
            fn_track: null,

            // Interstitial Launch Function
            fn_launch: null,

            //markup of External Link Message
            msg: false,

            // Exit Messege
            msg_exit: false,
            internal: false,

            // Popup Title for interstitial
            popup_title: ''
        }, settings);

        return this.each(function () {

            // optimization:
            var e = $(this);

            var e_url = settings.url || e.attr('href');
            var e_flash = settings.flash;
            var e_call = settings.call;
            var e_type = settings.type;
            var e_top = settings.top;
            var e_pos = settings.pos;
            var e_opacity = settings.mask_opacity;
            var e_color = settings.mask_color;
            var e_anim = settings.mask_anim;

            var e_popup_title = settings.popup_title;

            // removes onclick function and fires it when the launch button is clicked
            var e_fntrack = settings.fn_track || e.attr('onclick'); e.removeAttr('onclick');

            var e_fnlaunch = settings.fn_launch;
            var e_name = 'qi_dialog_' + (e.attr('id') || Math.floor(Math.random() * 100001));
            var e_maskdiv = null;

            var e_int = settings.internal;

            var b_wrap = null;
            var b_mask = null;
            var b_space = null;
            var b_frame = null;

            //which msg to use?
            var e_msg = '';
            var e_exitmsg = '';

            switch (e_type) {
                case 'pdf':
                    e_msg = '<div class="qi_msg"><div class="intHeader"></div><div class="qi_ext"><span>To view and print this document, you&#8217;ll need to install a copy of the free Adobe<span class="reg">&reg;</span> Reader<span class="reg">&reg;</span>. If you already have Adobe Reader installed, click VIEW PDF below. If you need Adobe Reader, you can download it from the <a class="qi_adobe" href="http://get.adobe.com/reader/">Adobe Reader Download page</a>.</span><a class="btnViewPDF qi_targeturl" href="#"></a><div class="div"></div><a class="btnCancel qi_btn_cancel" href="#"></a><div class="pdfIcon">The requested information is provided in Portable Document Format (PDF).</div><div class="clearFloatLeft"></div><input id="showMessage" type="checkbox" class="qi_checkbox"/><label for="showMessage">Don&#8217;t show me this message again.</label><div class="clearFloatBoth"></div></div></div>';
                    e_exitmsg = '<div class="qi_msg"><div class="intHeader">Adobe Reader Download page</div><div class="qi_ext"><p>You are leaving the SPRIX.com website.</p><span>You are now leaving SPRIX.com. The content of the website you will be visiting is not controlled by Regency Therapeutics. The link is being offered for your convenience.</span><a class="qi_targeturl btnContExt" href="#"></a><div class="div"></div><a class="qi_btn_cancel btnStay" href="#"></a><div class="clearFloatBoth"></div></div></div>';
                    break;
                case 'ext':
                    e_msg = '<div class="qi_msg"><div class="intHeader"></div><div class="qi_ext"><p>You are leaving the SPRIX.com website.</p><span>You are now leaving SPRIX.com. The content of the website you will be visiting is not controlled by Regency Therapeutics. The link is being offered for your convenience.</span><a class="qi_targeturl btnContExt" href="#"></a><div class="div"></div><a class="qi_btn_cancel btnStay" href="#"></a><div class="clearFloatBoth"></div></div></div>';
                    e_exitmsg = settings.msg_exit || '';
                    break;
                case 'ext1':
                    e_msg = '<div class="qi_msg"><div class="intHeader"></div><div class="qi_ext"><p>You are leaving the SPRIX.com website.</p><span>You are now leaving the SPRIX.com website and will be redirected to the Regency Therapeutics home page.</span><a class="qi_targeturl btnContExt" href="#"></a><div class="div"></div><a class="qi_btn_cancel btnStay" href="#"></a><div class="clearFloatBoth"></div></div></div>';
                    e_exitmsg = settings.msg_exit || '';
                    break;
                case 'custom':
                    e_msg = settings.msg;
                    e_exitmsg = settings.msg_exit || '';
                    break;
                default:
                    e_msg = settings.msg;
                    break;
            }



            // pluggin behavior: Click for interstitial, Initiate interstitial, Initiate URL
            switch (e_call) {
                case false: // Launch Interstitial on click
                    e.click(qi_btn);
                    break;
                case true: // Launch Interstitial now
                    qi_opendialog();
                    break;
                case 'now': // Launch Link NOW!
                    qi_launchurl();
                    break;
                case 'click': // Launch Link on Click!
                    e.click(function () {

                        qi_launchurl();

                        switch (typeof (e_fnlaunch)) {
                            case 'string': eval(e_fnlaunch); break;
                            case 'function': e_fnlaunch(); break;
                        }

                        e.blur();
                        return false;
                    });
                    break;
            }

            // Button Function
            function qi_btn() {
                if (e_type != 'pdf') {
                    qi_opendialog();
                } else {
                    if (qi_cookieget() == 1) {
                        qi_launchurl();
                    } else {
                        qi_opendialog();
                    }
                }
                e.blur();
                return false;
            }

            // Initiates Interstitial
            function qi_opendialog() {
                b_frame = $('<iframe id="' + e_name + '_iframe" class="qi_iframe" src="" width="1" height="1" scrolling="no" frameborder="0"></iframe>');
                b_frame.css({ opacity: 0 });
                b_wrap = $('<div id="' + e_name + '" class="qi_wrapper"></div>');
                b_wrap.css({ 'z-index': zTop() });

                b_mask = $('<span id="' + e_name + '_mask" class="qi_mask"></span>');
                if ($('.qi_wrapper').length > 0) e_color = $('.qi_mask').css('background-color');
                if (e_color) b_mask.css({ 'background-color': e_color });
                b_mask.css({ opacity: e_opacity });
                b_mask.click(qi_msgkill);

                if (e_anim) b_mask.css({ opacity: 0 }).animate({ opacity: e_opacity }, e_anim);

                b_wrap.append(b_mask);

                if (check_ie8_flash()) {
                    // setups of flash on IE8 - Full screen flash on IE8 has some issues...
                    //$('.qi_flipper').css({opacity: 1 - settings.mask_opacity});
                }

                // sets height 
                b_space = $('<span class="qi_space">&nbsp;</span>');
                b_wrap.append(b_space);

                b_wrap.append(e_msg); // adds code		

                //for adobe links
                b_wrap.find('a.qi_adobe').click(function () {
                    b_wrap.find('div.qi_msg').html(e_exitmsg);
                    b_wrap.find('a.qi_cancel, .qi_btn_cancel').click(qi_msgkill);
                    b_wrap.find('a.qi_targeturl').qi_dialog({ call: 'click', type: 'ext', url: $(this).attr('href') }).click(qi_msgkill);
                    return false;
                });

                b_wrap.find('.pdfIcon').click(function () {
                    b_wrap.find('a.qi_adobe').click();
                });

                //display the acrobat warning again?
                b_wrap.find('.qi_checkbox').change(function () {
                    if ($(this).val() == 'on') {
                        qi_cookieset(1);
                    } else {
                        qi_cookieset(0);
                    }
                    return false;
                });

                //Adds button kill feature
                b_wrap.find('.qi_cancel, .qi_btn_cancel').click(qi_msgkill);

                //Adds URL launch function
                b_wrap.find('a.qi_targeturl').click(function () {
                    qi_launchurl();
                    return false;
                });

                if (e_type == "pdf" || e_type == "ext" || e_type == "ext1")
                    b_wrap.find('div.intHeader').html(e_popup_title);

                $('body').append(b_frame).append(b_wrap);
                // Does the initial mask resizing
                qi_resizemask();

                // Launches Custom function to happen after dialog launches
                // Useful for flash intergration or adding interactivity
                switch (typeof (e_fnlaunch)) {
                    case 'string':
                        eval(e_fnlaunch);
                        break;
                    case 'function':
                        e_fnlaunch();
                        break;
                }

                // WINDOW RESIZING
                $(window).bind('resize', qi_resizemask);

                return false;
            }

            function qi_launchurl() {
                // If tracking is involved
                switch (typeof (e_fntrack)) {
                    case 'string': eval(e_fntrack); break;
                    case 'function': e_fntrack(); break;
                }
                // The windowline for opening pop ups

                if (e_url != "#" && e_url != "" && !e_int) {
                    var wline = "";
                    switch (e_type) {
                        case 'pdf':
                            wline = 'directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,titlebar=yes,toolbar=no';
                            break;
                        case 'ext':
                        case 'ext1':
                            wline = 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=600,height=500';
                            break;
                    }
                    if ($.browser.safari && parseInt($.browser.version) < 400) { //if its not a Safari
                        window.location.href = e_url; //mac fix for OS X
                    } else {
                        var thelink = window.open(e_url, (e_name + '_window'), wline);
                    }
                } else {
                    if (e_int) window.location.href = e_url;
                }

                qi_msgkill();
            }

            // External closing functionality; Author: Andrew Mitryushkin
            //removes all interstitial messages. initiated by the qi_cancel button or clicking on the mask.
            function qi_msgkill() {
                if (b_wrap) {
                    b_wrap.find('.qi_msg iframe').attr('src', '');
                    b_wrap.remove();
                    b_frame.remove();
                    $(window).unbind('resize', qi_resizemask);
                }
                //qi_resizemask();

                return false;
            }

            function qi_resizemask() {
                //alert($(window).height() + ' ' + $('body').outerHeight() + ' ' + $('body').height() + ' ' + $(document).height());
                b_wrap.add(b_frame).add(b_mask).css({ width: 1, height: 1 });
                //var h = Math.max($(window).height(), $('body').outerHeight(), $(document).height());
                var h = wHeight();
                var w = $(window).width();
                b_wrap.add(b_frame).add(b_mask).css({ width: w, height: h });

                if (!settings.top) {
                    b_space.height(Math.max(0, ($(window).height() - b_wrap.find('.qi_msg').outerHeight()) / 2 + $(window).scrollTop()));
                } else {
                    switch (e_pos) {
                        case 'top':
                            b_space.height(e_top);
                            break;
                        default:
                            b_space.height(e_top + $(window).scrollTop());
                            break;
                    }
                }

                var h2 = wHeight();
                if (h2 > h) {
                    $('.qi_wrapper').add($('.qi_wrapper_iframe')).add('.qi_mask').css({ height: h2 });
                }
                //alert($(window).height() + ' ' + $('body').outerHeight() + ' ' + $('body').height() + ' ' + $(document).height());
            }

            function qi_cookieset(cookieValue) {
                var expires = new Date();
                expires.setTime(expires.getTime() + (1000 * 60 * 60 * 24 * 1)); //days ahead
                document.cookie = "acrobatint" + "=" + escape(cookieValue) + "; path=/" + "; expires=" + expires.toGMTString();
            }

            //FUNCTION-- retrieves a cookie - jsv 1.0
            function qi_cookieget() {
                var cookieNameStr = "acrobatint" + "=";
                var dc = document.cookie;
                if (dc.length > 0) {
                    var beginStr = dc.indexOf(cookieNameStr);
                    if (beginStr != -1) {
                        beginStr += cookieNameStr.length;
                        var endStr = dc.indexOf(";", beginStr);
                        if (endStr == -1) { endStr = dc.length; }
                        return unescape(dc.substring(beginStr, endStr));
                    }
                }
                return null;
            }

            function qi_cookiedel() {
                document.cookie = "acrobatint" + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
            }

            function check_ie8_flash() {
                if ($.browser.msie && $.browser.version >= 8 && $.browser.version < 9 && settings.flash != null && settings.flash != false) { // ie8 flash issues
                    return true;
                } else {
                    return false;
                }
            }

            function zTop() {
                // sets the z-index
                var zorder = 0;
                $('*').each(function () {
                    var ztemp = parseInt($(this).css('z-index'));
                    if (ztemp > zorder) zorder = ztemp;
                });
                return zorder + 100;
            }

            function wHeight() {
                if (!$.browser.msie) {
                    return Math.max($(window).height(), $('body').outerHeight(), $(document).height())
                } else {
                    return Math.max(document.documentElement.scrollHeight, $('body').outerHeight())
                }
            };
        });
    };
})(jQuery);
