$(document).ready(function () {

    initializeTextResizing();
    initializeRollovers();
    initializeSpacing();
    initializeToolsAndDownloads();

    //Superfish drop down menu
    //uses hoverIntent.js, jquery.bgiframe.min.js, superfish.js, supersubs.js
    jQuery('ul.sf-menu').supersubs({
        minWidth: 12,   //em units
        maxWidth: 27,   //em units 
        extraWidth: 1
    }).superfish({
        delay: 500,
        speed: 'fast',
        autoArrow: true,
        dropShadows: false
    })

    //Modal Popup windows


    $('#modalWindow').jqm();

    $('.jqmClose').bind('click', function () {
        $('#modalWindow').jqmHide();
    });

    $('.jqmOpen').bind('click', function (event) {
        event.preventDefault();

        url = this.href;
        title = this.title;

        $('#popUpFrame').attr('src', url);

        if ($(this).attr("id") == "btnTellaFriend")
            $(".popTitle").attr('src', "images/popTAFTitle.gif");
        else if ($(this).attr("id") == "btnRegister" || $(this).attr("id") == "sitemapRegister" || $(this).attr("id") == "lnkRegister" || $(this).attr("id") == "A1" || $(this).attr("id") == "tout_btn_register")
            $(".popTitle").attr('src', "images/popRFUTitle.gif");
        else if ($(this).attr("id") == "btnDiscGuide")
            $(".popTitleArea").attr('style', "display:none;");
        // $(".jqmWindow").attr('style', "width: 700px;");            
        else
            $(".popTitle").attr('src', "images/popLeavingTitle.gif");


        $('#modalWindow').jqmShow();
        $('body').prepend($('#modalWindow')); //fix IE layer problem
    });



    // To HCP site popup
    $('#leavingSiteHCP').jqm();

    $('.leavingSiteHCP').bind('click', function (event) {

        // added to detect ipad users
        var isiPad = navigator.userAgent.match(/iPad/i) != null;
        if (isiPad == true) {
            window.scrollTo(0, 0);
        }

        event.preventDefault();
        $('#btn_continue').attr("href", this.href);
        $('#btn_continue').attr("target", "_blank");
        $('#leavingSiteHCP').jqmShow();
        $('body').prepend($('#leavingSiteHCP')); //fix IE layer problem
    });

    $('#btn_continue').bind('click', function () {
        parent.$("#leavingSiteHCP").jqmHide();
    })

    $('#btn_return').bind('click', function (event) {
        event.preventDefault();
        $("#leavingSiteHCP").jqmHide();
    })


    //leaving site popup
    $('#leavingSite').jqm();

    $('.leavingSite').bind('click', function (event) {
        // added to detect ipad users
        var isiPad = navigator.userAgent.match(/iPad/i) != null;
        if (isiPad == true) {
            window.scrollTo(0, 0);
        }

        event.preventDefault();
        //changed to use outbound-url attribute to avoid double exit tracking
        $('#btn_ok').attr("href", $(this).attr("outbound-url"));
        $('#btn_ok').attr("target", "_blank");
        $('#leavingSite').jqmShow();
        $('body').prepend($('#leavingSite')); //fix IE layer problem
        _gaq.push(["_trackPageview", "/pop-leaving-site/"]);
    });

    $('#btn_ok').bind('click', function () {
        parent.$("#leavingSite").jqmHide();
    })

    $('#btn_cancel').bind('click', function (event) {
        event.preventDefault();
        $("#leavingSite").jqmHide();
    })

    //Share Your Story popup
    $('#SharePopup').jqm();

    $('.openSharePopup').bind('click', function (event) {
        event.preventDefault();
        $('#SharePopup').jqmShow();
        $('body').prepend($('#SharePopup')); //fix IE layer problem
    });



    $('.popUpBreakOut').bind('click', function () {
        url = this.href
        window.parent.location = url;
    });


    // To Doc finder Required format popup
    $('#docFinderFormat').jqm();

    $('.docFinderFormat').bind('click', function (event) {

        // added to detect ipad users
        var isiPad = navigator.userAgent.match(/iPad/i) != null;
        if (isiPad == true) {
            window.scrollTo(0, 0);
        }

        event.preventDefault();
        $('#btn_continue').attr("href", this.href);
        $('#btn_continue').attr("target", "_blank");
        $('#docFinderFormat').jqmShow();
        $('body').prepend($('#docFinderFormat')); //fix IE layer problem
    });

    $('#btn_continue').bind('click', function () {
        parent.$("#docFinderFormat").jqmHide();
    })

    $('#btn_return').bind('click', function (event) {
        event.preventDefault();
        $("#docFinderFormat").jqmHide();
    })   



    /*watermark */
    $('.watermark').focus(function (event) {
        $('.watermark').val('').addClass("watermarkFocus").removeClass("watermarkBlur");
    });

    $('.watermark').blur(function (event) {

        if ($('.watermark').val() == '')
            $('.watermark').val('Type or paste your story here.').addClass("watermarkBlur").removeClass("watermarkFocus");
    });

    /* Message character countdown*/
    var countdown = {
        init: function () {
            countdown.remaining = countdown.max - $(countdown.obj).val().length;
            if (countdown.remaining > countdown.max) {
                $(countdown.obj).val($(countdown.obj).val().substring(0, countdown.max));
            }
            $(countdown.obj).siblings(".remaining").html(countdown.remaining + " characters remaining.");
        },
        max: null,
        remaining: null,
        obj: null
    };
    $(".countdown").each(function () {
        $(this).focus(function () {
            var c = $(this).attr("class");
            countdown.max = parseInt(c.match(/limit_[0-9]{1,}_/)[0].match(/[0-9]{1,}/)[0]);
            countdown.obj = this;
            iCount = setInterval(countdown.init, 1000);
        }).blur(function () {
            countdown.init();
            clearInterval(iCount);
        });
    });



});


function initializeRollovers() {
    //preload
    $(window).load(function() {
        $(".rollover").each(function() { $("<img>").attr("src", $(this).attr("src").replace("-off.", "-on.")); });
    });

    $(".rollover").hover(
        function() { $(this).attr("src", $(this).attr("src").replace("-off.", "-on.")); },
        function() { $(this).attr("src", $(this).attr("src").replace("-on.", "-off.")); }
    );
}

function initializeSpacing() {
    $("h2 + p").addClass("noMarginTop");
    $("h2 + ul").addClass("noMarginTop");
}

function initializeToolsAndDownloads() {
    $(".btnClickHere").each(function () {
        $(this).bind('click', function () {
            $(this).attr("href", $(this).prev("select").val());
			thisHref = $(this).prev("select").val();
			
			if (typeof(thisHref) != "undefined" && thisHref != null) {
				var re = new RegExp("(http(s?)://)?" + window.location.host, "gi");
				if (thisHref.match("http(s?):\/\/") && !thisHref.match(re)) {
					_gaq.push(["_trackEvent", "Exit Links", "Exit", removeQuery(thisHref)]);		
					if (thisHref.match(/lundbeck.com\/.+/gi)) _gaq.push(["_trackPageview", "/outboundlinks" + GaPageview + removeQuery(thisHref) + "/"]);

					IsExitLink = true;
				}
				if (thisHref.match(/\.(pdf|doc|xls)$/ig)) {
					if (IsExitLink) _gaq.push(["_trackEvent", "Exit Links", "File Download", thisHref]);
					else _gaq.push(["_trackPageview", "/downloads" + GaPageview + thisHref + "/"]);
				}
			}
        });
    });

}


function popupClose() {
    $('#modalWindow').jqmHide();
}


//Cookie functions
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

    //Text resize functions

initializeTextResizing = function () {
    // alert("init text res");
    var textSize = readCookie("text-size");

    if (textSize == null) {
        setTextsize("med");
    }
    else {
        setTextsize(textSize);
    }
}

    setTextsize = function (size) {
        var el = $("link[id$=textsize]");

        el.attr("href", "styles/textSize-" + size + ".css");

        createCookie("text-size", size);
    }


    increaseTextsize = function () {        

        var el = $("link[id$=textsize]");

        var currentSize = readCookie("text-size");

        if (currentSize === "large") {
            return;
        }

        switch (currentSize) {
            case "small":
                currentSize = "med";
                break;
            case "med":
                currentSize = "large";
                break;
        }

        setTextsize(currentSize);
    }

    decreaseTextsize = function () {
        var el = $("link[id$=textsize]");

        var currentSize = readCookie("text-size");

        if (currentSize === "small") {
            return;
        }

        switch (currentSize) {
            case "large":
                currentSize = "med";
                break;
            case "med":
                currentSize = "small";
                break;
        }

        setTextsize(currentSize);
    }

    textsizeSmall = function () {
       
        setTextsize("small");
    }

    textsizeMed = function () {
        
        setTextsize("med");
    }

    textsizeLarge = function () {
       
        setTextsize("large");
    }                        

function exit_ga(el){
	_gaq.push(["_trackEvent", "Exit Links", "Exit", GaPageview + " - " + removeQuery(el.href)]);
	if (el.href.match(/lundbeck.com\/.+/gi)) _gaq.push(["_trackPageview", "/outboundlinks" + GaPageview + removeQuery(el.href) + "/"]);
	
	if (el.href.match(/\.(pdf|doc|xls)$/ig)) {
		_gaq.push(["_trackEvent", "Exit Links", "File Download", this.href]);
	}
}

