﻿function changeInputType(inputId, type) {
    var input = $("#" + inputId),
        newInput = $("<input />")
            .val(input.val())
            .attr("id", inputId)
            .attr("placeholder", input.attr("placeholder"))
            .attr("type", type)
            .insertBefore('#' + inputId);
    input.remove();
}

$.fn.slideshow = function (options) {
    var defaults = {
        item: ".feature",
        prev: ".prev",
        next: ".next",
        tweenSpeed: 500,
        transitionTimingFunction: "cubic-bezier(0.190, 1.000, 0.220, 1.000)",
        easingFunction: function (x, t, b, c, d) {
            return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
        },
        featureTitleText: "hgroup .title",
        featureSubTitleText: "hgroup .sub-title"
    };
    var settings = $.extend(defaults, options);

    var vP = "";
    var transitionEnd = "TransitionEnd";
    if ($.browser.webkit) {
        vP = "-webkit-";
        transitionEnd = "webkitTransitionEnd";
    } else if ($.browser.msie) {
        vP = "-ms-";
    } else if ($.browser.mozilla) {
        vP = "-moz-";
        transitionEnd = "transitionend";
    } else if ($.browser.opera) {
        vP = "-o-";
        transitionEnd = "oTransitionEnd";
    }
    var transitionDuration = vP + "transition-duration";

    return this.each(function () {

        var isFullScreen = false;
        var slideshow = $(this);
        var slides = slideshow.find(settings.item).addClass("left").hide();
        var center = slides.first().removeClass("left").addClass("center").fadeIn();
        var count = slides.length;
        var nxt = slideshow.find(settings.next);
        var prv = slideshow.find(settings.prev);
        var index = 0;
        var currentSlide = slideshow.find("nav .index");
        var totalSlides = slideshow.find("nav .total b");
        var placeMarker;

        //set up numbering
        totalSlides.html(count);
        currentSlide.html(1);

        //hide all captions apart from current
        //slides.find("figcaption").hide();
        //center.find("figcaption").show();


        var lock = false;
        if (count <= 1) slideshow.addClass("no-pagination");

        slideshow.bind('goto', function (event, index) {
            gotoInd(index);
        });

        function gotoInd(no, dir) {

            if (index == no || lock) { return; }

            dir = dir || -1;
            index = no;
            center = transition(center, slides.eq(index), dir);
            center.trigger("resize");
        }

        if (Modernizr.csstransitions) {
            slides
                .css(vP + "transition-property", "all")
                .css(vP + "transition-timing-function", settings.transitionTimingFunction);
        };

        function transition(from, to, dir) {

            if (Modernizr.csstransitions) {

                lock = true;

                var fromClass = (dir == 1) ? "right" : "left";
                var toClass = (dir == 1) ? "left" : "right";


                //remove video if playing and reset view
                if (from.hasClass("video")) {
                    $("body").removeClass("video");
                    $(".feature.active").removeClass("playing");
                    $(".video-player").text("");

                }

                return to
                //set inital move from position
                    .show()
                    .css(transitionDuration, "0ms")
                    .removeClass("left right center")
                    .addClass(toClass)
                    .delay(50, "doMove").queue("doMove", function () {
                        //move
                        from
                            .css(transitionDuration, settings.tweenSpeed + "ms")
                            .removeClass("center")
                            .addClass(fromClass);
                        $(this)
                            .css(transitionDuration, settings.tweenSpeed + "ms")
                            .removeClass(toClass)
                            .addClass("center")
                            .bind(transitionEnd, function () { lock = false; transitionFinished(); });
                    }).dequeue("doMove");
            } else {
                from
                    .stop(true, true)
                    .animate({ "left": dir * from.width() }, settings.tweenSpeed);

                return to
                    .show()
                    .stop(true, true)
                    .css("left", -1 * dir * from.width())
                    .animate({ "left": "0" }, settings.tweenSpeed, transitionFinished);
            }
        }

        var learnMore = $('#learnMore');
        function transitionFinished() {
            currentSlide.html(index + 1);
            $(settings.featureTitleText).html(center.attr("data-title"));
            $(settings.featureSubTitleText).html(center.attr("data-sub-title"));
            learnMore.attr('href', center.attr('data-href'));
        }

        function next() {
            if (index == count - 1)
                gotoInd(0, -1);
            else
                gotoInd(+index + 1, -1);
        }

        function prev() {
            if (index > 0)
                gotoInd(+index - 1, 1);
            else
                gotoInd(+count - 1, 1);
        }

        nxt.click(next);
        prv.click(prev);


        var lightboxEventClick = function (evt) {

            if ($("body").hasClass("contact")) return;

            if ($(this).hasClass("video")) {

                var vidPlayerContents = $("<div class='video-player'><iframe frameborder='0' src='" + $(this).attr("data-video-src") + "' webkitAllowFullScreen allowFullScreen></iframe></div>");
                $(this)
                        .addClass("playing")
                        .children(".video-player")
                        .replaceWith(vidPlayerContents);

                $("body").addClass("video");

                if ($("body").hasClass("lightbox-activated")) {
                    return;
                }

            } else {

                if (!$("body").hasClass("lightbox-activated") && $("body").hasClass("article")) {
                    window.location = $(this).data("href");
                    return true;
                }

                $("body").removeClass("video");

                $(".feature.active").removeClass("playing");
                $(".video-player").text("");
            }

            $("body").toggleClass("lightbox-activated");
            $("a.lightbox").toggle();

        }

        //Lightbox events
        $(".lightbox-activated section.featured").live("mousedown touchstart", function (e) {
            if (e.target.nodeName == "SECTION")
                lightboxEventClick();
        });
        $("a.lightbox, nav.secondary .close-lightbox, .feature").bind("click", lightboxEventClick);

        //disable for googlemaps
        if (!slideshow.find(".googlemap").length > 0) {
            //Touch Events
            $(slideshow).touchwipe({
                wipeLeft: function () {
                    next();
                },
                wipeRight: function () {
                    prev();
                },
                min_move_x: 20,
                min_move_y: 20,
                preventDefaultEvents: false
            });
        }

        //Keypress events
        $(document.documentElement).keydown(function (e) {
            //console.log(e.keyCode);
            if (e.keyCode == 37) { // left	
                prev();
            }
            if (e.keyCode == 39) { // right	
                next();
            }
        });
    });
};

$.fn.loadGoogleMaps = function () {

    return this.each(function () {
        var $this = $(this);
        var latlng = new google.maps.LatLng($this.data("lat"), $this.data("long"));
        var myOptions = { zoom: $this.data("zoom"), center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
        var map = new google.maps.Map($this.find("div")[0], myOptions);
        var clustaMarkerImage = new google.maps.MarkerImage(GoogleMapsIconLocation + '/clusta-map-icon.png', new google.maps.Size(25, 25), new google.maps.Point(0, 0), new google.maps.Point(12, 12));
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: clustaMarkerImage,
            title: $this.data("title")
        });

        var contentString = '<div id="content"><h2 class="title">' + $this.data("title") + "</h2>" + $this.data("popupcontent1") + "<br />" + $this.data("popupcontent2")+'</div>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });

        $this.live("resize", function () {
            google.maps.event.trigger(map, 'resize');
            map.setCenter(latlng);
        });
    });
};

//Footer
$(window).smartresize(function () {

    if ($("body").hasClass("lightbox-activated")) { return; }

    var footer = $("[role=contentinfo]")
    footerHeight = footer.height(),
                    footerOffset = footer.offset(),
                    windowHeight = $(window).height();

    if (footerOffset.top + footerHeight <= windowHeight) {
        footer.addClass("fixed");
    } else {
        footer.removeClass("fixed");
    }

}).trigger("resize");

//Search
$("[role=navigation] .search a").click(function () {

    $(this)
                    .parent()
                    .toggleClass("active");
    $("[role=search]")
                    .toggleClass("hide", 300)
                    .find(".input-text")
                    .focus();
});

$("#search").submit(function () {
    return $(this).find(".input-text").val().trim().length > 1;
});

//Footer Office address
$("[role=contentinfo] .contact > a").click(function () {
    $(this)
                    .addClass("current")
                    .siblings("a")
                    .removeClass("current");
    $(this)
                    .next(".office")
                    .addClass("current")
                    .show()
                    .siblings(".office")
                    .hide();
});

//Expandable sections
$(".expandable + .content").hide();
$(".expandable").click(function () {
    $(this)
                    .toggleClass("icon-hidden")
                    .next(".content")
                    .slideToggle("fast");

    if ($.browser.msie && parseInt($.browser.version) == 7) {
        //Fix IE7 render glitch by forcing redraw
        $(this)
                        .next(".content")
                        .addClass("fixie");
    }
});

//Blog Archive
$("nav.secondary .archive").hide();
$("nav.secondary .archive-trigger").click(function () {
    $(this)
                    .parent("li")
                    .toggleClass("current");
    $("nav.secondary .archive")
                    .removeClass("collapsed")
                    .toggle("fast");
});

$("nav.secondary .archive .close-handle").click(function () {
    $(this)
                    .parent(".archive")
                    .hide();

$("nav.secondary .archive-trigger")
                    .parent("li")
                    .toggleClass("current");
});

$("nav.secondary .archive .year + ol")
                .hide();

$("nav.secondary .archive .default")
                .addClass("current")
                .next("ol")
                .show();

$("nav.secondary .archive .year").click(function () {
    $(this)
                    .addClass("current")
                    .siblings(".year")
                    .removeClass("current");
    $(this)
                    .next("ol")
                    .show()
                    .siblings("ol")
                    .hide();
});

//Filters
$("nav.secondary .work .filter").click(function () {
    var filter = $(this).attr("rel");

    $("nav.secondary .filters ol")
                    .removeClass("collapsed")
                    .hide();

    $(this)
                    .parent()
                    .addClass("current")
                    .siblings()
                    .removeClass("current")

    if (filter == "all") {
        //Do something for All
        return
    }

    $(this)
                    .parents(".level-1")
                    .siblings(".filters")
                    .children("ol")
                    .filter("." + filter)
                    .show();
});

$("nav.secondary .filters a").click(function () {
    var filters = $(this).closest('.filters');
    $(filters).find('li a').removeClass('selected');
    $(this)
                    .toggleClass("selected");
    //Filter selected
});

//Placeholder text effect on textarea
$("textarea").focus(function () {

    var e = $(this);
    if (!e.attr("placeholder")) return;

    if (e.text() === e.attr("placeholder")) {
        e.text("");
    }

}).change(function () {

    var e = $(this);
    if (!e.attr("placeholder")) return;

    if (e.text() === "") {
        e.text(e.attr("placeholder"));
    }

});

//Tooltips
$("body").append("<div id='tooltip'></div>");

var tooltip = $("#tooltip");
tooltip.hide();

$("a.tooltip").bind("mouseover", function () {
    var offset = $(this).offset();
    tooltip
                    .css({
                        left: offset.left + 17 + ($(this).width() / 2),
                        top: offset.top + 30
                    })
                    .show()
                    .html($("<span>" + $(this).attr("rel") + "</span>"));
}).bind("mouseleave", function () {
    tooltip
                    .hide();
});

// slideshow
$(".featured").slideshow();
$("a.googlemap").loadGoogleMaps();

//GA: Event Tracking
$("a[href$=pdf]").click(function () {
    var name = $(this).attr("title") || "";
    _gaq.push(['_trackEvent', 'PDF', 'Download', name]);
});

// feature tests
if (!Modernizr.input.placeholder) {
    $("input[placeholder]").each(function () {
        var $e = $(this),
                        placeholder = $e.attr("placeholder");
        $e.removeAttr("placeholder").val(placeholder);
        $e.bind("focus blur", function (e) {
            if (e.type === "focus" && $e.val() === placeholder) { $e.val(""); }
            else { if (!$e.val()) { $e.val(placeholder); } }
        });
    });
}

// iPad item fix
if (Modernizr.touch) {
    $('a.item.col').on('hover', function () {
        window.location = $(this).attr('href');
    });
}
