var request = false;

var hideSpecialCookieFromJava, messageDivNameFromJava;
var bannerTypeFromJava, SpecialTagBannerFromJava;
// hideSpecialCookieFromJava, messageDivNameFromJava
// bannerTypeFromJava, SpecialTagBannerFromJava will be defined
// page by page when it calls drawHideMessageJavascript method

var tagWhereYFromJava = "whereY";
// tagWhereYFromJava is set by different java page and passed to here


// This is the code for the special message utils.
(function() {
  var getMsgDiv = function() {
    if (document.getElementById) {
      return document.getElementById(messageDivNameFromJava);
    }
    else {
      return document.all[messageDivNameFromJava];
    }
  };

  var hideSpecialMessage = function(noCookieSet) {
    if (!noCookieSet) {
      document.cookie = hideSpecialCookieFromJava + '=hide_message; path=/';
    }
    var theDiv = getMsgDiv();
    theDiv.innnerHTML = '';
    // Part of fix for bug 7825 -ecurtis 9/21/06
    // Removed height:0
    // Added display:none
    theDiv.style.visibility = 'hidden';
    theDiv.style.display = 'none';
  };

  var drawSpecialMessageFromRequest = function() {
    if (request.readyState == 4) {
      if (request.status == 200) {
        var messageText = request.responseText;
        if (messageText.length > 0) {
          var theDiv = getMsgDiv();
          theDiv.innerHTML = messageText;
          theDiv.style.visibility = 'visible';
          // Part of fix for bug 7825 -ecurtis 9/21/06
          // Added display:block -- this displays the div
          theDiv.style.display = 'block';
        }
        else {
          hideSpecialMessage(true/* Don't set the cookie */);
        } // end if messageText.length > 0
      } // end if request.status == 200
    } // end if request.readyState == 4
  };

  var getSpecialMessage = function() {
    try {
      request = new XMLHttpRequest();
    } catch (error) {
      try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
      } catch (error) {
        try {
          request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (error) {
          request = false;
        }
      }
    } // end try
    if (request) {
      // Fix bug 11904 -ecurtis 1/18/08 -- add try-catch
      try {
        var url =
          '/servlets/quia.common.modules.SpecialMessageServlet?'
        + SpecialTagBannerFromJava + '=' + bannerTypeFromJava;
        request.open('GET', url, true);
        request.onreadystatechange = drawSpecialMessageFromRequest;
        request.send(null);
      } catch(error) {}
    } // end if request
  };

  // Expose some of the APIs
  window.hideSpecialMessage = hideSpecialMessage;
  window.getSpecialMessage = getSpecialMessage;

})();


// javascript that will disable the enter key
function handleEnter (field, event) {
  var keyCode = event.keyCode || event.which || event.charCode;

  // normally, the enter key has a keycode value of 13.
  // however, on the mac, the "right-side" enter key has a value of 3!
  return keyCode != 13 && keyCode != 3;
} // end func

// ARG!!! http://inmyexperience.com/archives/000428.shtml
// http://msdn.microsoft.com/library/default.asp?
// url=/workshop/author/dhtml/reference/methods/createelement.asp
//
// Javascript to allow us to disable all submit buttons the moment any
// submit button is clicked

function disableAllSubmitButtons(formObj) {
  if (document.forms && document.createElement) {

    var fIndex = 0,
        fLen = document.forms.length,
        eIndex,
        eLen,
        tempForm,
        el,
        elType;

    for ( ; fIndex < fLen; fIndex++) {
      tempForm = document.forms[fIndex];
      eIndex = 0;
      eLen = tempForm.elements.length;
      for (; eIndex < eLen; eIndex++) {
        el = tempForm.elements[eIndex];
        elType = el.type.toLowerCase();
        if (elType == "submit" || elType == "reset") {
          el.disabled = true;
        } // end if
      } // end for
    } // end for
    var input = document.createElement('input');
    input.style.display = 'none';
    input.style.visibility = 'hidden';
    if (input.setAttribute) {
      input.setAttribute("name", formObj.name);
      input.setAttribute("value", formObj.value);
    }
    else {
      input.name = formObj.name;
      input.value = formObj.value;
    } // end if
    formObj.form.appendChild(input);
    formObj.form.submit();
  } // end if
  return true;
} // end func

// taken from http://wwww.quirksmode.org/js/findpos.html
function getYOffset(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    var curObj = obj;
    while (curObj.offsetParent) {
      curtop += curObj.offsetTop;
      curObj = curObj.offsetParent;
    } // end while
  }
  else if (obj.y){
    curtop += obj.y;
  } // end if
  return curtop;
} // end func

function getFormElementInDocument(elemName) {
  var elem = null;
  if (document.forms) {
    for (var fIndex=0;elem == null && fIndex < document.forms.length;fIndex++){
      var tempForm = document.forms[fIndex];
      for (var index = 0;elem == null && index < tempForm.length; index++){
        var tempobj = tempForm.elements[index];
        if (tempobj.name == elemName) {
          elem = tempobj;
        } // end if
      } // end for
    } // end for
  } // end if
  return elem;
} // end func

function getWindowHeight() {
  var winHeight = -1;
  if (window.innerHeight) {
    winHeight = window.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight
            && document.documentElement.clientHeight > 0) {
    winHeight = document.documentElement.clientHeight;
  }
  else if (document.body.clientHeight) {
    winHeight = document.body.clientHeight;
  } // end if
  return winHeight;
} // end func

// draw the javascript necessary to save and go to a scroll location
function getCurYLoc() {
  var yLoc = -1;
  if (window.pageYOffset) {
    yLoc = window.pageYOffset;
  }
  else if (document.body.scrollTop) {
    yLoc = document.body.scrollTop;
  } // end if
  return yLoc;
} // end func

function saveScrollCoordinates(curForm) {
  var yLoc = getCurYLoc();
  if (document.createElement) {
    var yInput = document.createElement("input");
    yInput.name = tagWhereYFromJava;
    yInput.id = tagWhereYFromJava;
    yInput.value = yLoc;
    // -ecurtis 7/6/06
    // Doing a try-catch when setting the type because it causes and uncaught
    // exception in IE5.
    // see: http://alt-tag.com/blog/archives/2006/02/ie-dom-bugs/
    try {
      yInput.type = "hidden";
    } catch(e) { yInput.style.visibility = 'hidden'; }
    curForm.appendChild(yInput);
  } // end if
} // end func

function scrollToCoordinates(whereY) {
  if (whereY != -1) {
    window.scrollTo(0, whereY);
  } // end if
} // end func

function gotoUrlWithWhereY(url) {
  var yLoc = getCurYLoc();
  url = url + "&" + tagWhereYFromJava + "=" + yLoc;
  window.location = url;
} // end func

function getWhereYandScroll(fieldName, whereY){
  if (fieldName != null) {
    var fieldElem = getFormElementInDocument(fieldName);
    if (fieldElem != null) {
      var fieldY = getYOffset(fieldElem);
      var winHeight = getWindowHeight();
      if (fieldY > -1 && winHeight > 0) {
        var quarterHeight = winHeight / 4;
        whereY = fieldY - quarterHeight;
      } // end if
    } // end if fieldElem != null
  } // end if fieldName != null
  if (whereY >= 0) {
    scrollToCoordinates(whereY);
  } // end if
} // end func


// addLoadEvent functionality
function addLoadEvent(func) {
  YAHOO.util.Event.onDOMReady(func);
}

// script to handle Quia Web Home functions, such as focus and blur,
// prepare teacher search field etc.

(function() {
  var lightColor = '#CCCCCC',
      origColor  = '#444444',
      firstTxt   = 'First Name',
      lastTxt    = 'Last Name',
      firstName  = 'firstName',
      lastName   = 'lastName';

  var setText = function(el, txt, color) {
    el.value = txt;
    el.style.color = color || lightColor;
  };

  // Expose the QUIHOME API
  window.QUIAHOME = {

    focus : function (target) {
      if ( (target.value === firstTxt && target.id === firstName) ||
           (target.value === lastTxt && target.id === lastName) ) {
        setText(target, '', origColor);
      }
    },

    blur  : function (target) {
      if (target.value === '' && target.id === firstName){
        setText(target, firstTxt);
      }
      if (target.value === '' && target.id === lastName){
        setText(target, lastTxt);
      }
    },

    prepareFindTeacher : function () {
      var firstObj = document.getElementById(firstName),
          firstVal = firstObj.value,
          secObj = document.getElementById(lastName),
          secVal = secObj.value;
      if (firstVal === '' || firstVal === firstTxt){
        setText(firstObj, firstTxt);
      }
      if (secVal === '' || secVal === lastTxt) {
        setText(secObj, lastTxt);
      }
    },

    processFindTeacherSubmit : function (formObj) {
      var firstObj = document.getElementById(firstName);
      var secObj = document.getElementById(lastName);
      if (firstObj.value === firstTxt) {
        firstObj.value = '';
      }
      if (secObj.value === lastTxt) {
        secObj.value = '';
      }
    }

  };
})();

// beforeUnload event handler
(function() {
  var YU = YAHOO.util,
      Dom = YU.Dom,
      Event = YU.Event;

  var alwaysTrue = function() {
    return true;
  };

  var alwaysFalse = function() {
    return false;
  };

  var isSubmitOrReset = function (el) {
    var type = (el.type ? el.type.toLowerCase() : null);
    return type === "submit" || type === "reset";
  };

  window.createBeforeUnload = function(msg, method, submitNotOK) {

    // Old versions of Safari don't play well with disabling submit buttons
    // and having the beforeUnload event. To fix this, don't add a beforeUnload.
    if (YAHOO.env.ua.webkit && YAHOO.env.ua.webkit < 419) {
      return;
    }

    method = method || alwaysFalse;

    // Initially okToLeave is true
    var okToLeave = true;

    // Most of the time, we want the submit button to be a test for determining
    // if it's okToLeave the page.  However, we want the flexibility to turn
    // this default behavior off by passing in "true" to submitNotOK.
    if (!submitNotOK) {

      // If we're testing for the form submission, change okToLeave to false
      okToLeave = false;

      // A function to say, yes it is ok to leave the page. 
      var markOkToLeave = function() {
        okToLeave = true;
      };

      // Add listeners to all the forms submit events, as well as the click
      // events for all submit and reset buttons.
      Dom.getElementsBy(alwaysTrue, "form", document, function(frm){
        Event.addListener(Dom.getElementsBy(isSubmitOrReset, "input", frm), "click", markOkToLeave);

        // Unfortunately, a call from javascript to "submit" doesn't fire the
        // submit event, so we have to work around this by overriding the
        // real submit function with a fake one.
        frm._submit = frm.submit;
        frm.submit = function() {
          markOkToLeave();
          frm._submit();
        };
      });
    }

    // Listen for the beforeunload event
    Event.addListener(window, "beforeunload", function(ev) {
      if (!okToLeave && !method()) {
        if (ev) {
          ev.returnValue = msg;
        }
        return msg;
      }
    });

  };
})();
