/* Time-stamp: <[ap2007.js] last modified by N. Sussman at 15:43:47 on Tuesday, July 31, 2007 using iLab workstation 5M8DLC1-NYO> 
** Notes:
** append ?tabFocus=stackUp to force the stackup tab to have focus when the page loads
*/
var LIBRARY = {
  setUpBalloons : function (list){
    for (var i=0; i< list.length; i++){
      this.makeBalloonTrigger(list[i]);
    }
  },
  makeBalloonTrigger : function (helpTriggerEl) {
    /* because the triggers are all links, I can't append the popup to the trigger 
       (because then the whole popup will be a link) so I wrap the trigger in a div
     */
    var wrapper = document.createElement('div');
    var balloon = document.createElement('div');
    helpTriggerEl.parentNode.insertBefore(wrapper, helpTriggerEl);
    wrapper.appendChild(helpTriggerEl);
    var helpTrigger = wrapper;
    helpTrigger.onmouseover = helpPopup;
    /*
    **  onmouseover for the FIRST time only
    */
    function helpPopup () {
      var helpText = LIBRARY.getElementsByClassName(this.parentNode, 'div', 'popup')[0];
      var headline = document.createElement('h1');  //this h1 and its copy probably should be in the markup
      var nipple = document.createElement('div');
      helpTrigger.appendChild(balloon);
      headline.innerHTML = 'How important is this?';
      nipple.className = 'nipple';
      helpText.insertBefore(headline, helpText.firstChild);
      balloon.appendChild(helpText);
      balloon.appendChild(nipple);
      balloon.style.visibility = 'hidden';
      helpText.className='whatThisMeans';
      balloon.className='balloon';
      balloon.style.marginTop = balloon.style.marginTop - balloon.clientHeight - 13 + 'px';
      balloon.style.visibility = '';
      helpTrigger.onmouseout = helpUnpop;
      //if ie6- then links inside divs that have transparent backgrounds aren't clickable.  There are workarounds for this, but none that seem to work here.  So let the hacks begin!
/*       if( is_ie6down ){ */
/* 	balloon.onclick = function(){ */
/* 	  if (helpText.getElementsByTagName('a').length > 1) { */
/* 	    //the first link in helpText is the named anchor */
/* 	    //the second link should be the 'learn more' link */
/* 	    ///	    alert(helpText.getElementsByTagName('a').length); */
/* 	    document.location = helpText.getElementsByTagName('a')[1].href; */
/* 	  } */
/* 	} */
/*       } */
      //end if ie6-
    }
    /*
    ** onmouseout
    */
    function helpUnpop () {
     balloon.style.display = 'none';
      //onmouseover AFTER the first time
      helpTrigger.onmouseover = function () {
	balloon.style.display = 'block';
	helpTrigger.onmouseout = helpUnpop;
      }
    }
  },
  makeFadeOnFocus : function (idOrEl) {
    var el = (typeof idOrEl == 'string' ? document.getElementById(idOrEl) : idOrEl);
    el.fade = this.fadeBehavior;
    el.onmouseover = function  (e) {
      var event = e || window.event;
      //     document.getElementById('bread').innerHTML = 'i has a fade';
      this.fade.down();
      //kludge
      document.getElementById('column-two').className = 'over';
      /* stop the event from bubbling up past here, 
	 or else it would trigger the fade up event on the BODY tag, 
	 and it would look like nothing happened.
	 see 'PPK On JavaScript,' p. 314 
      */
      if (event.stopPropagation) {
	event.stopPropagation();
      } else {
	event.cancelBubble = true;
      }
    }
  },
  undoFadeOnFocus : function (idOrEl) {
 
    /* IE doesnt associate event handlers with OPTIONs, if I put a mouseout action on the Update Profile module,
       it would get triggered when I moused over an OPTION */
    var el = (typeof idOrEl == 'string' ? document.getElementById(idOrEl) : idOrEl);
    el.fade = this.fadeBehavior;
   if (checkProfileForm()) {    	
    	el.onmouseover = function () {
      	//  document.getElementById('bread').innerHTML = 'cancelin the fadez0rx';
          
      	this.fade.up();
     	//kludge
	document.getElementById('column-two').className=' ';
      	}	 
    
    }
  },
  fadeBehavior : {
    fadeThese : ['college-list', 
		 'compare', 
		 'column-one', 
		 'column-one-stackup', 
		 'matches'],
    down: function () {
      this.fader(this.fadeThese, false);
    },
    up : function (list) {
    	this.fader(this.fadeThese, true);
    },
    //fade opacity up if 'direction' is true, fade down if false
    fader : function (list, direction) {
      for (var i=0; i< list.length; i++){
	(direction ? this.fadeUp(list[i]) : this.fadeDown(list[i]));
      }
    },
    fadeDown: function (id) {
      var objToFade = document.getElementById(id);
      //conditional to detect which type of opacity to apply was snagged from http://www.gtalbot.org/DHTMLSection/DynamicOpacity.html
      if(typeof objToFade.style.opacity == "string") {
	objToFade.style.opacity = 0.5;
      } else { 
	//trying to access document.getElementById(id).filters.alpha.opacity throws an error here, I do not know why.  So I don't test to make sure this block only executes for IE, we just always wind up here if opacity isn't available :-p
	objToFade.className += ' faded';
      }
    }, 
    fadeUp : function (id) {
      var objToFade = document.getElementById(id);
      if(typeof objToFade.style.opacity == "string") {
	objToFade.style.opacity = 1;
      } else {
	objToFade.className = objToFade.className.replace(/ faded/, '');
      }
    }
  },
  makeSwitchChartTriggers: function () {
    /* 
       this method EXPECTS MULTIPLE ARGUMENTS, each of which shold be the ID of a trigger
       it should be run onload, to set up the chart switcher links
    */
    
    for (var j=0; j<arguments.length; j++) {
      if (document.getElementById(arguments[j]) == null) continue;
      var links = document.getElementById(arguments[j]).getElementsByTagName('a');
      var preferredChart = this.getCookie(arguments[j]+'_chart');
      for (var i=0; i<links.length; i++) {
	links[i].onclick = this.switchChart;
	links[i].doCookie = this.setCookie;
      }
      if (preferredChart > -1 &&
	  links[preferredChart]) {
	//get cookie and select chart
	links[preferredChart].onclick();
      } else {
	//otherwise, check if the default chart is not reported, and if so, hide it and show the messaging
	//var images = document.getElementById(arguments[j]).parentNode.parentNode.getElementsByTagName('img');
	var chart = this.getElementsByClassName(document.getElementById(arguments[j]).parentNode, 'div', 'generatedChart')[0];
	//	console.debug('chart is',chart, document.getElementById(arguments[j]));
	var images = chart.getElementsByTagName('img');
	if (images[0].className.match(/\bnot-reported\b/)) {
	  /*assume that, if the default chart is not reported, then the JSP will add the hiding class "popup" 
	    to both the chart image and the LI in the scores list.
	    In the future, it would be best not to expect special treatment from the JSP.
	  */
	  this.notReported(images[0]);
	}
      }
    }
  },
  notReported: function (chartEl) {
    var msg = LIBRARY.getElementsByClassName(chartEl.parentNode.parentNode, 'p', 'not-reported')[0];
    chartEl.parentNode.className += ' popup';
    chartEl.parentNode.parentNode.getElementsByTagName('ul')[0].className += ' popup';
    LIBRARY.getElementsByClassName(chartEl.parentNode.parentNode, 'a', 'what')[0].className += ' popup';
    msg.className = msg.className.replace(/\bpopup\b/, '');
  },
  switchChart: function  () {
    clearNotReported(this);
    //    clearNotReported(window.galaxian);
    /*
    ** I assume that the links are in the same order as the corresponding images in the source
    ** some may argue that this is fragile, however I conceive of it as using the HTML as a "semantic" array
    ** since I used the word "semantic," it is therefore the best way ~.^
    */
    var currentSelection = this.parentNode.getElementsByTagName('strong')[0];
    var images = this.parentNode.parentNode.getElementsByTagName('img');
    var tables = this.parentNode.parentNode.getElementsByTagName('table');
    var scoreItems = this.parentNode.parentNode.getElementsByTagName('li');
    //turn the STRONG tag into a link
    var newLink = document.createElement('a');
    newLink.innerHTML = currentSelection.innerHTML;
    newLink.title = currentSelection.title;
    newLink.onclick = arguments.callee;  //Take that, causality!!!
    if (! newLink.doCookie) newLink.doCookie = this.doCookie;
    //workaround as replaceChild is throwing an error here.  no idea why.
    currentSelection.parentNode.insertBefore(newLink, currentSelection);
    currentSelection.parentNode.removeChild(currentSelection);
    /*================================================================
      ==      At this specific point in this function's execution, 
      ==      all of the choices are links, therefore, right now, 
      ==      there are  the same number of images as there are links
      ==      This is NOT the case throughout the entire execution however.
      ================================================================*/
    var links = document.getElementById(this.parentNode.id).getElementsByTagName('a');  //get all of the links in this controller
    if (tables.length != 0) {
      for (var i=0; i < tables.length; i++) {
	if (tables[i].className.match('popup') == null) {
	  tables[i].className += ' popup';
	} else if (links[i] == this) {
	  if (tables[i].className.match(/\bnot-reported\b/) != null) {
	    LIBRARY.notReported(tables[i]);
	  } else {
	    tables[i].className = tables[i].className.replace(' popup', '');
	    /* now to subtract one from the index submitted to the cookie, because there will be one less link in this control when the page loads.  Remember, this block executes after I have turned the previously selected STRONG into an A, and before I have transformed the chosen A into a STRONG. */
	    this.doCookie(this.parentNode.id+'_chart', i-1);  
	  }
	}
      }
    } else {
      for (var i=0; i < images.length; i++) {
	if (images[i].className == '') {
	  images[i].className = 'popup';
	  scoreItems[i].className += ' popup';
	} else if (links[i] == this) {
	  if (images[i].className.match(/\bnot-reported\b/) != null) {
	    LIBRARY.notReported(images[i]);
	  } else {
	    images[i].className = '';
	    scoreItems[i].className = scoreItems[i].className.replace(/\bpopup\b/g, '');
	  }
	  this.doCookie(this.parentNode.id+'_chart', i-1);  	  
	}
      }
    }
    //turn the link just clicked into a STRONG tag
    var strongLink = document.createElement('strong');
    strongLink.innerHTML = this.innerHTML;
    strongLink.title = this.title;
    //replaceChild works just fine /here/ O.o
    this.parentNode.replaceChild(strongLink, this);
    return false;
    
    function clearNotReported (triggerEl) {
      var container = triggerEl.parentNode.parentNode;
      var msgContainers = LIBRARY.getElementsByClassName(container, 'p', 'not-reported');  //very BAD to use literal string 'LIBRARY' here
      if (msgContainers.length == 0) {
	return false; 
      }
      var msg = msgContainers[0];
      var chartContainer = LIBRARY.getElementsByClassName(container, 'div', 'generatedChart')[0];
      chartContainer.className = chartContainer.className.replace(/\bpopup\b/, '');
      container.getElementsByTagName('ul')[0].className = container.getElementsByTagName('ul')[0].className.replace(/\bpopup\b/, '');;
      LIBRARY.getElementsByClassName(container, 'a', 'what')[0].className = LIBRARY.getElementsByClassName(container, 'a', 'what')[0].className.replace(/\bpopup\b/, '');
      if (msg.className.match(/\bpopup\b/) == null) {
	msg.className = msg.className  += ' popup';
      }
    }
  },
  switchToTrack: function () {
 
    var that = this;
    return function () {
      document.getElementById('column-one-stackup').className = 'popup';
      document.getElementById('column-one').className = '';
      that.setCookie('tabFocus', 'onTrack');
      return false;
    }
  },
  switchToStackUp: function () {
    
    var that = this;
    return function () {
      document.getElementById('column-one-stackup').className = '';
      document.getElementById('column-one').className = 'popup';
      that.setCookie('tabFocus', 'stackUp');
      return false;
    }
  },
  setIEHoverState :  function (id,tagname) {  //fix the :hover pseudoclass in IE6-
    el = document.getElementById(id);
    if(el) {
      tn = el.getElementsByTagName(tagname);
      for(i=0;i<tn.length;i++){
	tn[i].onmouseover= function(){
	  this.className ? this.className += ' over' : this.className = 'over';
	}
	tn[i].onmouseout = function(){
	  this.className = this.className.match(/ over/) ? this.className.replace(/ over/,'') : this.className.replace(/^over/,'');
	}
      }	
    }
  },
  setCookie: function ( id, value) {
    document.cookie = id+'='+value+';path=/;expires='+cookieTime(365);
  },
  getCookie: function( id, defaultValue ) {
    var re          = new RegExp(id+'=(.*)');
    var value       = re.exec(document.cookie);
    return (value) ? value[1].split(';')[0] : defaultValue;
  },
  getElementsByClassName : function (oElm, strTagName, oClassNames){  //supports multiple classes  --  gratefully copied from http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
      for(var i=0; i<oClassNames.length; i++){
	arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
      }
    }
    else{
      arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
      oElement = arrElements[j];
      bMatchesAll = true;
      for(var k=0; k<arrRegExpClassNames.length; k++){
	if(!arrRegExpClassNames[k].test(oElement.className)){
	  bMatchesAll = false;
	  break;
	}
      }
      if(bMatchesAll){
	arrReturnElements.push(oElement);
      }
    }
    return (arrReturnElements)
  }
} 
/* initialize at window.onload */
appendToFunctionArray(
     function() {
     

		      
  /* simulate li:hover in IE6- */
  if(is_ie5up && is_ie6down){ 
    LIBRARY.setIEHoverState('stnav','li');
    LIBRARY.setIEHoverState('stnav-stackup','li');
  }
  
  /* Tab event handers
     this could be _much_ cleaner, and so could the associated HTML (I could have done with only one set of tabs, for instance), but deadline looms and I just want to KEEP IT WORKING --N.S. at 5:42:53 PM EST on Monday, May 21 2007*/
  document.getElementById('ontrackTrigger').onclick = LIBRARY.switchToTrack();
  document.getElementById('stackupTrigger').onclick = LIBRARY.switchToStackUp();
  document.getElementById('ontrackTrigger-stackup').onclick = LIBRARY.switchToTrack();
  document.getElementById('stackupTrigger-stackup').onclick = LIBRARY.switchToStackUp();
 
  //focus the Stack Up tab if the cookie or parameter says so
  //I have not provided a way to explicitly focus the On Track tab
  if( document.location.search.indexOf('pg=1') == -1 && 
      (document.location.search.indexOf('pg=2') != -1 ||
       LIBRARY.getCookie('tabFocus') == 'stackUp')) {
    document.getElementById('stackupTrigger').onclick();
  } else {
   document.getElementById('ontrackTrigger').onclick();  //set the cookie for the on track tab
  }
  /* SELECT COLLEGE */
  //show the Select College greybox if a parameter is passed
  //  --N.S. at  8:07:27 PM EST on Saturday, July 14 2007   There is also a hardcoded call in the JSP that launches the lightbox onload, so I'm not sure now whether this ever really gets called:
  if( document.location.search.indexOf('selectCollege=true') != -1) {
    //     GB_showCenter("Select College", "../select_college.html", 466, 500);

    //invoking the onload popup this way should force it to appear in the correct vertical position, rather than being stuck tot he top of the viewport.    --N.S. at  1:18:49 PM EST on Saturday, July 14 2007
    document.getElementById('select').getElementsByTagName('a')[0].onclick();
  }
  //popup for How To Convert GPA
  document.getElementById('howToConvert').onclick = function () {
    return popup('http://www.collegeboard.com/html/academicTracker-howtoconvert.html');
  }
  /* for charts that have multiple versions, switch charts when the corresponding link is clicked  */
  LIBRARY.makeSwitchChartTriggers('region', 'testSubject', 'actSubject');
  /* fade the rest of the interface when mousing over Update Profile module */
  LIBRARY.undoFadeOnFocus(document.body);  //workaround for IE, see above
  LIBRARY.makeFadeOnFocus('update-profile');
  LIBRARY.makeFadeOnFocus(document.getElementById('column-two').getElementsByTagName('h3')[0]);
  /* 'what does this mean for me' balloons */
  LIBRARY.setUpBalloons( LIBRARY.getElementsByClassName(document.getElementById('two-column'), 'a', 'what') );
  /****************************************************************
   **   hackage for destroying greybox iframe white bg in IE -- doesn't work as yet
   ****************************************************************/
/*   document.getElementById('select').onclick = function (){ */
/*     document.getElementById('GB_window').childNodes[1].childNodes[0].allowtransparency = 'true'; */
/*   } */

if (!checkProfileForm()) {
	var body = document.getElementById("body").getElementsByTagName('a');
	for (var i=0; i<body.length;i++) {
		if (body[i].parentNode.id != 'buttons') {
			body[i].href = '#';
			body[i].onclick = function() {
				return false;
			}
		}
	}
	var select = document.getElementById('select');
	if (select) {select.getElementsByTagName('a')[0].rel = '';}
	
}			
});  /* end of appendToFunctionArray */
		      
/*
Old scenario implemented by siteworx, Nov 12 2007
Here for backup and testing purposes.


function checkProfileForm(){
	if (p_oForm = document.getElementById('updateProfileForm')) {
		//Academic Profile Form Validation
		if ((p_oForm.English.selectedIndex!=0)
			|| (p_oForm.History.selectedIndex!=0)
			|| (p_oForm.Foreign_Language.selectedIndex!=0)
			|| (p_oForm.Math.selectedIndex!=0)
			|| (p_oForm.Science_total.selectedIndex!=0)
			|| (p_oForm.of_Science_Lab.selectedIndex!=0)
			|| (p_oForm.Social_Studies.selectedIndex!=0)
			|| (p_oForm.Electives.selectedIndex!=0)
			|| (p_oForm.SAT_Critical_Reading.selectedIndex!=0)
			|| (p_oForm.SAT_Math.selectedIndex!=0)
			|| (p_oForm.SAT_Writing.selectedIndex!=0)
			|| (p_oForm.ACT_Composite.selectedIndex!=0)
			|| (p_oForm.ACT_English.selectedIndex!=0)
			|| (p_oForm.ACT_Math.selectedIndex!=0)
			|| (p_oForm.GPA.selectedIndex!=0)
			|| (p_oForm.Class_Rank.selectedIndex!=0)
			|| (p_oForm.AP_Course_Ind[0].checked) 
			|| (p_oForm.AP_Course_Ind[1].checked) 
			|| (p_oForm.SAT_Reasoning_Test.checked)
			|| (p_oForm.SAT_Subject_Test.checked)
			|| (p_oForm.ACT.checked)
			|| (p_oForm.TOEFL.checked)) {
			// Something is filled out in form return true;
		} else {
		// FORM is BLANK
			LIBRARY.fadeBehavior.fader(LIBRARY.fadeBehavior.fadeThese, false);
			var rightRail;
			if (rightRail=document.getElementById('column-two')) {rightRail.className='over';}
			return false;
		}
	}
	
}*/
   
   
   
   
/* New Senario implemented by Siteworx, Nov 19 2007 */
function checkProfileForm(){
	if (p_oForm = document.getElementById('updateProfileForm')) {
		//Academic Profile Form Validation
		if (document.getElementById('greyLeft').value !='true') {return true;}
	} else {
		// FORM is BLANK
		LIBRARY.fadeBehavior.fader(LIBRARY.fadeBehavior.fadeThese, false);
		var rightRail;
		if (rightRail=document.getElementById('column-two')) {rightRail.className='over';}
		return false;
	}
	
}
 

 

