﻿/// <reference path="jquery-1.4.2-vsdoc.js" />
function CyclicIncreaseFont(id) {

    if ($(id).css("font-size") == "14px")
        $(id).css("font-size", "16px");
    else if ($(id).css("font-size") == "16px")
        $(id).css("font-size", "19px");
    else if ($(id).css("font-size") == "19px")
        $(id).css("font-size", "14px");
}

function setFontSize(id, fontSize) {
    $(id).css("font-size", fontSize + 'px');
}

function IncreaseFont(id) {

    if ($(id).css("font-size") == "14px")
        $(id).css("font-size", "16px");
    else if ($(id).css("font-size") == "16px")
        $(id).css("font-size", "19px");
}

function DecreaseFont(id) {
    if ($(id).css("font-size") == "19px")
        $(id).css("font-size", "16px");
    else if ($(id).css("font-size") == "16px")
        $(id).css("font-size", "14px");
}

//function OpenDocumentOverlay(fileName, documentPath) {
//    $.fn.colorbox({ href: ApplicationPath + "DownloadOverlay.aspx?doc=" + fileName + "&path=" + documentPath,
//        innerWidth: "370px", innerHeight: "175px", iframe: true, overlayClose: false, escKey: false
//    });
//}

function OpenDocumentOverlay() {
    $.fn.colorbox({ href: ApplicationPath + "DownloadOverlay.aspx?",
        innerWidth: "500px", innerHeight: "300px", iframe: true, overlayClose: false, escKey: false
    });
}


$(document).ready(function () {

    $("#footerNoteCopy").html($("#footerNote").html())

    if (location.href.toLowerCase().indexOf("cmspagemode=edit") == -1) {
        $("#footerNote").hide();
    }
    else {
        $("#footerNote").show();
        $("#footerNoteCopy").hide();
    }


    //Code to play video in Colorbox
    $(".divVideo a").click(function (event) {

        var url = $(this).attr("href");
        var inner_Width = 267;
        var inner_Height = 200;

        if ($(this).closest(".divVideo").attr("class").indexOf("AR_16_9") != -1) {
            inner_Width = 356;
        }
        if (url.indexOf("http://vimeo.com/") >= 0)
            url = url.replace("http://vimeo.com/", "http://player.vimeo.com/video/");
        else if (url.indexOf("http://www.vimeo.com/") >= 0)
            url = url.replace("http://www.vimeo.com/", "http://player.vimeo.com/video/");

        if (url.indexOf("http://player.vimeo.com/video/") >= 0 || url.indexOf("http://youtube.com") >= 0 || url.indexOf("http://www.youtube.com") >= 0) {
            //            $("#divVideoEmbedded #divVideoDetails").html($($(".divVideo div")[1]).html());
            //            $("#divVideoEmbedded #frmVideo").attr("src", url);
            //            $.fn.colorbox({ href: "#divVideoEmbedded", inline: true, overlayClose: false, escKey: false, width: 640
            //            });
            $.fn.colorbox({ href: url,
                innerWidth: inner_Width + "px", innerHeight: inner_Height + "px", iframe: true, overlayClose: false, escKey: false
            });
            event.preventDefault();
        }

    });

    //for hiding list title
    $(".MedicarePlanQuestions").children(".sf_listTitle").hide();

    bannerRotator('.slideshow', '1000', '7000');
    if ($(".rxQuestions").length > 0) {
        $($(".rxQuestions > .sf_anchorList")[1]).prepend("<p style='margin-left: -20px;'><strong>Common Questions about CareOregon Advantage</strong></p>");
    }
    renderVideos();

    $("#ulMainNav>li").hover(
          function () {
              if ($(this).attr("class") == "navItem")
                  $(this).attr("class", "currentNode currentTemp");
          },
          function () {
              if ($(this).attr("class") == "currentNode currentTemp")
                  $(this).attr("class", "navItem");
          }
    );
    AddHoverEffectsToTabs();

    $(".collapsed").click(function () {
        expandCollapseList(this);
    });
    $(".expanded").click(function () {
        expandCollapseList(this);
    });

    $(".subscribeToUpdates").colorbox({ href: ApplicationPath + "SubscribeOverlay.aspx",
        width: "450px", height: "550px", iframe: true, overlayClose: false, escKey: false
    });

    $(".btnActionEnroll").click(function () {
        var planID = $(this).find(".planID").html();
        var formHtml = '<form method="post" id="FormNew" action="https://enrollmentcenter.medicare.gov/Enrollsplash.aspx"> <input type="hidden" name="SourceID" id="SourceID" value="OEC80837" /> <input type="hidden" name="ReturnURL" id="ReturnURL" value="http://www.careoregon.org/HealthPlans/MedicarePlans/Applynow.aspx" /> <input type="hidden" name="ContractID" id="ContractID" value="H5859" /> <input type="hidden" name="PlanID" id="PlanID" value="' + planID + '" /> <input type="hidden" name="SegmentID" id="SegmentID" value="000" /> <input type="hidden" name="ZIP" id="ZIP" value="97204" /></form>'
        $($(this).closest("div")).append(formHtml);
        $("#FormNew").submit();
    });

    AddTargetWindowForExternalLinks();

    try {
        $.translate(function () {  //when the Google Language API is loaded

            function translateTo(destLang) { //this can be declared in the global scope too if you need it somewhere else
                $('body').translate('english', destLang, {   //translate from english to the selected language
                    not: '.languagesSection, .noTranslation',  //by default the generated element has this className
                    fromOriginal: true   //always translate from english (even after the page has been translated)
                    //unnecessary in v1.4, the default value is true
                });
            }
            if (CurrentLanguage != "en")
                translateTo(CurrentLanguage);
        });
    }
    catch (exception) {
        //alert('error');
    }

    // ie6 png fix //

    if (document.all && /MSIE (5\.5|6)/.test(navigator.userAgent)) {
        DD_belatedPNG.fix('span.btn_BlueRightPtrNew, .btn_BlueRightPtr, a.btn_BlueLeftNew, span.btn_BlueRightPtr ,a.btn_BlueLeft, .btn_BlueMiddleNew');
        DD_belatedPNG.fix('#bannerPaging');
        DD_belatedPNG.fix('.storyPaging');
        DD_belatedPNG.fix('#leftContent img');
        DD_belatedPNG.fix('#footer img');
        DD_belatedPNG.fix('#boardOfDirectors img');
        DD_belatedPNG.fix('.divMasterHead img');
        var fixFilePath = 'Res/Scripts/iepngfix.htc';
    }

    $(".readMoreText").click(function () {
        //        $(this).closest("td").find(".sf_singleNews").toggle();

        var tdContent = $(this).closest("td");
        var $hidden = $(tdContent).find('.sf_singleNews');

        if ($hidden.is(':hidden')) {
            $(this).text("[Collapse]");
        //    $(tdContent).find(".sf_newsSummary").hide();
            $hidden.show();
        } else {
            $(this).text("More...");
          //  $(tdContent).find(".sf_newsSummary").show();
            $hidden.hide();
        }
    });
});

function renderVideos() {
    $(".co_MemberStory").each(function (index) {
        $(this).find("ul li").hide();
        $(this).find(".sf_listTitle").hide();
        $(this).find(".sf_listItemTitle").hide();
        $($(this).find("ul li")[0]).show();
        var parentIndex = index;
        var pageLinks = "";
        $(this).find("ul li").each(function (index) {
            var selectedClass = "";
            if (index == 0)
                selectedClass = "selected";
            pageLinks += "<a class='" + selectedClass + "' onclick='ChangeStory(" + index + ",this," + parentIndex + ");'>" + (index + 1) + "</a>";
        });

        $(this).append("<div class='bannerPaging storyPaging'>" + pageLinks + "</div>");
    });
}

function ChangeStory(index, object, parentIndex) {
    var videoList = $(".co_MemberStory").toArray();
    var currentVideoList = $(videoList[parentIndex]);
    currentVideoList.find("ul li").hide();
    $(currentVideoList.find("ul li")[index]).show();
    currentVideoList.find('.storyPaging a').removeClass("selected");
    $(object).addClass("selected");
}

function AddHoverEffectsToTabs() {
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {

        $("#tabrow li").hover(
            function () {
                $(this).addClass("hovered");
            },
            function () {
                $(this).removeClass("hovered");

            }
        );
    }
}

function AddTargetWindowForExternalLinks() {
    $('a.external').each(function () {
        $(this).attr("target", "_blank");
    });

    $('a').each(function () {
        if ($.trim($(this).text()) != '') {
            if ($(this).attr("href")) {
                var hrefString = $(this).attr("href").toLowerCase();
                if (hrefString.indexOf('.pdf') != -1 &&
                (hrefString.indexOf('/res') == 1) || (hrefString.indexOf('res') == 1 || (hrefString.indexOf('careoregon.org') > -1) && hrefString.indexOf('careoregon.org') < 12))
                    $(this).removeAttr("target");
                //$(this).addClass('external');
            }
            if ($(this).attr("href") && $(this).attr("href").toLowerCase().indexOf('app.dotcalmail.com') != -1) {
                $(this).attr("target", "_blank");
            }
        }
    });

}

function expandCollapseList(object) {
    $($(object).closest("div")).find(".expandable").toggle();
    $(object).toggleClass("collapsed expanded");
}

function GoToURLByClosingOverlay(url) {
    parent.location.href = url;
    parent.$.fn.colorbox.close();
}

function clickButton(e, buttonid) {

    var evt = e ? e : window.event;
    var btn = document.getElementById(buttonid);

    if (btn) {
        if (evt.keyCode == 13) {
            if (document.all) {
                btn.click();
                __doPostBack('ctl00$btnSearch', '');
            }
            __doPostBack('ctl00$btnSearch', '');
            return false; //  __doPostBack(buttonid, '');
        }
    }
}

function AddUndeline(id) {
    $('#' + id).addClass("underline");
}

function RemoveUndeline(id) {
    $('#' + id).removeClass("underline");
}

function RedirectToSelectedJumpToPage(selectedValue) {
    var selectedValueIndex = parseInt(selectedValue);

    switch (selectedValue) {
        case "1":
            window.location.href = ApplicationPath + "Members/FindAProvider.aspx";

            break;
        case "2":
            window.location.href = ApplicationPath + "Providers/PharmacyHelpDesk/FormularylistAndUpdates.aspx";
            break;
        case "3":
            window.location.href = ApplicationPath + "ContactUs/EmailUs.aspx";
            break;
        case "4":
            window.location.href = ApplicationPath + "forms_documents.aspx";
            break;
        case "5":
            window.location.href = ApplicationPath + "HealthPlans/MedicaidServicesOHP.aspx";
            break;
        case "6":
            window.location.href = ApplicationPath + "HealthPlans/MedicarePlans.aspx";
            break;
        case "7":
            window.location.href = ApplicationPath + "Members/CommonQuestions/Glossaryofterms.aspx";
            break;
        case "8":

            $('body').append('<form id="new_form" method="get" action="http://www.healthwise.net/careoregon/Content/CustDocument.aspx"><input type="text" id="XML" name="XML" value="STUB.XML" /><input type="text" id="XSL" name="XSL" value="CD.FRONTPAGE.XSL" /></form>');
            $('#new_form').submit();

            break;
    }
}

function AdjustPhoneNumber(objEvent, num) {
    var number = num.value.length;
    var ikeyCode = objEvent.keyCode || objEvent.which;
    var ctrl = num;
    if (ikeyCode != 8) {
        if ((ikeyCode != 40 || ikeyCode != 41 || ikeyCode != 45) && number >= 9) {
            if (ctrl.value.search("-") == -1 && ctrl.value.indexOf("(") == -1 && ctrl.value.indexOf(")") == -1)
                ctrl.setAttribute('maxLength', 10);
            else
                ctrl.setAttribute('maxLength', 18);
        }
        else if (number >= 9) {
            ctrl.setAttribute('maxLength', 18);
        }
    }
}

function FormatPhoneNumber(num, val) {
    var number = document.getElementById(num).value;

    number = $.trim(number);
    number = number.replace(/ /g, "");
    number = number.replace(/-/g, "");

    while (number.indexOf("(") != -1 || number.indexOf(")") != -1) {
        number = number.replace("(", "");
        number = number.replace(")", "");
    }

    if (number.length >= 10 && Number(number)) {
        if (number.length == 10)
            number = number.substr(0, 3) + "-" + number.substr(3, 3) + "-" + number.substr(6, 4);
        else if (number.length > 10) {
            number = number.substr(0, 10);
            number = number.substr(0, 3) + "-" + number.substr(3, 3) + "-" + number.substr(6, 4);
        }

        document.getElementById(num).value = number;
        ValidatorValidate(document.getElementById(val));
    }
}

$('document').ready(function () {

    $('.content').each(function (index) {
        //alert(this.name);
        truncate('#' + $(this).attr('id'));
    });

    $('.readMoreLink').live('click', function () {
        var divContent = $(this).closest('.content');
        var $hidden = $(divContent).find('.hiddenText');

        if ($hidden.is(':hidden')) {
            $hidden.show();
            $(this).appendTo($(this).closest('.content')).children('.readMoreText').text('[Collapse]').siblings().hide();
            $(this).siblings('.revealText').find('.moreDots').hide();
        } else {
            $(this).appendTo($(this).closest('.content')).children('.readMoreText').text('More...').siblings().show();
            $hidden.hide();
            $(this).siblings('.revealText').find('.moreDots').show();
        }
    });

    $('.readMoreLink').click();

    function truncate(element) {
        $(element + ' p').css({ display: 'inline' });

        var theText = $(element).html();        // Original Text
        var item;                               // Current tag or text area being iterated
        var convertedText = '<span class="revealText">';    // String that will represent the finished result
        var limit = 230;                        // Max characters (though last word is retained in full)
        var counter = 0;                        // Track how far we've come (compared to limit)
        var lastTag;                            // Hold a reference to the last opening tag
        var lastOpenTags = [];                  // Stores an array of all opening tags (they get removed as tags are closed)
        var nowHiding = false;                  // Flag to set to show that we're now in the hiding phase

        theText = theText.replace(/[\s\n\r]{2,}/g, ' ');            // Consolidate multiple white-space characters down to one. (Otherwise the counter will count each of them.)
        theText = theText.replace(/(<[^<>]+>)/g, '|*|SPLITTER|*|$1|*|SPLITTER|*|');                      // Find all tags, and add a splitter to either side of them.
        theText = theText.replace(/(\|\*\|SPLITTER\|\*\|)(\s*)\|\*\|SPLITTER\|\*\|/g, '$1$2');           // Find consecutive splitters, and replace with one only.
        theText = theText.replace(/^[\s\t\r]*\|\*\|SPLITTER\|\*\||\|\*\|SPLITTER\|\*\|[\s\t\r]*$/g, ''); // Get rid of unnecessary splitter (if any) at beginning and end.
        theText = theText.split(/\|\*\|SPLITTER\|\*\|/);            // Split theText where there's a splitter. Now we have an array of tags and words.

        for (var i in theText) {                                     // Iterate over the array of tags and words.
            item = theText[i];                                      // Store current iteration in a variable (for convenience)
            lastTag = lastOpenTags[lastOpenTags.length - 1];        // Store last opening tag in a variable (for convenience)
            if (!item.match(/<[^<>]+>/)) {                         // If 'item' is not a tag, we have text
                if (lastTag && item.charAt(0) == ' ' && !lastTag[1].match(/span|SPAN/)) item = item.substr(1);   // Remove space from beginning of block elements (like IE does) to make results match cross browser
                if (!nowHiding) {                                        // If we haven't started hiding yet...
                    counter += item.length;                             // Add length of text to counter.
                    if (counter >= limit) {                              // If we're past the limit...
                        var length = item.length - 1;                   // Store the current item's length (minus one).
                        var position = (length) - (counter - limit);    // Get the position in the text where the limit landed.
                        while (position != length) {                     // As long as we haven't reached the end of the text...
                            if (!!item.charAt(position).match(/[\s\t\n]/) || position == length)   // Check if we have a space, or are at the end.
                                break;                                  // If so, break out of loop.
                            else position++;                            // Otherwise, increment position.
                        }
                        if (position != length) position--;
                        var closeTag = '', openTag = '';                // Initialize open and close tag for last tag.
                        if (lastTag) {                                   // If there was a last tag,
                            closeTag = '</' + lastTag[1] + '>';         // set the close tag to whatever the last tag was,
                            openTag = '<' + lastTag[1] + lastTag[2] + '>';  // and the open tag too.
                        }
                        // Create transition from revealed to hidden with the appropriate tags, and add it to our result string
                        var transition = '<span class="moreDots">...</span><span class="readMoreLink bodMore"><a href="javascript:void(0);" class="readMoreText">More...</a></span>' + closeTag + '</span><span class="hiddenText">' + openTag;
                        convertedText += (position == length) ? (item).substr(0) + transition
                                                                : (item).substr(0, position + 1) + transition + (item).substr(position + 1).replace(/^\s/, '&nbsp;');
                        nowHiding = true;       // Now we're hiding.
                        continue;               // Break out of this iteration.
                    }
                }
            } else {                                                // Item wasn't text. It was a tag.
                if (!item.match(/<br>|<BR>/)) {                      // If it is a <br /> tag, ignore it.
                    if (!item.match(/\//)) {                         // If it is not a closing tag...
                        lastOpenTags.push(item.match(/<(\w+)(\s*[^>]*)>/));     // Store it as the most recent open tag we've found.
                    } else {                                                    // If it is a closing tag.
                        if (item.match(/<\/(\w+)>/)[1] == lastOpenTags[lastOpenTags.length - 1][1]) {    // If the closing tag is a paired match with the last opening tag...
                            lastOpenTags.pop();                                                         // ...remove the last opening tag.
                        }
                        if (item.match(/<\/[pP]>/)) {            // Check if it is a closing </p> tag
                            convertedText += ('<span class="paragraphBreak"><br> <br> </span>');    // If so, add two line breaks to form paragraph
                        }
                    }
                }
            }
            convertedText += (item);            // Add the item to the result string.
        }
        convertedText += ('</span>');           // After iterating over all tags and text, close the hiddenText tag.
        $(element).html(convertedText);         // Update the container with the result.
    }
});

function submitFormToHealthTrio(button) {
    $("#__EVENTARGUMENT").remove();
    $("#__EVENTTARGET").remove();
    $("#__EVENTVALIDATION").remove();
    $("#__VIEWSTATE").remove();
    $(".ddlJumpTo").remove();
    $(".tbSearchBox").remove();
    $(button).attr("name", "login");
    $("form").attr("action", "https://www.healthtrioconnect.com/index.cfm");
    $("form").attr("autocomplete", "off");
}
