var cancelForm = false;

// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') { window.onload = func;
  } else { window.onload = function() { oldonload(); func(); } }
}

function addEventToElement(elem,func,event){
  if(typeof elem != "object"){ return false; }
  if(typeof func != "function"){ return false; }
  
  if(typeof event == "object"){
    for(var i=0;i<event.length;i++){ addEventToElem(elem,func,event[i]); }
  }
  else if(typeof event == "string") {
    var elemEvent = eval("elem."+ event);
    var old = elemEvent;
    if (typeof elemEvent != 'function') { elemEvent = func; } 
    else {
      elemEvent = function() { old(); func(); }
    }
    switch(event){
    case "onload":
      elem.onload=elemEvent;
      break;
    case "onchange":
      elem.onchange=elemEvent;
      break;
    case "onfocus":
      elem.onfocus=elemEvent;
      break;
    case "onblur":
      elem.onblur=elemEvent;
      break;
    case "onclick":
      elem.onclick=elemEvent;
      break;
    case "onmouseover":
      elem.onmouseover=elemEvent;
      break;
    case "onmouseout":
      elem.onmouseout=elemEvent;
      break;
    }
  }
}

function changePage(frm){ window.location=frm.options[frm.options.selectedIndex].value; }

function changeMonth(frm){  
	URL = frm.site.options[frm.site.selectedIndex].value; 
	window.location.href = URL;
}

function openAthleticsWindow(link){
  window.open(link.href,'sjaathletics','width=300,height=300,location=no,menubar=no,resizable=yes,toolbar=no,status=no,scrollbars=yes');
}

function openWindow(link){
  window.open(link,'sjaathletics','width=400,height=300,location=no,menubar=no,resizable=yes,toolbar=no,status=no,scrollbars=yes');
}

function openGalleriesWindow(link){
  window.open(link,'sjagalleries','width=650,height=450,location=no,menubar=no,resizable=yes,toolbar=no,status=no,scrollbars=yes');
}


addLoadEvent(function(){
  if(document.getElementById){
    var cMenu=document.getElementById('childrenMenu');
    if(cMenu){
      cMenu.onchange=function(){ changePage(this); }
    }
  }
});

//--------------------------------------------------------------
// check if flash can be played
var checkFlashCookieDomain='.stjosephacademy.org';
MM_FlashCanPlay = checkFlash();
function checkFlash(){
  var MM_contentVersion = 6;
  var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
  if (plugin) {
    var words = navigator.plugins["Shockwave Flash"].description.split(" ");
    for (var i = 0; i < words.length; ++i){
      if (isNaN(parseInt(words[i])))
      continue;
      var MM_PluginVersion = words[i]; 
    }
    var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
  }
  else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
    && (navigator.appVersion.indexOf("Win") != -1)) {
    oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + MM_contentVersion + "');");
    if(oFlash) { MM_FlashCanPlay = true; }
  }
  
  expires = new Date();
  expires.setFullYear(expires.getFullYear()+1);
  if(window.location.search == "?noflash=1"){ 
  	MM_FlashCanPlay = 0; 
  	// set no flash cookie
  	document.cookie="flash=0; expires="+ expires.toGMTString() +"; domain="+ checkFlashCookieDomain;
  }
  else if(window.location.search == "?noflash=0" || window.location.search == "?flash=1"){
  	document.cookie="flash=1; expires="+ expires.toGMTString() +"; domain="+ checkFlashCookieDomain;
  }
  else {
  	var c 	= document.cookie;
  	var pos = c.indexOf("flash=");
  	if(pos != -1){
  		var start = pos + 6;
  		var end   = c.indexOf(";",start);
  		if (end == -1){ end = c.length; }
  		var val = c.substring(start,end);
  		
  		if(val == "0"){ MM_FlashCanPlay = 0; }
  	}
  }
  return MM_FlashCanPlay;
}

//--------------------------------------------------------------
// PNMGFlash
var PNMGFlash=new Array();
function Flash(file,width,height,div,image,flashCanPlay){
  this.file = file;
  this.width = width;
  this.height = height;
  this.div = div;
  this.image = image;
  this.flashCanPlay = flashCanPlay;
  
  if(this.flashCanPlay){ this.register(); }
}
Flash.prototype.getObject = function(){
  return '<object type="application/x-shockwave-flash" data="'+ this.file +'" width="'+ this.width +'" height="'+ this.height +'">'+
    '<param name="movie" value="'+ this.file +'" /><param name="wmode" value="transparent" /></object>';
}
Flash.prototype.register = function(){
  if(addLoadEvent){
    PNMGFlash[PNMGFlash.length]=this;
  }
  else { alert("PNMGFlash error: Could not show the flash because the function addLoadEvent() does not exist."); }
}
Flash.prototype.show = function(){
  if(document.getElementById){
    var e = document.getElementById(this.div);
    if(e){
      if(document.getElementById(this.image)){
        document.getElementById(this.image).className='printOnly';
        h=e.innerHTML + this.getObject();
        e.innerHTML='';
        e.innerHTML=h;
        e.style.height=this.height;
      }
      else { alert("PNMGFlash error: The image '"+ this.image +"' does not exist."); }
    }
    else { alert("PNMGFlash error: The flash div '"+ this.div +"' does not exist.");  }
  }
}
addLoadEvent(function(){
  for(var i=0;i<PNMGFlash.length;i++){
    PNMGFlash[i].show();
  }
});


/*--------------------------------------------------------------
  getAttribute()
  
  A crossbrowser way to get an attribute from an element.
  
  Arguments:
    elem      the element reference
    attr      a string for the attribute name
 */
function getAttribute(elem,attr){
  if(elem.getAttribute){
    a = elem.getAttribute(attr);
    if(a != null){ return a; }
  }
  if(elem.attributes && elem.attributes[attr]){ return elem.attributes[attr].value; }
  for(var i=0;i<elem.attributes.length;i++){
    if(elem.attributes[i].specified){
      if(elem.attributes[i].name == attr){ return elem.attributes[i].value; }
    }
    else { return elem.attributes[i]; }
  }
  return null;
}


/*--------------------------------------------------------------
  checkPageForms()
 */
function checkPageForms(frm, formName){
  if(!cancelForm){
    // Check if the form element exists
    if(!frm){ return false; }
    // Browser must pass this basic test to proceed
    if(document.getElementById){
      var id = getAttribute(frm,'id');
      // If a form name is passed to this function, then
      // it must equal the value of the ID of this form
      // (this is so multiple forms can be checked on a
      // single page)
      if(id == formName || formName == ""){
        var labels = frm.getElementsByTagName('label');
        var error  = false;
        var eFocus = null;
        var titles = "";
        for(var i=0; i<labels.length;i++){
          var l = labels[i];
          if(l.className.indexOf('required') >= 0 || l.className.indexOf('error') >= 0){
            var elemID = getAttribute(l,'for');
            var e = document.getElementById(elemID);
            if(e){
              // Process the different input types
              var nodeName = e.nodeName;
              if(nodeName.toLowerCase() == "input"){
                // Input elements
                var eType = getAttribute(e,'type');
                if(eType == "text"){            // TEXT
                  if(qTrim(e.value) == ""){
                    // found an error
                    l.className = "error";
                    error = true;
                    e.className += " error";
                    var t = getAttribute(e,'title');
                    if(t){ titles += "\n  - "+ t; }
                    if(eFocus == null){ eFocus = e; }
                  }
                  else { l.className = "required"; }
                }
								else if(eType == "password"){    // PASSWORD
                  if(qTrim(e.value) == ""){ 
                    // found an error
                    l.className = "error"; 
                    error = true;
                    var t = getAttribute(e,'title');
                    if(t){ titles += "\n  - "+ t; }
                    if(eFocus == null){ eFocus = e; }
                  }
                  else { l.className = "required"; }
                }
                else if(eType == "radio"){      // RADIO BUTTONS
                  if(!e.checked){ 
                    l.className="error"; 
                    error = true;
                    var t = getAttribute(e,'title');
                    if(t){ titles += "\n  - "+ t; }
                    if(eFocus == null){ eFocus = e; }
                  }
                  else { l.className = "required"; }
                }
                else if(eType == "file"){            // FILE
                  if(qTrim(e.value) == ""){
                    // found an error
                    l.className = "error";
                    error = true;
                    e.className += " error";
                    var t = getAttribute(e,'title');
                    if(t){ titles += "\n  - "+ t; }
                    if(eFocus == null){ eFocus = e; }
                  }
                  else { l.className = "required"; }
                }
              }
              else if(nodeName.toLowerCase() == "select"){  // SELECT
                // Select elements
                var ix = e.selectedIndex;
                var o = qTrim(e.options[ix].value);
                if(o == "#" || o == "-" || o == "" || o == "--" || o == "##"){
                  // found an error
                  l.className = "error"; 
                  error = true;
                  var t = getAttribute(e,'title');
                  if(t){ titles += "\n  - "+ t; }
                  if(eFocus == null){ eFocus = e; }
                }
                else { l.className = "required"; }
              }
              else if(nodeName.toLowerCase() == "textarea"){  // TEXTAREA
                // Textarea elements
                if(qTrim(e.value) == ""){ 
                  // found an error
                  l.className = "error"; error = true;
                  var t = getAttribute(e,'title');
                  if(t){ titles += "\n  - "+ t; }
                  if(eFocus == null){ eFocus = e; }
                }
                else { l.className = "required"; }
              }
            }
          }
        }
        if(error){
          if(eFocus != null){ eFocus.focus(); }
          if(titles == ""){
            alert("There was an error with the form. Please enter a value "+
                  "for all the fields marked in red.");
          }
          else { 
            alert("There was an error with the form. Please enter a value "+
                  "for all the following fields (marked in red):\n"+titles);
          }
          error = false;
          return false;
        }
      }
      else { return true; }
    }
  }
  return true;
}

//*****Mask function from http://digitalbush.com/projects/masked-input-plugin**************************************************//
function mask() {
  if ($('#formValidate').length < 1) return false;
  $('.zip').mask('99999');
  $('.phone').mask('(999) 999-9999');
  $('.date').mask('99/99/9999');
  $('.ssn').mask('999-99-9999');
  $('.year').mask('9999');
}
//*****jQuery form validation from http://bassistance.de/jquery-plugins/jquery-plugin-validation/**************************************************//
function validate() {
  if ($('#formValidate').length < 1) return false;
  $('#formValidate').validate({
    highlight: function(element, errorClass) {//add the error class to the label and element
		  if ($(element).is(':radio')) {
		    $(element).parent().prev().addClass(errorClass);
		  } else {
        $(element).addClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
      }
    },
    unhighlight: function(element, errorClass) {//remove error class from label and element once valid
		  if ($(element).is(':radio')) {
		    $(element).parent().prev().removeClass(errorClass);
		    $(element).parent().prev().addClass('valid');
		  } else {
        $(element).removeClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
      }
    },
    success: function(label) {//add the green box and checkmark for valid fields
		  if (label.prev().is(':checkbox')) {
        label.next().addClass("valid");
        label.addClass("valid").text("✓");
      } else {
        label.prev().addClass("valid");
        label.addClass("valid").text("✓");
      }
    },
    onfocusout: false,
    onkeyup: false,
    onclick: false,
    //do not use the title attribute as the error message
    ignoreTitle: true,
    //make the error text wrapped in a span
    errorElement: 'span',
    //javascript instead of class specified rules
    rules: {
      'rdoLiveWith[]': 'required'
    },
    //messages other than the default 'X'
    messages: {
		  'rdoLiveWith[]': '<br />X Please select one of the options below<br />'
		},
    // the errorPlacement has to take the h2 of radio buttons into account
		errorPlacement: function(error, element) {
		  if ( element.is(':radio') )
		    error.appendTo( element.parent().prev() );
		  else
				error.insertAfter(element);
		}
  });
}

/*--------------------------------------------------------------
  qTrim()
 */
function qTrim(value) { return value.replace(/\n/,"").replace(/\r/,"").replace(" ",""); }

//*****The following function make it possible to have web standard popups**************************************************//
function initializeCycle() {
  if (!$('ul.pics').length > 0) return false;
  $('ul.pics').cycle('fade');
}
$(document).ready(function(){
	//**************************************************Clear search text out search box on focus**************************************************//
	$('#txtSearch').focus(function() {
    if ($(this).val() == "SEARCH") {
      $(this).val('');
	  }
  });
  initializeCycle();
  mask();
  validate();
});