// ---------------------------------------------------------------------
// $Id: common.js 15522 2009-06-04 00:57:46Z 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();
    }
};

