/** 
 * This function gathers parameters and sends a request to the php script for database information  
 */
function searchCatalog() {
		
	setOpacity(40,'programlist');                // Set opacity

	document.getElementById('loadinggif').innerHTML = '<img style="margin-top:20px" src="/templates/common/imx/icons/loading.gif" />';
	myEffects('appear','loadinggif',.1);	
	var and_vals = '&'; 
	var andItems = new Array('division_id','program_level','location');
	
	for(var i = 0 ; i < andItems.length ; i++) {
       	if(document.getElementById(andItems[i]).value) {
			and_vals += document.getElementById(andItems[i]).value + '&'; 
		}	
	}	
	
	if(document.getElementById('personality').value!='')      { and_vals += 'personality=' + document.getElementById('personality').value + '&'; }	        // Add personality		
	if(document.getElementById('area_of_interest').value!='') {	and_vals += 'areaofinterest=' + document.getElementById('area_of_interest').value + '&'; }	// Add Area of Interest
	and_vals += 'myfilters=' + document.getElementById('myfilters').value.replace(/\&/g,'ampers_and') + '&'; // Add the filters for caching
	
	and_vals += 'start=' + document.getElementById('start').value + '&'; // Set starting point
		
       str   = and_vals;
       //alert(str);
       // Send the stuff on over to the url
	var myobj = fetchObj();
       myobj.open("POST", '/catalogsearch/php/xt-catalogsearch.php', true);
       myobj.onreadystatechange = function() {
		if(myobj.readyState == 4) {
			//alert(myobj.responseText);
		
			var myhtml = myobj.responseText.split('^ajax^');
		
			/** 
			 *  Re-write menus
			 */
			if(document.getElementById('active').value==1) {
				var reset = /Unset Filter/;
				var lis = /li>/;
				if(lis.test(myhtml[1])) { document.getElementById('div_program_level').innerHTML    = myhtml[1]; }
				if(lis.test(myhtml[2])) { document.getElementById('div_location').innerHTML         = myhtml[2]; }
				if(lis.test(myhtml[3])) { document.getElementById('div_division_id').innerHTML      = myhtml[3]; }
				if(lis.test(myhtml[4])) { document.getElementById('div_personality').innerHTML      = myhtml[4]; }
				if(lis.test(myhtml[5])) { document.getElementById('div_area_of_interest').innerHTML = myhtml[5]; }
				document.getElementById('searchStats').innerHTML 									= myhtml[6]; 
			}

			/** 
			 * Set new contents for div
			 */
			//document.getElementById('programlist').innerHTML = myobj.responseText;
			document.getElementById('programlist').innerHTML = myhtml[7];
			//document.getElementById('programlist').innerHTML = myhtml[8];
			
			/**
			 * Conditionally show the custom ad-banners
			 */
			if(trim(myhtml[8])) {
				//alert(myhtml[8]);
				document.getElementById('custombanners').innerHTML          = myhtml[8];
				document.getElementById('custombanners').style.minHeight    = '100px';
				document.getElementById('globalbanners').style.marginBottom = '10px';    // Add margin to global banners div
			}
			else {
				document.getElementById('custombanners').innerHTML          = '';
				document.getElementById('custombanners').style.minHeight    = '0px';
				document.getElementById('globalbanners').style.marginBottom = '0px';    // Remove margin from global banners div
			}	
			
			/**
			 * Write hiddden div for count of custom adbanners
			 */
			document.getElementById('adcustomhid').innerHTML = myhtml[9];
			
			//myEffects('appear','programlist',.01)
			
			document.getElementById('loadinggif').innerHTML  = '';
			setOpacity(100,'programlist'); // Reset programlist opacity
			
			window.location='#'; // Go to the results proper
			myobj = null;
		} // if(request.readyState == 4)
       }
       myobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       myobj.send(str);
}

/* ------------------------------------ This function is for setting and unsetting the filter flags ------------------------------------ */
function setFilter(div,myparam,mytext,ANDLogic) { 
	
	// Set the active flag in order to shuffle/re-write menus
	document.getElementById('active').value=1;
	
	//myEffects('slideUp',div,.3);
	//myEffects('slideDown',div + '_unset',.5);
	//alert(div + '|' + myparam + '|' + mytext);
	
	// Only do this for the 'AND' logic filters because only one of those can be set at any one time
	
	// Current filter
	var str    = document.getElementById('myfilters').value;
	var addnew = true;
	
	if(ANDLogic) {
		//document.getElementById('div_' + div).innerHTML = '<span class="unsetFilter"><a style="cursor:hand;cursor:pointer" onclick="unsetFilter(\'' + div + '\',' + '\'' + myparam + '\',\'' + mytext +'\'' + ')">[unset filter]</a></span>';
    	//document.getElementById('div_' + div).innerHTML = '<div class="search-li"><ul><li><a style="cursor:hand;cursor:pointer" onclick="unsetFilter(\'' + div + '\',' + '\'' + myparam + '\',\'' + mytext +'\'' + ')">[Unset Filter]</a></li></ul></div>';
    	document.getElementById('div_' + div).innerHTML = '<div class="search-li"><ul><li><a style="cursor:hand;cursor:pointer" onclick="unsetFilter(\'' + div + '\',' + '\'' + myparam + '\',\'' + mytext +'\'' + ')">[Unset Filter]</a></li></ul></div>';
    }
	else {
		var currentFilters = document.getElementById('myfilters').value.split('|');

		// Ensure no duplicates
		for(var i = 0; i < currentFilters.length ; i++ ) {
			addnew = currentFilters[i] == div + '^' + myparam + '^' + mytext? false:addnew;
		}
	}
	// Make the filter string
	if(addnew) {
		if(str != '') {
			str += '|' + div + '^' + myparam + '^' + mytext;
		} else {
			str =  div + '^' + myparam + '^' + mytext;
		}		
	}
	
	// Store filter
	document.getElementById('myfilters').value = str;
	
	// List the filters
	listFilters();
	
	setTimeout(searchCatalog,50);
}


/* ------------------------------------ Remove the set filter and requery the database ------------------------------------ */
function unsetFilter(div,myparam,mytext) { 
	// Set the active flag in order to shuffle/re-write menus
	document.getElementById('active').value=1;

	// Remove the filter string from current
	var currentFilters = document.getElementById('myfilters').value.split('|');
	var newFilters     = '';
	
	// This is the string I am removing from the string
	var togo = div + '^' + myparam + '^' + mytext;
	
	// Execute the removal
	for(var i = 0; i < currentFilters.length ; i++ ) {
		if(currentFilters[i] != togo && currentFilters[i] != '') {
			newFilters = newFilters == ''? currentFilters[i]:newFilters + '|' + currentFilters[i];
    	}
	}	
	// Store filter
	document.getElementById('myfilters').value = newFilters;
	
	// Clear the parameter from the div in question
	switch(div) {
		case 'personality':
		case 'area_of_interest':
			var currentValues = document.getElementById(div).value.split('|');
			var newValues     = '';
		
			for(var i = 0; i < currentValues.length ; i++) {
				if(currentValues[i] && currentValues[i] != myparam) {
					newValues = newValues == ''? currentValues[i]:newValues + '|' + currentValues[i];
				}	
			}	
			document.getElementById(div).value = newValues;
		break;
		default: 
	    	document.getElementById(div).value = '';
    }
		
	
	// List the filters
	listFilters();
	
	// Re-call the searchCatalog() routine
	searchCatalog();
}

/* ------------------------------------ List filters ------------------------------------ */
function listFilters() {
	var myhtml    = '<div id="selectedFilters"><ul>';
	
	var libottommargin = '0px';
	var redgiftop      = '3px';
	
	if(navigator.userAgent.indexOf('MSIE 6.0') > 0) {
		var libottommargin = '4px';
		var redgiftop      = '2px';
	}
	else if (navigator.userAgent.indexOf('MSIE 7.0') > 0) {
		var redgiftop      = '2px';
	}
	
	if(document.getElementById('myfilters').value == '') {
		myhtml = '<div style="color:#686868;font-weight:bold;font-size:12px;">Click to Add a Filter:</div>';
	} 
	else {	
		var myfilters = document.getElementById('myfilters').value.split('|');
		for(var i = 0 ; i < myfilters.length ; i++) {
		
			var myinfo = myfilters[i].split('^');
			if(myinfo[2] != '') {
				myhtml = myhtml + '<li style="margin-bottom: ' + libottommargin + ';"><a style="cursor:hand;cursor:pointer" onclick="unsetFilter(\'' + myinfo[0] + '\',\'' + myinfo[1] + '\',\'' + myinfo[2] + '\')"><img style="margin-right:5px; position:relative;top: ' + redgiftop + ';" src="/templates/common/imx/icons/graphic_delete_red.gif" /></a>' + myinfo[2] + '</li>';
			}
		}
		//alert(myhtml);
		if(trim(myhtml)!='') {
			myhtml = '<div style="color:#686868;font-weight:bold;font-size:12px;">Selected Filters:</div>' + myhtml;
		} else {
			myhtml = '<div style="color:#686868;font-weight:bold;font-size:12px;">Click to Add a Filter:</div>';
		}
	}
	
	var litags = /<\/li>/;
	
	if(litags.test(myhtml)) { myhtml += '</ul></div>'; } // Close ul and div tags
		
	// Write the filter information
	document.getElementById('div_filters').innerHTML = myhtml;
	
	// Reset the navigation counter
	document.getElementById('start').value=0;
	//alert(55);
	
	// Ensure menus are open
	$('#menupixeline').css('display','');
	$('#menu_programs').css('display','');
	$('#menu_classes').css('display','none');
	$('#viewing-programs').attr('checked',true);
}

/* ------------------------------------ Set the OR values for Personality and Areaof Interest ------------------------------------ */
function setORValue(div,val) {
	
	var addnew         = true;
	var currentFilters = document.getElementById(div).value.split('|');
	var str            = document.getElementById(div).value;
	
	// Ensure no duplicates
	for(var i = 0; i < currentFilters.length ; i++ ) { addnew = currentFilters[i] == val? false:addnew; }
		
	if(addnew) {
		if(str != '') { str += '|' + val; } else { str = val; }		
	}	
	
	document.getElementById(div).value = str;
}	

/*----------------------------------------------------------------------------------------------------------------------------------*/

/**
 * Remove the set filters and view all
 */
function viewAll(cat) {
	
	document.getElementById('active').value=1;     // Set the active flag in order to shuffle/re-write menus
	
	var currentFilters = document.getElementById('myfilters').value.split('|');	
	var newFilters     = '';

	switch(cat) {
		case 'program_level':    var remove = /program_level/;    break;	
		case 'location':         var remove = /location/;         break;	
		case 'division_id':      var remove = /division_id/;      break;	
		case 'area_of_interest': var remove = /area_of_interest/; break;
		case 'personality':      var remove = /personality/;      break;	
	}	
	
	for(var i = 0; i < currentFilters.length ; i++ ) {		 // Execute the removal
		if(!remove.test(currentFilters[i])) {
			newFilters = newFilters == ''? currentFilters[i]:newFilters + '|' + currentFilters[i];
		}
	}	
	
	document.getElementById(cat).value = ''; 				  // Clear the hidden value
	document.getElementById('myfilters').value = newFilters;  // Store filter
	listFilters();	    									  // List the filters
	searchCatalog();										  // Re-query
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

/**
 * This does the swap between the programs and classes requests
 */
function switchView(showme) {
	//alert(navigator.userAgent);
	$('#menupixeline').css('display','');
	
	if(navigator.userAgent.indexOf('MSIE 6.0') > 0) {
		var showEffect = 'slideDown';
		var hideEffect = 'slideUp';
	}
	else {
		var showEffect = 'appear';
		var hideEffect = 'fade';	
	}	
	//alert(showme);
	switch(showme) {
		case 'schedules':
				document.getElementById('socialBookMarks').style.visibility = 'hidden'; // Hide social bookmarks
				myEffects(showEffect,'menu_classes',.5);
				myEffects(showEffect,'scheduleResults',.5);
				myEffects(hideEffect,'catalogResults',.5);
				myEffects(hideEffect,'menu_programs',.5);
				if(document.getElementById('tipsopen').value=='y') { myEffects('blindUp','tooltips',.5); }
				myEffects(showEffect,'disclaimer',.5);
				try{ document.getElementById('rightCell').style.display = 'none'; } catch(err) {} // Toggle right cell
				document.getElementById('centerCell').style.borderRight = '0px';
				$('#menu_programs').css('display','none');
				$('#menu_classes').css('display','');
		break;
		case 'programs':
				setTimeout("document.getElementById('socialBookMarks').style.visibility = 'visible'",600); // Show social bookmarks
				myEffects(showEffect,'menu_programs',.5);
				myEffects(hideEffect,'menu_classes',.1);
				myEffects(showEffect,'catalogResults',.5);
				if(document.getElementById('tipsopen').value=='y') { myEffects('blindUp','tooltips',.5); }
				//myEffects(hideEffect,'disclaimer',.5); 
				myEffects(hideEffect,'scheduleResults',.1);
				setTimeout(rebuildTable,100);
				$('#menu_programs').css('display','');
				$('#menu_classes').css('display','none');
				/*
				*/
		break;
	}
	function rebuildTable() {
		try{document.getElementById('rightCell').style.display      = 'block';}	catch(err) {   // Toggle right cell - IE
			document.getElementById('rightCell').style.display      = 'table-cell';             // Toggle right cell - Firefox
		}
			document.getElementById('centerCell').style.borderRight = '1px solid #cccccc'; // Restore border
	}	
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

/**
 * Fetch schedules drop down
 */
function schedules(semester) {
	setOpacity(40,'dropdowncell');                          // Set opacity
	document.getElementById('disclaimer').innerHTML = '';   // Remove connectND disclaimer
	
	document.getElementById('loadinggif_schedule').innerHTML = '<img style="margin-top:100px" src="/templates/common/imx/icons/loading.gif" />';
			
	var str = '&semester=' + semester + '&crscat=' + document.getElementById('subject').value;
       //alert(str);
       // Send the stuff on over to the url
	var myobj = fetchObj();
       myobj.open("POST", '/catalogsearch/php/xt-schedules.php', true);
       myobj.onreadystatechange = function() {
		if(myobj.readyState == 4) {
			//alert(myobj.responseText);
			
			document.getElementById('dropdowncell').innerHTML     = myobj.responseText; // Write results back
			document.getElementById('loadinggif_schedule').innerHTML = '';                       // Remove loading gif
			setOpacity(100,'dropdowncell');                                                      // Set opacity
			
			if(trim(document.getElementById('subject').value)) {	                             // Update schedules table if there is already a subject selected
				try { setTimeout(getSchedules,250); } catch(err) {}
			}
			else {
				window.location = '#'; // Go to the results proper
			}
			myobj = null;
		} // if(request.readyState == 4)
       }
       myobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       myobj.send(str);
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

/**
 * Fetch subject schedules on request
 */
function getSchedules() {
	setOpacity(40,'schedule_bottom');                // Set opacity
	document.getElementById('loadinggif_schedule').innerHTML = '<img style="margin-top:100px" src="/templates/common/imx/icons/loading.gif" />';
	
	var str = '&crscat='   + document.getElementById('subject').value + 
	          '&semester=' + document.getElementById('semester').value +
			  '&starttime=' + document.getElementById('starttime').value +
			  '&offered=' + document.getElementById('offered').value +
			  '&subject='  + document.getElementById('subject_text').value.replace(/\&/g,'ampers_and');

	// Send the stuff on over to the url
	var myobj = fetchObj();
	switch(document.getElementById('subject').value) {
		case 'ALL': myobj.open("POST", '/catalogsearch/php/xt-getSchedules-All.php', true); break;
		default:    myobj.open("POST", '/catalogsearch/php/xt-getSchedules.php', true);
	}
	myobj.onreadystatechange = function() {
		if(myobj.readyState == 4) {
			//alert(myobj.responseText);
			var myresults = myobj.responseText.split('^ajax^');
			document.getElementById('schedule_bottom').innerHTML     = myresults[0];                 // Write results back
			//if(document.getElementById('keycell').innerHTML=='') { document.getElementById('keycell').innerHTML             = myresults[1]}; 	             // Write the key												   
			document.getElementById('keycell').innerHTML             = myresults[1]; 	             // Write the key												   
			setOpacity(100,'schedule_bottom');                                                       // Set opacity
			document.getElementById('loadinggif_schedule').innerHTML = '';                           // Remove loading gif
			window.location = '#';                        						                     // Go to the results proper				
			document.getElementById('subselect').selectedIndex = 0;
			document.getElementById('starttime').value = '';
			myobj = null;
		} // if(request.readyState == 4)
	}
	myobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	myobj.send(str);
}	

/**
 * Toggle the tips for using the search tool
 */
function toggleTips(ask) {
	
	switch(ask) {
		case 'open':
		    myEffects('blindDown','tooltips',.4);            // Show tips
			//myEffects('blindUp','scheduleResults',.4);
			//myEffects('blindUp','catalogResults',.4);
			document.getElementById('tipsopen').value = 'y'; // Set 
		break;
		case 'close':
		    myEffects('blindUp','tooltips',.4);
			//myEffects('blindDown','scheduleResults',.4);
			//myEffects('blindDown','catalogResults',.4);
			document.getElementById('tipsopen').value = 'n';
		break;
	}
}

/**
 * Fade adbanners in and out
 */
function fadeBanners(showme,myobject) {
	var piccount        = parseInt(document.getElementById(myobject + 'Count').value);
	var showduration    = 10000;
	//alert(parseInt(document.getElementById(myobject + 'Count').value)); 
		
	if(parseInt(document.getElementById(myobject + 'Count').value) > 1 && parseInt(document.getElementById('swapbanner').value)) {
		
		document.getElementById('currentBanner').value = myobject; // Debugging line
		
		document.getElementById('swapbanner').value = 0; // Hold session
		showme         = parseFloat(showme);
		var showEffect = 'appear';	
		var hideEffect = 'fade';	
		var tohide     = (showme-1);
		if(tohide < 0) { tohide = piccount -1; }

		//myEffects(hideEffect,myobject + tohide, .85);
		Effect.Fade(myobject + tohide, { duration:.85, from:1.0, to:0 }); 
		
		setTimeout(showit,850);   // Show the next image
		setTimeout(loopit,showduration); // Continue the loop
	}
	else {
		setTimeout("fadeBanners('" + showme + "','" + myobject + "')",1500);
	}
	function showit() { myEffects(showEffect,myobject + showme, 2); }
	function loopit() { 
		document.getElementById('swapbanner').value = 1;
		var nextpic = parseInt(showme) + 1; 
	
		if(nextpic == parseInt(document.getElementById(myobject + 'Count').value)) { nextpic = 0; } // Ensure tnext image is set and valid
		document.getElementById('currentBanner').value = document.getElementById('currentBanner').value + '|' + nextpic + '(' + parseInt(document.getElementById(myobject + 'Count').value) + ')';  // Debugging line
		
		setTimeout("fadeBanners('" + nextpic + "','" + myobject + "')",1500); 
	}
}

/**
 * Fetch programs for the department
 */	
function divisionPrograms(dept,mymode,start) {

	if(document.getElementById('divprogsReady').value=='1') {
	
	document.getElementById('divprogsReady').value = 0;
	
	var str   = '&dept=' + dept + '&mymode=' + mymode + '&start=' + start;
	var myobj = fetchObj();
    myobj.open("POST", '/academics/php/xt-divisionPrograms.php', true);
	myobj.onreadystatechange = function() {
		if(myobj.readyState == 4) {
			//alert(myobj.responseText);
			document.getElementById(mymode + dept).innerHTML = myobj.responseText;  
			document.getElementById('divprogsReady').value = 1;
			myobj = null;
		} // if(request.readyState == 4)
	}
	myobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	myobj.send(str);
	}
	else {
		document.getElementById(mymode + dept).innerHTML = '<img style="margin-top:100px" src="/templates/common/imx/icons/loading.gif" />';
		setTimeout("divisionPrograms('" + dept + "','" + mymode + "','" + start + "')",100);
	}	
}	

/**
 * Show and hide rows
 */	
function showHideRows(rowtype){
	var myrows = $('#myrows').html().split('|');
	
	var c = 0; var bgcolor = '';
	var count = 0;
	if(trim(rowtype)){
		for(var i = 0; i < myrows.length ; i++){
			bgcolor = (c++%2)? '#E2E2E1':'#FFFFFF'; // Alternate row color
			if(myrows[i].indexOf(rowtype) > -1) {
				var tdtoken = myrows[i].split('_');
				for(var j = 0 ; j < 11 ; j++){     // Alternate row colors but do not re-color the cancelled and closed rows
					if($('#' + tdtoken[1] + j).attr('style').indexOf('ff6600') < 0 && $('#' + tdtoken[1] + j).attr('style').indexOf('ffcc33') < 0){
						$('#' + tdtoken[1] + j).css('background-color',bgcolor);
					}
				}
				$('#' + myrows[i]).css('display',''); // Display the row
				count++; // Increment class counter
			}
			else {
				c++; // Increase color counter
				$('#' + myrows[i]).css('display','none'); // Hide the row
			}
		}
	} 
	else { 
		for(var i = 0; i < myrows.length ; i++){ 
			var tdtoken = myrows[i].split('_'); bgcolor = (c++%2)? '#E2E2E1':'#FFFFFF'; // Alternate row color
			for(var j = 0 ; j < 11 ; j++){
				if($('#' + tdtoken[1] + j).attr('style').indexOf('ff6600') < 0 && $('#' + tdtoken[1] + j).attr('style').indexOf('ffcc33') < 0){
					$('#' + tdtoken[1] + j).css('background-color',bgcolor);
				}
			} 
			$('#' + myrows[i]).css('display','');		
			count++; // Increment class counter	
		} 
	}
	$('#classcount').html(count);
}
