/// <reference path="/msbuild/jquery-1.6.1-vsdoc.js" />
/*
*	MECU
*	Author Samuel Chalmers
*   Copyright (c) 2011, reactive.com
*   All rights reserved.
*/
var reactive = {

    init: function () {

        reactive.cufon.init();

        $(document).ready(function () {

            /* ---------------------- CUFON ---------------------------*/

            reactive.navigation.init();
            reactive.banner.init();



            if ($.browser.msie) {
                if ($.browser.version > 8) {
                    reactive.greyscaleInit.init();
                }
            } else {
                reactive.greyscaleInit.init();
            }
            if ($('#filter').length) {
                reactive.filter.init();
                reactive.cycle.init();
                reactive.pinboardoverlay.init();
            }

            if ($('#toolmenu').length) reactive.tooldrops.init();
            if ($('#newsticker').length) reactive.newsticker.init();
            if ($('#login').length) reactive.search.init();
            if ($('.takepoll').length) reactive.poll.init();
            reactive.accordian.init();
            reactive.sustainabilityReport2011.init();
            //remember to add sustainabilityReport2011 down the bottom

            //ADDED TO ALLOW CLICK TO CLOSE LIGHTBOX
            $("#closeIt,#closeItText").bind("click", null, function () {
                parent.$.fancybox.close();
                return false;
            });
        });


    },

    /* ---------------------- Z-INDEXING FOR MAIN NAVIGATION ---------------------------*/

    navigation: {

        init: function () {

            var preZ = 999999;

            //FIX TOOLS Z-INDEX
            $('#toolmenu ul').each(function (index) {

                var thisZ = preZ--;

                $(this).css('z-index', thisZ);

            });

        }

    },


    /* ---------------------- POLL ---------------------------*/

    poll: {

        init: function () {

            // assuming all checkboxes are unchecked at first
            $("span[class='radio']").addClass("unchecked");

            // set value on page load
            var rbList = $("input[name='pollOption']");
            var checkedRB = rbList.filter(":checked");
            var hiddenPollInput = $("#ctl00_RContentPlaceHolder5_ctl00_ctl00_ctl00_PollSelectedAnswer");
            hiddenPollInput.val(checkedRB.val());

            $(".radio").click(function () {

                //reset all to unchecked
                $(".radio").children("input").attr({ checked: "" });
                $(".radio").removeClass("checked");
                $(".radio").addClass("unchecked");
                // check the one pressed
                $(this).children("input").attr({ checked: "checked" });
                $(this).removeClass("unchecked");
                $(this).addClass("checked");

                var rbList = $("input[name='pollOption']");
                var checkedRB = rbList.filter(":checked");
                var hiddenPollInput = $("#ctl00_RContentPlaceHolder5_ctl00_ctl00_ctl00_PollSelectedAnswer");
                hiddenPollInput.val(checkedRB.val());
            });


            $('.votenow').bind('click', null, function () {

                if (!$("input[@name='pollOption']:checked").val()) {
                    $('#errorpoll').show();
                    return false;
                }
                else {
                    $('#errorpoll').hide();
                    var pollQuestion = $("#pollQuestion").html();
                    var selectedVoteInput = $("input:radio[name='pollOption']:checked");
                    var selectedVoteLabel = $("label[for=" + $(selectedVoteInput).attr('id') + "]").text();
                    pageTracker._trackEvent('WebPolls', pollQuestion, selectedVoteLabel);
                }
            });
        }
    },


    /* ---------------------- MAIN BANNER ---------------------------*/

    banner: {


        init: function () {

            var $active = $('#image_reel li.active');
            var index = 0;
            var currentSlide = 1;
            var interval = setInterval(slideSwitch, 5000);

            $('#image_reel li').delay(500).fadeIn('fast');
         

            //create the rotating slideshow

            function slideSwitch() {

                $active = $('#image_reel li.active');

                if ($active.length == 0) $active = $('#image_reel li:last');

                var $next = $active.next().length ? $active.next() : $('#image_reel li:first');

                $active.addClass('last-active');

                $next.css({
                    opacity: 0.0
                }).addClass('active').animate({
                    opacity: 1.0
                }, 1000, function () {
                    $active.removeClass('active last-active');
                    //add 1 to current slide
                    currentSlide++;
                });


            }

            /* ---------------------- BANNER INTERVALS---------------------------*/

            //pause slideshow on rollover li
            $('#image_reel li').hover(function () {
                interval = clearInterval(interval);
            }, function () {
                interval = setInterval(slideSwitch, 5000);
            });


            function clearRotationInterval() {

                interval = clearInterval(interval);
                interval = setInterval(slideSwitch, 5000);

            }

            /* ---------------------- PAGINATION FOR MAIN BANNER ---------------------------*/

            $("#paging_main li a").click(function () {
                index = $("#paging_main li a").index(this);

                
                if (index !== currentSlide-1) {

                    currentSlide = index;

                    //required for thumbs
                    $('#paging_main li').removeClass('current');
                    $('#paging_main li:eq(' + currentSlide + ')').addClass('current');

                    //add 1 to the current slider
                    currentSlide++;

                    //Reset Timer
                    clearRotationInterval();
                    $('#image_reel li.active').addClass('last-active');
                    $active = $('#image_reel li.active');
                    $('#image_reel li:eq(' + index + ')').css({
                        opacity: 0.0
                    }).addClass('active').animate({
                        opacity: 1.0
                    }, 1000, function () {
                        $active.removeClass('active last-active');
                    });

                }

                return false; //Prevent browser jump to link anchor
            });

        }



    },

    /* ---------------------- SEARCH ---------------------------*/

    search: {


        init: function () {

            $('#search').click(function () {
                $('#login').animate({
                    right: '118'
                }, 'slow', function () {
                    $(".search span").animate({
                        left: '20'
                    }, 'fast', function () {
                        $('#searchinput').fadeIn('slow');
                    });
                    $('.search p a').fadeOut();
                });
            });



        }



    },

    /* ---------------------- NEWS TICKER ---------------------------*/

    newsticker: {

        init: function () {

            $("#newsticker").jCarouselLite({
                vertical: false,
                hoverPause: true,
                btnPrev: ".previous",
                btnNext: ".next",
                visible: 2,
                auto: 3000,
                speed: 500
            });


        }


    },

    /* ---------------------- TOOLDROPS ---------------------------*/

    tooldrops: {

        init: function () {

            // This adds class selected to the menu so that it behaves like a drop down
            $('.tooldrops dt').click(function () {
                $(this).parent().parent().addClass('selected');
                //$(this).parents('#toolmenu').find('#join').fadeOut('slow');
                return false;
            });

            $('.tooldrops').bind('mouseleave', function () {
                $(this).find("li").removeClass("selected");
                //$('#join').fadeIn('slow');
            });


        }



    },


    cycle: {


        init: function () {

            $('.hide').fadeIn('fast');

            $('#pincontainer').bind('mouseover', null, function () {
                $('#pincontainer').cycle('pause');
            });

            $('#pincontainer').bind('mouseout', null, function () {
                $('#pincontainer').cycle('resume');
            })


            $('#pincontainer').cycle({
                fx: 'scrollHorz',
                timeout: 10000,
                delay: -2000,
                prev: '#prev',
                next: '#next',
                pager: '#nav',
                pagerAnchorBuilder: pagerFactory
            });

            function pagerFactory(idx, slide) {
                var s = idx > 2 ? ' style="display:none"' : '';
                return '<li' + s + '><a href="#">' + (idx + 1) + '</a></li>';
            };



        }



    },

    /* ---------------------- POPOVERLAY FOR PINBOARD ---------------------------*/


    pinboardoverlay: {

        init: function () {


            $(".panel a.popVid, .panel a.popImg").fancybox({
                'width': 590,
                'height': '100%',
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none'
            });

            $(".panel a.popVid, .panel a.popImg").click(function () {
                //var contentId = $(this).attr("href");
                var contentId = $(this).html();
                $("#videocontainer").hide();
                $.ajax({
                    type: "POST",
                    url: "/Services/PinboardService.asmx/GetPinboard",
                    data: "{contentId: '" + contentId + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var pinboard = $.parseJSON(data.d);
                        var title = pinboard[0].Title;
                        var urlLink = pinboard[0].UrlLink;
                        var longDescription = pinboard[0].LongDescription;
                        var youtubeId = pinboard[0].YoutubeId;
                        var pinboardCategory = pinboard[0].Category.replace(/\s+/g, '');

                        $("#detailview").attr("class", pinboardCategory);
                        $("#pop").html(title);
                        $("#popparagraph").html(longDescription);
                        $("#findoutmore").attr("href", urlLink);
                        if (youtubeId !== null) {
                            var videoUrl = "http://www.youtube.com/embed/" + youtubeId + "?wmode=Opaque&rel=0";
                            $("#player").attr("src", videoUrl);
                            $("#videocontainer").show();
                        }
                        Cufon.replace('.pop-wrapper-590 h1', {
                            fontFamily: 'AvenirRoman',
                            hover: true
                        });
                    }
                });


                return false;
            });

            $(".panel a.popText").fancybox({
                'width': 905,
                'height': '100%',
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none'
            });

            $(".panel a.popText").click(function () {
                var contentId = $(this).html();
                $("#videocontainertext").hide();
                $.ajax({
                    type: "POST",
                    url: "/Services/PinboardService.asmx/GetPinboard",
                    data: "{contentId: '" + contentId + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var pinboard = $.parseJSON(data.d);
                        var title = pinboard[0].Title;
                        var urlLink = pinboard[0].UrlLink;
                        var longDescription = pinboard[0].LongDescription;
                        var youtubeId = pinboard[0].YoutubeId;
                        var pinboardCategory = pinboard[0].Category.replace(/\s+/g, '');

                        $("#detailtextview").attr("class", pinboardCategory);

                        $("#poptext").html(title);
                        $("#popparagraphtext").html(longDescription);
                        $("#findoutmoretext").attr("href", urlLink);
                        if (youtubeId !== null) {
                            var videoUrl = "http://www.youtube.com/embed/" + youtubeId + "?wmode=Opaque&rel=0";
                            $("#playertext").attr("src", videoUrl);
                            $("#videocontainertext").show();
                        }
                        Cufon.replace('.pop-wrapper-920 h1', {
                            fontFamily: 'AvenirRoman',
                            hover: true
                        });
                    }
                });


                return false;
            });


        }

    },


    /* ---------------------- FILTER ---------------------------*/


    filter: {

        init: function () {

            $('#prev').hide();

            $('#next').bind('click', null, function () {
                $('#prev').show();
            });

            //create an Array to store the Filter ids
            var filterIDs = [];
            var tempBGColors = ['#003258', '#525e03', '#7f400d', '#933210'];
            var tempBorderBottomColors = ['#005ca4', '#a5bd07', '#FF811A', '#e34c16'];
            var tempAllItems = ['.customer-owned', '.benefits', '.responsibility', '.community'];
            var filtersToMatchAgainstArr = ['.customer-owned', '.community', '.benefits', '.responsibility'];
            var doesexist = false;

            //create the listeners for the filters
            //on click make add active to their states so that they show that they have been choosen
            $('#customer-owned, #benefits, #responsibility, #community').bind('click', null, function () {



                $('#all').removeClass("active");

                var itemID = $(this).attr('id');

                if (jQuery.inArray("." + itemID, filterIDs) == -1) {

                    filterIDs.push('.' + itemID);

                    $(this).addClass("active");

                } else {

                    for (var i = 0; i < filterIDs.length; i++) {

                        if (['.' + itemID] == filterIDs[i]) {

                            $(this).removeClass("active");


                            filterIDs.splice($.inArray(filterIDs[i], filterIDs), 1);


                        }


                    }


                }

                matchResults();

                return false;

            });


            $('#all').bind('click', null, function () {


                if ($(this).hasClass('active')) {

                    fadeOutItems(tempAllItems);


                } else {
                    //reset bg colors and border colors

                    for (var i = 0; i < tempAllItems.length; i++) {

                        $(tempAllItems[i]).animate({
                            backgroundColor: tempBGColors[i]
                        }, 200, false).find('.heading').animate({
                            borderBottomColor: tempBorderBottomColors[i]
                        }, 200, false);
                    }

                    filterIDs = [];

                    $('.panel').fadeTo('0.2', 1).find('.img_grayscale').animate({
                        opacity: 1
                    }, 200, false);

                    $('#customer-owned, #benefits, #responsibility, #community').removeClass("active");

                }

                $(this).toggleClass("active");


                return false;


            });

            function fadeOutItems(objectsToFade) {

                $(objectsToFade.toString()).fadeTo('0.2', .2).find('.img_grayscale').animate({
                    opacity: 0,
                    backgroundColor: "#666"
                }, 200).end().animate({
                    backgroundColor: "#666"
                }, 200).find('.heading').stop().animate({
                    borderBottomColor: "#333"
                }, 200);

            }


            /* ---------------------- MATCH RESULTS ---------------------------*/


            function matchResults() {


                var tempString = filterIDs.toString();

                $(tempString).animate({
                    opacity: 1
                }, { duration: 200 }).find('.img_grayscale').animate({
                    opacity: 1
                }, { duration: 200 });

                for (var i = 0; i < tempAllItems.length; i++) {
                    if (jQuery.inArray(tempAllItems[i], filterIDs) > -1) {
                        $(tempAllItems[i]).animate({
                            backgroundColor: tempBGColors[i]
                        }, 200, false).find('.heading').animate({
                            borderBottomColor: tempBorderBottomColors[i]
                        }, 200, false);
                    }
                }

                find_diff(filtersToMatchAgainstArr, filterIDs);

            }

            /* ---------------------- COMPARE DIFFERENCES ---------------------------*/


            function find_diff(arr1, arr2) {
                diff = [];


                $.each(arr1, function (i, val) {
                    if ($.inArray(val, arr2) < 0)
                        diff.push(val);
                });



                $(diff.toString()).fadeTo('0.2', .2).find('.img_grayscale').animate({
                    opacity: 0,
                    backgroundColor: "#666"
                }, 200).end().animate({
                    backgroundColor: "#666"
                }, 200).find('.heading').animate({
                    borderBottomColor: "#333"
                }, 200);
            }



        }



    },

    /* ---------------------- GREYSCALER ---------------------------*/

    greyscaleInit: {

        init: function () {

            /* ---------------------- CHANGE ITEM COLOR ---------------------------*/

            $('.panel img').each(function () {
                var el = $(this);
                el.css({
                    "position": "absolute"
                }).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({
                    "position": "absolute",
                    "z-index": "998",
                    "opacity": "0"
                }).insertBefore(el).queue(function () {
                    var el = $(this);
                    el.parent().css({
                        "width": this.width,
                        "height": this.height
                    });
                    el.dequeue();
                });

                try {
                    this.src = grayscale(this.src);
                }
                catch (err) {
                    //Handle errors here

                }

            });

            //force the image to show the color 
            $('.panel img').parent().find('img:first').stop().animate({
                opacity: 1
            }, 0);


            // Grayscale w canvas method

            function grayscale(src) {
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                var imgObj = new Image();
                imgObj.src = src;
                canvas.width = imgObj.width;
                canvas.height = imgObj.height;
                ctx.drawImage(imgObj, 0, 0);



                var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
                for (var y = 0; y < imgPixels.height; y++) {
                    for (var x = 0; x < imgPixels.width; x++) {
                        var i = (y * 4) * imgPixels.width + x * 4;
                        var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                        imgPixels.data[i] = avg;
                        imgPixels.data[i + 1] = avg;
                        imgPixels.data[i + 2] = avg;
                    }
                }
                ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
                return canvas.toDataURL();
            }


        }

    },
    /* ---------------------- ACCORDIAN ---------------------------*/

    accordian: {

        init: function () {

            var $accordian = $(".list_accordian");
            if (!$accordian.length) return;

            $accordian.delegate(".list_accordian_title", "click", function (e) {
                e.preventDefault();
                var $title = $(this);
                var $content = $title.next();
                $('.list_accordian li a.list_accordian_title').removeClass("list_accordian_title_exp");
                // Toggle content
                if ($title.hasClass("list_accordian_title_exp")) {
                    $title.removeClass("list_accordian_title_exp");
                    $content.hide();
                } else {

                    $title.addClass("list_accordian_title_exp");
                    // Hide all content
                    $accordian.find(".list_accordian_content").hide()

                    $content.show();
                }
            });

            // Hide all content
            $accordian.find(".list_accordian_content").hide();
        }

    },
    /* ----------------------SUSTAINABILITY REPORT 2011 ---------------------------*/

    sustainabilityReport2011: {

        init: function () {
            // Get archive link
            var $archiveLink = $(".nav_sust2011 .nav_archive > a");
            if (!$archiveLink.length) return;

            // Get archive list
            var $archiveList = $(".nav_archive_list_wrap");

            // Show/hide archive list when hovering on link or list itself
            $archiveLink.add($archiveList).hover(function () {
                $archiveLink.parent().addClass("nav_archive_current");
                $archiveList.addClass("nav_archive_list_wrap_visible");
            }, function () {
                $archiveLink.parent().removeClass("nav_archive_current");
                $archiveList.removeClass("nav_archive_list_wrap_visible");
                Cufon.refresh();
            });

            //Get navigation list
            var $navigationList = $(".nav_sust2011 li");

            $navigationList.hover(function () {
                if ($("a", this).hasClass("current") != true) {
                    $('.menu-bubble-item', this).css('opacity', '0').show().animate({ 'opacity': 1 }, 200);
                }
            }, function () {
                $('.menu-bubble-item', this).css("display", "none").animate({ 'opacity': 0 }, 200); ;
            });

        }

    },

    /* ---------------------- CUFON ---------------------------*/

    cufon: {
        init: function () {
            Cufon.replace('h1.cufon, .info h2, #previousbanner, #nextbanner, .cufon_litterbox', {
                fontFamily: 'litterbox',
                hover: true
            });
            Cufon.replace('h1.pop, .content h2, #content h2, .cta h2, h3, h4, #join, nav a, nav h2, nav h4, .join, .contact, .info p, .nav_sust2011 a, .nav_sust2011_ex a, .heading h4, .heading p, #filter li a, .list_subnav a, .cufon_avenir', {
                fontFamily: 'AvenirRoman',
                hover: true
            });


        }
    }


};

reactive.init();

