/* BEGIN gradview.js */

// Begin the code to animate the main navigation and validate the site search.

function cssNavHoverOn(tarDiv) {
  document.getElementById(tarDiv).style.cursor = "pointer";
  document.getElementById(tarDiv).style.backgroundPosition = "0px -38px";
}

function cssNavHoverOff(tarDiv) {
  setTimeout("cssNavHoverAnim('"+tarDiv+"',-38)",1);
}

//David Gilardi 12/11/2007:  Added cssNavTabFlip functions to flip between keyfacts navigation tabs
// Use this function to flip between "on" and "off" tab positions
// If the backgroundPosition = "0px - 30px" then flip to "0px 0px" and vice versa
// The onOff variable will refer to whether the tab icon is "on" or "off"
// with "on" being the currently selected tab
// NOTE:  I kind of overloaded the function with the addition of tabName.  This
// parameter is only relevant for the clicked button so it is only used from
// contect of the clicked button.  I did this to keep from having another 
// function call.
function cssNavTabFlip(tarDiv, onOff, tabName) {
  var position = document.getElementById(tarDiv).style.backgroundPosition;
  //alert(position);

  if (position == "0px 0px" && onOff == 0) {
    document.getElementById(tarDiv).style.cursor = "pointer";
    document.getElementById(tarDiv).style.backgroundPosition = "0px -30px";

  } else if (position == "0px -30px" & onOff == 1) {
    document.getElementById(tarDiv).style.cursor = "pointer";
    document.getElementById(tarDiv).style.backgroundPosition = "0px 0px";

    //Set the value of hub_keyfactsTabInfo based off of tabName
    document.getElementById('hub_keyfactsTabInfo').innerHTML = tabName;

  }

}
//End function add

function cssNavHoverAnim(tarDiv,yPos) {
  // alert(yPos);
  if (yPos == null) {
    yPos = -39;
  } else {
    if (yPos < 1) {
      yPos = yPos+8;
      document.getElementById(tarDiv).style.backgroundPosition = "0px "+yPos+"px";
      setTimeout("cssNavHoverAnim('"+tarDiv+"',"+yPos+")",1);
    } else {
      document.getElementById(tarDiv).style.backgroundPosition = "0px 0px";
    }
  }
}

function validNavSearch() {
  var form = document.navSearchForm;
  if ( form.query.value != null && form.query.value != "" ) {
   
      form.action="/sitesearch/search.jsp";
   
    return true;
  } else {
  
    alert("Please enter a search term.");
    return false;
    
  }
}

// End the code to animate the main navigation and validate the site search.



function wrapLink(targetDiv,setClass) {
  document.getElementById(targetDiv).className = setClass;
}

function validateResponseForm() {
  var alertString = "";
  
  if (document.response.FirstName.value == null || document.response.FirstName.value == "") {
    alertString = alertString + "- First Name\n";
  }
  
  if (document.response.LastName.value == null || document.response.LastName.value == "") {
    alertString = alertString + "- Last Name\n";
  }
  
  if (document.response.Email.value == null || document.response.Email.value == "") {
    alertString = alertString + "- E-mail Address\n";
  } else {
    var varValue = document.response.Email.value;
    var valResult = validRegExp("Email",varValue);
    if (valResult == 1) {
      alertString = alertString + "- Valid E-mail Address\n";
    }
  }
  
  if (document.response.phone.value != null && document.response.phone.value != "") {
	if(!document.response.phone.value.match(/.{0,1}\d{3}.{0,1}\d{3}.{0,1}\d{4}/)){
		alertString = alertString + "If entering a phone number it must be in (###)###-#### format\n";
	}
  }
  
  if (document.response.WhoAmI.value == null || document.response.WhoAmI.value == "") {
    alertString = alertString + "- I Am a\n";
  }
  
  if (document.response.sendTo.value == null || document.response.sendTo.value == "") {
    alertString = alertString + "- Subject\n";
  }
  
  if (document.response.Comments.value == null || document.response.Comments.value == "") {
    alertString = alertString + "- Comments or Questions\n";
  }
  
  if (alertString == null || alertString == "") {
    return true;
  } else {
    alert("Please include the required fields listed below:\n" + alertString)
    return false;
  }
}

function validRegExp(pattern,varValue) {
  var reglist=new Array();
  reglist["Phone"]="\\(\\d{3}\\)\\d{3}-\\d{4}";
  reglist["Email"]="\\w{2,}@(\\w|-){2,}\\.\\w{2,}";
  var x=varValue;
  var y=new RegExp(reglist[pattern]);
  if(y.test(x)) {
    var goodForm = 0;
  } else {
    var goodForm = 1;
  }
  return goodForm;
}

function toggleMessage(target,action) {
  var hidden = target;
  var shown = target + "_full";

  if (action == 0) {
    document.getElementById(hidden).className = "mycv_messageSchoolHolderShow";
    document.getElementById(shown).className = "mycv_messageHolderHide";
  } else if (action == 1) {
    document.getElementById(hidden).className = "mycv_messageSchoolHolderHide";
    document.getElementById(shown).className = "mycv_messageHolderShow";
  }
}

function openWindow(theURL,winName,features) { 
	window.open(theURL,winName,features);
}

var adBaseShade = 0;
function showBaseShade(target) {
  if (adBaseShade != 1) {
    document.getElementById(target).style.visibility = "visible";
    adBaseShade = 1;
  } else {
    document.getElementById(target).style.visibility = "hidden";
    adBaseShade = 0;
  }
}

function tabFeaturedToggle(newActive) {
  for (var i=1; i<5; i++) {
    var newTarget = "section_header_tab_"+i;
    var newDisplay = "section_tab_"+i+"_content";

    if (newDisplay == newActive) {
      document.getElementById(newTarget).className = "section_header_tab_active";
      document.getElementById(newDisplay).style.display = "block";
    } else {
      document.getElementById(newTarget).className = "section_header_tab_inactive";
      document.getElementById(newDisplay).style.display = "none";
    }
  }
}

// This function is necessary to work arounnd the ID "Click to activate issue"
function loadFlashApp(path,width,height) {
  document.write("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='"+width+"' height='"+height+"'>");
  document.write("  <param name='movie' value='"+path+"'>");
  document.write("  <param name='quality' value='high'>");
  document.write("  <embed src='"+path+"' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='"+width+"' height='"+height+"'></embed>");
  document.write("</object>");
}


function friendForm() {
  var mName = document.loungeEmailForm.name1.value;
  var mAddy = document.loungeEmailForm.address1.value;
  var fName = document.loungeEmailForm.name2.value;
  var fAddy = document.loungeEmailForm.address2.value;
  var comments = document.loungeEmailForm.comments.value;
  
  var alertMsg = "";
  
  if (!mName) {
    alertMsg = alertMsg+"- Please include your name\n";
    // highlightFormField("loungeEmailForm","name1");
  }
  if (!mAddy) {
    alertMsg = alertMsg+"- Please include your email Address\n";
  }
  if (!fName) {
    alertMsg = alertMsg+"- Please include your friend's name\n";
  }
  if (!fAddy) {
    alertMsg = alertMsg+"- Please include your friend's email address\n";
  }
  
  if (!alertMsg) {
    return true;
  } else {
    alert(alertMsg);
    return false;
  }
}

function highlightFormField(formName,targetField) {
  document.getElementById(targetField).style.border = "1px solid #ff0000";
  document.getElementById(targetField).style.backgroundColor = "#dddddd";
}

/* All functionality for the Article Rating Tool */

function rateArticlesHover(swapImg,targetImg) {
  var image = new Image();
  image.src = "/_img/"+swapImg;

  document[targetImg].src=image.src;
}

function rateArticles(prodAreaID,rate,articlePath) {
  document.getElementById("rankingHolder").innerHTML="<div class='rankings'><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='150' height='20'><param name='movie' value='/_f/load_rating.swf' /><param name='quality' value='high' /><embed src='/_f/load_rating.swf' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='150' height='20'></embed></object></div>";
  var scoreArticle = getArticleCookie(prodAreaID,rate,articlePath);
  loadArticleXML("/_proc/articleRating.jsp?score="+rate+"&articlePath="+articlePath+"&scoreIt="+scoreArticle);
}

function loadArticleXML(url) {
	req = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() { processRating(); }
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() { processRating(); }
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processRating() {
  if (req.readyState == 4) {
    document.getElementById("rankingHolder").innerHTML=req.responseText;
  }
}

function getArticleCookie(prodAreaID,rate,articlePath) {
	var nameEQ = "HOB100106ARTICLE=";
	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 updateArticleCookie(c.substring(nameEQ.length,c.length),prodAreaID,rate,articlePath);
      }
    }
	}
  if(rate > 0) {
    createArticleCookie(prodAreaID,articlePath);
  }
	return true;
}

function createArticleCookie(prodAreaID,articlePath) {
  var value = prodAreaID +"^"+ articlePath;
  setCookie(value);
}

function updateArticleCookie(currentVals,prodAreaID,rate,articlePath) {
  var value = "";
  var ar = true;
  var cVal = currentVals.split('|');
  for (var x=0; x<cVal.length; x++) {
    var cElem = cVal[x].split('^');
    if(prodAreaID == cElem[0] && articlePath == cElem[1]) {
      ar = false;
      break;
    }
  }
  if(ar && rate > 0) {
    value = currentVals+"|"+prodAreaID+"^"+articlePath;
    setCookie(value);
  }
  return ar;
}

function setCookie(value) {
  var date = new Date();
  date.setTime(date.getTime()+(30*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();
	document.cookie = "HOB100106ARTICLE="+value+expires+";path=/";
}

function saveArticle() {
  var form = document.myGVArticle;
  form.articleUrl.value = location.pathname;
  form.submit();
}

/* END gradview.js */


/* BEGIN adCalls.js */
var _url='';

function getTopBannerAd() {
  if(document.location.pathname.substring(0,30)=="/collegesearch/ViewResults.jsp") {        
      admanager1=new AdManager(324,_url,1);
      admanager1.getAds();         
  } else if(document.location.pathname.substring(0,22)=="/school/school_hub.jsp") {
      admanager1=new AdManager(325,_url,1);
      admanager1.getAds();
  } else if(document.location.pathname.substring(0,7)!="/school" && document.location.pathname!="/" && document.location.pathname!="/index.html") {
      admanager1=new AdManager(301,_url,1);
      admanager1.getAds();  
  } else if(document.location.pathname.substring(0,7)!="/school" && (document.location.pathname=="/" || document.location.pathname=="/index.html")) {
      admanager1=new AdManager(321,_url,1);
      admanager1.getAds();
  }
}

function getMiddleBannerAd() {
  if(document.location.pathname.substring(0,30)=="/collegesearch/ViewResults.jsp") {
      admanager1=new AdManager(326,_url,1);
      admanager1.getAds();         
  }
}

function getRightHandAds() {
  admanager1=new AdManager(322,_url);
  admanager1.getAds();  
}

function getBlockAds() {
  admanager1=new AdManager(341,_url);
  admanager1.getAds();
}

/* END adCalls.js */


/* BEGIN addisplayfunctions.js */

var _baseURL="/_proc/ad_display_controller_limit_number.jsp";

function AdManager(ad_location,url,slots){
	this.slots=slots;
	this.ad_loc=ad_location;
	//temp_loc=(document.location+"").substring("8");
	temp_loc=document.location.pathname;
	
	//this.url=temp_loc;
	if(url==null || url==''){
  		this.url=temp_loc;
	}else{
		this.url=url;
  	}
	this.title=document.title;
  	//alert(this.title);
	this.getAds=_getAds;
	//alert(this.url);
}


function _getAds(){
  try{	
  	var querystring=''
  	try{
    		querystring=location.search.substring(1,location.search.length);
  	}catch(error){ }
  	//alert(querystring);
	//prompt("username",_baseURL+"?slots="+this.slots+"&pageTitle="+this.title+"&url="+this.url+"&location="+this.ad_loc+"&"+querystring,"ad_loc_"+this.ad_loc);
	_loadXMLDoc(_baseURL+"?slots="+this.slots+"&pageTitle="+this.title+"&url="+this.url+"&location="+this.ad_loc+"&"+querystring,"ad_loc_"+this.ad_loc);
  }catch(loadError){  }
}


function _loadXMLDoc(url, locationDiv) 
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() { _processReqChange(locationDiv, req); }
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        var req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() { _processReqChange(locationDiv, req); }
            req.open("GET", url, true);
            req.send();
        }
    }
}

function _processReqChange(locationDiv, req) 
{
    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
			var res=req.responseText;
			var res=res.replace(/\s/g, '');
			
			if(res!='' && res!="<!--0-->"){
			//	alert("Ad=" + res +"*");
				document.getElementById(locationDiv).innerHTML=req.responseText;	    
			}
			
        } else {
            // alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}

/* END addisplayfunctions.js */


/* BEGIN track.js */

/*
 * Created on Mar 3, 2009 by plucas/thoward: fixed CVSITE-2002
 * This function improves upon a previous solution implemented in footer.html and footer1024.html (aka function linkFix).
 * Overview:
 * As an <a> is clicked, this function determines if the link is external (compares hosts).
 * If it is external, then:
 *  1. Its 'target' attribute is changed to '_blank' to open the link in a new window.
 *  2. The URL '/_inc/track_click.jsp' is invoked, which handles the SQL query to store the external link. Note: This JSP was implemented well before this new feature.
 * 
 * For performance reasons, the SQL query is invoked asynchronously. This does require that the link be opened in a new window.
 * At the time this ticket was fixed, this behavior had already been requested and implemented.
 */
 function externalizeLink(eventObject) {
	/*
	 * This regex is compliments of jQuery plugin:
	 * 			http://projects.allmarkedup.com/jquery_url_parser/
	 */
	var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

	var uriInfo = parser.exec(decodeURI(window.location));
	// 0=source, 1=protocol, 2=authority, 3=userInfo, 4=user, 5=password, 6=host, 7=port, 8=relative, 9=path, 10=directory, 11=file, 12=query, 13=anchor
	var serverHost = uriInfo[6];

	// kick off AJAX call to track the click (note: JSP handles both internal and external links, and contains the SQL)
	if (isExternalLink(this.href, serverHost)) {
		ajax_InvokeTrackClick(this.href);
    if(jQuery(this).hasClass('targetSelf')){
      jQuery(this).attr('target', '_self');
    }else{  
  		jQuery(this).attr('target', '_blank');
    }  
	}
}

/*
 * Helper method called by externalizeLink.
 * Params:
 * 		href: The link to be checked (value of 'href' attribute for DOM element <a>)
 *		serverHost: The host of the server (as opposed to the server of 'href' parameter)
 */
function isExternalLink(href, serverHost) {
	/*
	 * This regex is compliments of jQuery plugin:
	 * 			http://projects.allmarkedup.com/jquery_url_parser/
	 */
	var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;

	var linkInfo = parser.exec(decodeURI(href));
	// 0=source, 1=protocol, 2=authority, 3=userInfo, 4=user, 5=password, 6=host, 7=port, 8=relative, 9=path, 10=directory, 11=file, 12=query, 13=anchor
	var hrefSource = linkInfo[0];
	var hrefHost = linkInfo[6];

	// console.log("------------------------------------------");
	// console.log("href = " + href);
	// console.log("serverHost = " + serverHost);
	// console.log("hrefSource = " + hrefSource);
	// console.log("hrefHost = " + hrefHost);
	// console.log("\t" + "hrefHost != serverHost = " + (hrefHost != serverHost));
	// console.log("\t" + "hrefHost != '' = " + (hrefHost != ''));
	// console.log("\t" + "!isStartsWith(hrefSource, '#') = " + !isStartsWith(hrefSource, '#'));
	// console.log("\t" + "!isStartsWith(hrefSource, 'javascript', true) = " + !isStartsWith(hrefSource, 'javascript', true));

	return hrefHost != '' // relative path indicates internal link
			&& !isStartsWith(hrefSource, '#') // intra-page links are certainly internal
			&&  hrefHost != serverHost // hosts must match
			&& !isStartsWith(hrefSource, 'javascript', true); // assume javascript-href is internal
}

/*
 * Helper function called by isExternalLink.
 */
function isStartsWith(str, startsWith, caseSensitive) {
	if (caseSensitive == true) {
		return (startsWith == str.substring(0, startsWith.length));
	} else {
		return (startsWith.toLowerCase() == str.substring(0, startsWith.length).toLowerCase());
	}
}

/*
 * Helper function called by externalizeLink.
 * Encapsulates invocation of URL '/_inc/track_click.jsp'.
 * See discussion in comment for externalizeLink concerning requirements for this call to be made asynchronously.
 * Parameters:
 * 		eventObject: The jQuery event object (generated by the click action)
 */
function ajax_InvokeTrackClick(p_href) {
	// console.log('BEGIN ajax_InvokeTrackClick');
	// console.log('p_href = ' + p_href);

	jQuery.ajax({
		type: "GET",
		async: true,
		url: "/_inc/track_click.jsp",
		dataType: "html",
		data: { href: p_href }
	});
	// console.log('fired call to "/_inc/track_click.jsp?href="' + p_href + '"');
}


/*
 * Explanation:
 * This is our first use of the jQuery live() feature, which allows us to define an event delegate instead of binding to individual elements.
 * This has several benefits:
 * 	1. More scalable. jQuery docs cite this site as a reference: http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/
 *  2. Works better with asynchronous DOM. This is especially important, given that a bind()-based solution would have to be re-invoked whenever the DOM was modified (eg: Keyfacts data on hub page)
 * 
 * Here's how it works:
 * We use live() to register the 'externalizeLink' function on all <a> tags (we do a live binding of ).
 * That method converts the target=_blank for the clicked link only if it's an external link.
 * By converting *each* <a> in DOM, we guarantee that the specific link that was clicked will open in a new window (when browser handles navigation immediately after this method completes).
 */
// as per documentation, live() may only be called on a selector (not individual elements), which is the desired functionality
jQuery('a').live('click', externalizeLink);

/* END track.js */


/* BEGIN comment form validation */

jQuery(document).ready(function() {
	jQuery('#commentform').submit(function(event) {
		var self = jQuery(this);

		var errors = [];

		var domAuthor = self.find('#author');
		if (domAuthor.length > 0) {
			// only validate if input is present (input is omitted when logged in)
			if (domAuthor.val() == '') {
				errors.push('Please provide your name');
			}
		}

		var domEmail = self.find('#email');
		if (domEmail.length > 0) {
			// only validate if input is present (input is omitted when logged in)
			if (domEmail.val() == '') {
				errors.push('Please provide your e-mail (will not be published)');
			} else if (! domEmail.val().match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) {
				errors.push('Please provide a valid e-mail (will not be published)');
			}
		}

		var domComment = self.find('#comment');
		if (domComment.val() == '') {
			errors.push('Please provide a comment');
		}

		if (errors.length > 0) {
			event.preventDefault();
			alert(errors.join('\n'));
		}
	});
});

/* END comment form validation */

