var mTipId = "0"; //location.href.replace(/.*\/(\d+).aspx/, "$1");
var mOrderId = "ORDERID";

$(document).ready(function() {
    var tipColumnsHeight;
    var textSize = $.cookie('textSize');
    switch (textSize) {
        case 'small':
            decreaseFont();
            break;
        case 'large':
            increaseFont();
            break;
        default:
            resetFont();
            break;
    }
    if ($.browser.safari == true) {
        $('.btnName').text('Choose File');
    }
    if ($.browser.mozilla == true) {
        $('.threeColumn .leftColumn').css({ 'paddingBottom': $('.threeColumn .centerWell').outerHeight() - $('.threeColumn .leftColumn ul').outerHeight() - 10 });
    }
    $(".addTip a").click(function(fTE) {
        var tipCount = $("#tipCount").val();

        if (tipCount > 9)
            $(this).hide();
        else {
            var newTip = $(".tipSection:eq(0)").clone();
            var newSelect = newTip.find("select");
            var newTextArea = newTip.find("textarea");

            newTip.append("<a href='#' class='removeTip'>Remove this tip</a>").find(".errorCopy").html("");

            newSelect.val("").attr("id", newSelect.attr("id") + tipCount).attr("name", newSelect.attr("name") + tipCount);
            newTextArea.val("").attr("id", newTextArea.attr("id") + tipCount).attr("name", newTextArea.attr("name") + tipCount);

            $(".tipSection:last").after(newTip).after("<div class='divider'></div>");

            $("#tipCount").val(++tipCount);
        }

        fTE.preventDefault();
    });

    $(".removeTip").live("click", function(fTE) {
        var val = $("#tipCount").val();
        $("#tipCount").val(--val)
        $(this).parents(".tipSection").prev().remove().end().remove();


        $(".tipSection").each(function(i) {

            if (i) {
                $(this).find("select").attr("id", "Author_OriginalCategoryId" + i);
                $(this).find("textarea").attr("id", "Author_OriginalTip" + i);
            }
        });

        fTE.preventDefault();
    });

    $(".logoCopy .inlineInterstitial").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_HCPDirectory_NFA_Interstitial");

        if (!$(this).hasClass("leavingFromHere")) {
            $(this).addClass("leavingFromHere");

            $(".iSLinks .button, .iSLinks .continueB").live("mousedown", function(fTE) {
                GetActionTagImg("CT_FT_Resources_HCPDirectory_NFA_Interstitial_Cont");
            });
        }
    });

    $("#inlinePreview").live("mousedown", function(fTE) {
        GetActionTag("FT_EmailProgram_SharewithFriend_Signup_Preview");
    });

    $(".tipSection select").live("change", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Topic");
    });

    $("#Author_TermsReleaseInfo").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Terms1");
    });

    $("#Author_TermsWaiveRights").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Terms2");
    });

    $("#Author_TermsVerifyDiagnosis").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Terms3");
    });

    $("#s1, #s2, #s3, #s4").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Supporter_Type");
    });

    $("#imageFile").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_PhotoBrowse");
    });

    $("#d1").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Iam_Diagnosed");
    });

    $("#d2").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Iam_Supporter");
    });

    $("#Author_DiagnosedYear").live("change", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_HadFibroSince");
    });

    $("#g2").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Gender_M");
    });

    $("#g1").live("click", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Gender_F");
    });

    $("#Author_BirthMonth").live("change", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Born_Month");
    });

    $("#Author_BirthYear").live("change", function(fTE) {
        GetActionTagImg("CT_FT_SubmitTip_Form_Born_Year");
    });

    // begin list of tags for resources page

    $(".linkList a[title='American College of Rheumatology']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_ACR_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_ACR_Interstitial_Cont");
        });
    });

    $(".linkList a[title='National Fibromyalgia Association']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_NFA_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("FT_Resources_NFA_Interstitial_Cont");
        });
    });

    $(".linkList a[title='National Fibromyalgia Research Association']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_NFRA_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_NFRA_Interstitial_Cont");
        });
    });

    $(".linkList a[title='American Pain Foundation']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_APF_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_APF_Interstitial_Cont");
        });
    });

    $(".linkList a[title='American Chronic Pain Association']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_ACPA_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_ACPA_Interstitial_Cont");
        });
    });

    $(".linkList a[title='Arthritis Foundation']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_Arthritis_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_Arthritis_Interstitial_Cont");
        });
    });

    $(".linkList a[title='American Pain Society']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_AmPainSoc_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("FT_Resources_AmPainSoc_Interstitial_Cont");
        });
    });

    $(".linkList a[title='American Academy of Pain Medicine']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_AAPMed_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_AAPMed_Interstitial_Cont");
        });
    });

    $(".linkList a[title='American Academy of Pain Management']").live("mousedown", function(fTE) {
        GetActionTag("FT_Resources_AAPMan_Interstitial");

        $(".iSLinks .continueB").die("mousedown").live("mousedown", function(fTE) {
            GetActionTagImg("CT_FT_Resources_AAPMan_Interstitial_Cont");
        });
    });

    // end list of tags for resources page

    $(".picAndLinks .dialog").live("mousedown", function(fTE) {
        GetActionTag("FT_FibroTips_Tip_ReadMore_SubmitTip/v3/ato.ORDERID/atc1." + mTipId);
        fTE.preventDefault();
    });

    $(".print").live("mousedown", function(fTE) {
        GetActionTagImg("CT_FT_Print_Page/v3/ato." + mOrderId + "/atc1." + mTipId);
    });

    $(".email").live("mousedown", function(fTE) {
        GetActionTag("FT_Email_Page/v3/ato." + mOrderId + "/atc1." + mTipId);
    });

    $(".inlineInterstitialSavella").live("mousedown", function(fTE) {
        GetActionTag("FT_LearnAboutPerscription_Interstitial");
    });

    $(".interstitialSavella a#interstitial").live("mousedown", function(fTE) {
        GetActionTagImg("CT_FT_LearnAboutPerscription_Interstitial_Cont");
    });

    $(".subnotes .inlineInterstitial").live("mousedown", function(fTE) {
        GetActionTag("FT_UnderstandingFibro_RefRheum_Interstitial");

        if (!$(this).hasClass("leavingFromHere")) {
            $(this).addClass("leavingFromHere");

            $("#interstitial").live("mousedown", function(fTE) {
                GetActionTagImg("CT_FT_UnderstandingFibro_RefRheum_Interstitial_Con");
            });
        }
    });

    $(".leavingFromSymptoms").live("mousedown", function(fTE) {
        GetActionTagImg("CT_FT_UnderstandingFibro_RefRheum_Interstitial_Con");
    });

    $(".goToNFAFromSupport").live("mousedown", function(fTE) {
        GetActionTag("FT_TalkingFibro_Support_NFA_Interstitial");

        if (!$(this).hasClass("leavingFromHere")) {
            $(this).addClass("leavingFromHere");

            $("#interstitial").live("mousedown", function(fTE) {
                GetActionTagImg("CT_FT_TalkingFibro_Support_NFA_Interstitial_Cont");
            });
        }
    });

    $(".paginator a").live("click", function(fTE) {
        var page = $(this).attr("class").charAt($(this).attr("class").length - 1);
        var ts = parseInt(new Date().getTime().toString().substring(0, 10));
        $(".paginator").hide();
        $(".headerBox .block").remove();

        $.getJSON($(this).parent().attr("tipsUrl") + "?index=" + page + "&pageSize=10&ts=" + ts, function(mData) {
            $(mData.tips).each(function() {
                $(".tipsList").append('<div class="block"><div class="photo"><div class="overlay"></div><img src="'
                + this.imageUrl
                + '"/></div><div class="copy">'
                + (this.recommended == 0 ? '' : '<div class="highlight"><span>Recommended</span> +' + this.recommended + '</div>')
                + '<div class="info"><b>'
                + this.firstName
                + (this.age <= 17 ? '' : ', ' + this.age)
                + '</b> - <i>Living with fibromyalgia for '
                + this.numberOfYearsDiagnosed
                + ' years</i></div><p>"'
                + this.teaser
                + '..."</p><p class="link"><a href="'
                + this.url
                + '">&nbsp;Read more ></a></p></div></div>'
                );
            });

            if (mData.pageCount > 1) {
                if (page < 1)
                    $(".paginator").html("");
                else
                    $(".paginator").html("<a href='#' class='page" + (page - 1) + "'>< Previous</a>");


                for (mI = 0; mI < mData.pageCount; ) {
                    if (mI > 0)
                        $(".paginator").append(" | ");

                    if (mI == page)
                        $(".paginator").append("<span class='page" + mI + "'>" + ++mI + "</span>");
                    else
                        $(".paginator").append("<a href='#' class='page" + mI + "'>" + ++mI + "</a>");
                }

                if (++page < mData.pageCount)
                    $(".paginator").append("<a href='#' class='page" + page + "'>Next ></a>");

                $(".paginator").show();
            }
        });

        fTE.preventDefault();
    });

    $(".paginatorBottom a.page0").click();

    var mCookieName = "fibroTip" + mTipId;

    if ($.cookie(mCookieName) == "recommended")
        $(".recommend .action").addClass("gray")
    else {
        var ts = parseInt(new Date().getTime().toString().substring(0, 10));
        $(".recommend .action").bind("click.recommend", function(fTE) {
            $.post($("form[name='recommendForm']").attr("action"), { time: ts }, function(mData) {
                $(".tipCount").text(mData);
            });

            $.cookie(mCookieName, "recommended", { expires: 7 });
            $(this).addClass("gray").unbind("click.recommend"); ;
            $(".highlight").removeClass("hide");

            GetActionTag("FT_FibroTips_Tip_ReadMore_RecommendTip/v3/ato.ORDERID/atc1." + mTipId);

            fTE.preventDefault();
        });
    }

    /******************************/
    //Recommend a Tip
    /******************************

    var cookie = $.cookie('voted');

    function updateTips() {
    var returnArr = [];

        if (cookie !== null && cookie !== '') {

            returnArr = getVotes(cookie);
    cookie = returnArr[1];
    var elements = returnArr[0];

            updateCookie(cookie);

            $('.recommend a').each(function() {

                var id = this.id,
    patt = new RegExp(id),
    matches = (patt).test(elements.join());


                if (matches === true) {

                    disableButton(this);

                }
    });
    }

    }



    updateTips();

    $('.recommend a').click(function() {
    var id = this.id,
    hasVoted = $.data(this, 'hasVoted');

        if (hasVoted === false || hasVoted === undefined) {
    disableButton(this);
    updateCookie(cookie, id);

        } else {
    return false;
    }
    });


    function isValid(aDate) {
    var d = new Date();
    var now = d.getTime(),
    diff = now - aDate,
    num_days = (((diff / 1000) / 60) / 60) / 24;

        var valid = (num_days < 7) ? true : false;
    return valid;
    }

    function disableButton(that) {
    $(that)
    .addClass('disabled')
    .css('cursor', 'default')
    .unbind('click')
    .children('span')
    .addClass('disabled');
    $(that)
    .attr('onclick', 'return false');

        $.data(that, 'hasVoted', true);

    }

    function updateCookie(box) {

        var ballot,
    id = arguments[1];

        if (id !== null && id !== '') {
    var patt = new RegExp(id),
    idFound = (patt).test(cookie);

            if (idFound === false) {
    //id doesn't exist in the ballotbox. better add it.




                var d = new Date();
    ballot = id + ':' + d.getTime();
    if (box !== null) {
    box += ',' + ballot;
    } else {
    box = ballot;
    }
    $.cookie('voted', box, { expires: 7, path: '/', secure: false });
    }
    } else {
    //id is null or undefined. box must be updated.
    $.cookie('voted', box, { expires: 7, path: '/', secure: false });
    }
    }

    function getVotes(c) {
    var elements = [];

        if (c !== null && c !== '') {
    var arr = c.split(',');

            if (c.length > 0) {
    var i = arr.length;
    while (i--) {

                    var arr2 = arr[i].split(':');

                    //check for validity of the cookie string
    var valid = isValid(arr2[1]);

                    if (valid === false) {
    //if not valid, remove that string from the array
    arr.splice(arr[i].indexOf(arr2[0] + ':' + arr2[1]), 1);
    } else {
    elements.push(arr2[0]);
    }
    }
    }

        } else {
    c = null;
    }
    return [elements, c];
    }


    ******************************/
    //END Recommend a Tip 
    /******************************/



    // Submit a tip form - show/hide functionality
    // check to see, on load, whether patient or supporter is checked

    if ($("#d1").is(":checked")) {
        $(".sinceWhen").show();
        $("#patientTerms").show();
    }
    if ($("#d2").is(":checked")) {
        $(".sinceWhen").show();
        $("#supporterDetails").show();
    }

    // patient is checked
    $("#d1").click(patientView);
    patientView();


    // supporter is checked
    $("#d2").click(supporterView);
    supporterView();

    // check to see, on load, if the optional box is checked
    if ($("#optional").is(":checked")) {
        $("#optionalChoices").show();
    } else {
        $("#optionalChoices").hide();
    }

    // optional box is checked
    $("#optional").click(function() {
        if ($("#optional").is(":checked")) {
            $("#optionalChoices").show("fast");
        } else {
            $("#optionalChoices").hide("fast");
        }
    });

    // Modals (inline popups)
    $.fn.fancybox.defaults.overlayOpacity = .5;

    $("a#inline, a.inline").fancybox({
        'frameWidth': 715,
        'frameHeight': 560,
        'hideOnContentClick': false,
        'callbackOnStart': resetForm,
        'callbackOnShow': roundCorners,
        'centerOnScroll': false
    });

    $("a.inlineLink").fancybox({
        'frameWidth': 415,
        'frameHeight': 245,
        'hideOnContentClick': false
    });

    $("#patientTipLink a.inlineLink").fancybox({
        'frameWidth': 445,
        'frameHeight': 453,
        'hideOnContentClick': false
    });

    $("#supporterTipLink a.inlineLink").fancybox({
        'frameWidth': 445,
        'frameHeight': 290,
        'hideOnContentClick': false
    });

    $("a#inlinePreview, a.inlinePreview").fancybox({
        'frameWidth': 568,
        'frameHeight': 552,
        'hideOnContentClick': false,
        'centerOnScroll': false,
        'callbackOnShow': function() {
            $(".sendersName").text($("#name").val());
            $(".fromEmail").text($("#fromEmail").val());
            $(".toEmail").text($("#toEmail").val());
        }
    });

    $("a.inlinePreviewClose, .iSLinks #interstitial, .interstitial #interstitial, .continueB")
		.live('click', function(fTE) {
		    $('#fancy_close').click();
		});

    $("a#inlinePreviewClose, .emailConfirm a")
		.live('click', function(fTE) {
		    $('#fancy_close').click();
		    fTE.preventDefault();
		});

    $("a.gray, a.interviewGray").live("click", function(fTE) {
        fTE.preventDefault();
    });

    // Font size changer
    // Decrease Font Size
    $(".decreaseFont").click(function() {
        decreaseFont();
    });

    // Reset Font Size
    $(".resetFont").click(function() {
        resetFont();
    });

    // Increase Font Size
    $(".increaseFont").click(function() {
        increaseFont();
    });

    function decreaseFont() {
        $('.centerWell, .twoColumn .leftColumn, .headerInfo, .fourColumn').css('font-size', '0.8em');
        $('.lMore').css('font-weight', 'bold');
        $('.aaa .decreaseFont').addClass('active');
        $('.aaa .resetFont').removeClass('active');
        $('.aaa .increaseFont').removeClass('active');
        $('#content .fourColumn .column').equalHeights(500, 600).css('overflow', 'hidden');

        $.cookie('textSize', 'small', { path: '/' });
    }

    function resetFont() {
        $('.centerWell, .twoColumn .leftColumn, .headerInfo, .fourColumn').css('font-size', '1.0em');
        $('.aaa .decreaseFont').removeClass('active');
        $('.aaa .resetFont').addClass('active');
        $('.aaa .increaseFont').removeClass('active');
        $('#content .fourColumn .column').equalHeights(600, 700).css('overflow', 'hidden');

        $.cookie('textSize', 'normal', { path: '/' });
    }

    function increaseFont() {
        $('.centerWell, .twoColumn .leftColumn, .headerInfo, .fourColumn').css('font-size', '1.2em');
        $('.aaa .decreaseFont').removeClass('active');
        $('.aaa .resetFont').removeClass('active');
        $('.aaa .increaseFont').addClass('active');
        $('#content .fourColumn .column').equalHeights(800, 1100).css('overflow', 'hidden');

        $.cookie('textSize', 'large', { path: '/' });
    }

    // Interstitial code
    $("#interstitial").click(function() {
        // window.opener.location = $.jqURL.qs();
        window.open($.jqURL.qs(), 'externalLink');
        window.close();
    });

    // form radio button toggles
    $(".inputContainer2").hide();
    radioCheck();
    $("#i1").click(radioCheck);
    $("#i2").click(radioCheck);
    $("#i3").click(radioCheck);
    $("#i4").click(radioCheck);
    $("#i5").click(radioCheck);

    $(".block .info b, .block .copy h2").each(function() {
        $(this).text($(this).text().replace(", 0", ""));
    });

    //Equal height for the tips page
    $(".tips .column").equalHeights(600, 900).css('overflow', 'hidden');
    tipColumnsHeight = $(".tips .column").height();
    /*******************************************/
    //Fancy box for the external links
    /*******************************************/
    var currentHost = window.location.host;
    $('a').mouseover(function() {
        //var ext = !(/currentHost/).test(this.href) && !(/http/).test(this.href);	
    });

    $("a.inlineInterstitial").each(function() {
        extFancy.call(this, 690, 460, interOnMouseDown, interOnShow);
    });

    $("a.inlineInterstitialSavella").each(function() {
        extFancy.call(this, 690, 420, interOnMouseDown, interOnShow);
    });

    $("a.inlineExternal").each(function() {
        extFancy.call(this, 690, 460, interOnMouseDown, interOnShow);
    });

    /**************************/
    //External Link functions
    /**************************/


    function extFancy(frameWidth, frameHeight, callback1, callback2) {
        $(this)
			.mousedown(callback1)
			.fancybox({
			    'frameWidth': frameWidth,
			    'frameHeight': frameHeight,
			    'callbackOnShow': callback2,
			    'hideOnContentClick': false
			});
    }


    function interOnShow() {
        var body = $('body').get(0);
        if ($.data(body, 'qsExists') === true) {
            var path = $.data(body, 'redirect_path');
            var loc = path.search(/\?url/);
            path = path.substr(loc + 5);
            $('#interstitial').attr('href', path);
        }

    }

    function interOnMouseDown() {
        var path = $(this).attr('href');
        var qsExists = (/\?url=/).test(path);
        var body = $('body').get(0);
        $.data(body, 'qsExists', qsExists);
        if (qsExists === true) {
            $.data(body, 'redirect_path', path);
        }
    }

    /*******************************************/
    //end fancy box for the external links
    /*******************************************/

    // end document ready
});

// email this page
function resetForm(){
    $(".emailThis").show();
    $(".emailConfirm, .errorCopy span").hide();
    $(".submitButton").attr('value', 'Submit');
    $(".sButton").removeClass("sendingDotDotDot");
    $("#fancy_outer").removeClass("confirmEmailBox");
}

function roundCorners() {
    //$("#fancy_inner").corner("round 5px");
}


function GetActionTag(URL) {
    if (URL) {      // Get the script element.
        var element = document.getElementById(URL);
        var TrackTag = "https://view.atdmt.com/jaction/";

        if (element) {
            document.body.removeChild(element);
        }
        element = document.createElement('script');
        element.setAttribute('id', URL);
        element.setAttribute('type', 'text/javascript');
        document.body.appendChild(element);

        element.src = TrackTag + URL + '/?' + Math.random();
    }
}

function GetActionTagImg(URL) {
    var TrackTag = "https://view.atdmt.com/action/"
    //create new image
    var rf_img = new Image();
    //set src of new image, add random # cache killer
    rf_img.src = TrackTag + URL + '/?' + Math.random();
    document.body.appendChild(rf_img);
}


function radioCheck(){
    if($("#i1").is(':checked')){
        $(".inputContainer1").show('fast');
        $(".inputContainer2").hide('fast');
    }
    if($("#i2").is(':checked')){
        $(".inputContainer1").hide('fast');
        $(".inputContainer2").hide('fast');
    }
    if($("#i3").is(':checked')){
        $(".inputContainer1").hide('fast');
        $(".inputContainer2").show('fast');
    }
    if($("#i4").is(':checked')){
        $(".inputContainer1").hide('fast');
        $(".inputContainer2").hide('fast');
    }
    if($("#i5").is(':checked')){
        $(".inputContainer1").hide('fast');
        $(".inputContainer2").hide('fast');
    }
}

function patientView(){
    if($('#d1').is(':checked')){
        $(".sinceWhen").show();

        if ($("#d1").is(":checked")) {
            $("#patientyears").show();
            $("#supporteryears").hide();

            $("#supporterDetails").hide();

            $("#patientTipLink").show();
            $("#supporterTipLink").hide();

            $("#patientTerms").show();
        }
    }
}

function supporterView(){
    if($('#d2').is(':checked')){
        $(".sinceWhen").show();

        if ($("#d2").is(":checked")) {
            $("#supporteryears").show();
            $("#patientyears").hide();

            $("#supporterDetails").show();

            $("#supporterTipLink").show();
            $("#patientTipLink").hide();

            $("#patientTerms").hide();
        }
    }
}

