window.addEvent('domready', function() {

	var links;
	var locInj;
	
	function viewportPOS(){
		var winsize=window.getSize();
		$('viewport').setStyles({
    		'top': window.getScroll().y,
			'height':winsize.y-40
  		});
	}
	
	function movePort(parentDIV){
		var vPOS=$('viewport').getCoordinates();
		vPOS=(vPOS.top+vPOS.height)-10;
		var divPOS=parentDIV.getCoordinates().top;							
		if(vPOS<=divPOS)
			var myFx = new Fx.Scroll(window).toElement(parentDIV);
	}

	viewportPOS();
	window.addEvent('scroll', function() {
  		viewportPOS();
	});

	$$(".gradDegreeLink").addEvent('click',function(e){
		e.stop();	
		//get the number from the link (the first array element)
		links=this.getProperty('href').split('#l')[1];
		//the parent should be the table row of the cell clicked
		locInj=this.getParents('tr.gradDegreeRow');
		//check if we need to inject a new table row... class 'i' is used as a flag
		//has to be converted to a string because hasClass returns an object
		var checkInj=String(locInj.hasClass('i'));
		if(checkInj=='false'){
			//add the flag i
			locInj.addClass('i');
			//create and inject new table row and td
			var row=new Element('tr',{'class':'injection'});
			var td=new Element('td',{'colspan':3});
			row.inject(locInj[0],'after');
			td.inject(row);
		}
		//dont send a request if the information is already on the page
		if(!$("added"+links))
			advResp.send('s='+links);
	});


	var advResp=new Request.JSON({
		url:'/academics/feeds/gradadvise.php',
		method:'get',
		onComplete: function(e) {
			//alert(e.name);
			//in case you have an empty response
			if(e.name==null){
				e.email='valerie.lariscy@utdallas.edu';
				e.name='Graduate Studies';
				e.phone='972-883-2228';
				e.other='';
			}
			
			//create a closer link
			var anchorClose=new Element('a',{
				'class':'close',
				'href':'#',
				'html':'Close',
				'events':{
					click:function(e){
						//destroy the div (parent) on click of the closer
						e.stop();
						this.getParent().destroy();
					}
				}
			});
			
			if(e.email!='')
				var jsonStr='<strong>'+e.degree+'</strong><br /><a href="mailto:'+e.email+'">'+e.name+'</a><br />'+e.phone+'<br /><br />'+e.other;
			else
				var jsonStr='<strong>'+e.degree+"</strong><br />"+e.name+'<br />'+e.phone+'<br /><br />'+e.other;
			
			//create a div to add the content from the json response
			var advDiv=new Element('div',{
				'class':'showBlock',
				//flag to ensure the same information is not requested twice. see line 24
				'id':'added'+links,
				'html':jsonStr
				
			});
			
			//inject the closer at the top of the div
			anchorClose.inject(advDiv,'top');
			//scroll to the table row in case it is below the fold and the user does not notice it was injected
			movePort(locInj[0]);
			locInj=locInj[0].getNext().getLast();//[1].get('text'));
			advDiv.inject(locInj);			
		}//end oncomplete
	});
	
});