﻿function bindCloseModalHover() {
    $('.reveal-modal.countryselect a.close-reveal-modal, .reveal-modal.popup a.close-reveal-modal').hover(function () {
        $(this).addClass("close-hover");
    }, function () {
        $(this).removeClass("close-hover");
    });
}





$(document).ready(function () {

    $('a').click(function () {
        var fullUrl = $(this).attr('href');

        if (fullUrl != null) {
            if (fullUrl.indexOf('http://') != -1) {
                var splitUrl = fullUrl.split("/");

                if ((splitUrl[2].toLowerCase().indexOf('localhost') == -1) && (splitUrl[2].toLowerCase().indexOf('phdww.com') == -1) && (splitUrl[2].toLowerCase().indexOf('www.phdww.com') == -1)) {
                    $(this).attr("target", "_blank");
                }
            } else if (fullUrl.toLowerCase().indexOf(".pdf") != -1) {
                $(this).attr("target", "_blank");
            }
        }
    });


    //$("form").jqTransform();

    /*
    var i;

    for (i = 0; i < $("#selCountry option").length; i++) {
    $("#selCountry option")[i].innerText = $("#selCountry option")[i].innerText.toUpperCase();
    }
    */

    //search box text persistance

    $(".searchBox .search").focus(function () {
        if ($(".searchBox .search").val() == searchPrompt) {
            $(".no-search-text").hide();

            $(".searchBox .search").val('');
            $(".searchBox .search").removeClass('searchinactive');
        }
    });

    $(".searchBox .search").blur(function () {
        if ($(".searchBox .search").val() == '') {
            $(".searchBox .search").val(searchPrompt);
            $(".searchBox .search").addClass('searchinactive');
        }
    });

    //searchBoxContent
    if ($(".searchBoxContent").text() != "") {
        $(".searchBox .search").val($(".searchBoxContent").text());

        if ($(".searchBox .search").val() == searchPrompt) {
            $(".searchBox .search").val(searchPrompt);
        }

        if ($(".searchBox .search").val() == searchPrompt) {
            $(".searchBox .search").addClass('searchinactive');
        } else {
            $(".searchBox .search").removeClass('searchinactive');
        }
    } else {
        $(".searchBox .search").addClass('searchinactive');
    }

    $('.search-submit').click(function (e) {
        if ($('.searchBox .search').val() == searchPrompt) {

            $(".no-search-text").show();

            e.preventDefault();
        }
    });

    //search result news focus
    if ($('.searchResultArticleHeading').text() != '') {
        if ($('#node' + $('.searchResultArticleHeading').text()) != null) {
            //$('#node' + $('.searchResultArticleHeading').text()).focus();
            $.scrollTo($('#node' + $('.searchResultArticleHeading').text()), 500, { axis: 'y' });
        }
    }

    //email unsubscription request
    if ($(".requestemail").text() != "") {
        $(".UnsubscriptionEmail").val($(".requestemail").text());
    }

    //search summary
    if ($(".hiddenSummary").text() != "") {
        var summary = $.parseJSON($(".hiddenSummary").text());
        var summaryText;

        summaryText = "Showing results ";
        summaryText += ((parseInt(summary.Page) * 10) - 9).toString();
        summaryText += " to ";

        if (parseInt(summary.Items.toString()) < parseInt(summary.Page) * 10) {
            summaryText += summary.Items.toString();
        } else {
            summaryText += (parseInt(summary.Page) * 10).toString();
        }

        summaryText += " of ";
        summaryText += summary.Items.toString();

        summaryText += ' matches for "' + $(".searchBoxContent").text() + '"';

        $("#searchSummary").text(summaryText);
    }

    //search pagination
    if ($(".searchPagingData").text() != "") {
        var pagination = $.parseJSON($(".searchPagingData").text());
        var tempHtml;

        if (pagination.CurrentPage == pagination.TotalPages) {
            //disable last button
            $("#paginationLast").replaceWith('<span class="' + $("#paginationLast").attr("class") + '" id="' + $("#paginationLast").attr("id") + '">' + $("#paginationLast").text() + '</span>');

            $("#paginationLast").addClass("disabled");

            //disable next button
            $("#paginationNext").replaceWith('<span class="' + $("#paginationNext").attr("class") + '" id="' + $("#paginationNext").attr("id") + '">' + $("#paginationNext").text() + '</span>');

            $("#paginationNext").addClass("disabled");
        }

        if (pagination.CurrentPage == "1") {
            //disabled first button
            $("#paginationFirst").replaceWith('<span class="' + $("#paginationFirst").attr("class") + '" id="' + $("#paginationFirst").attr("id") + '">' + $("#paginationFirst").text() + '</span>');

            $("#paginationFirst").addClass("disabled");
            //disabled prev button
            $("#paginationPrev").replaceWith('<span class="' + $("#paginationPrev").attr("class") + '" id="' + $("#paginationPrev").attr("id") + '">' + $("#paginationPrev").text() + '</span>');

            $("#paginationPrev").addClass("disabled");
        }


        $(".pageNumber" + pagination.CurrentPage).replaceWith('<span class="' + $(".pageNumber" + pagination.CurrentPage).attr("class") + '" ><strong>' + $(".pageNumber" + pagination.CurrentPage).text() + '</strong></span>');

        $(".pageNumber" + pagination.CurrentPage).addClass("disabled");
    }


    $('.reveal-modal.countryselect .country-select-hold ul li a').hover(function () {
        $(this).addClass("hovered");
    }, function () {
        $(this).removeClass("hovered");
    });

    $('.reveal-modal.countryselect .country-select-hold ul li .modalContinentLink').click(function (e) {

        //Add class to current country to show sub menu and remove from others
        $('.reveal-modal.countryselect .country-select-hold ul li').removeClass('hot');

        $(this).parent().addClass('hot');

        //Calculate the height of the current menu and apply it to the container, header + current menu height
        var modalHeader = $('div.reveal-modal.countryselect > header');
        var headerHeight = modalHeader.height();
        headerHeight += parseInt(modalHeader.css("padding-top"), 10);
        headerHeight += parseInt(modalHeader.css("padding-bottom"), 10);

        var currentMenu = $(this).next('ul');

        var menuHeight = currentMenu.height();
        menuHeight += parseInt(currentMenu.css("padding-top"), 10);
        menuHeight += parseInt(currentMenu.css("padding-bottom"), 10);

        var wrapperHeight = menuHeight + headerHeight;

        $('div.reveal-modal.countryselect').height(wrapperHeight);

    });

    bindCloseModalHover();


    $('.thought-articles li:nth-child(even)').addClass('alternate');

    if ($("#firstInsightArticle").text() != "") {
        var firstArticleJSON = $("#firstInsightArticle").text();
        var firstArticle = jQuery.parseJSON(firstArticleJSON);

        $("#articleTitle").html(FormatURL(firstArticle.title));

        //if there is a vimeo link/image
        if ((firstArticle.image != '') && (firstArticle.id != '')) {
            $("#articleImage").attr("src", firstArticle.image);

            $("#articleLink").attr("title", firstArticle.title);
            $("#articleLink").attr("rel", firstArticle.id);

            $("#articleType").text("Latest Video");

            $("#articleDate").remove();
            //flickr image
        } else if ((firstArticle.image != '') && (firstArticle.id == '')) {
            $("#articleImage").attr("src", firstArticle.image);

            $("#articleLink").attr("title", firstArticle.title);

            $("#articleDate").text(firstArticle.date);

            $("#articleType").text("");
        } else {
            //if it is a twitter feed
            $("#articleType").addClass("tweeter");

            $("#articleType").text("phdworldwide London");
            $("#articleDate").text(firstArticle.date);
        }

        if ((firstArticle.link !== null) && (firstArticle.link != "")) {
            if ((firstArticle.image != '') && (firstArticle.id == '')) {
                $("#articleTitle").html("<a href=\"#\" class=\"popupbuttonflickr\" rel=" + firstArticle.image + "  >" + $("#articleTitle").text() + "</a>");
            } else {
                $("#articleTitle").html("<a href=\"" + firstArticle.link + "\" target=\"_blank\">" + $("#articleTitle").text() + "</a>");
            }
        }

        $("#articleShare").html($("#firstInsightArticleShare").html());

        if ($("#firstInsightArticlePopup").html() != null) {
            $("#articleTitle").html($("#articleTitle").html() + $("#firstInsightArticlePopup").html());
        }
        //$("#articleTitle").attr("style", "width:350px");
    }


    function FormatURL(twitterStatus) {

        var startURL;
        var endURL;
        var urlEnd;
        var urlStart;

        if (twitterStatus.indexOf("http") != -1) {
            urlStart = twitterStatus.indexOf("http");
            urlEnd = twitterStatus.indexOf(" ", urlStart);

            if (urlEnd == -1) {
                urlEnd = twitterStatus.length;
            }

            startURL = twitterStatus.substring(urlStart, urlEnd);

            endURL = "<a href='" + startURL + "' target='_blank'>" + startURL + "</a>";
        }

        if (startURL != "") {
            twitterStatus = twitterStatus.replace(startURL, endURL);

            while (twitterStatus.indexOf("%23") != -1) {
                twitterStatus = twitterStatus.replace('%23', '#');
            }
        }

        return twitterStatus;
    }

    if (navigator.platform == "Mac") {
        $("h3").attr("style", "font-weight:normal");
    } else {
    }

    $('#selCountry').click(function (e) {
        e.preventDefault();
        $('.countryselect').reveal();
    });

    $('.countyselectbutton').click(function (e) {
        e.preventDefault();
        $('.countryselect').reveal();
    });

    $('.popupbutton').click(function (e) {
        e.preventDefault();
        $(this).parent().next('.popup').reveal();
    });


    $('.popupbuttonflickr').click(function (e) {
        e.preventDefault();
        var pageOffset = 0;
        var $popuphtml;
        if ($('body').hasClass("sectionInsights")) {
            pageOffset = -100;
        } else {
            pageOffset = 100;
        }
        var triggerOffset = $(this).position().top + pageOffset;
        var whichpic = $(this).attr('rel');
        if ($(this).attr('rel') != undefined) {
            if ($(this).parent().next('.popup').html() == null) {
                $popuphtml = $(this).parent().find('.popup').html()

                triggerOffset = $(this).position().top + 100;
            }

            if ($(this).parent().find('.popup').html() == null) {
                $popuphtml = $(this).parent().next('.popup').html()
            }

            $("#modal-container").html($popuphtml).css('top', triggerOffset);
            $("#modal-container").reveal();
            $("#modal-container").find('.flickrimg').html('<img style="width:700px;" class="flickrpopup" src=\"' + whichpic + '" > ');
            //$("#modal-container").find('.flickrimg').html("<object width=\"400\" height=\"300\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" data=\"http://www.flickr.com/apps/video/stewart.swf?v=49235\" type=\"application/x-shockwave-flash\">);
            bindCloseModalHover();
        }
    });

    if ($("#articleLink").attr('rel') == undefined) {
        $("#articleImage").unwrap();
        $("#articleLink").remove();
    }

    $('.clickclosevimeo').click(function (e) {
        e.preventDefault();

        $(this).next().html('<p>Empty</p>');
    });

    $('.clickcloseflickr').click(function (e) {
        e.preventDefault();
        $(this).next().html('<p>Empty</p>');
    });

    $('.firstarticleclickme').click(function (e) {
        e.preventDefault();

        var getheight = $(this).parent().parent().height();
        var trueheight = getheight + 34;
        //alert(trueheight);
        $(this).next().height(trueheight);
        $(this).next().slideToggle('slow', function () {
            // Animation complete.
        });
    });

    $('.twitterclickme').click(function (e) {
        e.preventDefault();

        var getheight = $(this).parent().parent().height();
        var trueheight = getheight + 40;
        //alert(trueheight);
        $(this).next().height(trueheight);
        $(this).next().slideDown('slow', function () {
            // Animation complete.
        }).toggleClass("open");
        $("#offers-wrapper").addClass("suppressed");
        $('.threecolumns').addClass("overflow");
        $('.threecolumns ul').addClass('below');
        $(this).parent().parent().parent().addClass('above');
    });

    $('.handle-filter').click(function () {
        $(this).parent().removeClass('suppressed');
        $('.share .inner').slideUp().removeClass('open');
        $('.threecolumns ul').removeClass('above');
        $('.threecolumns').removeClass('overflow');

    });

    $('.clickme').click(function (e) {
        e.preventDefault();

        if ($(this).parent().parent().height() != 0) {
            var getheight = $(this).parent().parent().height();
        } else {
            var getheight = $("article").height();
        }

        var trueheight = getheight + 30;
        //alert(trueheight);
        $(this).next().height(trueheight);
        $(this).next().slideToggle('slow', function () {
            // Animation complete.
        });
    });


    $('.book .clickclose').click(function (e) {
        e.preventDefault();

        $(this).parent().slideToggle('slow', function () {
            // Animation complete.
        }).toggleClass("open");
        $("#offers-wrapper").removeClass("suppressed");
        $('.threecolumns').removeClass("overflow");
        $('.threecolumns ul').removeClass('above');
    });

    $(".selCountry").change(function () {
        window.location = this.value + '.aspx';
    });

    if (window.location.hash) {
        if (window.location.hash.split("-")[2] != null) {
            $('a[rel="' + window.location.hash.split("-")[2] + '"]').focus();

            $('a[rel="' + window.location.hash.split("-")[2] + '"]').click();
        }
    }

    $('a[href^="http://vimeo.com/"]').each(
        function () {
            var vimeoRel = $(this).attr("href");
            vimeoRel = vimeoRel.replace("http://vimeo.com/", "");
            vimeoRel = vimeoRel.replace(/\D/, "");
            $(this).attr("rel", vimeoRel);
            $(this).attr("href", "#");
            $(this).attr("class", "popupbuttonvimeo");
            $(this).attr("target", "_self");
        }
    )

    $('.popupbuttonvimeo').click(function (e) {
        e.preventDefault();
        if (whichvid == "") return;
        var triggerOffset = 100;
        if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
            triggerOffset += -200;
        }
        var whichvid = $(this).attr('rel');
        var $popupDiv = $('#vimeoPopup');
        if ($(this).attr('rel') != undefined) {
            $("#modal-container").html($popupDiv.html()).css('top', triggerOffset);
            $("#modal-container").reveal();
            $("#modal-container").find('.vimeoiframe').html('<iframe src=\"http://player.vimeo.com/video/' + whichvid + '\" width=\"700\" height=\"400\" frameborder=\"0\"> ');
            bindCloseModalHover();
        }

    });

    $('.intro').each(function () {
        var whitespaceOnly = /^\s*$/;
        var introText = $(this).text();
        if (whitespaceOnly.test(introText)) {
            $(this).hide();
        };
    })




});


















function megaHoverOver() {
    $(this).find(".SubCMSListMenuUL").stop().fadeTo('fast', 1).show();
    //Calculate width of all ul's
    (function ($) {
        jQuery.fn.calcSubWidth = function () {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function () { rowWidth += $(this).width(); });
        };
    })(jQuery);

    if ($(this).find(".row").length > 0) { //If row exists...
        var biggestRow = 0;
        //Calculate each row
        $(this).find(".row").each(function () {
            $(this).calcSubWidth();
            //Find biggest row
            if (rowWidth > biggestRow) { biggestRow = rowWidth; }
        });
        //Set width
        $(this).find(".SubCMSListMenuUL").css({ 'width': biggestRow });
        $(this).find(".row:last").css({ 'margin': '0' });
    } else { //If row does not exist...
        $(this).calcSubWidth();
        //Set Width
        $(this).find(".SubCMSListMenuUL").css({ 'width': rowWidth });
    }
}

function megaHoverOut() {
    $(this).find(".SubCMSListMenuUL").stop().fadeTo('fast', 0, function () { $(this).hide(); });
}

$(function () {
    var config = { sensitivity: 2, interval: 100, timeout: 500, over: megaHoverOver, out: megaHoverOut };
    $(".navtop .CMSListMenuUL li .SubCMSListMenuUL").css({ 'opacity': '0' });
    $(".navtop .CMSListMenuUL li").hoverIntent(config);
    $(".navtop .CMSListMenuUL li ul.SubCMSListMenuUL li")
        .mouseover(function () {
            $(this).addClass("subNavHover").prev().addClass("subNavHideBorder");
            $(this).parentsUntil('ul.CMSListMenuUL').addClass('CMSListMenuKeepHighlightedLI');
        })
        .mouseout(function () {
            $(this).removeClass("subNavHover").prev().removeClass("subNavHideBorder");
            $(this).parentsUntil('ul.CMSListMenuUL').removeClass('CMSListMenuKeepHighlightedLI');
        });

    $(".navtop .CMSListMenuUL li ul.SubCMSListMenuUL li.SubCMSListMenuHighlightedLI, .navtop .CMSListMenuUL li ul.SubCMSListMenuUL li.SubCMSListMenuHighlightedLIlast")
        .prev().addClass("subNavKeepHideBorder");
});


