// ---------------------------------------------------------------------
// $Id: common.js 29426 2010-02-02 06:39:30Z eric $
// ---------------------------------------------------------------------
// Common functions, and common code to run on every Foundation page.
// ---------------------------------------------------------------------

/*@cc_on @*/     // Turn on conditional comments for IE.

// ---------------------------------------------------------------------
// Cookies
// ---------------------------------------------------------------------

function getCookie(name) {
  var start = document.cookie.indexOf(name + "=");
  var len = start + name.length + 1;
  if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
  if (start == -1) return null;
  var end = document.cookie.indexOf( ";", len );
  if (end == -1) end = document.cookie.length;
  return unescape(document.cookie.substring(len, end));
}  


// ---------------------------------------------------------------------
// Popup Windows
// ---------------------------------------------------------------------

function popupWindow (name, url, w, h, l, t, statusbar) {
    var opts = "scrollbars,resizable";
    if (statusbar) opts += ",status";
    opts += ",width=" + w + ",height=" + h;
    opts += ",left=" + l + ",top=" + t;
    
    var popup = window.open(url, name, opts);
    popup.focus();
    return false;
};


// --------------------------------------------
// Star Ratings
// --------------------------------------------

function dnSetupStarRatings(selects, starOffImgSrc, starOnImgSrc) {
    // First, create a function for updating the rating spans.
    var updateRatingDisplay = function (ratingSpan, rating) {
        ratingSpan.select("img").each(function (img, i) {
            img.src = i + 1 <= rating ? starOnImgSrc : starOffImgSrc;
        });
    };
    
    $A(selects).each(function (sel) {
        // Use a span to hold the ratings star images.
        var ratingSpan = new Element("span", { "class": "dnStarRating" });
        ratingSpan.setStyle({ cursor: "pointer"});
        
        // Create the ratings span elements with the curent value.
        var curRating = sel.value ? parseInt(sel.value) : 0;
        for (var i = 1; i <= 5; i++) {
            ratingSpan.insert( new Element("img", {
                src: i <= curRating ? starOnImgSrc : starOffImgSrc,
                title: i == 1 ? "1 star" : i + " stars",
                alt: i  // Keep the rating value in the alt attribute.
            }));
        }
        
        // Attach event handlers to the star images.
        ratingSpan.select("img").each(function (img) {
            img.observe("click", function (e) {
                sel.value = img.alt;
                updateRatingDisplay(ratingSpan, parseInt(this.alt));
            });
        
            img.observe("mouseover", function (e) {
                if (this.dnStarRatingsMouseIn) return;
                this.dnStarRatingsMouseIn = true;
                updateRatingDisplay(ratingSpan, parseInt(this.alt));
            });
            
            img.observe("mouseout", function (e) {
                this.dnStarRatingsMouseIn = false;
                updateRatingDisplay(ratingSpan, parseInt(sel.value));
            })
        });
        
        // Hide the select and add the new ratings elements.
        $(sel).hide().insert({ after: ratingSpan });
    });
};


// ---------------------------------------------------------------------
// Fixup links to my public Profile page to go to MyProfile page.
// ---------------------------------------------------------------------

function fixupProfileLinks (profileUrl, myProfileUrl) {
    if (getCookie("memberOid")) {
        Event.observe(document, "dom:loaded", function () {
            var myOid = getCookie("memberOid");
            $$('a[href^="' + profileUrl + '"]').each(function (a) {
                if (a.href.match(new RegExp("Profile\\?oid=(?:oid(?:%3A|:)?)?" + myOid + "$"))) {
                    a.href = myProfileUrl;
                }
            });
        });
    }
}

/* animates the move to an anchor link */
/* xxx - should have a way to turn this behavior off (rel="noglide") */
function setupGlide() {
  var all_links = $$('a');
  all_links.each(function(thelink) {
      if (thelink.getAttribute('href') && thelink.getAttribute('href').match(/^#/) && $(thelink.getAttribute('href').split('#')[1]) && !thelink.getAttribute('onclick')) {
        thelink.onclick = function() {
          new Effect.ScrollTo(thelink.getAttribute('href').split('#')[1]);
          return false;
        }
      }
    });
}


// ---------------------------------------------------------------------
// Set up FancyZoom and FancyGlide
// ---------------------------------------------------------------------

Event.observe(window, "load", function () {
    /* Commented out until there's a solution that works with the flip book.
    $$("img").each(function (img) {
        var origWidth = img.readAttribute("data-orig-width");
        if (!origWidth) return;
        if (img.getWidth() >= parseInt(origWidth)) {
            img.up("a").insert({ after: img.remove() }).remove();
        }
    });
    */
    //if(document.setupZoom){setupZoom();}
    setupZoom();
    setupGlide();
});


// ---------------------------------------------------------------------
// Tools Setup
// ---------------------------------------------------------------------

function toolsSetup () {
    var toolsClass, panels;
    panels = $$("div.tools div.togglePanel");
    
    if (panels.size()) toolsClass = "tools";    
    else {
        panels = $$("div.tinyTools div.togglePanel");
        if (panels.size()) toolsClass = "tinyTools";
        else {
            panels = $$("div.horizontalTools div.togglePanel");
            toolsClass = "horizontalTools";
            
        }
    }
    
    var toggles = dnSetupToggleGroupAnimated(
        $$("div." + toolsClass + " a.toggleActivator"),
        panels
    );
    
    if (toolsClass == "horizontalTools") {
        panels.each(function (panel, i) {
            panel.addClassName("horizontalToolsTogglePanel");
            panel.remove();
            $(document.body).insert(panel);
            panel.absolutize();
            
            var toggle = toggles.getElementFromMap(panel);
            var pos = toggle.up().cumulativeOffset();
            pos[1] += toggle.up().getHeight();
            panel.setStyle({ left: pos[0] + "px", top: pos[1] + "px" });
        });
    }
    
    // Setup ajax request and related animations for the panels.
    panels.invoke("observe", "dnPanel:afterShow", function () {
        var panel = $(this);
        var updaterDiv = panel.down(".ajaxUpdater");
        if (updaterDiv) new Ajax.Updater(updaterDiv, "/gyrobase/Macros/ToolsAjax", {
            parameters: {
                macro: panel.readAttribute("data-toolsajaxmacro"),
                object: panel.readAttribute("data-toolsoid"),
                url: window.location
            },
            onComplete: function (t) {
                panel.down(".loading").blindUp({ duration: 0.3 });
                if (updaterDiv) updaterDiv.blindDown({ duration: 0.3 });
            }
        });
    });
    panels.invoke("observe", "dnPanel:afterHide", function () {
        var loading = $(this).down(".loading");
        if (loading) loading.show();
        
        var updater = $(this).down(".ajaxUpdater");
        if (updater) updater.hide();
    });
};


// ---------------------------------------------------------------------
// Tools Helper Functions
// ---------------------------------------------------------------------

function toolsAddToList (formid) {
    var listPanel = $(formid).up("div.togglePanel");
    listPanel.down(".loading").blindDown({ duration: 0.3 });
    listPanel.down(".ajaxUpdater").blindUp({
        duration: 0.3,
        afterFinish: function () {
            $(formid).request({ onComplete: function (t) {
                  listPanel.down(".ajaxUpdater").update(t.responseText);
                  listPanel.down(".loading").blindUp({ duration: 0.3 });
                  listPanel.down(".ajaxUpdater").blindDown({ duration: 0.3 });
            }});
        }
    });
};

function toolsRemindMe (formid) {
    var rmPanel = $(formid).up("div.togglePanel");
    rmPanel.down(".loading").blindDown({ duration: 0.3 });
    rmPanel.down(".ajaxUpdater").blindUp({
        duration: 0.3,
        afterFinish: function () {
            $(formid).request({ onComplete: function (t) {
                  rmPanel.down(".ajaxUpdater").update(t.responseText);
                  rmPanel.down(".loading").blindUp({ duration: 0.3 });
                  rmPanel.down(".ajaxUpdater").blindDown({ duration: 0.3 });
            }});
        }
    });
};

// Toggle Custom Reminder Times
function toolsShowCustomRemindTime(oid) {
    if ($F('remindRelative'+oid) == 'other') {
        $('customRemindTime'+oid).show();
    } else {
        $('customRemindTime'+oid).hide();
    }
};


// ---------------------------------------------------------------------
// Foundation Namespace
// ---------------------------------------------------------------------

var Foundation = {};


// ---------------------------------------------------------------------
// Foundation.Ajax Class  --  Run components Ajaxily
// ---------------------------------------------------------------------

Foundation.Ajax = Class.create(Ajax.Request, {
    initialize: function ($super, component, options) {
        options = options || {};
        
        var params = window.location.search.substring(1).toQueryParams();
        if (options.parameters) {
            for (p in options.parameters) {
                params[p] = options.parameters[p];
            }
        }
        options.parameters = params;
        options.parameters.ajaxComponent = component;
        
        $super(window.location.toString().replace(/\?.*/, ""), options);
    }
});


// ---------------------------------------------------------------------
// Foundation.Paginator Class  --  Page through results with Ajax
// ---------------------------------------------------------------------

Foundation.Paginator = Class.create({
    initialize: function (component, view, navlinksSel, pageParam) {
        this.component = component;
        this.view = view;
        this.navlinksSel = navlinksSel;
        this.pageParam = pageParam || "page";
        this.navigationLinkSeutp();
        this.inProgress = false;
    },
    
    navigationLinkSeutp: function () {
        var links = $(this.view).select(this.navlinksSel);
        links.invoke("observe", "click", this.requestPage.bind(this));
    },
    
    requestPage: function (clickEvent) {
        clickEvent.stop();
        if (this.inProgress) return;
        this.inProgress = true;
        
        var url = clickEvent.findElement("a").readAttribute("href");
        var linkParams = url.replace(/[^?]+\?/, "").toQueryParams();
        
        var requestParams = {};
        requestParams[this.pageParam] = linkParams[this.pageParam];
        
        this.spinner = new Foundation.Spinner(this.view, { delay: 1 });
        new Foundation.Ajax(this.component, {
            method: "get",
            parameters: requestParams,
            onSuccess: this.updatePage.bind(this),
            onComplete: this.reset.bind(this)
        });
    },
    
    updatePage: function (r) {
        this.spinner.hide();
        this.spinner = null;
        
        new Effect.Opacity(this.view, {
            duration: 0.3,
            from: 1,
            to: 0,
            afterFinish: (function () {
                $(this.view).update(r.responseText);
                $(this.view).appear({ duration: 0.3 });
                this.navigationLinkSeutp();
            }).bind(this)
        });
    },
    
    reset: function () {
        this.inProgress = false;
        if (this.spinner) this.spinner.hide();
    }
});


// ---------------------------------------------------------------------
// Foundation.Spinner Class  --  Display a spinner centered over a div
// ---------------------------------------------------------------------

Foundation.Spinner = Class.create({
    initialize: function (elem, options) {
        this.content = $(elem);
        this.delay = options.delay || 0;
        this.width = options.width || 100;
        this.height = options.height || 100;
        this.img_src = options.img_src || "/foundation/images/loaders/spinner-white-on-black.gif";
        this.img_width = options.img_width || 32;
        this.img_height = options.img_height || 32;
        this.color = options.color || "#000000";
        this.borderRadius = options.borderRadius || 15;
        this.opacity = options.opacity || .75;
        
        if (this.delay) {
            var ms = Math.ceil(this.delay * 1000);
            this.timer = setTimeout(this.show.bind(this), ms);
        }
        else {
            this.show();
        }
    },
    
    show: function () {
        // Create the img and div elements for the spinner.
        var img = new Element("img", { src: this.img_src, alt: "Loading..." });
        this.spinner = (new Element("div")).insert(img);
        
        // Get position of the element we're placing the spinner over.
        var contentPos = $(this.content).cumulativeOffset();
        var contentDim = $(this.content).getDimensions();
        
        // Set the spinner img styles.
        img.setStyle({
            display: "block",
            position: "absolute",
            width: this.img_width + "px",
            height: this.img_height + "px",
            left: Math.floor((this.width / 2) - (this.img_width / 2)) + "px",
            top: Math.floor((this.height / 2) - (this.img_height / 2)) + "px"
        });
        
        // The spinner div styles.
        this.spinner.setStyle({
            display: "block",
            position: "absolute",
            backgroundColor: this.color,
            width: this.width + "px",
            height: this.height + "px",
            left: Math.floor(contentPos[0] + (contentDim.width / 2) - (this.width / 2)) + "px",
            top: Math.floor(contentPos[1] + (contentDim.height / 2) - (this.height / 2)) + "px",
            zIndex: "1000",
            borderRadius: this.borderRadius + "px",
            MozBorderRadius: this.borderRadius + "px",
            WebkitBorderRadius: this.borderRadius + "px"
        }).setOpacity(this.opacity);
        
        $(document.body).insert(this.spinner);
    },
    
    hide: function () {
        if (this.timer) clearTimeout(this.timer);
        if (this.spinner) this.spinner.remove();
    }
});

