/**
 * Setup the defaults for all jQuery.ajax requests
 *
 * @return void
 * @author Dan Bryant <db@leadingtone.org>
 * @copyright LearningChange LLC - Dan Bryant (Shared Source Initiave/Dual Ownership),  1 January, 2009
 * @package jquery.cfg.js
 * @version: 1.0
 * @perams:
 *
 **/
jQuery.ajaxSetup({
	timeout: 60000 // timout all ajax reuqests after 60 seconds
	,error: function(XMLHttpRequest,textStatus,errorThrown){ // By default pass jQuery.ajax errors to this handler which is automagically called first if not overridden: can be overridden on a per request basis
		/* jqueryAjaxLocalError(XMLHttpRequest,textStatus,errorThrown); */
		jqueryAjaxLocalError(XMLHttpRequest,textStatus,errorThrown);
	}
	,beforeSend: function(XMLHttpRequest){
		jQuery('body').loader.show();
	}
	,complete: function(XMLHttpRequest,textStatus){
		 jQuery('body').loader.hide();
	}
});

/**
 * handle local jQuery.ajax errors from jQuery.ajax({error:function()})
 *
 * @return void
 * @author Dan Bryant <db@leadingtone.org>
 * @copyright LearningChange LLC - Dan Bryant (Shared Source Initiave/Dual Ownership),  1 January, 2009
 * @package jquery.cfg.js
 * @version: 1.0
 * @perams:
 *
 **/
function jqueryAjaxLocalError(XMLHttpRequest,textStatus,errorThrown){

	var missing = 'undefined';

	// collect the error args
	var errors = new Object;
  	errors.event_timestamp				= $P.time();
  	errors.XMLHttpRequest_status		= $P.isset(XMLHttpRequest.status) ? XMLHttpRequest.status : missing;
  	errors.XMLHttpRequest_statusText	= $P.isset(XMLHttpRequest.statusText) ? XMLHttpRequest.statusText : missing;
  	errors.XMLHttpRequest_responseText	= $P.isset(XMLHttpRequest.responseText) ? XMLHttpRequest.responseText : missing;
  	errors.textStatus					= $P.isset(textStatus) ? textStatus : missing;
  	errors.errorThrown					= $P.isset(errorThrown) ? errorThrown : missing;

	// jQuery.jGrowl(
	// 	$P.sprintf(
	// 		'<p>A program error has occurred.</p><p>Details:</p><ul><li>http status: %s</li><li>error status: %s</li><li>error: %s</li></ul>',
	// 		errors.XMLHttpRequest_status,
	// 		errors.textStatus,
	// 		errors.errorThrown
	// 	),{ sticky: true, header:'Client-side AJAX Error Occurred' }
	// );
	jQuery.report($P.sprintf(
		'<p>A program error has occurred.</p><p>Details:</p><ul><li>http status: %s</li><li>error status: %s</li><li>error: %s</li></ul>',
		errors.XMLHttpRequest_status,
		errors.textStatus,
		errors.errorThrown
	),{type:'sticky'});

}



//panel animation control ==========================================================

function panel_out(settings){
	
	var setting = {
		reset: true
	}

	if(settings) jQuery.extend(setting, settings);

	var reset = setting.reset;
	
	jQuery('#slide_panel').animate({
		left: -128
		// style: '',
		// className: '',
		// opacity: 0.4,
		// backgroundColor: ''
	},'slow');

	if(reset) {
		jQuery('#view_cats').show();
		jQuery("#subcategories").BlindRight();
	}
	
	jQuery('#categories').animate({ /*opacity: 0*/ },'fast');

}

function panel_in(){

	jQuery('#slide_panel').animate({
		left: 29
		// style: '',
		// className: '',
		// opacity: 0.4,
		// backgroundColor: ''
	},'fast');

	// jQuery("#subcategories").BlindLeft();
	// BlindLeft, BlindRight, BlindToggleHorizontally

	jQuery('#categories').animate({ /*opacity: 1*/ },'slow');

}

function panel_gate(trig){
	// alert('got ' + trig.href);

	var trigger = trig.href;

	// if( jQuery(trig).attr('href') =="#services_index" ) // this does not work in ie 7 .. detecting the presence of #services_index instead
	if(trigger.search(/#services_index/) != -1){

		// alert('in the panel_gate() if()');

		jQuery("#subcategories").BlindLeft();

		// bc_reset(); // reset the breadcrumbs

		// send send in the slide panel showing only the cat list
		panel_reset = true;
		panel_in();

		//jQuery('#slide_panel').show();
	}else{

		// alert('in the panel_gate() else');

		jQuery('#slide_panel').hide();
		// jQuery('#slide_panel').attr({ left: -110 } );
		// alert('done running hide');
	}
}

// data loaders ==========================================================
function loadProjectDetail(nid){
	// alert( 'laoding department ' + id);

	jQuery.ajax({
		type: "POST"
		,url: 'service.findit_loadProjectDetail.php'
		,data: 'nid=' + nid
		,dataType: "html"
		,success: function(data){
			// jQuery('#department_detail').fadeOut('slow');
			jQuery('#department_detail').html('');
			jQuery('#department_detail').html(data);
			jQuery('#department_detail').fadeIn('slow');
		}
	});
}


function search(form){
	// get the search_text
	var query = (form == 'home_search') ? document.getElementById('home_search_text').value : document.getElementById('main_search_text').value;

	blank_error_msg = 'Sorry. I can&rsquo;t search a blank query.';

	var stype = jQuery('.service_type:checked').attr('value');

	var service = (stype == 'external') ? 'service.findit_search_fhn.php' : 'service.findit_search.php';

	if(query.replace(/^\s+$/,'') != ''){ // if search is not blank
		// perform the search -> send the query return the results into '#search_results'
		jQuery.ajax({
			type: "POST"
			,url: service
			,data: 'q=' + query
			,dataType: "json"
			,success: function(data){

				// console.log(data); 
				
				// extract json vars
				json = data.json;
				var status = json.status;
				var message = json.message;

				// report the error message returned from the server
				if(!status) {
					// jQuery.report(msg,{cls:'apperr', type:'sticky', inject: 'search_message'});
					jQuery.report(message,{cls:'apperr', type:'sticky'});
				} else { // load the results into the search results panel

					var department_results = json.departments;
					var document_results = json.documents;

					resultsResetPanels({zoneOneID:'docu_results',zoneTwoID:'dept_results',startWidth:340});

					// if no results in either side say error
					if(!department_results && !document_results) {

						var format = '<p>No %s results found for your search: <strong>%s</strong>. Please check your spelling or try a different phrase</p>';
						department_results = $P.sprintf(format,'Content',query);
						document_results = $P.sprintf(format,'Toolbox & Resources',query);

					} else { // else resize the region with content to 100% of the available width

						resultsManagePanels({
							zoneOneID:'docu_results'
							,zoneOneResults:document_results
							,zoneTwoID:'dept_results'
							,zoneTwoResults:department_results
							,fullWidth:680
						});

					}
					
					jQuery.report(message,{cls: 'message', inject: 'search_message'});
					
					// Are the results in string or in object format (JSON) 
					if (typeof department_results == 'string') {
						// The following is the old screen scrape code. 
						jQuery('#dept_results').html(department_results);
					} else {
					
						// The new code for the google custom search API.  
						// TODO: The config settings for the custom search API should probably go into
						//		 a more global config file. 
						var deptMarkup = ''; 
						for (var i in data.json.departments.items) {
							with(data.json.departments) {
								// deptMarkup += items[i].title + "\n"; 
								// deptMarkup += items[i].htmlSnippet + "\n";
								// deptMarkup += '<a target="_new" href="'+items[i].link+'">'+items[i].displayLink+'</a>'+"\n"; 
								
								deptMarkup += items[i].resultsMarkup + "\n"; 	
							}
						}

						jQuery('#dept_results').html(deptMarkup); 
					}

					jQuery('#docu_results').html(document_results);
					
					// If we are doing an internal search then 
					if(stype == 'internal') {
						setFilter();
						if(requestedTypeFilter){
							chooseContentType();													
						}
					} else {
						// Rehook the external search linkages to the scraper
						rehookExternalPager();
					}
				}
			}
			// ,complete: function(XMLHttpRequest,textStatus){
			// 	jQuery('body').loader.hide();
			// 
			// }
		});

	} else {
		jQuery.report(blank_error_msg,{cls: 'apperr', inject: 'search_message'});
	}

}

function rescrape(el){
	// Perform the search -> send the query return the results into '#search_results'
	var url = encode(el.href);

	jQuery.ajax({
		type: "POST"
		,url: 'service.findit_search_fhn.php'
		,data: 'rescrape=' + url
		,dataType: "json"
		,success: function(data){
	
			// extract json vars
			json = data.json;
			var status = json.status;
			var message = json.message;
	
			// report the error message returned from the server
			if(!status) {
				jQuery.report(message,{cls:'apperr', type:'sticky'});
			} else { // load the results into the search results panel
	
				var department_results = json.departments;
				jQuery('#dept_results').html(department_results);
				rehookExternalPager();
			}
		}
	});
}

function rehookExternalPager(){
	jQuery('#navbar a').bind('click',function(){
		rescrape(this);
		return false;
	});
}

function loadTerms(cname,el){

	// load the service area with the services for category "s"
	jQuery.ajax({
		type: "POST"
		,url: 'service.findit_loadTerms.php'
		,data: 'termKey=' + cname
		,dataType: "html"
		,success: function(data){
			jQuery('#cat_services_list').html(data);
		}
	});

	// alert('loading services for category ' + c_num);
	panel_out();

	// get the text to send into load_bc_cat(), etc...
	var service = jQuery(el).html();

	// set the instruction to match the chosen service
	jQuery('#service_departments').html('<div class="hint"><img src="'+GBL.ROOTURL+'service.lib/img/icon_hint.jpg" width="40" height="40" alt="Hint" /><p>Choose a service from the <strong>' + service + '</strong> list.</p></div>');
	// set the instruction to match the chosen service
	jQuery('#service_documents').html('<div class="hint"><img src="'+GBL.ROOTURL+'service.lib/img/icon_hint.jpg" width="40" height="40" alt="Hint" /><p>Choose a service from the <strong>' + service + '</strong> list.</p></div>');

	// set the category name breadcrumb to be the same as the text of the anchor tag that triggered load_service()
	load_bc_cat(unescape(cname));
	
}


function getServiceMembers(s_num,el){

	panel_out({reset:false});

	// set the category name breadcrumb to be the same as the text of the anchor tag that triggered load_service()
	var sname = jQuery(el).html();
	// console.log(sname);
	load_bc_service(sname);

	// load the service area with the services for category "s"
	jQuery.ajax({
		type: "POST"
		,url: 'service.findit_getServiceMembers.php'
		,data: 'sid=' + s_num + '&sname=' + sname
		,dataType: "json"
		,success: function(data){

			var json = data.json;

			if(!json.status){ // report the error message returned from the server
				jQuery.report(json.message,{type:'sticky'});
			}else{ // load the results into the correct areas

				var department_results = json.departments;
				var document_results = json.documents;

				resultsResetPanels({zoneOneID:'service_documents',zoneTwoID:'service_departments'});

				// if no results in either side say error
				if(!department_results && !document_results){

					var format = '<p>No %s results found for <strong>%s</strong></p>';
					department_results = $P.sprintf(format,'Content',sname);
					document_results = $P.sprintf(format,'Toolbox & Resources',sname);

				}else{ // else resize the region with content to 100% of the available width

					resultsManagePanels({
						zoneOneID:'service_documents'
						,zoneOneResults:document_results
						,zoneTwoID:'service_departments'
						,zoneTwoResults:department_results
					});

				}

				jQuery('#service_departments').html('');
				jQuery('#service_departments').html(department_results);
				jQuery('#service_departments').fadeIn('fast');

				jQuery('#service_documents').html('');
				jQuery('#service_documents').html(document_results);
				jQuery('#service_documents').fadeIn('fast');
				
			}
		}
		
	});

}

function resultsResetPanels(settings){

	var setting = {
		zoneOneID: ''
		,zoneTwoID: ''
		,startWidth: 275
	}

	if(settings) jQuery.extend(setting, settings);

	var zoneOneID = setting.zoneOneID;
	var zoneTwoID = setting.zoneTwoID;
	var startWidth = setting.startWidth;

	// open both results areas
	jQuery('#'+zoneOneID+'_outer,#'+zoneTwoID+'_outer').animate({
		width: startWidth
	},'fast');

	swapOpen({mode:'open',classPrefix:'content_panel_',selector:'#'+zoneOneID+'_outer,#'+zoneTwoID+'_outer'});

	jQuery('#'+zoneOneID+'_title, #'+zoneTwoID+'_title').show();

}


function resultsManagePanels(settings){

	var setting = {
		zoneOneID: ''
		,zoneTwoID: ''
		,zoneOneResults: ''
		,zoneTwoResults: ''
		,fullWidth: 550
	}

	if(settings) jQuery.extend(setting, settings);

	var zoneOneID = setting.zoneOneID;
	var zoneTwoID = setting.zoneTwoID;
	var zoneOneResults = setting.zoneOneResults;
	var zoneTwoResults = setting.zoneTwoResults;
	var fullWidth = setting.fullWidth;

	//	if !department_results animate department_results to 0 px
	if(!zoneOneResults){

		jQuery('#'+zoneOneID+'_title').hide();

		jQuery('#'+zoneOneID+'_outer').animate({
			width: 0
		},'fast');
		
		swapOpen({mode:'close',classPrefix:'content_panel_',selector:'#'+zoneOneID+'_outer'});

		jQuery('#'+zoneTwoID+'_outer').animate({
			width: fullWidth
		},'fast');
		
	}

	//	if !document_results animate document_results to 0 px
	if(!zoneTwoResults){

		jQuery('#'+zoneTwoID+'_title').hide();

		jQuery('#'+zoneTwoID+'_outer').animate({
			width: 0
		},'fast');
		
		swapOpen({mode:'close',classPrefix:'content_panel_',selector:'#'+zoneTwoID+'_outer'});
		
		jQuery('#'+zoneOneID+'_outer').animate({
			width: fullWidth
		},'fast');
		
	}

}

// reset the breadcrumbs and open the category panel
function bc_reset(){
	// alert('firing bc_reset()');
	panel_in();

	// reset the document display area.
	jQuery('#service_departments').html('<div class="hint"><img src="'+GBL.ROOTURL+'service.lib/img/icon_hint.jpg" width="40" height="40" alt="Hint" /><p>Choose a topic from the <strong>Resource Topics</strong> list.</p></div>');
	// reset the document display area.
	jQuery('#service_documents').html('<div class="hint"><img src="'+GBL.ROOTURL+'service.lib/img/icon_hint.jpg" width="40" height="40" alt="Hint" /><p>Choose a topic from the <strong>Resource Topics</strong> list.</p></div>');

	jQuery('#bc_cat').fadeOut('slow').html('');
	jQuery('#bc_service').fadeOut('slow').html('');
}

// breadcrumb functions ===================================================

// beacuse of rushed execution phase (read no pre programming planning!) the following two functions share this global!
// last_cat_text = '';

function load_bc_cat(cat_text){
	// set the cat html -> 	fade it in
	jQuery('#bc_cat').html(' &nbsp;&raquo;&nbsp; ' + cat_text).show();
	// reset the service breadcrumb
	jQuery('#bc_service').fadeOut('slow').html('');
}

function load_bc_service(svs_text){
	
	// check for setting the services breadcrumb without a category breadcrumb ... fix if you need to
	// if(jQuery('#bc_cat').html() == ''){ 
	var category = jQuery('#cat_services_list > h2').html();
		
	jQuery('#bc_cat').html(' &nbsp;&raquo;&nbsp; ' + category).show();
	// }
	
	// set the services breadcrumb
	jQuery('#bc_service').html(' &nbsp;&raquo;&nbsp; ' + svs_text).show();
}

function advancedSearch(type){

	if(jQuery('#advanced_search:visible').length || type == 'close'){ // close it
		if(jQuery('#advanced_search:visible').length){
			jQuery('#advanced_search').fadeOut('fast');	
			swapOpen({mode:'close',classPrefix:'advanced_search_',selector:'#search_results'});
		}
	}else{ // opening
		jQuery('#advanced_search').fadeIn('slow');
		swapOpen({mode:'open',classPrefix:'advanced_search_',selector:'#search_results'});
	}
}

function swapOpen(settings){
	var defaults = {
		mode: 'open' // can be closed or !close for open
		,selector: ''
		,openClass: 'open'
		,closeClass: 'close'
		,classPrefix: ''
	}

	if(settings) jQuery.extend(defaults, settings);

	var mode = defaults.mode;
	var selector = defaults.selector;
	var openClass = defaults.openClass;
	var closeClass = defaults.closeClass;
	var classPrefix = defaults.classPrefix;
	
	switch(mode){
		case 'close':		
			jQuery(selector).removeClass(classPrefix + openClass);			
			jQuery(selector).addClass(classPrefix + closeClass);
		
		break;
		
		default: // "open"
			jQuery(selector).removeClass(classPrefix + closeClass);			
			jQuery(selector).addClass(classPrefix + openClass);
	}
	
}

function manaageAdvancedSearch(el){
	
	setSearchServiceControlLabels(el.value);
	
	if(el.value == 'external'){ // dis-allow advanced search
		// hide the advanced search launcher
		jQuery('#advanced_search_control').fadeOut('fast');
		// hide the advanced search controls
		// if(jQuery('#advanced_search:visible').length){
		// 	jQuery('#advanced_search').fadeOut('fast');		
		// }	
		advancedSearch('close');
	}else{
		// show the advanced search launcher
		jQuery('#advanced_search_control').fadeIn('slow');
	}
}

function setSearchServiceControlLabels(type){
	if(type == 'internal'){
		// bold the #service_type_external_label label
		jQuery('#service_type_external_label').css({'font-weight':'normal'});
		jQuery('#service_type_internal_label').css({'font-weight':'bold'});
	}else{
		// bold the #service_type_internal_label label
		jQuery('#service_type_internal_label').css({'font-weight':'normal'});
		jQuery('#service_type_external_label').css({'font-weight':'bold'});
	}	
}

var requestedTypeFilter = false;
function chooseContentType(checkbox){

	if(checkbox){ // if a content tyep was manually requested then say so
		requestedTypeFilter = true;
	}
	
	// count the number of selected checkboxes
	var selectedCount = jQuery('.searchreturntype:checked').length;

	// if no content type is selected
	if(selectedCount == 0){

		// get the seleted checkbox
		var thisCheckbox = jQuery(checkbox).attr('id');
		
		// check the oposite checkbox
		if(thisCheckbox == 'toolsource'){
			jQuery('#content').attr({checked:'checked'});			
		}else{
			jQuery('#toolsource').attr({checked:'checked'});						
		}
		
	}
	
	var showToolsource = false;
	var showContent = false;
	
	// figure out which select box is selected
	if(jQuery('#content:checked').length){
		showContent = true;
	}
	
	if(jQuery('#toolsource:checked').length){
		showToolsource = true;
	}
	
	resultsResetPanels({zoneOneID:'docu_results',zoneTwoID:'dept_results',startWidth:340});
	
	// select the side to hide
	resultsManagePanels({
		zoneOneID:'docu_results' // toolsource
		,zoneOneResults:showToolsource
		,zoneTwoID:'dept_results' // content
		,zoneTwoResults:showContent
		,fullWidth:680
	});
	
}


function setFilter(){
	
	// var type = jQuery(checkbox).attr('value');
	// var checked = jQuery(checkbox).attr('checked');
	// if(checked){
	// 	jQuery('.'+type).show();
	// }else{
	// 	jQuery('.'+type).hide();
	// }
	// 
	// resultsResetPanels({zoneOneID:'docu_results',zoneTwoID:'dept_results',startWidth:340});
	// 
	// var ToolsourceHTML = jQuery('#docu_results div:visible').html();
	// var ContentHTML = jQuery('#dept_results #toolsource_drupal div:visible').html();
	// 
	// // console.log(new Array(ToolsourceHTML,ContentHTML));
	// 
	// // select the side to hide
	// resultsManagePanels({
	// 	zoneOneID:'docu_results' // toolsource
	// 	,zoneOneResults:ToolsourceHTML
	// 	,zoneTwoID:'dept_results' // content
	// 	,zoneTwoResults:ContentHTML
	// 	,fullWidth:680
	// });
	
	// show all .content
	// 
	
	// get a list of all of the types that are not selected: .typefilter_control
	var notSelected = new Array();
	var isSelected = new Array();
	jQuery('.typefilter_control').each(function(){

		// add the classes into their respective stacs
		if(this.checked){
			isSelected.push('.'+this.value);
		}else{
			notSelected.push('.'+this.value);
		}
		
	});
	
	var selectedTypes = isSelected.join(',');
	var notSelectedTypes = notSelected.join(',');
	
	// console.log('show: '+selectedTypes);
	// console.log('hide: '+notSelectedTypes);
	
	if(isSelected.length){ // show hide the selected items
		jQuery(notSelectedTypes).hide('fast');
		jQuery(selectedTypes).show('slow');		
	}else{ // show everything
		jQuery('.content').show('fast');
	}

}

// wrapper!
function encode(str)
{
	var str = encodeURIComponent(str);
	if(!str) return false;
	return str;
}

// wrapper!
function decode(str)
{
	var str = decodeURIComponent(str);
	if(!str) return false;
	return str;
}

// function resetTypeFilters(){
// 	jQuery('.typefilter_control').each(function(){
// 		jQuery(this).removeAttr('checked');
// 	});
// }

