﻿//
// Miscellaneous JavaScript utility functions.
// Most of these scripts are extremely elementary.  If you 
// find something you like feel free to steal it.
// And if you improve on one of these please share
// your improvement.  Thanks!
//
// - Jason Polete <jpolete0001@kctcs.edu>
//



//Cross-browser function to attach events to DOM objects
function addAnEventListener(obj, evt, func) {
    if(obj.addEventListener) {
        obj.addEventListener(evt, func, false);
    } else {
        //create property name for array to hold event handler functions
        var funcHolder = evt + "Funcs";
        //if event handler array does not already exist create it
        if(!(obj[funcHolder]) || !(obj[funcHolder] instanceof Array)) {
            obj[funcHolder] = new Array();
        }
        //add the function to the event handler array
        obj[funcHolder][obj[funcHolder].length] = func;
        //attach an anonymous function to call all event handlers in the array
        obj["on" + evt] = function() {
            for(var i = 0; i < this[funcHolder].length; i++) {
                this[funcHolder][i].call(this);
            }
        }
    }
}


//
//Convenience functions to add or remove a class for a given element
function addClassName(el, name) {
    el.className += " " + name;
}
function removeClassName(el, name) {
    var names = el.className.split(" ");
    var newClassName = "";
    for(var i = 0; i < names.length; i++) {
        if(names[i] != name && names[i] != " ") {
            newClassName += names[i] + " ";
        }
    }
    el.className = newClassName;
}


// This idea was taken from somewhere on www.alistapart.com, I think,
// but I am not sure exactly where.
// Makes links with a [rel="external"] attribute/value pair open in a new window
function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
            anchor.target = "_blank";
            if(anchor.title && anchor.title != "") anchor.title;
            anchor.title += "Opens new window";
        }
    }
}

addAnEventListener(window, "load", externalLinks);




////////////////////////////////////////////////////////////////////
//
// Preloads image rollovers and sets event handlers
//
//////////////////////////////////////////////////////////////////

function ImageButton(id, mouseOverUrl, mouseDownUrl) {
    //Set references
    this.el = document.getElementById(id);
    this.el.imageButton = this;
    //Save initial image url
    this.mouseOutImageUrl = this.el.src;
    //Initialize rollover
    if(mouseOverUrl) {
        this.preloadImage(mouseOverUrl);
        this.mouseOverImageUrl = mouseOverUrl;
    }
    if(mouseDownUrl) {
        this.preloadImage(mouseDownUrl);
        this.mouseDownImageUrl = mouseDownUrl;
    }
    //Assign event handlers
    if(this.mouseOutImageUrl) this.el.onmouseout = this.mouseout;
    if(this.mouseOverImageUrl) this.el.onmouseover = this.mouseover;
    if(this.mouseDownImageUrl) this.el.onmousedown = this.mousedown;
    this.el.onmouseup = this.mouseout;
}

ImageButton.prototype.preloadImage = function(url) {
    var img = new Image();
    img.src = url;
}

ImageButton.prototype.mouseover = function() {
    this.src = this.imageButton.mouseOverImageUrl;
}

ImageButton.prototype.mouseout = function() {
    this.src = this.imageButton.mouseOutImageUrl;
}

ImageButton.prototype.mousedown = function() {
    this.src = this.imageButton.mouseDownImageUrl;
}







// Changes focus to next input on the page after the 
// specified number of characters are typed.
// Add this function to a text input's onkeyup event handler.
//
// EXAMPLE: 
// <input type="text" name="areacode" onkeyup="changeFocus(this, 3)" />
// <input type="text" name="prefix" onkeyup="changeFocus(this, 3)" />
// <input type="text" name="lastfour" />
//
function changeInputFocus(el, chars) {
    if(el.value.length == chars) {
        var inputs = getTextFields(document.getElementsByTagName("input"));
        var nextEl = null;
        for(var i = 0; i < inputs.length; i++) {
            if(inputs[i].id == el.id) {
                var next = i + 1;
                nextEl = inputs[next];
                break;
            }
        }
        if(nextEl != null) nextEl.focus();
    }
}

function getTextFields(inputs) {
    var textFields = new Array();
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i].getAttribute("type") == "text")
            textFields[textFields.length] = inputs[i];
    }
    return textFields;
}






//Open a sized popup window w/o any toolbars
function openSizedWindow(href, height, width) {
    var sizedwindow = window.open(href, 'sizedwindow', 'height=' + height + ',width=' + width + ',menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=no');
    sizedwindow.focus();
    return false;
}


//Clears the default text of supplied input
function clearInput(input){
	if (input.defaultValue == input.value) input.value = ""
}


//STYLESHEET SWITCHER TAKEN FROM www.alistapart.com/articles/alternate/
function setActiveStyleSheet(title) {
   var i, a, main;
   for(i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
}




/////  COOKIE FUNCTIONS FROM QUIRKSMODE - WWW.QUIRKSMODE.ORG
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}














// Add Metrocollege Search to Firefox Search bar - adapted from mozilla's addEngine function
//function addEngine() {
//    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) { 
//        window.sidebar.addSearchEngine(
//           "https://www.metro-college.com/mozilla/searchplugins/Metrocollege.src",
//           "https://www.metro-college.com/mozilla/searchplugins/Metrocollege.src", "Metropolitan College", "Education");
//    } else {
//        alert("This is a feature of the Mozilla Firefox browser. The browser you are using does not support this feature.");
//    }
//}


//RANDOM NUMBER GENERATOR
function random(lower, upper) {
  var random_num;
  random_num = (Math.round((Math.random()*(upper - lower)) + lower));
  return random_num;
}


//ADD PAGE TO BOOKMARK
function addToFavorites(pageUrl, pageName) {
  if (window.external) {
      window.external.AddFavorite(pageUrl,pageName)
  } else { 
      alert("Your Browser does not support this function \n Click \"Favorites\" or \"Bookmarks\" on your browsers toolbar and then \"add\"");
  }
}


//WRITE CURRENT DATE TO PAGE
function writeDate(format) {
    var currentDate = new Date();
    var thisMonth = new Array("Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec");
    var today = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

    //Monday Jan 16, 2006 
    if(format == "") { 
        document.write(today[currentDate.getDay()] + " " + 
                       thisMonth[currentDate.getMonth()] + " " + 
                       currentDate.getDate() + ", " + 
                       currentDate.getFullYear());
    // Monday Jan 16, 2006
    }  else if(format == "1") { //
        document.write(today[currentDate.getDay()] + " " + 
                       thisMonth[currentDate.getMonth()] + " " + 
                       currentDate.getDate() + ", " + 
                       currentDate.getFullYear());
    //Jan 16, 2006
    }  else if(format == "2") {
        document.write(thisMonth[currentDate.getMonth()] + " " + 
                       currentDate.getDate() + ", " + 
                       currentDate.getFullYear());
    }
}

