/*Campain Event section search function JavaScript.  Written by Ari Koinuma, May 2008.  

Dependency: jQuery 1.2.3, DatePicker plugin 2.1.1.  The new jQuery UI library has a more recent version of DatePicker that may be worth looking into.  Also, for IE, bgiframe 2.1.1 plugin.  (DatePicker depends on it)
*/


//set up a regular expression to validate date format
var dateRE = /^\d{2}\/\d{2}\/\d{4}$/;

//set up the default date format.  
var defaultDateFormat = 'mm/dd/yyyy';

//set the date format for the datepicker calendars -- for start and end dates
Date.format = defaultDateFormat;

//clear the start date or the end date fields
function clearDate(field) {
	if (field.value == defaultDateFormat) {
		field.value = "";
	}
} 

//inser the default date values if the user delete values they entered.
 function resetDate(field) {
	if (field.value == "") {
		field.value = defaultDateFormat;
	}
} 

//Enable the date range field if the start and date ranges are back to default
/* function enableRange() {
	alert('enableRange is called');
	 if ((startDateValue == '' && endDateValue == defaultDateFormat) || (startDateValue == defaultDateFormat && endDateValue == '') || (startDateValue == defaultDateFormat && endDateValue == defaultDateFormat))  {
		$('#dateRange').removeAttr('disabled');
	}
}

function disableRange() {
		alert('Start date is '+ startDateValue);
		alert('End date is '+ endDateValue);
	if (startDateValue != "" || startDateValue != defaultDateFormat || endDateValue !="" || endDateValue != defaultDateFormat) {
			$('#dateRange').attr('disabled','disabled');
	}
} */

function toggleRange() {
		 //set the variables for start and end date values, as they get used often
		//alert('toggleRange is called');
		var startDateValue = $('#start_date').val();
		var endDateValue = $('#end_date').val();
		if (startDateValue.match(dateRE) || endDateValue.match(dateRE)){
			$('#dateRange').attr('disabled','disabled');
		} else {
			$('#dateRange').removeAttr('disabled');
		}
}


//convert the values of the date range options into a valid query string.
function processDateRange(value) {
	var dateQueryString;
	//calculate the "today" value
	if (value == "All" || value =="") {
		//Invalid query string
		return false;
	} else {
		if (value == "today") {
			var today = new Date();
			var todayDate = today.getDate();
			if (todayDate < 10) {todayDate = '0'+todayDate;} //add 0 to ensure that date is 2 digit
			var todayMonth = today.getMonth()+1; //month range is 0-11 in JS
			if (todayDate < 10) {todayMonth = '0'+todayMonth;}
			var todayYear = today.getFullYear();
			var todayQuery = todayYear+'-'+todayMonth+'-'+todayDate;
			dateQueryString = 'date='+todayQuery;
		} else {
			//calculate the date ranges
			var dateRange = value.slice(4); //returns the number, since the date range values are either "next##" or "prev##", where # is a number.
			if (value.match('prev')) { //previous
				dateQueryString = 'minus_days='+dateRange;
			} else { //next
				dateQueryString= 'plus_days='+dateRange+'&sort=time&sort_style=A';
			}
		}
		return dateQueryString; //output the query string in "fieldname=value" format
	}
}
			
function processQueryStrings() {
	//this is the base url.
	var queryStrings = new Array();
	var url = 'event_list.php';
	
	//use queryStrings variable to store the array of query strings. 

	var queryString; //variable for individual query strings.
	var ignoreDateRange = false;
	
	 //set the variables for start and end date values, as they get used often
	var startDateValue = $('#start_date').val();
	var endDateValue = $('#end_date').val();

	//strip out the query strings that may already be attached to the URL, except for the mode string
	var regEx = new RegExp( "[?&]([^=]+)(?:=([^&]*))?", "g" );
	var matchInfo;
	
	//window.location.search is the query string
	while(matchInfo = regEx.exec(location.search)){ //returns an array made up of: the query string, the portion before "=" (field name), the portion after "=" (field value)
		if (matchInfo[1] == "mode" /*|| matchInfo[1] == "sort" || matchInfo[1] == "sort_style"*/) {
			queryString = matchInfo[1] + '=' + matchInfo[2]; // if we use the matchInfo[0] it contains the question mark
			queryStrings.push(queryString);
		} 
			
	}
	
	
	

	//If either start or end date fields are filled out
	if (startDateValue != defaultDateFormat || endDateValue != defaultDateFormat) {
		//alert('Either the start or end date is filled out');
		//if neither the start or end dates is a valid entry, then throw an error
		if (!startDateValue.match(dateRE) && !endDateValue.match(dateRE)) {
			alert('The start date and/or the end date contains an invalid entry.  Please enter a date in ' + defaultDateFormat + ' format.');
		return false;
		} else { //either the start or end dates have valid entries			
			ignoreDateRange = true; //
			var startDateSplit = startDateValue.split("/"); //creates an array of month, date, year
			var endDateSplit = endDateValue.split("/");
			var jsStartDate = new Date();
			 jsStartDate.setDate(startDateSplit[1]);
			 jsStartDate.setMonth(startDateSplit[0]-1); // January = 0
			 jsStartDate.setFullYear(startDateSplit[2]);
			var jsEndDate = new Date();
			 jsEndDate.setDate(endDateSplit[1]);
			 jsEndDate.setMonth(endDateSplit[0]-1);
			 jsEndDate.setFullYear(endDateSplit[2]);
			var jsToday = new Date();
			if ((startDateValue !=defaultDateFormat && jsStartDate >= jsToday) || (startDateValue == defaultDateFormat && jsEndDate >=jsToday)) {
				queryString = 'sort=time&sort_style=A';
				queryStrings.push(queryString);
			} 
			if (startDateValue.match(dateRE)) {
				queryString = 'start_date=' + startDateSplit[2] + '-' + startDateSplit[0] + '-' + startDateSplit[1];
				queryStrings.push(queryString);
			}
			if (endDateValue.match(dateRE)) {
					queryString = 'end_date=' + endDateSplit[2] + '-' + endDateSplit[0] + '-' + endDateSplit[1];
					queryStrings.push(queryString);
			}
		}
	}
	
	// go through all "select" tags (drop downs) and add them to query strings
	var fields = $('select');
	for (var i=0; i<fields.length; i++) {
		var fieldName = fields[i].id;
		var options = fields[i].options;
		var index = fields[i].selectedIndex;
		var optionValue = options[index].value;
		// if the dateRange is something other than "all" and ignoreDateRange is not set
		if (fieldName == "dateRange" && ignoreDateRange == false) {
				//use the processDateRange function to convert the options into a valid query string
				queryString = processDateRange(optionValue);
				if (queryString != false){
					queryStrings.push(queryString);
				}
		} else { //all other select fields		
			if (index != 0 && fieldName != "dateRange") {
				queryString = fieldName + '=' + optionValue;
				queryStrings.push(queryString);
			}

		}
	}
	
	
	//finally, add the query strings to the url
	if (queryStrings.length > 0) {
		for (var j=0; j<queryStrings.length; j++) {
			if (j==0) { //first time through
				url = url + '?' + queryStrings[j];
			} else {
				url = url + '&' + queryStrings[j];
			}
		}
		//alert(url);
		window.location = url;
	} else { // if there's no querystring
		alert("This will retreive all the records in the database.  Proceed?");
		window.location = url;
	}
}


//function to parse the query strings in the URL and then toggle appropriate fields, so that the user can see how the search fields are set
function parseURL() {
	//See http://www.bennadel.com/blog/695-Ask-Ben-Getting-Query-String-Values-In-JavaScript.htm
	var regEx = new RegExp( "[?&]([^=]+)(?:=([^&]*))?", "g" );
	var matchInfo;
	
	//window.location.search is the query string
	while(matchInfo = regEx.exec(location.search)){ //returns an array made up of: the query string, the portion before "=" (field name), the portion after "=" (field value)
		var fields = $('select');
		var toBeSelected;
		for (var i=0; i<fields.length; i++) {
			//Start or end dates
			if (matchInfo[1] == "start_date") {
				var startDateSplit = matchInfo[2].split("-");
				
				$('#start_date').val(startDateSplit[1]+'/'+startDateSplit[2]+'/'+startDateSplit[0]);
			}
			if (matchInfo[1] == "end_date") {
				var endDateSplit = matchInfo[2].split("-");
				$('#end_date').val(endDateSplit[1]+'/'+endDateSplit[2]+'/'+endDateSplit[0]);
			}
			//if it involves a date range
			 if (matchInfo[1] == "plus_days" || matchInfo[1] == "minus_days" || matchInfo[1] == "date") {
				var dateRangeValue;
				if (matchInfo[1] == "plus_days") {
					dateRangeValue = "next" + matchInfo[2];				
				} else if (matchInfo[1] == "minus_days") {
					dateRangeValue = "prev" + matchInfo[2];
				} else {//assuming then that it's "today"
					dateRangeValue = "today";
				}
				toBeSelected = $('option[value='+dateRangeValue+']').get(0);
				$(toBeSelected).attr('selected','selected');
			} 
			
			//all the rest of fields
			if (fields[i].id==matchInfo[1]) {
				//var spaceInURL = new RegExp( "%20", "g");
				if (matchInfo[1] == 'city') {
					matchInfo[2] = matchInfo[2].replace(/\%20/g, ' ');
				}
				
				
				toBeSelected = $('option[value=' + matchInfo[2]+']').get(0);//returns an array if get[0] is not used.  But the result is a string, not a jQuery object
				$(toBeSelected).attr('selected','selected');
			}
		}
	
	}
}


//This is the function for the datepicker calendar.  It synchronizes the calendars for start and end dates, so if one is picked, then the other can't contradict (i.e. pick an end date that is before the start date)
function startEndDateBind() {
	$('#start_date').bind(
		'dpClosed',
		function(e, selectedDates)
		{
			var d = selectedDates[0];
			if (d) {
				d = new Date(d);
				$('#end_date').dpSetStartDate(d.addDays(1).asString());
			}
		}
	);
	$('#end_date').bind(
		'dpClosed',
		function(e, selectedDates)
		{
			var d = selectedDates[0];
			if (d) {
				d = new Date(d);
				$('#start_date').dpSetEndDate(d.addDays(-1).asString());
			}
		}
	);
}


//This will execute the functions on page load
$(document).ready(function(){
		//hide the form
		$('#event-search').hide();
		
		
		//bind the submit button to the script
		$('#event-search-submit').click(function() {
 			toggleRange(); // run the toggleRange one more time, otherwise if the user goes directly from setting up start or end date to submitting, then the dateRange remains enabled.  Not necessary, as the script is set to ignore the date range if either the start ot end date is set properly, but for peace of mind....				
		 	processQueryStrings();
			return false;
		 });
		 
		//parse the query string from URL
		 parseURL();
		 
 
		 //synch the start and end date calendars
 		 startEndDateBind();
		 
		 //enable the start and end date calendars, and also bind appropriate events to date-related field behaviors
		 $('.date-pick').datePicker({
		 	startDate:'01/01/2008',
			endDate:'12/31/2008'					 
		 }).bind('focus', function(){
			 clearDate(this);
		 }).bind('blur', function() {
			 resetDate(this);
 			 toggleRange();
		 });
		 
		 //add the enabling of date range to the reset button
		 $('#reset').click(function(){
				 $('#dateRange').removeAttr('disabled').val('');
				 return true;
		 });
		 
		 //check to see if a user already filled out start or end date, in case he hit reload with start or end dates filled out. 
		 toggleRange(); 
		 
		 //toggle the search box on and off
		 $('#toggle-search').click(function() {
				 $('#help').hide();
				 $('#event-search').toggle('fast');
				 $('#toggle-help').removeClass('popup-on');
				 $(this).toggleClass('popup-on');
		 });
		 
		 //toggle the help box on and off
		 $('#toggle-help').click(function() {
				 $('#event-search').hide();
				 $('#help').toggle('fast');
 				 $('#toggle-search').removeClass('popup-on');
				 $(this).toggleClass('popup-on');
				 
		 });
		 
		 //change the cursor for the search and help tabs
		 $('#toggle-search, #toggle-help').mouseover(function() {
				 $(this).css('cursor','pointer');
		 });
		 
		 //turn on the close buttons
		 $('.close-button').click(function() {
				 $(this).parent().hide('fast');
				 $('#toggle-search, #toggle-help').removeClass('popup-on');
		 }).mouseover(function() {
				 $(this).css({
						 cursor: "pointer",
						 textDecoration: "underline"
				 });
		 }).mouseout(function() {
			 $(this).css({
					 textDecoration: "none"
			 });
		 });
		 

						 
});

