var vCollege = vDegree = vDeadlines = vTests = 'none';
var putHere, trail, loader, doThis = null, doc = {};
var defaultContent, initail = false;
var debug = true;

window.dhtmlHistory.create();

window.onload = function() {
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(yourListener);
	
	if(!initail){
		yourListener(location.hash.replace(/^.*#/, ''));
	};
};

yourListener = function(newLocation, historyData){
	try{
		if(!initail) initail = true;
	
		if( newLocation == "" ){
			vCollege = vDegree = vDeadlinesv= vTests = 'none';
			resetTrial();
			putHere.html( defaultContent );
			$("#pager").hide();
		}
		else{
			getFromHash();	
		
			if( typeof doc[getPos()] == "undefined" ){
				getData();
			}
			else{
				buildTableData(doc[getPos()]);
			};
		};
	}
	catch(e){};
};

$(document).ready(function(){
	try{
		$('#optionsList a')
		.click(function(){
			var el = $(this);
			var opt = doThis = el.attr('rel');
			var val = el.attr('title');
			var txt = el.text();
			
			switch(opt){
				case "colleges":
					vCollege = val;
					break;
				case "degrees":
					vDegree = val;
					break;
				case "tests":
					vTests = val;
					break;
				case "deadlines":
					vDeadlines = val;
					break;
			};
			buildTrial( txt, val );		
			location.hash = getPos();
			return false;
		});
		
		$('#leave')
		.click(function(){
			vCollege = vDegree = vDeadlinesv= vTests = 'none';
			location.hash = getPos();
			buildTrial();	
		});
		
		putHere = $('#putHere');
		trail = $('#trail');
		loader = $('#loader');
		
		
		defaultContent = putHere.html();
	}
	catch(e){};
});

getPos = function(){
	return 	encodeURI(vCollege +'-'+ vDegree +'-'+ vDeadlines +'-'+ vTests);
};

getFromHash = function(){
	if( location.hash ){
		var h = location.hash.replace(/^.*#/, '').split('-');
		vCollege = h[0];
		vDegree = h[1];
		vDeadlines = h[2];
		vTests = h[3];
		
		for( i in h ){
			if({ }.hasOwnProperty.call(h, i)){
				if( h[i] != 'none' ){
					
					if( i == 0 ){
						doThis = "colleges";
					}
					else if( i == 1 ){
						doThis = "degrees";
					}
					else if( i == 2 ){
						doThis = "deadlines"
					}
					else if( i == 3 ){
						doThis = "tests";
					};
					
					var el = $('#optionsList a[href=#'+h[i]+']');
					buildTrial( el.text(),  el.attr('title'));
				};
			};
		};
		
		return true;
	}
	else{
		return false;
	};
};

getData = function(){
	try{
		loader.show();
		var pos = getPos();
		
		if( typeof doc[pos] != "undefined" ){
			buildTableData( doc[pos] );
		}
		else{
			$.ajax({
				dataType 	: 'html',
				data : {
						colleges:(vCollege=='none')?null:vCollege,
						degrees:(vDegree=='none')?null:vDegree,
						deadlines:(vDeadlines=='none')?null:vDeadlines,
						tests: (vTests=='none')?null:vTests
				},
				url		: '../matrix/process.asp',
				success	: function(data){
					doc[pos] = data;
					buildTableData(data);
				},
				error : function(e, a, o){
					try{
						console.log(e);	
						console.log(a);	
						console.log(o);	
						console.log(e.responseText);	
					}catch(e){}
				}
			});
		};
	}
	catch(e){};
};

buildTrial = function( txt, rel ){
	var ext = '';
	var h = location.hash.replace(/^.*#/, '').split("-");
	var doCol = doDeg = doDea = doTes = false;
	var filters = '';
	
	
	if( h[0] != 'none') doCol = true;
	if( h[1] != 'none') doDeg = true;
	if( h[2] != 'none') doDea = true;
	if( h[3] != 'none') doTes = true;
	
	var txt = "You are currently viewing requirements for {[deg]} for {[col]} with {[test]} and {[dead]}";
	
	if( doCol ){
		var el = $('#optionsList a[href=#'+h[0]+']');
		var t = el.text();
		txt = txt.replace('{[col]}', '<span>'+t+'</span>');
		filters =  '<span>' + t + ' <a href="#" rel="colleges" title="'+rel+'">[X]</a>';
	}
	else{
		txt = txt.replace('{[col]}', 'all academic units');
		filters = '';
	};
	
	if( doDeg ){
		var el = $('#optionsList a[href=#'+h[1]+']');
		var t = el.text();
		txt = txt.replace('{[deg]}', 'the <span>'+t+'</span> degree');
		if( filters.length ) filters +=  ',</span> ';
		filters +=  '<span>' + t + ' <a href="#" rel="degrees" title="'+rel+'">[X]</a>';
	}
	else{
		txt = txt.replace('{[deg]}', 'all degrees');
		if( !filters.length ) filters = '';
	};
	
	if( doDea ){
		var el = $('#optionsList a[href=#'+h[2]+']');
		var t = el.text();
		txt = txt.replace('{[dead]}', '<span>'+t+'</span>');
		if( filters.length ) filters +=  ',</span> ';
		filters +=  '<span>' + t + ' <a href="#" rel="deadlines" title="'+rel+'">[X]</a>';
	}
	else{
		txt = txt.replace('{[dead]}', 'any deadlines');
		if( !filters.length ) filters = '';
	};
	
	if( doTes ){
		var el = $('#optionsList a[href=#'+h[3]+']');
		var t = el.text();
		txt = txt.replace('{[test]}', '<span>'+t+'</span>');
		if( filters.length ) filters +=  ',</span> ';
		filters +=  '<span>' + t + ' <a href="#" rel="tests" title="'+rel+'">[X]</a>';
	}
	else{
		txt = txt.replace('{[test]}', 'any test');
		if( !filters.length ) filters = '';
	};
	
	if( filters.length ){ filters += "</span>";}
	else{filters = 'none';};

	
	$('#trail').empty().append(txt).append('<div>Remove Filters: '+filters+'</div>')
	.find('a').click(removeSelection);
	/*
	switch( doThis ){
		case "colleges":
			vCollege = rel;
			var el = $('#collegesEl');
			el.html(txt + ' <a href="#" rel="colleges" title="'+rel+'">[X]</a>')
			.find('a').click(removeSelection);
			break;
		case "degrees":
			vDegree = rel;
			var el = $('#degreesEl')
			el.html(txt + ' <a href="#" rel="degrees" title="'+rel+'">[X]</a>')
			.find('a').click(removeSelection);
			break;
		case "tests":
			vTests = rel;
			$('#testsEl').html(txt + ' <a href="#" rel="tests" title="'+rel+'">[X]</a>')
			.find('a').click(removeSelection);
			break;
		case "deadlines":
			vDeadlines = rel;
			$('#deadlinesEl').html(txt + ' <a href="#" rel="deadlines" title="'+rel+'">[X]</a>')
			
			break;
	};
	*/
};

resetTrial = function(){
	var el = $('#collegesEl,#degreesEl,#testsEl,#deadlinesEl').html('none');
};

removeSelection = function(){
	var c = $(this);
	var r = c.attr('rel');
	var t = c.attr('title');
	var p = c.parent();
		
	switch(r){
		case "colleges":
			vCollege = 'none';
			break;
		case "degrees":
			vDegree = 'none';
			break;
		case "tests":
			vTests = 'none';
			break;
		case "deadlines":
			vDeadlines = 'none';
			break;
	};

	p.text('None');
	location.hash = getPos();
	buildTrial();
	
	return false;
};

buildTableData = function(data){
	try{
		var perm = data;
		
		var arrReq = Array(
							"$60 App Fee",
							"Adm Initial Process Completed",
							"College Transcript 1",
							"College Transcript 2",
							"Copy of Passport ID Page",
							"Critical Thinking Que-MSW",
							"Department Form",
							"Expanded Goals Statement",
							"GMAT Scores",
							"GRE Scores",
							"Internat'l Student Info Sheet",
							"Intl Transcript English Transl",
							"Intl Transcript Evaluations",
							"Letter of Recommendation 1",
							"Letter of Recommendation 2",
							"Letter of Recommendation 3",
							"Nursing License",
							"Portfolio",
							"Praxis I Exam Scores",
							"Resume",
							"Sufficent Funds/Bank Statement",
							"TOEFL or Equivalent",
							"Work Description",
							"Writing Sample"
						   );
		
		var table = $('<table border="0" cellspacing="0" cellpadding="3" id="courseTable">');
		
		var thead = '<thead><tr><th scope="col" class="thProg">Program</th>';
		//thead += '<th scope="col" class="thSchool">School</th>';
		thead += '<th scope="col" class="col3">Degree</th>';
		thead += '<th scope="col" width="20">Credits</th>';
		thead += '<th scope="col" class="col4">Fall Deadline </th>';
		thead += '<th scope="col" class="col5">Spring Deadline </th>';
		thead += '<th scope="col" class="col6">Summer Deadline </th>';
		thead += '<th scope="col">Test Requirements </th>';
		thead += '<th scope="col" width="20"><abbr><span class="abbr" title="Resume">Res.</span></abbr></th>';
		thead += '<th scope="col" width="20"><abbr><span class="abbr" title="Recommendation">Rec.</span></abbr></th>';
		thead += '<th scope="col" width="20">Fee</th>';
		thead += '<th scope="col" width="20"><abbr><span class="abbr" title="Department Form">DF</span></abbr></th>';
		thead += '<th scope="col" width="20"><abbr><span class="abbr" title="Expanded Goal Statement">EGS</span></abbr></th>';
		thead += '<th scope="col" width="20"><abbr><span class="abbr" title="Writing Sample">WS</span></abbr></th>';
		thead += '<th scope="col" class="col13">Other</th>';
		//thead += '<th scope="col" width="20"><abbr title="Nursing Licensure">NL</abbr></th>';
		thead += '</tr>';
		
		var tbody = $("<tbody>");
		
		if( data == "null" ){
			data = '<tr><td colspan="15"><strong>No records with that criteria</strong></td></tr>';
		};
		
		tbody.append(data);
		
		table.append(thead).append(tbody);
		
		putHere.addClass('grid').empty().append(table);
	
	
		if( perm == "null" ){
			$("#pager").hide();
		}
		else{
			$("#pager").show();
			table.tablesorter({
				headers: { 
					3: {sorter: false},
					4: {sorter: false},
					5: {sorter: false} ,
					//6: {sorter: false} ,
					13: {sorter: false} 
				} 
			})
			.tablesorterPager({container: $("#pager"),positionFixed:false,seperator: " of "}); 
		};
		
		//$('abbr').tooltip({delay: 0,showURL: false});
	
		
		loader.hide();
	
	}
	catch(e){};
};

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		};
	};
	return false;
};


$(window).bind("load",function(){
	$('#optionsList').accordion({header:'DT',autoHeight:false,alwaysOpen:false});
});