/******************************************************************
 *
 * CONSTANTS
 *
 ******************************************************************/

// For switching between the main and songpage (see frameset.js)
var MAIN = 1;
var SONG = 2;

// Switch to the song page by clicking on a song name
function gotoSongPage(projectID, songID) {

   // If this is the first time we'll be seeing the song page, we'll direct the frame
   // to the song page script and use the query string to indicate the song to show.
   // Otherwise, we'll just change the song being viewed displayed on the song page.
   
   if (top.hasLoadedSongPage == true) {
      if (top.mainFrameset.visiblePages != (MAIN | SONG)) {
         top.mainFrameset.showPage(SONG);
         top.songPage.changeSong(projectID, songID);         
      }
   } else {
        top.mainFrameset.showPage(SONG,'projectID='+projectID+'&songID='+songID);
        //top.songPage.location = top.songPageUrl+'?projectID='+projectID+'&songID='+songID;
   }
}

/******************************************************************
 *
 * DOM functions
 *
 ******************************************************************/
 
/**
 *
 * $
 * Get a DOM element (or elements) by name
 *
 */

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

/**
 *
 * getElementsByClassName
 * Return an array of all DOM elements with the specified classname
 * 
 * oElm: The root element to search within
 * strTagName: The tag type to search (or * for all tags)
 * strClassName: The class name to search for
 *
 */

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

function createHiddenFormField (form, name, value) {
   
   var field = document.createElement('input');
   field.setAttribute('type','hidden');
   field.setAttribute('name',name);
   field.setAttribute('value',value);
   form.appendChild(field);
   return field;
   
}

/******************************************************************
 *
 * Array functions
 *
 ******************************************************************/

/*
append to end of array, optionally checking for duplicates
*/
Array.prototype.append=function(obj,nodup){
  if (!(nodup && this.contains(obj))){
    this[this.length]=obj;
  }
}

/*
return index of element in the array
*/
Array.prototype.indexOf=function(obj){
  var result=-1;
  for (var i=0;i<this.length;i++){
    if (this[i]==obj){
      result=i;
      break;
    }
  }
  return result;
}

/*
return true if element is in the array
*/
Array.prototype.contains=function(obj){
  return (this.indexOf(obj)>=0);
}

/*
empty the array
*/
Array.prototype.clear=function(){
  this.length=0;
}

/*
insert element at given position in the array, bumping all
subsequent members up one index
*/
Array.prototype.insertAt=function(index,obj){
  this.splice(index,0,obj);
}

/*
remove element at given index
*/
Array.prototype.removeAt=function(index){
  this.splice(index,1);
}

/*
return index of element in the array
*/
Array.prototype.remove=function(obj){
  var index=this.indexOf(obj);
  if (index>=0){
    this.removeAt(index);
  }
}

/******************************************************************
 *
 * Event routing object
 *
 ******************************************************************/

/* namespacing object */
var jsEvent=new Array();

jsEvent.domElements = new Array;
jsEvent.uid = 0;

/*
constructor function, specifying DOM element (or other object) to listen to,
and event type, which should be a valid browser event e.g. 'onmouseover' 'onclick' for DOM
elements
*/
jsEvent.EventRouter=function(el,eventType){
  this.lsnrs=new Array();
  this.el=el;
  var el = (this.el == 'window') ? window : $(this.el);
  el[eventType] = jsEvent.EventRouter.callback;   
}

/*
convenience method for adding a listener
*/
jsEvent.EventRouter.prototype.addListener=function(lsnr){
  this.lsnrs.append(lsnr,true);
}

/*
convenience method for removing a listener
*/
jsEvent.EventRouter.prototype.removeListener=function(lsnr){
  this.lsnrs.remove(lsnr);
}

/*
notify all listeners of an event - this is called by the callback, don't need
to invoke it yourself for DOM nodes, but if using bespoke events it is the
easiest way in
*/
jsEvent.EventRouter.prototype.notify=function(e){
  var lsnrs=this.lsnrs;
  var el = (this.el == 'window') ? window : $(this.el);
  for(var i=0;i<lsnrs.length;i++){
    var lsnr=lsnrs[i];
    lsnr.call(el,e);
  }
}

/*
'static' callback event handler, for which 'this' will be the DOM element. Simply
locate the reference to the router object, and notify() it
*/
jsEvent.EventRouter.callback=function(event){
  var e=event || window.event;
  var router=this.EventsRouter["on"+e.type+"_router"];
  router.notify(e)
}

jsEvent.EventsRouter = function(el) {
   
   if (el.id == '' || typeof el.id == 'undefined' ) {
      if (el == window) {
         el.id = 'window';
      } else {
         el.setAttribute('id','jsEvent'+jsEvent.uid);
         jsEvent.uid++;
      }
   }
   this.el = el.id;
   el.EventsRouter = this;

} ;

jsEvent.EventsRouter.prototype.addListener = function (event, lsnr) {
   if (typeof(this[event+"_router"])=='undefined') {
      if (this.reference_obj) {
         this[event+"_router"] = new jsEvent.EventRouter(this.reference_obj[this.reference_prop], event);
      } else {
         this[event+"_router"] = new jsEvent.EventRouter(this.el, event);
      }
   }
   this[event+"_router"].addListener(lsnr);
}

jsEvent.EventsRouter.prototype.removeListener = function (event, lsnr) {
   if (typeof(this[event+"_router"])=='undefined') {
      return;
   }
   this[event+"_router"].removeListener(lsnr);
}

function removeAllEventHandlers (el) {

   var clearElementProps = [
        'data',
        'onmouseover',
        'onmouseout',
        'onmousedown',
        'onmouseup',
        'ondblclick',
        'onclick',
        'onselectstart',
        'oncontextmenu',
        'onload',
        'onunload',
        'onselectitem'
    ];
    
   if (typeof (el.id) != 'undefined') {
      //alert(el.id);
      for(var c = clearElementProps.length;c--;){
         el[clearElementProps[c]] = null;
         if (el[clearElementProps[c]+"_router"]) {
            //alert(clearElementProps[c]);
            el[clearElementProps[c]+"_router"] = null;
         }
      }  
      el.eventsRouter = null;
   }
   
   // if no element is specified, remove ALL event handlers
   
   else {
       
      for (var i = 0; i < jsEvent.domElements.length; i++) {
         var el = jsEvent.domElements[i];
         //alert(el.tagName);
         for(var c = clearElementProps.length;c--;){
            el[clearElementProps[c]] = null;
            if (el[clearElementProps[c]+"_router"]) {
               //alert(clearElementProps[c]);
               el[clearElementProps[c]+"_router"] = null;
            }
         }  
         el.eventsRouter = null;
      }
      
      jsEvent.domElements = null;
      
   }
   
}
/******************************************************************
 *
 * Image functions
 *
 ******************************************************************/

/**
 *
 * highlightRow
 * 
 * Highlights a row in a table by changing the row class
 *
 * rolEl - a DOM TR element to highlight
 * highlight - indicates whether to highlight (true) or
 *             remove highlight (false)
 */
 
function highlightRow (rowEl, highlight) {
   
   var className = rowEl.className;

   if (highlight == true) {

      rowEl.className = className+" hi";
      
   } else {
      rowEl.className = className.replace(/\s*hi/, "");
      
   }   
}

function highlightButton (buttonEl, color, highlight) {
   
   var className = buttonEl.className;

   if (highlight == true) {      
      buttonEl.className = className + (" "+color+"button_over");      
   } else {
      var regEx = new RegExp("\s*"+color+"button_over");
      buttonEl.className = className.replace(regEx, "");      
   }   
}

/**
 *
 * initRollovers
 * Initializes all <img> tags on a page having the "rollover" class
 * to respond to the mouseover and mouseout actions with the swapImage
 * function (below).  The filename of the image to switch is placed
 * in the onmouseover attribute in the HTML.
 *
 * Example: <img class='rollover' src='first_img.gif' onmouseover='second_img.gif' />
 * 
 *
 */

function initRollovers() {

   var regEx = /.*\n{\n(.*)\n}/gi;
   var rollovers = getElementsByClassName(document.body, 'img', 'rollover');   
   for (var i = 0; i < rollovers.length; i++) {
      var rollover = rollovers[i];
      if (rollover.eventsRouter == undefined) {
         rollover.eventsRouter = new jsEvent.EventsRouter(rollover);
      }
      rollover.overImg = rollover.getAttribute('onmouseover');
      if (typeof(rollover.overImg) == 'function') {
          rollover.overImg = rollover.overImg.toString().replace(regEx,"$1")
      }
      
      rollover.outImg = rollover.src;
      rollover.EventsRouter.addListener('onmouseout',swapImage);
      rollover.EventsRouter.addListener('onmouseover',swapImage);
      rollover.over = false;
   }
   
}

/**
 *
 * swapImage
 * Switches one image file in an <img> tag with another
 * 
 * This function is added to <img> tags with the class of "rollover"
 * when initRollovers is called
 *
 */

function swapImage() {
   if (this.over) {
      this.src = this.outImg;
      this.over = false;
   } else {
      this.src = this.overImg;
      this.over = true;
   }
}

      
/******************************************************************
 *
 * Javascript include functions 
 *
 ******************************************************************/      
 
function include(script_filename, cache) {
   if (cache == false) {
       // Add a querystring to the script to make sure it's not cached
       script_filename += '?' + Math.random(0, 1000) + '=' + Math.random(0, 1000);
   }
   var html_doc = document.getElementsByTagName('head').item(0);
   var js = document.createElement('script');
   js.setAttribute('language', 'javascript');
   js.setAttribute('type', 'text/javascript');
   js.setAttribute('src', script_filename);
   html_doc.appendChild(js);
   return false;
}

// If this is being loaded into the top frameset, load the frameset.js
if (window == top) {
   include ("/includes/js/frameset.js");
}

function showMainPage(force) {
	if (top.mainPage && (force == true || window.parent == top.mainPage.mainframe.middle) && top.mainFrameset.visiblePages == SONG) {
		top.mainFrameset.showPage(MAIN);
	}
}

function showSongPage() {
	if (top.mainPage && window.parent == top.mainPage.mainframe.middle && top.mainFrameset.visiblePages == MAIN) {
		top.mainFrameset.showPage(SONG);
	}
}

function addWaitMask() {
    
    var maskDiv = document.createElement('div');
    maskDiv.id = 'waitMask';
    maskDiv.style.display = 'none';
    maskDiv.innerHTML = "<table width='100%' height='100%'><tr valign='middle'><td align='center'><img id='pleaseWaitLogo' src='/images/one_moment_please.gif'></td></tr></table>";
    document.body.appendChild(maskDiv);
    
    //objMyImg = new top.OpacityObject('waitMask','/common/images/dark_mask', document);
    objMyImg = new window.OpacityObject('waitMask','/common/images/dark_mask', document);
    objMyImg.setBackground();    
    
}

function toggleWaitMask(state, nologo) {
    if (state == true) {
        document.getElementById('waitMask').style.display = 'block';
        if (nologo != true) {
            document.getElementById('pleaseWaitLogo').style.display = '';
        } else {
            document.getElementById('pleaseWaitLogo').style.display = 'none';
        }
    } else {
        document.getElementById('waitMask').style.display = 'none';
        if (nologo != true) {
            document.getElementById('pleaseWaitLogo').style.display = 'none';
        } else {
            document.getElementById('pleaseWaitLogo').style.display = '';
        }
    }
}

window.eventsRouter = new jsEvent.EventsRouter(window);
window.eventsRouter.addListener('onload',initRollovers);
//window.eventsRouter.addListener('onload',addWaitMask);
//window.eventsRouter.addListener('onload',showMainPage);
window.eventsRouter.addListener('onunload',removeAllEventHandlers);
