function DirectorySearch(){
	this.data = false; //can be forced in conjunction with the next param...
	this.dataOverride = false; //set this to true to control form submission data via JS.
	this.forms = $(".formTarget form");
	this.cookieUrl = 'http://'+window.location.hostname+'/_common_KP3/actions/set/cookie.php';
	this.cookieName = 'urdirsearch';
	this.cookieLimit = 8;
	this.previousSearchLinks = false;
	this.searchResultsTarget = $('#search_results');
	this.previousSearchContainer = $("#recentSearches");
	
	this.photoUrl = false;
	
	this.units = false;
	this.orgUrl = 'http://directory.richmond.edu/queries/json/org.php?usecache=true';
	this.photoUrl = 'http://directory.richmond.edu/queries/photo.php';
	
	this.lookup = {
			input: false,
			items: false,
			matchTarget: false,
			timeout: false,
			query: false
	};
	
	this.content = {
		parent: ".person",
		collapse: ".info",
		trigger: ".name",
		animation: "Slide"	
	};
	
	
	
	this.appendRecentSearches = ds_appendRecentSearches;
	this.setRecentSearches = ds_setRecentSearches;
	this.setSubmitAction = ds_setSubmitAction;
	this.formatSearchResults = ds_formatSearchResults;
	this.toggleDisplay = ds_toggleDisplay;
	this.setPaginations = ds_setPaginations;
	
	//photos
	this.setPhotoTriggerAction = ds_setPhotoTriggerAction;
	
	//related content
	this.setOrgLinkAction = ds_setOrgLinkAction;
	this.doOrgLinkAction = ds_doOrgLinkAction;
	//this.getUnits = ds_getUnits;
	this.doPromoFlip = ds_doPromoFlip;
	//this.viewAllUnits = ds_viewAllUnits;
	
	//login
	this.setLoginSuccessAction = ds_setLoginSuccessAction;
	this.setPreferences = ds_setPreferences;
	
	this.toggleDisplayState = 'name';
	
	this.__construct = function(){	
		var obj = this;
		obj.setSubmitAction();
		obj.setRecentSearches();
		obj.setOrgLinkAction();
		obj.setPhotoTriggerAction();
		obj.setPreferences();
		obj.setPaginations();

	};
}

/********************************/
/***  Form Submission Events  ***/
/********************************/

function ds_setSubmitAction(){
	var obj = this;
	
	obj.forms.live('submit', function(){
		var el = $(this);
		
		if(obj.dataOverride == false){
			//normal circumstances.
			obj.data = el.serialize();
		}
		else{
			//if true, use the current value of obj.data, but set the control var back to false.
			obj.dataOverride = false;
		}
		
		if(obj.searchResultsTarget.children('.loader').length == 0){
			obj.searchResultsTarget.prepend(swod);
		}
		obj.searchResultsTarget.children('.loader').show();
		
		obj.searchResultsTarget.children('.face').empty();
		obj.searchResultsTarget.show();
		
		//return false;
		
		$.ajax({
			url: el.attr('action'),
			type: "GET",
			data: obj.data,
			dataType: "jsonp",
			success: function(data){
				eval(data);	
				
				//branch form results versus the login:
				if( (el.attr('id') == 'login') || (el.attr('id') == 'preferencesForm') ){
					obj.setLoginSuccessAction(data.results);
					return false;
				}
				
				obj.formatSearchResults(data.results, obj.searchResultsTarget.children('.frontside'));
					
				//write recent keyword searches to a cookie
				if(el.find('input[type="text"]').length == 1){
					obj.appendRecentSearches();
				}
			
				if(obj.searchResultsTarget.children('.backside').is(':visible')){
					obj.doPromoFlip(obj.searchResultsTarget);
				}
				else{
					obj.searchResultsTarget.children('.backside').hide();
					obj.searchResultsTarget.children('.frontside').parents().show();
					obj.searchResultsTarget.children('.frontside').slideDown();
				}

			}
		});
			
		el.find('input.input').trigger('blur');
		return false;
	});
}	

function ds_setRecentSearches(){
	var obj = this;
	
	$("#recentSearches ul li").live('click', function(){
		obj.forms.filter(':visible').find('input[type="text"]').val($(this).text());
		obj.forms.filter(':visible').submit();
	});	
}

function ds_appendRecentSearches(){
	var obj = this;
	var count = 0;
	var formVal = obj.forms.filter(':visible').find('input[type="text"]').val();
	
	//see if the link already exists; create it if not
	var exists = $("#recentSearches ul li").filter(function(){
		return $(this).text() == formVal;
	});
	
	if(exists.length == 0){
		var link = '<li>'+formVal+'</li>';	
		
		if($("#recentSearches ul li").length < obj.cookieLimit){
			//load searches initially
			$("#recentSearches ul").append(link);	
		}
		else{
			//once search terms are full, start replacing:
			$("#recentSearches ul").append(link);
			$("#recentSearches ul li:first").remove();
		}	
		
		//store all li values:
		var lis = '';
		$("#recentSearches ul li").each(function(){
			lis += encodeURIComponent($(this).text())+'|';
		});
		
		$.ajax({
			url: obj.cookieUrl+'?name='+obj.cookieName+'&method=directory',
			type: "POST",
			data: 'links='+lis,
			success: function(data){
				return true;
			}
		});	
	}
}


/***********************************/
/***  Search Results Formatting  ***/
/***********************************/

function ds_formatSearchResults(data, node, collapsedParent){
	var obj = this;
	
	node.html(data);
	
	//set phone numbers to be clickable on mobile devices
	if( (typeof(mobile) != 'undefined') && (mobile == true) ){
		var phones = obj.searchResultsTarget.find('.phone');
		phones.unbind('click');
		phones.bind('click', function(){
			window.location = 'tel:'+$(this).text();
		});
	}	
	
	//determine if offices or people came back:
	if(node.find('.person').length > 0){
		obj.content.parent = '.person';
	}
	else if(node.find('.office').length > 0){
		obj.content.parent = '.office';
	}
	
	//fire collapsed content (but not on bios or features)
	if(node.find('.bioList, .articles-list').length == 0){
		var ccResults = new CollapsedContent();
		ccResults.parent = obj.content.parent;
		ccResults.collapse = obj.content.collapse;
		ccResults.trigger = obj.content.trigger;
		ccResults.animation = obj.content.animation;
		
		$(ccResults.parent+' '+ccResults.trigger).unbind('click');
		ccResults.__construct();
	}	

	//check the name/title toggle and format:
	if(obj.toggleDisplayState == 'title'){
		obj.toggleDisplay();
	}
	
	//If there is only one item returned open it:
	if(obj.searchResultsTarget.find('.collapsible').length == 1){
		obj.searchResultsTarget.find('.collapsible:first').trigger('click');
	}
	
	//if a match was made based on a specialty tag, highlight that one:
	var top_picks = obj.searchResultsTarget.find('.person').has('.speciality[match="true"]');
	top_picks.each(function(){
		$(this).addClass('topMatch');
	});
	
	if(top_picks.length > 0){
		top_picks.prependTo('.people');
		$('.people').prepend('<div class="title topMatch">Top Matches</div>');
	}
	
	$(".loader").hide();
		
}


function ds_setPhotoTriggerAction(){
	var obj = this;
	var photos = obj.searchResultsTarget.find('.photoTrigger');
	
	photos.live('click', function(){
		var el = $(this);
		el.fadeOut();
		var infoText = el.parent();
		infoText.parent().prepend(swod);
		infoText.parent().prepend('<img src="'+obj.photoUrl+'?netid='+el.attr('netid')+'" style="position: absolute; top: 3px; left: 20px; width: 80px; display:none;" />');
		infoText.css('margin-left', '88px');
		infoText.css('min-height', '95px');
		infoText.parent().children('.loader:first').fadeOut(1800, function(){
			infoText.parent().children('img:first').fadeIn();
			infoText.parent().children('.loader:first').remove();
		});	
	});			
}

/************************************************/
/**********  Bio Pagination Functions  **********/
/************************************************/
function ds_setPaginations(){
	var obj = this;
	
	obj.searchResultsTarget.find('.paginationControls span a').live('click', function(){
		var q = $(this).attr('href');
		q = q.replace('?','');
		$(this).removeAttr('href');
		
		obj.data = q;
		obj.dataOverride = true;
		obj.forms.filter(':visible').trigger('submit');
	});
}



/***************************************/
/**********  Login Functions  **********/
/***************************************/
function ds_setLoginSuccessAction(authNotice){
	var obj = this;
	
	if(authNotice == 'Success'){		
		obj.searchResultsTarget.children('.frontside').html('<div class="notice">That worked.</div>');
		
		setTimeout(function(){
			$("#directoryNav > ul.tabMenu > li:last").text('Logout').click(function(){
				window.location += "?logout=1";
			});
			obj.searchResultsTarget.find('.frontside .notice').fadeOut();
			//get rid of any links in the page pointing to the login form:
			$("#jsLoginLink").parent().hide();
			
			//enable this for preferences
			$("#jsPreferencesLink").parent().fadeIn();
			
			$("#directoryNav > ul.tabMenu > li:first").trigger('click');
		}, 800);
		
	}
	else{
		obj.searchResultsTarget.children('.frontside').html('<div class="notice">Not quite. Try again.</div>');
	}
	obj.searchResultsTarget.find('.loader').hide();
}

function ds_setPreferences(){
	var obj = this;
	
	$("#jsPreferencesLink").live('click', function(){
		if($("#preferences").is(':hidden')){
			$("#jsPreferencesLink").text('Close Preferences');
			$("#preferences").slideDown();
		}
		else{
			$("#jsPreferencesLink").text('Update Preferences');
			$("#preferences").slideUp();
		}
	});
	
}

/**************************************************/
/***  Organizational Links/Hierarchy and Events ***/
/**************************************************/
function ds_setOrgLinkAction(){
	var obj = this;
	obj.searchResultsTarget.find('.orgInfo').live('click', function(){
		obj.doOrgLinkAction(this);
	});
}

function ds_doOrgLinkAction(el){
	var obj = this;
	var orgName = $(el).text();
	obj.searchResultsTarget.children('.loader').show();
	
	$.ajax({
		url: obj.orgUrl+'&positionid='+$(el).attr('positionid'),
		type: "GET",
		dataType: "jsonp",
		success: function(data){
			eval(data);
			//output all of the returned HTML:
			obj.formatSearchResults(data.results, obj.searchResultsTarget.children('.backside'), '.person');
			
			//setup the title/name toggle:
			obj.searchResultsTarget.children('.backside').append('<div id="displayToggle" class="tiny" style="padding: 10px; background: #ccc;">View by <input type="radio" name="display" value="name" /> Name <input type="radio" name="display" value="title" /> Title</div>');
			$("#displayToggle input:radio[value='"+obj.toggleDisplayState+"']").attr('checked', 'checked');
			$("#displayToggle input:radio").change(function(){
				obj.toggleDisplayState = $("#displayToggle input:radio:checked").val();
				obj.toggleDisplay();
			});
		
			obj.searchResultsTarget.find('.orgChart').append('<div class="back-button"></div>');			
			
			if(obj.searchResultsTarget.children('.frontside').is(':visible')){
				obj.doPromoFlip(obj.searchResultsTarget);
			}
			else{
				obj.searchResultsTarget.children('.face').hide();
				obj.searchResultsTarget.children('.backside').slideDown();
			}
			
			
			//remove the first visible unit that isn't a breadcrumb
			$('.orgChart .person .unit:first').hide();
			
			//set padding indents for reporting lines.
			//var startDepth = topUnit.parent().attr('hpath').split('/').length;
			var startDepth = $('.orgChart .breadcrumbs > *').length;
			$('.orgChart .person').each(function(){
				var pad = 15*($(this).attr('hpath').split('/').length - startDepth);
				$(this).css('padding-left', pad+'px');
			});
		
			//assign the click event to the new unit divs
			obj.searchResultsTarget.find('.orgChart .unit').bind('click', function(){
				obj.doOrgLinkAction(this, true);
			});
						
			$('.orgChart .back-button').click(function(){
				obj.doPromoFlip(obj.searchResultsTarget);
			});
			
			
			
		}
	});
}

function ds_toggleDisplay(){
	var obj = this;
	
	obj.searchResultsTarget.find('.orgChart .person').each(function(){
		var name = $(this).children('.name').text();
		var title = $(this).find('.positionTitle').text();
		
		$(this).children('.name').text(title);
		$(this).find('.positionTitle').text(name);
	});
}

function ds_doPromoFlip(item){
	var obj = this;
	
	if($.browser.webkit){
		item.css({
			'-webkit-transition' : 'all 0.5s ease-in-out',
			'-webkit-transform-style' : 'preserve-3d',
			'-webkit-backface-visibility': 'hidden'
		});		
		if(item.find('> .face.frontside').is(':visible')){
			item.css({
				'-webkit-transform' : 'rotateY(90deg)'
			});		
			setTimeout(function(){
				item.find('> .face.frontside').hide();
				item.find('> .face.backside, .flip').show();
				item.css({
					'-webkit-transition' : 'all 0.5s ease-out-in',
					'-webkit-transform' : 'rotateY(0deg)'
				});
				
			}, 500);
		}
		else{
			item.css({
				'-webkit-transform' : 'rotateY(90deg)'
			});		
			setTimeout(function(){
				item.find('> .face.backside').hide();
				item.find('> .face.frontside').show();
				item.css({
					'-webkit-transition' : 'all 0.5s ease-out-in',
					'-webkit-transform' : 'rotateY(0deg)'
				});
				
			}, 500);
		}
		
	}
	else{		
		if(item.find('> .face.frontside').is(':visible')){
			item.find('> .face.frontside').hide(300);
			item.find('> .face.backside, .flip').show(300);
		}
		else{
			item.find('> .face.backside').hide(300);
			item.find('> .face.frontside').show(300);
		}
		
	}
		
}
