/// <reference path="jquery-vsdoc.js" />
var bannerResize = function () {
    var bannerWidth = ($("body").width() - $("#page").width()) / 2;

    $(".banner-reskin").width(bannerWidth);
    $(".banner-reskin").height($("#footer").offset().top);
},
    scrolled = loaded = clicked = false;

$(function () {

    $(".banner-reskin img").bind("load", function () {
        bannerResize();
    });

    $("body").addClass("js");

    // SEARCH FIELD INPUT LABELS SHOW/HIDE
    $("label.block input, label.block textarea").each(function () {
        var $this = $(this);
        if ($this.val() != "") $this.prev("span").addClass("hide");
    });
    $("label input, label textarea").bind("focus keydown", function () {
        // console.log("focus given");
        $span = $(this).prev();
        $input = $(this);
        $span.addClass("hide");

        $input.bind("blur", function () {
            var $this = $(this);
            if ($this.val() == "") {
                $this.prev().removeClass("hide");
            }
        });
    });
    $("label:has(input), label:has(textarea)").bind("click keydown", function () {

        $span = $(this).find("span");
        $input.focus();
        $span.addClass("hide");

        $input.bind("blur", function () {
            var $this = $(this);
            if ($this.val() == "") {
                $this.prev().removeClass("hide");
            }
        });
    });

    // banners
    $(window).load(function () {
        bannerResize();
        loaded = true;
    }).resize(function () {
        bannerResize();
    }).scroll(function () {
        if (loaded && !scrolled) {
            scrolled = true;
            bannerResize();
        }
    });

    // navigation
    $("#nav > li").hover(function () {
        var $this = $(this),
                className = "over",
                capClassName,
                cap = right = false;

        if ($this.hasClass("nav-8")) {
            capClassName = "nav-8-over";
            cap = right = true;
        } else if ($this.hasClass("nav-1")) {
            capClassName = "nav-1-over";
            cap = true;
        }

        if (cap) {
            $this.addClass(capClassName);
        } else {
            $this.addClass(className);
        }
    }, function () {
        var $this = $(this),
                className = "over",
                capClassName,
                cap = right = false;

        if ($this.hasClass("nav-8")) {
            capClassName = "nav-8-over";
            cap = right = true;
        } else if ($this.hasClass("nav-1")) {
            capClassName = "nav-1-over";
            cap = true;
        }

        if (cap) {
            $this.removeClass(capClassName);
        } else {
            $this.removeClass(className);
        }
    });

    $("#nav li:has(ul) li").hover(function () {
        var $this = $(this);

        $this.addClass("over");
        if ($this.hasClass("last")) {
            $this.parent().addClass("over");
        }
    }, function () {
        var $this = $(this);
        $this.removeClass("over");
        if ($this.hasClass("last")) {
            $this.parent().removeClass("over");
        }
    });

    // button rollovers
    $(".rollover").rollover();

    // class applications
    $("#copy :last").addClass("last");
    $("#carousel li:has('a.play'):eq(0)").addClass("active");

    // print page
    $(".print").click(function (e) {
        e.preventDefault();
        window.print();
    });

    // case study rollovers to activate accompanying image/title
    $("li.external-cs").hover(function () {
        $(this).next().find("a").addClass("over");
    }, function () {
        $(this).next().find("a").removeClass("over");
    });

    $("li.casestudy").hover(function () {
        $(this).prev().addClass("over");
    }, function () {
        $(this).prev().removeClass("over");
    });

    $(".links li:has(a[disabled])").each(function () {
        $(this).css("backgroundPosition", "0 0");
    });

    // gallery classes
    $(".gallery li:nth-child(3)").addClass("last");


    // carousel setup
    $(".big-item-block li").hover(function () {
        var $this = $(this);
        if (!$this.hasClass("active")) {
            if ($.support.opacity) {
                $(this).find(".frame-hover, .play").fadeIn(500);
            } else {
                $(this).find(".frame-hover, .play").show();
            }
        }
    }, function () {
        var $this = $(this);
        if (!$this.hasClass("active")) {
            if ($.support.opacity) {
                $this.find(".frame-hover, .play").fadeOut(500);
            } else {
                $this.find(".frame-hover, .play").hide();
            }
        }
    });

    // carousel setup
    $("#carousel li").hover(function () {
        var $this = $(this);
        if (!$this.hasClass("active")) {
            if ($.support.opacity) {
                $(this).find(".frame-hover, .play").fadeIn(500);
            } else {
                $(this).find(".frame-hover, .play").show();
            }
        }
    }, function () {
        var $this = $(this);
        if (!$this.hasClass("active")) {
            if ($.support.opacity) {
                $this.find(".frame-hover, .play").fadeOut(500);
            } else {
                $this.find(".frame-hover, .play").hide();
            }
        }
    });

    $("#carousel .play").click(function (e) {
        e.preventDefault();
        var index = $("#carousel .play").index(this),
                $this = $(this);

        if ($this.parent().hasClass("active")) {
            return false;
        }

        clicked = true;

        $("#carousel li.active").removeClass("active");
        $f(0).play(playlist[index]);
        $this.parent().addClass("active");
        $this.parent().find(".frame-hover, .play").css("display", "");
        $f(0).unmute();
    });

    $("div#carousel ul").jcarousel({
        buttonNextHTML: '<a title="Next" class="btn next" href="javascript:void(0)">Next</a>',
        buttonPrevHTML: '<a title="Previous" class="btn prev" href="javascript:void(0)">Previous</a>',
        wrap: "both",
        scroll: 1,
        easing: "swing"
    });

    // flowplayer setup
    // key = array of keys for use on multiple domains i.e. stage/live (2nd key [#@5e22...] is Orchard staging key - 3rd key [#@d12...] is for localhost)
    var key = ["#@381cc0bf707bcea3f52", "#@5e2257fc4cbfebffce6", "#@d120d7af4975dee766a"],
            carousel = true,
            playlist = [];

    if ($("#carousel").length < 1) {
        carousel = false;
        if ($("a[id$=linkvideo], a[id$=linkVideo]").length > 0 && $("a[id$=linkvideo], a[id$=linkVideo]").attr("href") != "") {
            playlist.push($("a[id$=linkvideo], a[id$=linkVideo]").attr("href")); // single video link
        }
    }

    if (carousel) {
        $("#carousel a.play").each(function () {
            playlist.push($(this).attr("href"));
        });
    }

    if ($("#flash").length > 0 && playlist.length > 0) {
        $f("flash", {
            src: "/Common/Flash/flowplayer.commercial-3.2.5.swf",
            version: [9, 115],
            onFail: function () {
                $("#info").html('<div id="flash"><div class="wrap"><h2>Flash&reg; Player 9.1 required</h2><p>In order to view this content you will need to install <a href="http://get.adobe.com/flashplayer/" rel="external">Adobe&reg; Flash&reg; Player</a> 9.1 or higher.</p></div></div>');
            },
            wmode: "transparent"
        },
        {
            key: key,
            clip: {
                autoPlay: (function () {
                    return navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null ? false : true;
                })(),
                autoBuffering: true,
                onStart: function (clip) {
                    if (!$("form").hasClass("internal") && !clicked) {
                        $f(0).mute();
                    } else {
                        $f(0).unmute();
                    }
                    var $current = $("#carousel li:has(a.play[href='" + clip.completeUrl + "'])");
                    if (!$current.hasClass("active")) {
                        $("#carousel li.active").removeClass("active");
                        $current.addClass("active");
                        $(".jcarousel-next").trigger("click");
                    }
                }
            },
            screen: {
                height: "100pct",
                width: "100pct",
                backgroundColor: "transparent"
            },
            contextMenu: [
		        'MCN Video player 1.0.0'
	        ],
            playlist: playlist,
            plugins: {
                controls: {
                    autoHide: {
                        enabled: true,
                        fullscreenOnly: false,
                        hideDelay: 500,
                        hideDuration: 513,
                        hideStyle: "fade",
                        mouseOutDelay: 500
                    },
                    backgroundColor: "rgba(0, 122, 192, 0.8)",
                    backgroundGradient: [0.5,
                      0.20000000000000001,
                      0
                    ],
                    border: "0px",
                    borderRadius: 17,
                    bottom: "8pct",
                    bufferColor: "#a3a3a3",
                    bufferGradient: "none",
                    builtIn: false,
                    buttonColor: "#ffffff",
                    buttonOverColor: "#ffffff",
                    display: "block",
                    durationColor: "#b8d9ff",
                    fastBackward: false,
                    fastForward: true,
                    fullscreen: true,
                    height: 33,
                    left: "50pct",
                    margins: [2,
                      6,
                      2,
                      12
                    ],
                    mute: true,
                    name: "controls",
                    opacity: 1,
                    play: true,
                    playlist: false,
                    progressColor: "#4599ff",
                    progressGradient: "none",
                    scrubber: true,
                    scrubberBarHeightRatio: 0.29999999999999999,
                    scrubberHeightRatio: 0.40000000000000002,
                    sliderBorder: "1px solid rgba(128, 128, 128, 0.7)",
                    sliderColor: "#000000",
                    sliderGradient: "none",
                    slowBackward: false,
                    slowForward: true,
                    spacing: {
                        all: 2,
                        time: 6,
                        volume: 8
                    },
                    stop: false,
                    time: true,
                    timeBgColor: "rgb(0, 0, 0, 0)",
                    timeBgHeightRatio: 0.80000000000000004,
                    timeBorder: "0px solid rgba(0, 0, 0, 0.3)",
                    timeBorderRadius: 20,
                    timeColor: "#ffffff",
                    timeFontSize: 12,
                    timeSeparator: " ",
                    tooltipColor: "rgba(0, 0, 0, 0)",
                    tooltipTextColor: "#ffffff",
                    tooltips: {
                        buttons: false,
                        marginBottom: 5,
                        scrubber: true,
                        volume: true
                    },
                    volume: true,
                    volumeBarHeightRatio: 0.29999999999999999,
                    volumeBorder: "1px solid rgba(128, 128, 128, 0.7)",
                    volumeColor: "#4599ff",
                    volumeSliderColor: "#ffffff",
                    volumeSliderGradient: "none",
                    volumeSliderHeightRatio: 0.40000000000000002,
                    width: "90pct",
                    zIndex: 1
                }
            },
            canvas: {
                backgroundColor: 'transparent',
                borderGradient: "none",
                border: "8px solid #ffffff",
                borderRadius: 20
            }
        });

        var simulate = false;
        // HTML5 video support
        /*if (Modernizr.video && Modernizr.video.h264 != "") {
        simulate = true;
        }*/

        if (playlist.length > 0) {
            $f(0)
            .setVolume(50)
            .ipad({ simulateiDevice: simulate, controls: true })
            .load(); // removes alternate content and loads first video into player

            if (!$("form").hasClass("internal")) {
                $f(0).mute();
            } else {
                $f(0).unmute();
            }
        }
    }

    // channel specific 
    if ($("form").hasClass("channels")) {
        $("#channels li:nth-child(9)").addClass("last");

        $('.filter select').each(function () {
            $(this).change(function () {
                var i = $('.filter select').index($(this)[0]),
                    j = $(this)[0].selectedIndex;

                $('#channels dt a').removeClass();
                $('.filter select:not(:eq(' + i + '))').resetSelection();

                console.log($('#channels dd:contains(' + $('option:selected', this).text() + ')'));

                if (j == 0) {
                    $('.filter select').resetSelection();
                    $('#channels a').addClass('selected');
                    //$('h3.applied').fadeOut(500);
                } else {
                    $('#channels dd:contains(' + $('option:selected', this).text() + ')').each(function () {
                        $('a', $(this).prev()).addClass('selected');
                    });
                    //$('h3.applied').text($('option:selected', this).text() + ' filter selected').fadeIn(500);
                }
            });
        });
    }

    // management specific
    if ($("form").hasClass("management")) {
        $("#management li").clickpanel();
    }

    // careers specific
    if ($("form").hasClass("slides")) {
        $("#internal ul.links li a:not([disabled])").click(function (e) {
            e.preventDefault();
            var $this = $(this),
                panel = $this.attr("href");

            if ($this.parent().hasClass("active")) return false;

            $(".slide:visible").fadeOut(500, function () {
                $(panel).fadeIn(500);
                $("ul.links li.active").removeClass("active");
                $this.parent().addClass("active");
                bannerResize();
            });
        });
    }

    // contact details specific
    if ($("form").hasClass("contact")) {

        $("#internal .links li").click(function (e) {
            e.preventDefault();
            var $this = $(this);

            $("#internal .links li.active").removeClass("active");
            $(".wrap-map:visible").hide();
            $this.addClass("active").parent().next().show();
        });

        $(".wrap-map:gt(0)").hide();

        function initialize() {

            function createMarker(point, number, map) {

                var tinyIcon = new GIcon();
                tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
                tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
                tinyIcon.iconSize = new GSize(12, 20);
                tinyIcon.shadowSize = new GSize(22, 20);
                tinyIcon.iconAnchor = new GPoint(6, 20);
                markerOptions = { icon: tinyIcon };

                var marker = new GMarker(point, markerOptions);
                return marker;
            }

            function createMap(i) {
                var $e = $(".wrap h2 a:eq(" + i + ")"),
                    elem = $("#map-" + $e.text().split(" ")[0].toLowerCase()),
                    map = {},
                    center;

                map.canvas = new google.maps.Map2(elem[0]);
                map.canvas.addControl(new GSmallMapControl());

                var marker = $e.attr('href'),
                    xspot = marker.slice(marker.indexOf('&ll='), marker.indexOf('&spn=')).slice(4).split(','),
                    point = new GLatLng(xspot[0], xspot[1]);

                switch (i) {
                    case 0:
                        center = point;
                        break;
                    case 1:
                        center = new GLatLng(-37.811804, 144.937063);
                        break;
                    case 2:
                        center = new GLatLng(-27.454425, 153.035720)
                        break;
                    case 3:
                        center = new GLatLng(-31.941723, 115.831174)
                        break;
                }

                map.canvas.addOverlay(createMarker(point, i, map));
                map.canvas.setCenter(center, 16);
            }

            $('.wrap h2 a').each(function () {
                var index = $(".wrap h2 a").index(this);

                createMap(index);
            });
        }

        $(window).load(function () {
            initialize();
            $("#internal .links:eq(0) li").addClass("active");
        });
    }
});
