/*
--------------------------------------------------
PIMCO.com
Global Scripts [global.js]
Lee Allen [lee.allen@acquitygroup.com]
12/28/2009
Copyright (c) 2009 Acquity Group LLC
--------------------------------------------------
*/

if (typeof PimcoETF == "undefined") {
    var PimcoETF = {};
}

PimcoETF.namespace = function () {
    var a = arguments,
        o = null,
        i, j, d;
    for (i = 0; i < a.length; i = i + 1) {
        d = a[i].split(".");
        o = window;
        for (j = 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};


$(function () {




    /**
    Zebra-stripe tables
    */
    $('table tbody tr:even').addClass('odd');




    /**
    Bind print action
    */
    $('.print').click(function () {
        window.print();
    });


    $(document).ready(function () {

        $("#fund-tabs").tabs({
            ajaxOptions: {
                error: function (xhr, status, index, anchor) {
                    $(anchor.hash).html("Could not load this tab. We'll try to fix this as soon as possible.");
                }
            }
        });

        $('a.ealert').click(function () {
            try {
                emailModalWin();
            }
            catch (e) { 
                //nothing
            }
        });



        $(".etf-finder-control").click(function (evt) {
            $(this).toggleClass("expanded");
            if ($(this).hasClass("expanded")) {
                $(this).html("-");
            }
            else {
                $(this).html("+");
            }
            $("#etf-finder").toggleClass("expanded");

        });


        $(".fund-filter-control").click(function (evt) {
            $(this).toggleClass("expanded");
            if ($(this).hasClass("expanded")) {
                $(this).html("-");
                $(".reset-filters-link").show();
                $.cookie('fund-listing-filter', 'expanded');
            }
            else {
                $(this).html("+");
                $(".reset-filters-link").hide();
                $.cookie('fund-listing-filter', 'collapse');
            }
            $("#funds-filter").toggleClass("expanded");

        });





        $(".sidebar #how-to-invest li a").click(function (evt) {
            evt.preventDefault();
            $(this).parent().toggleClass("expanded");
        });

        //fix scrollbar
        $("#s4-workspace").height($(window).height() - $("#s4-ribbonrow").height());

    });






    /**
    Slideshow
    */
    var slideshowElement = $('#slideshow');
    var defaultSlideTimeout = 6000;
    var menuItemsCount = slideshowElement.find('ol li').length;
    var slideCount = slideshowElement.find('div.slide').length;
    var autoSlide = slideshowElement.find('a.AutoSlide');
    var slidePosition = slideshowElement.find('a.SlidePosition');
    var slideTimeout = null;
    var transitionSpeed = 750;
    var swapSlideTimer;


    // Show menu only if JavaScript is enabled
    slideshowElement.find('ol.hidden').removeClass('hidden');

    // Count number of menu items and apply appropriate class for menu item positioning
    // Only apply if number of menu items is between 1 and 6
    if (menuItemsCount > 0 && menuItemsCount < 7) {
        slideshowElement.find('ol').addClass('slide-total-' + menuItemsCount);
    }

    // Remove accessible hiding and actually hide elements
    slideshowElement.find('div.slide.hidden').removeClass('hidden').hide();

    // Add positioning class to stack slides on top of one another
    // This positioning is only appropriate if JavaScript and transitions are enabled
    slideshowElement.find('div.slide').addClass('stack');

    // Check for a custom timeout for current slide and return
    var getTimeout = function () {

        var currentSlide = $('div.slide:first');

        if (currentSlide.attr('data-timeout')) {
            return currentSlide.attr('data-timeout');
        } else {
            return defaultSlideTimeout;
        }
    };

    // Slide swapper
    var swapSlides = function () {

        var currentSlide = $('div.slide:first');
        var nextSlide = currentSlide.next();
        var lastSlide = $('div.slide:last');

        // nextSlide.fadeOut(750);
        if (slidePosition.length > 0) {
            if (slidePosition.attr('rel') == "top") {
                // Swap slides
                currentSlide.fadeOut(750, function () {
                    $(this).insertAfter(lastSlide).css({
                        'display': 'none'
                    })
                });
            }
            else {
                // Swap slides
                currentSlide.fadeOut(750, function () {
                    $(this).appendTo(slideshowElement).css({
                        'display': 'none'
                    })
                });
            }
        }
        else {

            // Swap slides
            currentSlide.fadeOut(750, function () {
                $(this).appendTo(slideshowElement).css({
                    'display': 'none'
                })
            });
        }

        nextSlide.fadeIn(transitionSpeed).css({
            'display': 'block'
        }); //.animate({ 'opacity': 100, 'filter': "alpha('opacity=100')" }, transitionSpeed);
        // Swap selected menu item
        var currentMenuItem = $(slideshowElement.find('ol li.selected'));
        var nextMenuItem = null;
        if (currentMenuItem.next().length) {
            nextMenuItem = currentMenuItem.next()
        } else {
            nextMenuItem = $(slideshowElement.find('ol li:first'));
        }
        currentMenuItem.removeClass('selected');
        nextMenuItem.addClass('selected');


        if (autoSlide.length > 0) {
            if (autoSlide.attr('rel') != 'off') {

                slideTimeout = getTimeout();
                clearInterval(swapSlideTimer);
                swapSlideTimer = setInterval(swapSlides, slideTimeout);
                // Clear current timer
                setTimeout(function () {
                    clearInterval(swapSlideTimer)
                }, slideTimeout + 2000);


            }

        }
        else {

            slideTimeout = getTimeout();
            //clearInterval(swapSlideTimer);
            swapSlideTimer = setInterval(swapSlides, slideTimeout);

            // Clear current timer
            setTimeout(function () {
                clearInterval(swapSlideTimer)
            }, slideTimeout + 2000);


        }

    };

    // Setup menu mouseover behavior
    slideshowElement.find('ol li a').click(function () {

        var nextSlide = $($(this).attr('href'));

        // Swap slides
        // Hide all slides
        $('div.slide').hide();
        nextSlide.show().animate({
            'opacity': 1
        }, 0);

        // Swap selected menu item
        var currentMenuItem = $(slideshowElement.find('ol li.selected'));
        var nextMenuItem = $(this).parent();
        currentMenuItem.removeClass('selected');
        nextMenuItem.addClass('selected');

        if (autoSlide.length > 0) {
            if (autoSlide.attr('rel') != 'off') {

                // Clear current timer
                clearInterval(swapSlideTimer);
            }

        }
        else {
            // Clear current timer
            clearInterval(swapSlideTimer);
        }



        return false;
    });


    $(document).ready(function () {


        if ($('#slideshow').length > 0) {
            if (autoSlide.length > 0) {
                if (autoSlide.attr('rel') != 'off') {

                    slideTimeout = getTimeout();
                    swapSlideTimer = setInterval(swapSlides, slideTimeout);

                    // Clear current timer
                    setTimeout(function () {
                        clearInterval(swapSlideTimer)
                    }, slideTimeout + 2000);

                }

            }
            else {


                slideTimeout = getTimeout();
                swapSlideTimer = setInterval(swapSlides, slideTimeout);

                // Clear current timer
                setTimeout(function () {
                    clearInterval(swapSlideTimer)
                }, slideTimeout + 2000);

            }
        }
    });

    /**
    Global navigation z-index fix
    */
    if ($('body').hasClass('browserIE7') || $('body').hasClass('browserIE6')) {
        var zIndexNumber = 1000;
        $('li').each(function () {
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= 10;
        });
    }

    if ($("#videos").length != 0) {
        $("#section-nav").mouseover(function () {
            $("#videos").css({
                'display': 'none'
            })
        }).mouseout(function () {
            $("#videos").css({
                'display': 'block'
            })
        });
    }

    if ($(".ui-tabs-nav").length != 0) {
        $("#section-nav").mouseover(function () {
            $(".ui-tabs-nav").css({
                'visibility': 'hidden'
            });
            $(".graph-legend-index").css({
                'visibility': 'hidden'
            });
        }).mouseout(function () {
            $(".ui-tabs-nav").css({
                'visibility': 'visible'
            });
            $(".graph-legend-index").css({
                'visibility': 'visible'
            })
        });
    }


    /**
    Clear form elements on focus
    */
    $(document).ready(function () {
        var inputs = $('#search_area input, #ETF-search-term');
        for (var i = 0; i < inputs.length; i++) {
            inputs[i].setAttribute('rel', inputs[i].defaultValue);
            inputs[i].onfocus = function () {
                if (this.value == this.getAttribute('rel') && this.getAttribute('type') != 'submit' && this.getAttribute('type') != 'reset') {
                    this.value = '';
                } else {
                    return false;
                }
            }
            inputs[i].onblur = function () {
                if (this.value == '' && this.getAttribute('type') != 'submit' && this.getAttribute('type') != 'reset') {
                    this.value = this.getAttribute('rel');
                } else {
                    return false;
                }
            }
            inputs[i].ondblclick = function () {
                this.value = this.getAttribute('rel')
            }
        }

        var inputs = $('#search_area input');

    });


});

function activateTooltips() { //Adding a custom tooltip to any tag with a title attribute:
    $('[title]').colorTip({
        color: 'white'
    });
}

//Date parameters for graph controls
var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var day = today.getDate();
var selectedRange = 3; //adjust this value to affect the range - currently adjusting the month range
//additional modifiers can be added to adjust for YTD, 1yr, etc... with onclick events

function activateDatepicker() {
    var fromMonth = today.getMonth() - selectedRange;
    var todaysDate = months[month] + " " + day + ", " + year;
    var daysInMonthCheck = 32 - new Date(year, fromMonth, 32).getDate();

    if (day > daysInMonthCheck) {
        day = daysInMonthCheck;
    }
    if (fromMonth < 0) {
        fromMonth = (12 - selectedRange);
    }

    var pastDate = months[fromMonth] + " " + day + ", " + year;

    $("#graph-date-from").val(pastDate); //set the default date in the from date field
    $("#graph-date-to").val(todaysDate); //set the default date in the to date field
    var dates = $("#graph-date-from, #graph-date-to").datepicker({ //function for establishing datepicker
        dateFormat: 'M d, yy',
        maxDate: '+0d',
        //maxDate available is today
        onSelect: function (selectedDate) {
            var option = this.id == "graph-date-from" ? "minDate" : "maxDate",
                instance = $(this).data("datepicker"),
                date = $.datepicker.parseDate(
                instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            dates.not(this).datepicker({
                option: date
            });
        }

    });

}

var broadcastWin = null;

function newBroadcastPopup(url) {
    if (broadcastWin == null || (broadcastWin && broadcastWin.closed)) {
        broadcastWin = window.open(
        url, 'broadcastPopup', 'height=500,width=900,left=50,top=10,resizable=yes,scrollbars=yes,' + 'toolbar=no,menubar=no,location=no,directories=no,status=no');
    }
}



$(document).ready(function () {

    InitializeConfirmations();

    //ipad and iphone fix
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {

        $('#s4-ribbonrow').html("").hide();
        $('body').css({
            'overflow': ''
        });
        $('body').removeAttr('scroll');

        //  $('head').append('<link rel="stylesheet" href="/_layouts/PimcoETF/css/iOSView.css" type="text/css" />');
    }

});



function InitializeConfirmations() {

    //grab all external URL and add confirmleave class
    $("a[href*='http://']:not([href*='" + location.hostname + "']),[href*='https://']:not([href*='" + location.hostname + "'])").each(function () {
        if (!ConfirmDomain($(this))) {
            if ($(this).attr("href").indexOf('javascript:') < 0) {
                if ($(this).hasClass('confirmleave') == false) {
                    $(this).addClass('confirmleave');
                }
            }
        }

        if (ConfirmPIDomain($(this))) {
            if ($(this).attr("href").indexOf('javascript:') < 0) {
                if ($(this).hasClass('confirmleave') == false) {
                    $(this).addClass('confirmleave');
                }
            }
        }

        if (ConfirmInvestorDomain($(this))) {
            if ($(this).attr("href").indexOf('javascript:') < 0) {
                if ($(this).hasClass('confirmleave') == false) {
                    $(this).addClass('confirmleave');
                }
            }
        }

    });

    //Configure Confirmation Modal
    $("#confirm").dialog({
        title: 'Confirmation',
        autoOpen: false,
        closeText: '',
        dialogClass: 'ms-rteCustom-BodyCopy',
        modal: true,
        resizable: false
    });

    //Check and bind all href to Confirmation.
    BindLinkWithConfirmations();



    //Setup Alert Modal for Internet Exploer lower than IE7
    $("#IEAlert").dialog({
        title: 'Message',
        autoOpen: false,
        closeText: '',
        dialogClass: 'ms-rteCustom-BodyCopy',
        modal: true,
        resizable: false
    });

    //Check and Alert users on Internet Exploer lower than IE7
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        if ($.cookie('PIMCO_Brower_Check') != 'true') {
            $.cookie('PIMCO_Brower_Check', 'true');
            $("#IEAlert").dialog({
                buttons: {
                    "Ok": function () {
                        $(this).dialog("close");
                    }
                }
            });

            $("#IEAlert").dialog("open");
        }
    }
}

function BindLinkWithConfirmations() {
    $("#confirm").html("<p style='font-size:11px;'>You are now leaving www.pimcoetfs.com.<p>");
    var orignalHtmlMessage = $("#confirm").html();

    //Bind Confirmation Modal Event to all class confirmleave
    $('a.confirmleave').click(function (e) {
        e.preventDefault();
        var targetUrl = $(this).attr("href");
        var targetPopUp = $(this).attr("target").toLowerCase();
        var msg = $(this).attr("msg");

        if (msg != undefined && msg != "") {
            $("#confirm").html("<p>" + msg + "</p>");
        }
        else {
            $("#confirm").html(orignalHtmlMessage);
        }

        if (ConfirmPIDomain($(this))) {
            $("#confirm").html("<p style='font-size:11px;'>You are entering PIMCO INVESTMENTS LLC<p>");
        }

        if (ConfirmInvestorDomain($(this))) {
            $("#confirm").html("<p style='font-size:11px;'>Please confirm you are an Institutional investor.<p>");
        }

        $("#confirm").dialog({
            buttons: {
                "Confirm": function () {
                    if (targetPopUp == "_blank") {
                        $(this).dialog("close");
                        window.open(targetUrl);
                    }
                    else {
                        window.location.href = targetUrl;
                    }
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });

        $("#confirm").dialog("open");
    });

}

function OpenConfirmation(cLink) {
    if ($(cLink).hasClass('confirmleave') == false) {
        $(cLink).addClass('confirmleave');
    }
    InitializeConfirmations();
    $(cLink).click();
}

function ConfirmDomain(check_item) {
    var OkDomain = ['allianz.myvurv.com', 'auth-media-pimco.cn.us1.1corp.org', 'prod-media-pimco.allianzgi-us.com', 'www2.pimco.com', 'media.pimco-global.com', 'pimcoetf.com', 'pimcoetfs.com','prospectus-express.newriver.com'];
    var checked = false;
    $.each(OkDomain, function () {
        if (getHostname($(check_item).attr("href")).toLowerCase().indexOf(this) > -1) {
            checked = true;
            return checked;
        }
    });
    return checked;
}

function ConfirmPIDomain(check_item) {
    var PIDomain = ['investments.pimco.com'];
    var checked = false;
    $.each(PIDomain, function () {
        if (getHostname($(check_item).attr("href")).toLowerCase().indexOf(this) > -1) {
            checked = true;
            return checked;
        }
    });
    return checked;
}

function ConfirmInvestorDomain(check_item) {
    var PIDomain = ['www.source.info'];
    var checked = false;
    $.each(PIDomain, function () {
        if (getHostname($(check_item).attr("href")).toLowerCase().indexOf(this) > -1) {
            checked = true;
            return checked;
        }
    });
    return checked;
}

function getHostname(str) {
    var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
    var hn = str.match(re);
    if (hn != null) {
        return hn.toString();
    }
    else {
        return "";
    }
}

function confirmation(_url, _newwindow) {

    var answer = confirm("You are leaving www.pimcoetfs.com");
    if (answer) {
        if (_newwindow) window.open(_url);
        else window.location = _url;
    }

}

ScrollToElement = function (elementname) {
    try {
        var el = document.getElementById(elementname);
        $('#s4-workspace').animate({
            scrollTop: $(el).offset().top + $(el).height()
        }, 800);
    }
    catch (Error) {
        //nothing
    }
}

function showMonthlyOrQuarterly(type) {
    if (type == 'month') {
        $('.quarterly-table').fadeOut(750);
        $('.monthly-table').delay(500).fadeIn(1500);
    }
    else {
        $('.monthly-table').fadeOut(750);
        $('.quarterly-table').delay(500).fadeIn(1500);
    }
}

//function Call WebTrends


function WebTrendsCall() {
    try {



        //grab Meta of video
        dcsAllianzVar();
        dcsFunc("dcsAdv");
        dcsMeta();
        //Send to WebTrends Server
        dcsTag();
    }
    catch (err) {
        //error on webtrends call
    }
}

function emailModalWin() {
    var obj = $("<div style='width:980px'><iframe src='/Documents/NewsLetterSignup.htm' width='100%' height='549' scrolling='yes' frameborder='0' allowtransparency='true'></iframe><div align='left'></div>");
    var dlog = obj.dialog({
        autoOpen: true,
        modal: true,
        draggable: true,
        position: 'middle',
        resizable: false,
        zindex: 3000,
        closeOnEscape: true,
        width: 1000,
        scrolling:'yes',
        close: function (ev, ui) {
        }
    });
}




