/// <reference path="jquery-1.3.2-vsdoc2.js" />

/* main.js */

var mnec = {

    cornerRadius: 3,

    init: function() {
        this.setCorners();
        this.setTextImageReplacements();
        this.setExternalLinks();

        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' }

            );

        }

        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();
        }

        // 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");
            });
        }


        if ($("#individual-widget")) {

            //alert("Test");
            $("#individual-widget").click(function() {
                mnec.openModal("MyChallenge=true");
            });
        }

        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);
                });
            });
        }


    },

    /**
    * Loads blog display.
    */
    getBlog: function() {
        $("#blog-feed").load("/MNEnergyChallenge/FeedService/FeedService.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");
        $(".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");





            $(".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");

        // 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");
        }
    },

    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;
            });
        });
    },

    /**
    * Replaces the contents of the matched element(s) with a dynamically
    * generated image representing the contents of the matched element(s).
    * Ref: http://johndyer.name/post/2008/04/dynamic-text-replacement-with-javascript-csharp-asp-net.aspx
    */
    setTextImageReplacements: function() {

        // "fontWriterUrl" should be a relative path to the location of the 
        // FontWriter web handler file (.ashx).
        var fontWriterUrl = "/CMSTemplates/MNEnergyChallenge/fontwriter/fontwriter.ashx";

        // "fontsPath" should be a relative path (relative to the location of
        // the FontWriter web handler file (.ashx)) to the directory that 
        // contains the font files utilized by the FontWriter web handler.
        var fontsPath = "../../../../MNEnergyChallenge.Fonts/";


        var isIE6 = false;

        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            //alert("this isIE6 or lower");
            isIE6 = true;
        }

        //alert(isIE6);

        // Don't replace content header text with PNG in IE6
        if (isIE6 == false) {
            // Content header, section landing page
            $("#content-header h1.fw").each(function() {
                var text = $(this).html();
                if (text.length > 0) {
                    $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=transparent&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=30px&size=30px&text=' + escape(text) + '" alt="' + text + '"/>');
                }
            });

            // Content header, section (sub) page
            $("#content-header div.fw").each(function() {
                var text = $(this).html();
                if (text.length > 0) {
                    $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=transparent&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=30px&size=30px&text=' + escape(text) + '" alt="' + text + '"/>');
                }
            });
        }


        //Content main, dark gray H1 on white
        $("#content-main h1.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=38px&size=38px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Team titles on team detail page, dark gray H1 on white
        $("#team-detail-page .team-info h1.name").each(function() {
            var text = $(this).html();
            if (text.length > 0 && text.length < 33) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=38px&size=38px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Content main, dark gray H2 on white
        $("#content-main h2.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=24px&size=24px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Content main, dark gray LEGEND on white
        $("#content-main .form legend.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=24px&size=24px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // widget overlay, dark gray H2 on white
        $(".widget-wrapper h2.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolorbcolor=ffffff&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=24px&size=24px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Content main, large orange identifiers on white used for faq lists 
        $("#content-main div.faq-q").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=f0af00&font=' + fontsPath + '/Klavika-Bold.ttf&height=28px&size=28px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Team Standings, large orange numbers on white used for team lists
        $(".team-items div.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=f0af00&font=' + fontsPath + '/Klavika-Bold.ttf&height=34px&size=34px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Team Category, large orange numbers on white used for tabular team lists
        $(".team-items td.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=f0af00&font=' + fontsPath + '/Klavika-Bold.ttf&height=34px&size=34px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Sidebar, dark gray H2 on white
        $("#sidebar h2.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=454537&font=' + fontsPath + '/Klavika-Bold.ttf&height=24px&size=24px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // Content main, WYSWIG generated dark gray H2 on white
        $("#content-main .wysiwyg h2").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=28px&size=28px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // My Challenge tab navigation labels, generated dark gray on white 
        $("#challenge-navigation li a.fw").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=727260&font=' + fontsPath + '/Klavika-Bold.ttf&height=19px&size=19px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // My Challenge tab navigation labels, generated orange on white 
        $("#challenge-navigation a.fw-selected").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=d69d00&font=' + fontsPath + '/Klavika-Bold.ttf&height=19px&size=19px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });

        // "Change Password" on ParticipantProfile page, dark gray LEGEND on white
        $("#content-main #change-password-heading").each(function() {
            var text = $(this).html();
            if (text.length > 0) {
                $(this).html('<img src="' + fontWriterUrl + '?' + 'bcolor=ffffff&color=575757&font=' + fontsPath + '/Klavika-Bold.ttf&height=24px&size=24px&text=' + escape(text) + '" alt="' + text + '"/>');
            }
        });
        
        // Add a negative margin to offse the extra space aroun the text in the 
        // image. This needs to happen AFTER the generated image is placed.
        $(".fw img").css("margin-left", "-4px");
    },

    // 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
