
/* -------------------------------------------------------------------
 config for matching between the input and the hidden fields  */

// simple search
var localisation = new Array("district_id", "commune_id", "region_id");
var simple_profession = new Array("simple_profession_id");

// advanced search
var profession = new Array("professionId");
var localisationAdvanced = new Array("advdistrict_id", "advcommune_id", "advregion_id");
var nogaDivision = new Array("nogaClassId", "nogaDivisionId");

// save in one object
var fieldToId = new Object();
fieldToId.localisation = localisation;
fieldToId.simple_profession = simple_profession;
fieldToId.profession = profession;
fieldToId.localisationAdvanced = localisationAdvanced;
fieldToId.nogaDivision = nogaDivision;

// object to keep value of each field after the modification
var fieldBackup = new Object();

/*----------------- END OF FIELD CONFIG --------------------- */


function hideLoading() {	jQuery("#loadingDiv").loading('hide');}
function showLoading() {	jQuery("#loadingDiv").loading('show');}
	
function showCompanyDetails(id) {
	showLoading();
	callback = hideLoading;	
	jQuery("#companyDetailsContainer").load("index.php?option=com_company&format=raw&task=show&id="+id, null, callback);
	jQuery("#companyDetailsContainer").show();	
} 

function toggleLine(triggerEl) {
	cell = jQuery(triggerEl).parent();
	cell.find("a,img").each(function() {
		jQuery(this).toggle();
	});	
	
	row = cell.parent();
	row.find("span,input").each(function (i) {
		jQuery(this).toggle();
	}); 
	
}

function editLine(image) {
	toggleLine(image)
}

function cancelChanges(trigger) {
	toggleLine(trigger); 
}



// function to handle the change of style for the feedback zone
// type can be: positive (1) or negative (-1)
function ajaxFeedback(data, options) {
	status = data[0].status;
	message = data[0].message;
	
	if (status == 0) {
		cssClass = "positive";
		callback = options.posCallback ? options.posCallback : null;
	} else if (status > 0) {
		cssClass = "negative";
		callback = options.negCallback ? options.negCallback : null;
	} else {
		// unknown type, do nothing
		return;
	}
	
	if (callback) {
		callback();
	}
	
	hideHtml = "<span class='link' onclick='hideFeedback()'>Masquer</span>";
	var feedbackZone = jQuery("#feedbackZone");
	feedbackZone.removeClass("positive negative");
	feedbackZone.html(hideHtml + "<p>" + message + "</p>");
	feedbackZone.addClass(cssClass);
	feedbackZone.addClass("active");
	feedbackZone.show();
	
}

//resize the thickbox
var MAX_HEIGHT = 600;
var  MIN_HEIGHT = 200;
function resizeBlockEditionWindow() {
	var t=setTimeout(function() {
		titleHeight = jQuery("#TB_title").outerHeight();
		formHeight = jQuery("#updateCompanyForm").outerHeight();
		newHeight = titleHeight + formHeight + 25;
		jQuery("#TB_window").height(newHeight);
		},200);
}
function resizeHistoryWindow() {
	var t=setTimeout(function() {
		titleHeight = jQuery("#TB_title").outerHeight();
		tableHeight = jQuery("#historyTable").outerHeight();
		newHeight = Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, titleHeight + tableHeight));
		jQuery("#TB_ajaxContent").height(newHeight - 60);
		jQuery("#TB_window").height(newHeight);
		},200);
}
function resizeTextWindow() {
	var t=setTimeout(function() {
		titleHeight = jQuery("#TB_title").outerHeight();
		totHeight = titleHeight;
		jQuery("#TB_ajaxContent p").each(function() {
			totHeight += jQuery(this).outerHeight();
		});
		newHeight = totHeight + 40;
		jQuery("#TB_window").height(newHeight);
		},200);
	
}

function hideFeedback() {
	var feedbackZone = jQuery("#feedbackZone");
	feedbackZone.hide();
	feedbackZone.removeClass("active");
}


/* for the account creation page */
function showMessageIfNeeded() {
	if(!jQuery("#terms").attr('checked')) {
		alert("Vous devez accepter les termes d'utilisation.");
		return false;
	}	
	return true;
}



// ====== FOR THE SEARCH PAGE ========

function saveSearch(fields, url, formId) {
	var dataStr = "";	
	fields.forEach(function(field) {
		underscoreField = field.replace(/([A-Z]+)/g, "_$1").toLowerCase();
//		console.log("#"+formId + " [name="+field+"]");
		dataStr += underscoreField + "=" + jQuery("#"+formId + " [name='"+field+"']").attr('value') + '&';
	})
	jQuery.ajax({
		type:"POST",
		url: url,
		data: dataStr, 
		success: function(json) {
		 	data = eval(json);
         	options = new Array();
//         	options["posCallback"] = function() {jQuery("#removeBasketLink, #addBasketLink").toggle();};
         	ajaxFeedback(data, options);  
		}
	});
}

function saveAdvancedSearch() {	
	fields = new Array("name", "advcommune_id", "professionId", "advdistrict_id", "advregion_id", "nogaDivisionId", "nogaClassId", "rc_observation", "contactName");
	url = "index.php?option=com_usersearches&task=saveAdvanced&format=raw";
	formId = "searchCompanyForm";
	saveSearch(fields, url, formId);
}

function saveSimpleSearch() {
	fields = new Array("simple_profession_id", "commune_id", "district_id", "region_id", "rc_observation");
	url = "index.php?option=com_usersearches&task=saveSimple&format=raw";
	formId = "quickSearchForm";
	saveSearch(fields, url, formId);	
}

function showPrintPage(formId) {
	// determine what type of search it is
	var form;
	form = jQuery("#" + formId);
	
	// build the new href and open it in a new window
	var action = "index.php?format=print&limitstart=0&limit=100&layout=print";
	params = form.serialize();
	params = params.replace("&format=raw", "");
	action = action + "&" + params;
	window.open(action);	
}

function toAdvancedSearch() {
	 jQuery("#advancedSearchContainer").slideDown("slow");	
	 jQuery("#simpleSearchContainer").slideUp("slow");
}

function toSimpleSearch() {
	 jQuery("#simpleSearchContainer").slideDown("slow");
	 jQuery("#advancedSearchContainer").slideUp("slow");
}

// helper function to get the input field from the corresponding id field 
function getInputField(name) {
	var pairField = "";
	if (name.substr(l-2,l)=="Id") {
//      console.log("found Id");
      pairField = name.substr(0, l-2);
      // exception for noga classes and divisions share the same field
      if (name == "nogaClassId") {
    	  pairField = pairField.replace("Class", "Division");
      }
    } else {
   	  // exception for the localisation fields
      if (name == "district_id" || name=="region_id" || name=="commune_id") {
		  pairField = "localisation";
      } else if (name == "advdistrict_id" || name=="advregion_id" || name=="advcommune_id") {
    	  pairField = "localisationAdvanced";
	  } else {
    	  pairField = name.substr(0, l-3);
	  }
    }
	return pairField;
}

function isStrEmpty(s) {
	if (s == "" || s.match(/^\s+$/)) {
		return true;		
	} else {
		return false;
	}
}



function eraseOldIds(formId) {
	isEmpty = true;
	form = jQuery("#"+formId);
	form.find("input[type='hidden']").each(function() {
		name = jQuery(this).attr('name');
		l = name.length;	
		if (name.substr(l-2,l)=="Id" || name.substr(l-3,l)=="_id") {
			var pairField = getInputField(name);
			valToCheck = jQuery("#"+pairField).attr('value');
			if (isStrEmpty(valToCheck)) {
			//        console.log("field was null");
			    jQuery(this).attr("value", "");
			} else {
				isEmpty = false;
			} 
		}
	});
	
	form.find("input[type='text']").each(function() {
		  val = jQuery(this).attr('value');
		  if (val != "" && !val.match(/^\s+$/)) {
			isEmpty = false;
		  }
	 });
	 return isEmpty;
}

//helper function to erase id on focus of a field 
function cleanIdFields(inputField) {
//	console.log("cleaning");
	
	var name = jQuery(inputField).attr('name');

	// store the old value so that if the user just goes through the field without
	// changing the value, we can get it back
	var val = jQuery(inputField).attr('value');
//	console.log("saving " + val);
	fieldBackup[name] = val; 
	
	var idFields = fieldToId[name];
	jQuery.each(idFields, function(key, fieldName) {
		fieldBackup[fieldName] = jQuery("#" + fieldName).attr('value'); 
		jQuery("#" + fieldName).attr('value', "");
	});
}

//helper function to tell whether an input field has a corresponding hidden value entered
function isIdFieldCompleted(name) {
	var idFields = fieldToId[name];
	var completed = false;
//	console.log(idFields.length);
	jQuery.each(idFields, function(key, fieldId) {
		var val = jQuery("#"+fieldId).attr('value');
		completed = completed || !isStrEmpty(val);
//		console.log(completed);
	});
	return completed;
}

// check that a field has been completed correctly by the autocompleter
function checkAutoCompleteUsed(elem) {
	elem = jQuery(elem);
	var val = elem.attr('value');
//	console.log(val);
	var fieldName = elem.attr('name');
	
	// check whether we need to warn
	if (!isStrEmpty(val) && !isIdFieldCompleted(fieldName)) {
//		// autocomplete has not been used => warn
		elem.removeClass("autocompleted");
		elem.addClass("nonautocompleted");
		jQuery("#autocompleteWarning").show();
		return false;
	} else {
		elem.removeClass("nonautocompleted");
		elem.addClass("autocompleted");
		return true;
////		jQuery("#autocompleteWarning").hide();
	}	
}

function checkSearchAutocompleted(searchType) {	
	var autocompleted = true;
	var autocompletedFields;
	if (searchType == "simple") {
		autocompletedFields = new Array("localisation", "simple_profession");
	} else {
		autocompletedFields = new Array("localisationAdvanced", "nogaDivision", "profession");
	}
	jQuery.each(autocompletedFields, function(key, field) {
		autocompleted = checkAutoCompleteUsed("#" + field) && autocompleted;
	});
	return autocompleted;
}


function hideHowItWorks() {
	jQuery('#howItWorks').hide();
	
}

function reinitCompanyDetails() {
	jQuery("#companyDetails").html("<p style=\"font-weight: lighter;\">Les détails de l'entreprise apparaîtront ici</p>");
}



// ================== FOR THE SLIDESHOW ==============
jQuery(document).ready(function() {		
	
	//Execute the slideShow, set 4 seconds for each images
	slideShow(5000);

});

function slideShow(speed) {
	//append a LI item to the UL list for displaying caption
	//jQuery('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>');

	//Set the opacity of all images to 0
	jQuery('ul.slideshow li').css({opacity: 0.0});
	
	//Get the first image and display it (set it to full opacity)
	jQuery('ul.slideshow li:first').css({opacity: 1.0});
	
	//Get the caption of the first image from REL attribute and display it
	jQuery('#slideshow-caption h3').html(jQuery('ul.slideshow a:first').find('img').attr('title'));
	jQuery('#slideshow-caption p').html(jQuery('ul.slideshow a:first').find('img').attr('alt'));
		
	//Display the caption
	jQuery('#slideshow-caption').css({opacity: 0.7, bottom:0});
	
	//Call the gallery function to run the slideshow	
	var timer = setInterval('gallery()',speed);
	
	//pause the slideshow on mouse over
	jQuery('ul.slideshow').hover(
		function () {
			clearInterval(timer);	
		}, 	
		function () {
			timer = setInterval('gallery()',speed);			
		}
	);
	
}

function gallery() {
	//if no IMGs have the show class, grab the first image
	var current = (jQuery('ul.slideshow li.show')?  jQuery('ul.slideshow li.show') : jQuery('#ul.slideshow li:first'));

	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? jQuery('ul.slideshow li:first') :current.next()) : jQuery('ul.slideshow li:first'));
		
	//Get next image caption
	var title = next.find('img').attr('title');	
	var desc = next.find('img').attr('alt');	
		
	//Set the fade in effect for the next image, show class has higher z-index
	next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);
	
	//Hide the caption first, and then set and display the caption
	jQuery('#slideshow-caption').animate({bottom:-70}, 300, function () {
			//Display the content
		jQuery('#slideshow-caption h3').html(title);
		jQuery('#slideshow-caption p').html(desc);				
		jQuery('#slideshow-caption').animate({bottom:0}, 500);	
	});		

	//Hide the current image
	current.animate({opacity: 0.0}, 1000).removeClass('show');

}

// ================  END OF SLIDESHOW ============== 

// ============= COMPANY AND BASKET =================

function addCompanyToBasket(companyId) {
	jQuery.ajax({
		type: "POST",
        url: "index.php?option=com_company&task=addToBasket&format=raw",
        data: "company_id=" + companyId,
        success: function(json) {
			data = eval(json);
			options = new Array();
			options["posCallback"] = function() {
				jQuery("#removeBasketLink").show();
				jQuery("#addBasketLink").hide();
			}
			ajaxFeedback(data, options);	 	        	
        }
	});
}

function removeCompanyFromBasket(companyId) {
	jQuery.ajax({
		type: "POST",
        url: "index.php?option=com_company&task=removeFromBasket&format=raw",
        data: "company_id=" + companyId,
        success: function(json) { 
			data = eval(json);
			options = new Array();
			options["posCallback"] = function() {
				jQuery("#removeBasketLink").hide();
				jQuery("#addBasketLink").show();
			}
			ajaxFeedback(data, options);     	
		}
	});
}

function removeFromBasket(caller) {
	// TODO find out why it does not work with the following line:
	// var compId = jQuery(caller).prev().attr('value');
	sib = jQuery(caller).siblings();
	sib = sib[0];
	sib = jQuery(sib);
	var compId = sib.attr('value');
	var row = jQuery(caller).parent().parent();
	// send request and delete html on success
	jQuery.ajax({
			type: "POST",
			url: "index.php?option=com_company&task=removeFromBasket&format=raw",
			data: "company_id=" + compId,
			success: function(json) {
				data = eval(json);
				options = new Array();
				options["posCallback"] = function() {
					status = data[0].status;
					if (status==0) {
						row.remove();
					}
				};
				ajaxFeedback(data, options);	        	
			}
	});
}


function deleteSearch(caller,type) {
	var task = "deleteAdvanced";
	if (type=="simple") {
		task = "deleteSimple";
	}
	
	// TODO: see why it does not work with:
	// search_id = jQuery(caller).prev().attr('value');
	sib = jQuery(caller).siblings();
	sib = sib[0];
	sib = jQuery(sib);
	var search_id = sib.attr('value');
	var row = jQuery(caller).parent().parent();

	// send request and delete html on success
	jQuery.ajax({
			type: "POST",
			url: "index.php?option=com_usersearches&task="+task+"&format=raw",
			data: "search_id=" + search_id,
			success: function(json) { 
				var data = eval(json);
				var options = new Array();
				options["posCallback"] = function() {
					status = data[0].status;
					if (status==0) {
						row.remove();
					}
				};
				ajaxFeedback(data, options);     	
			}
	});
}







