/// <reference path="jquery-1.7-vsdoc.js" />

/* main.js */

var mnec = {

    cornerRadius: 3,

    init: function() {
        if (!Modernizr.borderradius) {
            this.setCorners();
        }
        this.setExternalLinks();
        this.slidesInit();

        if ($("#home-flash").length > 0) {
            $("#home-flash").html("");
            $("#home-flash").flash(
                {
                    src: '/CMSTemplates/MNEnergyChallenge/swf/EveryActionCounts.swf',
                    width: 960,
                    height: 288,
                    wmode: "opaque"
                },
                { version: '8' }
            );
        }

        this.setLabeledTextBoxes();

        if ($("#ctl00_txtSearchTerms").length > 0) {
            var searchBoxDefault = "Search";

            $("#ctl00_txtSearchTerms").focus(function() {
                if ($(this).attr("value") == searchBoxDefault) $(this).attr("value", "");
            });
            $("#ctl00_txtSearchTerms").blur(function() {
                if ($(this).attr("value") == "") $(this).attr("value", searchBoxDefault);
            });
        }

        if ($("#blog-feed").length > 0) {
            this.getBlog();
        }

        if ($("#tolby-blog-feed").length > 0) {
            this.getTolbyBlog();
        }

        // Set up widget overlay and link.
        if ($("#get-widget-overlay")) {

            $("#get-widget-overlay").remove("a");
            $("#get-widget-overlay").html("Get the widget");
            $("#get-widget-overlay").click(function() {
                mnec.openModal("Test");
            });
        }

        $(".modal a").click(function () {
            $.fancybox({
                'padding': 0,
                'centerOnScroll': true,
                'overlayColor': '#46473f',
                'overlayOpacity': 0.8,
                'showCloseButton': false,
                'titleShow' : true,
                'titlePosition': 'outside',
                'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                'type': 'swf',
                'swf': {'wmode':'transparent','allowfullscreen':'true'},
                'width': 720,
                'height': 430,
                'title': '<center><a onclick="$.fancybox.close();" style="cursor: pointer;"><img src="/CMSTemplates/MNEnergyChallenge/images/master/modal-close.png" alt="" /></a></center>'
            });
            
            return false;
        });


    if ($("#individual-widget")) {

        //alert("Test");
        $("#individual-widget").click(function() {
            mnec.openModal("MyChallenge=true");
            return false;
        });
    }

    if ($("#team-widget")) {


        var gid = $("#team-widget").attr("href");

        $("#team-widget").attr("href", "javascript:void(0);");
        $("#team-widget").click(function() {
            mnec.openModal("GroupID=" + gid.substring(64));
        });

    }

    if ($(".vehicle-count").length > 0) {
        $(".vehicle-count").change(function() {
            mnec.setVehicleCount();
        });
        mnec.setVehicleCount();
    }



    if ($(".popup").length > 0) {

        // Apply this code to each link with class="popup"
        $("a.popup").each(function(i) {

            // Add an onClick behavior to this link
            $(this).click(function(event) {

                // Prevent the browser's default onClick handler
                event.preventDefault();

                // Grab parameters using jQuery's data() method
                var params = $(this).data("popup") || {};

                // Use the target attribute as the window name
                if ($(this).attr("target")) {
                    params.windowName = $(this).attr("target");
                }

                // Pop up the window
                var windowObject = mnec.popupOpen(this.href, params);

                // Save the window object for other code to use
                $(this).data("windowObject", windowObject);
            });
        });
    }


},

slidesInit: function() {
    if ($(".slide-scroller").size() > 0) {
        var slideCount = $(".slides .slide").size();
        var activeSlideIndex = 0;
        var loop;

        $(".slides .slide").each(function(index, slide) {
            if (index == 0) {
                $(".slide-scroller .dots").append('<div class="dot active"></div>');
            } else {
                $(".slide-scroller .dots").append('<div class="dot"></div>');
            }
        });

        $(".slide-scroller .dots").css("marginLeft", (($(".slide-scroller .dots").width() / 2) * -1));

        $(".slide-scroller a.next, .slide-scroller a.prev").click(function() {
            clearTimeout(loop);
            var control = $(this);
            if (control.hasClass("next")) {
                // GET NEXT SLIDE
                if (activeSlideIndex != (slideCount - 1)) {
                    activeSlideIndex++;
                    mnec.animateToSlide(activeSlideIndex);
                } else {
                    activeSlideIndex = 0;
                    mnec.animateToSlide(activeSlideIndex);
                }
            } else {
                // GET PREV SLIDE
                if (activeSlideIndex != 0) {
                    activeSlideIndex--;
                    mnec.animateToSlide(activeSlideIndex);
                } else {
                    activeSlideIndex = (slideCount - 1);
                    mnec.animateToSlide(activeSlideIndex);
                }
            }
        });
        
        function infiniteLoop() {
            loop = setTimeout(function () {
                if (activeSlideIndex != (slideCount - 1)) {
                    activeSlideIndex++;
                    mnec.animateToSlide(activeSlideIndex);
                } else {
                    activeSlideIndex = 0;
                    mnec.animateToSlide(activeSlideIndex);
                }
                infiniteLoop();
            },7000);
        }
        
        infiniteLoop();

        $(".dots .dot").click(function() {
            clearTimeout(loop);
            var dot = $(this);
            activeSlideIndex = dot.index(".dots .dot");
            mnec.animateToSlide(activeSlideIndex);
        });
    }
},

animateToSlide: function(index) {
    var currentDotIndex = $(".dots .dot.active").index(".dots .dot");
    var slideDifference = (index - currentDotIndex);
    var pixelChange = Math.abs(slideDifference) * 960;

    if (slideDifference > 0) {
        // Next n
        $(".slides .slide").stop(true, true).animate({ left: "-=" + pixelChange + "" }, "slow", "easeInOutQuart");
    } else {
        // Prev n
        $(".slides .slide").stop(true, true).animate({ left: "+=" + pixelChange + "" }, "slow", "easeInOutQuart");
    }

    $(".dots .dot.active").removeClass("active");
    $(".dots .dot").eq(index).addClass("active");
},

/**
* Loads blog display.
*/
getBlog: function() {
    $("#blog-feed").load("/MNEnergyChallenge/FeedService/FeedService.aspx");
},

getTolbyBlog: function() {
    $("#tolby-blog-feed").load("/MNEnergyChallenge/FeedService/TolbyFeedService.aspx");
},

/* create overlay dialog */
openModal: function(params) {

    // Add overlay markup to DOM.
    $("body").append("<div class=\"overlay-wrapper\"><div class=\"dimmer\"></div><div class=\"overlay-container\">" + "</div></div>");

    // "dimmer" background click event handler.
    $(".dimmer").click(function() {
        $(".overlay-container").fadeOut(200, function() {
            $(".dimmer").fadeOut(200, function() {
                $(".overlay-wrapper").remove();
            });
        });
    });

    // Dim the background layer.
    $(".dimmer").css("opacity", 0.1);
    $(".dimmer").css("height", $(document).height());
    $(".dimmer").animate({ opacity: 0.7 }, 200, "linear", function() { });

    // Set up the overlay container.
    $(".overlay-container").css("left", ($(window).width() - 800) / 2);
    $(".overlay-container").css("top", ($(document).scrollTop() + 100) + "px");
    if (!Modernizr.borderradius) {
        $(".overlay-container").corners(mnec.cornerRadius + "px transparent");
    }

    // Load the widget selector page into the overlay.
    $(".overlay-container").load("/MNEnergyChallenge/Widgets/ChallengeWidgetSelector.aspx?" + params, {}, function() {

        // "Close" click event handler.
        $(".close-overlay").click(function() {
            $(".overlay-container").fadeOut(200, function() {
                $(".dimmer").fadeOut(200, function() {
                    $(".overlay-wrapper").remove();
                });
            });
        });

        // "Overview" tab "click" event handler.
        $(".nav-size-0").click(function() {
            $(".nav-size-0").css("font-weight", "bold");
            $(".nav-size-0").css("color", "#d29900");
            $(".nav-size-1").css("font-weight", "normal");
            $(".nav-size-1").css("color", "#666666");
            $(".nav-size-2").css("font-weight", "normal");
            $(".nav-size-2").css("color", "#666666");

            $(".size-0").css("display", "block");
            $(".size-1").css("display", "none");
            $(".size-2").css("display", "none");
        });

        // "275px x 370px" tab "click" event handler.
        $(".nav-size-1").click(function() {
            $(".nav-size-0").css("font-weight", "normal");
            $(".nav-size-0").css("color", "#666666");
            $(".nav-size-1").css("font-weight", "bold");
            $(".nav-size-1").css("color", "#d29900");
            $(".nav-size-2").css("font-weight", "normal");
            $(".nav-size-2").css("color", "#666666");

            $(".size-0").css("display", "none");
            $(".size-1").css("display", "block");
            $(".size-2").css("display", "none");
        });

        // "180px x 360px" tab "click" event handler.
        $(".nav-size-2").click(function() {
            $(".nav-size-0").css("font-weight", "normal");
            $(".nav-size-0").css("color", "#666666");
            $(".nav-size-1").css("font-weight", "normal");
            $(".nav-size-1").css("color", "#666666");
            $(".nav-size-2").css("font-weight", "bold");
            $(".nav-size-2").css("color", "#d29900");


            $(".size-0").css("display", "none");
            $(".size-1").css("display", "none");
            $(".size-2").css("display", "block");
        });

        // HACK: (JM) Did not find where the default visbility was being set.
        // So, setting the default visibility here. TODO: Remove unnecessary
        // code that is setting the default visibility.
        $(".size-0").css("display", "block");
        $(".size-1").css("display", "none");
        $(".size-2").css("display", "none");

        // bold 1st tab
        $(".nav-size-0").css("font-weight", "bold");
        $(".nav-size-0").css("color", "#d29900");
        $(".nav-size-1").css("font-weight", "normal");
        $(".nav-size-1").css("color", "#666666");
        $(".nav-size-2").css("font-weight", "normal");
        $(".nav-size-2").css("color", "#666666");




        if (!Modernizr.borderradius) {
            $(".size-0").corners(this.cornerRadius + "px transparent");
            $(".size-1").corners(this.cornerRadius + "px transparent");
            $(".size-2").corners(this.cornerRadius + "px transparent");
        }

        $(".overlay-container").fadeIn();
    });
},

/**
* Open popup window using a URL. An optional params object can be passed.
* @param {String} href
* @param {Object} params
* @return {WindowObjectReference}
*/
popupOpen: function(href, params) {
    // Defaults (don't leave it to the browser)
    var defaultParams = {
        "width": "800",   // Window width
        "height": "600",   // Window height
        "top": "0",     // Y offset (in pixels) from top of screen
        "left": "0",     // X offset (in pixels) from left side of screen
        "directories": "no",    // Show directories/Links bar?
        "location": "no",    // Show location/address bar?
        "resizeable": "yes",   // Make the window resizable?
        "menubar": "no",    // Show the menu bar?
        "toolbar": "no",    // Show the tool (Back button etc.) bar?
        "scrollbars": "yes",   // Show scrollbars?
        "status": "no"     // Show the status bar?
    };

    var windowName = params["windowName"] || "new_window";

    var i, useParams = "";

    // Override defaults with custom values while we construct the params string
    for (i in defaultParams) {
        useParams += (useParams === "") ? "" : ",";
        useParams += i + "=";
        useParams += params[i] || defaultParams[i];
    }

    return window.open(href, windowName, useParams);

},

setCorners: function() {
    $("#page-footer #navigation-copyright").corners(this.cornerRadius + "px transparent top-left bottom-left");
    $("#page-footer #social-networking").corners(this.cornerRadius + "px transparent top-right bottom-right");
    $("#content-body .event-message").corners(mnec.cornerRadius + "px transparent");
    $("#page-footer .tweets .tweet_list li .tweet_text").corners(this.cornerRadius + "px transparent");

    // TODO: Refactor for better code organization. Separate out page specific stuff.
    if ($("#participant-dashboard-page").length > 0) {
        $("#participant-dashboard-page #content-body").corners(mnec.cornerRadius + "px transparent top-right bottom-left bottom-right");
    } else {
        $("#content-body").corners(mnec.cornerRadius + "px transparent");
    }
},

setLabeledTextBoxes: function() {
    $('#page-footer input[type="text"]').each(function() {

        this.value = $(this).attr("title");
        $(this).addClass("text-label");

        $(this).focus(function() {
            if (this.value == $(this).attr("title")) {
                this.value = '';
                $(this).removeClass("text-label");
            }
        });

        $(this).blur(function() {
            if (this.value == '') {
                this.value = $(this).attr("title");
                $(this).addClass("text-label");
            }
        });
    });
},

setExternalLinks: function() {
    $("a.external").each(function() {
        var url = $(this).attr("href");

        $(this).click(function() {
            // Open the link in a new browser window.
            window.open(url, "w");
            // Cancel the click through in the original browser window.
            return false;
        });
    });
},

// DEV: Might need to sandbox this to a page, so that additional page-sepcific ui script can run.
addActionToUsersActions: function(actionId, multiplier) {
    //alert("actionId:" + actionId + ",multiplier:" + multiplier);
    $.get("/MNEnergyChallenge/actions/AddActionToUsersActions.aspx",
            { actionId: actionId, multiplier: multiplier, timestamp: Date() },
            function(data) {
                //alert("Added Action: " + data);
                $("#action_" + actionId + " .isuseraction").html("x");
            });

    // Prevent the PostBack event.
    return false;
},

setVehicleCount: function() {
    var c = $(".vehicle-count").val();
    for (i = 1; i <= 4; i++) {

        if (i <= c) {
            $("#vehicle-" + i).slideDown(200);
        } else {
            $("#vehicle-" + i).slideUp();
        }
    }
}
}

$(document).ready(function () {
    mnec.init();
});

// EOF

