// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var IE7 = document.all && navigator.appVersion.indexOf("MSIE 7.") != -1;
var isCrap = IE6 || IE7;

function x() {};

Element.addMethods({
  //  getPosition : function(element) {
  //    var offset = Element.cumulativeOffset(element);
  //    var top = offset.top;
  //    var left = offset.left;
  //    var bottom = top + element.offsetHeight;
  //    var right = left + element.offsetWidth;
  //    return {top:top, bottom:bottom, left:left, right:right};
  //  },

  getPosition: function(el) {
    var obj = $(el);
    var left = 0;
    var top = 0;

    if (obj.offsetParent) {
      do {
        left += obj.offsetLeft;
        top += obj.offsetTop;
      } while (obj = obj.offsetParent);
    }

    return {top:top, bottom:top + el.offsetHeight, left:left, right:left + el.offsetWidth};
  },

  hasPosition : function(el, x, y) {
    el = $(el);
    var pos = el.getPosition();

    return (y >= pos.top && y < pos.bottom &&
            x >= pos.left && x < pos.right);
  }
});


/** One on One namespace to avoid naming collisions. */
var Ono = {};
Ono.debug = true;
Ono.crumbs = [];
Ono.currentCrumbZ = 999;

Ono.handleError = function(error) {
  if (Ono.debug) {
    alert(error);
  }
};

Ono.openForm = function(url) {
  window.open(url, 'form_window', 'status=no,titlebar=no,toolbar=no,scrollbars=yes,location=no,height=650,width=820');
};

Ono.Handlers = {
  onToggle: function(event) {
    var el = Event.element(event || window.event);
    Ono.Effects.toggle(el);
  },

  onCrumbClick: function(event) {
    event = event || window.event;
    var el = Event.element(event);

    while (el) {
      Element.extend(el);
      if (el.readAttribute("crumb_list")) {
        Ono.Effects.showCrumb(el);
        break;
      }
      el = el.parentNode;
    }
  },

  onMouseMove: function(event) {
    event = event || window.event;
    Ono.mouseX = Event.pointerX(event);
    Ono.mouseY = Event.pointerY(event);
    Ono.Effects.hideCrumbLists();
  }
};

/**
 * Initializes the unobtrusive JavaScript on the page. */
Ono.init = function() {
  try {
    // initialize toggling elements
    var togglers = $$("div a[toggle=true]");
    togglers.each(function(el) {
      Event.observe(el, "mouseup", Ono.Handlers.onToggle);
      //el.observe("mouseup", Ono.Handlers.onToggle);
      el.setAttribute("href", "javascript:x()");
    });

    // initialize the breadcrumb navigation
    var crumbs = $$("div.breadcrumbs div[crumb=true]");
    crumbs.each(function(crumb) {
      Element.extend(crumb);
      Event.observe(crumb, "click", Ono.Handlers.onCrumbClick);
      var list = $(crumb.readAttribute("crumb_list"));
      Ono.crumbs.push({crumb:crumb,list:list});

      // extract the DOM element from its current position and add it to the body
      // this allows the z-indexing to sit above other elements correctly.
      list.remove();
      document.body.appendChild(list);
    });

    Event.observe(document.documentElement, "mousemove", Ono.Handlers.onMouseMove);
    setTimeout('Ono.Messages.showServerMessage()', 500);
  } catch(ex) {
    Ono.handleError(ex);
  }
};

Ono.redirect = function(uri) {
  try {
    setTimeout("top.location='" + uri + "'", 100);
  } catch(ex) {
    Ono.handleError(ex);
  }
};

Ono.xhrUpdate = function(id, url, params) {
  new Ajax.Updater(id, url, {parameters: params, onComplete: function() {
    $(id).show();
  }});
};

Ono.quickFind = function() {
  var degreeSelect = $('degree_select');
  var courseSelect = $('course_select');
  var url = null;

  if (courseSelect) {
    url = courseSelect[courseSelect.selectedIndex].value;
  }

  if (!url || url.match(/^choose/i)) {
    var value = degreeSelect[degreeSelect.selectedIndex].value;
    if (value != '') {
      url = 'online-degrees_' + value;
    }
  }

  if (url && !url.match(/^choose/i)) {
    top.location = url;
  }
};


Ono.Messages = {
  showServerMessage: function() {
    var message = Ono.Cookies.read('message');
    if (message && message.strip().length > 0) {
      message = message.gsub(/\+/, ' ');
      Ono.Messages.show(message);
      Ono.Cookies.erase('message');
    }
  },

  show: function(message) {
    var el = $('message');
    el.innerHTML = message;
    if (document.all) {
      el.show();
    } else {
      Effect.Appear(el);
    }
    setTimeout("Ono.Messages.hide()", 3000);
  },

  hide: function() {
    var el = $('message');
    if (document.all) {
      el.hide();
    } else {
      Effect.Fade(el);
    }
  }
};

Ono.Effects = {
  showCrumb: function(crumb) {
    try {
      if (crumb.hiding) {
        return;
      }

      crumb = $(crumb);
      crumb.active = true;
      var crumbList = $(crumb.readAttribute('crumb_list'));
      if (!crumbList.visible()) {
        crumbList.setStyle({position:'absolute'});

//        crumbList.clonePosition(crumb, {
//          setWidth: false,
//          setHeight: false,
//          offsetTop: crumb.getHeight()
//        });

        // ensure the list width is at least as large as the crumb
        var crumbWidth = crumb.getWidth();
        if (crumbWidth > crumbList.getWidth()) {
          //crumbList.style.width = (crumbWidth + 10) + "px";
          crumbList.select("table")[0].setStyle({width:(crumbWidth + 5) + "px"});
        }

        Ono.currentCrumbZ += 1;
        crumbList.setStyle({zIndex:Ono.currentCrumbZ});

        if (isCrap) {
          crumbList.setStyle({top:(Ono.mouseY - 20) + 'px'});
          crumbList.setStyle({left:(Ono.mouseX - 40) + 'px'});
        } else {
          var pos = crumb.getPosition();
          crumbList.setStyle({top:pos.bottom + 'px'});
          crumbList.setStyle({left:pos.left + 'px'});
        }

        if (document.all) {
          crumbList.show();
        } else {
          Effect.Appear(crumbList, {duration:.2});
        }
      }
    } catch(ex) {
      Ono.handleError(ex);
    }
  },

  hideCrumbLists: function() {
    try {
      var len = Ono.crumbs.length;
      for (var i = 0; i < len; i++) {
        var crumb = Ono.crumbs[i].crumb;
        var list = Ono.crumbs[i].list;
        var x = Ono.mouseX;
        var y = Ono.mouseY;
        crumb.id = crumb.id || 'crumb_' + i;
        crumb.active = false;
        if (list.visible() && !list.hasPosition(x, y) && !crumb.hasPosition(x, y)) {
          clearTimeout(crumb.hideTimeout);
          crumb.hiding = true;
          crumb.hideTimeout = setTimeout("Ono.Effects.hideCrumb('" + crumb.id + "', '" + list.id + "')", 250);
        } 
      }
    } catch(ex) {
      Ono.handleError(ex);
    }
  },

  hideCrumb: function(crumb, list) {
    crumb = $(crumb);
    list = $(list);

    var x = Ono.mouseX;
    var y = Ono.mouseY;
    if (list.visible() && !list.hasPosition(x, y) && !crumb.hasPosition(x, y)) {
      crumb.hiding = true;
      if (isCrap) {
        list.hide();
      } else {
        Effect.Fade(list, {duration:.1});
      }

      setTimeout("$('" + list.id + "').setStyle({zIndex:''})", 200);
    } else {
      Ono.currentCrumbZ += 1;
      list.setStyle({zIndex:Ono.currentCrumbZ});
    }

    crumb.hiding = false;
  },

  /**
   * Animated toggle effect to show/hide an element.
   * The trigger element must supply the required meta data via attributes for this to work.
   * Namely:
   * - toggle_target
   * - toggle_visible_text
   * - toggle_hidden_text */
  toggle: function(el) {
    try {
      var trigger = $(el);
      var target = $(trigger.readAttribute("toggle_target"));

      target.toggle();
      var text = trigger.readAttribute("toggle_visible_text");

      if (target.visible()) {
        text = trigger.readAttribute("toggle_hidden_text");
      }

      if (text) {
        trigger.innerHTML = text;
      }
    } catch(ex) {
      Ono.handleError(ex);
    }
  },

  toggleSubTab: function(section) {
    var trigger = $('sub_tab_' + section);
    var el = $('section_' + section);

    var index = 1;
    Element.extend(trigger.parentNode);
    trigger.parentNode.childElements().each(function(el) {

      if (el.tagName == 'LI') {
        var section = $('section_' + index);
        section.hide();
        el.removeClassName('activ');
        index += 1;
      }
    });
    el.show();
    trigger.addClassName('activ');
  }
};

/**
 * Object for managing user preferences.
 */
Ono.Preferences = {
  values: {},

  changeFontSize: function(ch) {
    try {
      if (ch.toString().match(/px$/i)) {
        document.body.style.fontSize = ch;
        return;
      }

      var currentSize = document.body.style.fontSize;

      if (currentSize == '') {
        currentSize = "14";
        document.body.style.fontSize = currentSize + 'px';
      }

      currentSize = parseInt(currentSize);

      if (ch == '0') {
        if (currentSize < 18) {
          currentSize += 1;
          document.body.style.fontSize = currentSize + 'px';
        }
      }
      else {
        if (parseInt(document.body.style.fontSize) > 10) {
          currentSize -= 1;
          document.body.style.fontSize = currentSize + 'px';
        }
      }
    } catch(ex) {
      Ono.handleError(ex);
    }
  },

  apply: function(prefs) {
    try {
      if (prefs && prefs["font_size"]) {
        this.changeFontSize(prefs["font_size"] + "px");
      }
    } catch(ex) {
      Ono.handleError(ex);
    }
  },

  reset: function() {
    try {
      document.body.style.fontSize = "14px";
    } catch(ex) {
      Ono.handleError(ex);
    }
  }
};

Ono.Cookies = {
  create: function(name, value, days) {
    var expires = null;
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toGMTString();
    }
    else {
      expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
  },

  read: function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  },

  erase: function(name) {
    Ono.Cookies.create(name, "", -1);
  }
};

Ono.index = {
  showTab: function(name) {
    var tabs = ['degrees', 'degree_types', 'universities', 'states'];
    tabs.each(function(t) {
      $(t + '_tab').removeClassName('selected');
      $(t).hide();
    });

    $(name + '_tab').addClassName('selected');
    $(name).show();
  }
};


// setup easy access variables for the objects above
var prefs = Ono.Preferences;

Event.observe(window, "load", Ono.init);
