// GLOBALS =================================================================================================

/* ID of recipe search form */
var recipeSearchForm = 'krlSearchForm';
var recipes_slider_time;

// PUBLIC ==================================================================================================

/*
 * This initializes the slider with a handle its initial value (depeding on the form field maxtime).
 * USE:
 * - call once onload or when the page is initialized.
*/
function genericSliderInitParams(slider_id, step, start, end, div_id, sortingParam, toggleSrcList) {

	 recipes_slider_time = new Slider(slider_id, 'recipeSlider');
	 recipes_slider_time.setValueChangeFunc(function(val) {
	  	genericSliderValueChanged(val, div_id);
	 }); 
	 recipes_slider_time.setMouseUpFunc(function(val) {
	 	genericSliderClick(val, sortingParam, toggleSrcList);
	 }); 
		 
	 recipes_slider_time.setBlockIncrement(step);
	 recipes_slider_time.setUnitIncrement(step);
	 recipes_slider_time.setMaximum(end);
	 recipes_slider_time.setValue(start);
	 recipes_slider_time.setMinimum(start);
	 
	 recipes_slider_form = $(recipeSearchForm);
	 recipes_slider_formField = $(recipeSearchForm)['maxtime'];
	 
	 var currentValue = recipes_slider_formField.value;
	 
	 if (currentValue!=null && currentValue!='') {
	 	if (currentValue<start) {
	 		currentValue=start; 
	 	}
	 	if (currentValue>end) {
	 		currentValue=end;
	 	}
	 } else {
 		currentValue=end;
	 }	 	 
 	recipes_slider_time.setValue(currentValue);
 }

/* Toggle the time filter:
 * - The toggle Image will be exchanged.
 * - If the filter gets disabled:
 * -- The slider is set to the end value.
 * -- The form will be submitted with an empty value.
 * - If the filter gets enabled:
 * -- The slider is set to the start value.
 * -- The form will be submitted with the start value.
 * USE:
 * - onClick of toggle image 
*/ 
function toggleFilterTime(toggleEle, locToggleSrcList, startValue, endValue, sortingParam) {
	if (toggleEle) {
		var lIndex = toggleToggleImage(locToggleSrcList, toggleEle);
		if (lIndex >= 0) {
			var disable = (lIndex ==1);
			if (disable) {
				recipes_slider_time.setValue(endValue);
				sendFormSubmit(null, '', '');
			} else {
				recipes_slider_time.setValue(startValue);
				sendFormSubmit(null, startValue, sortingParam);
			}
		}
	}
}

/* Toggle the rating filter:
 * - The toggle Image will be exchanged.
 * - If the filter gets disabled:
 * -- All rating point images are set inactive.
 * -- The form will be submit with an empty rating parameter.
 * - If the filter gets enabled:
 * -- Nothing more is done.
 * USE:
 * - onClick of toggle image 
*/ 
function toggleFilterRating(div_id, toggleEle, rpSrcList, locToggleSrcList) {
	if (toggleEle) {
		var lIndex = toggleToggleImage(locToggleSrcList, toggleEle);
		if (lIndex >= 0) {
			var disable = (lIndex ==1);
			if (disable) {
				activateRankingPoints4all(0, rpSrcList);
				sendFormSubmit('', null, '');
			} else {
				// nothing more to be done?
			}
		}
	}
}

/* Selects a rating point:
 * - The rating point images will be activated until this point.
 * - The rating point will be set mouseover.
 * - The form will be submit with the rating point value.
 * USE:
 * - onClick of rating point image 
*/ 
function selectRatingPoint(rbId, locRPSrcList, toggleSrcList, rpIndex, sortingParam) {
	activateRankingPoints(rpIndex+1, locRPSrcList, rbId);
	toggleRatingPoint(true, locRPSrcList, rpIndex, rbId);
	enableAllToggleImage(toggleSrcList);
	sendFormSubmit(rpIndex+1, null, sortingParam);
}

/* Toggles the RatingPoint-Image from mouseover to normal and vice versa. The result image depends also, whether
 * the RP-Image is active or not. All images up to the mouseover'd image will be switched.
 * USE:
 * - onMouseover + onMouseOut of rating point images  
*/
function toggleRatingPoint(isOver, locRPSrcList, num, rbId) {
	var pointPrefix = 'rating_point_';
	var ratingBarDiv = $(rbId);
	if (ratingBarDiv) {
		var imgElems = Element.select(ratingBarDiv, 'img');
		if (imgElems) {
			for (var i = 0; i < imgElems.length; i++) {
				var name = Element.readAttribute(imgElems[i], 'name');
				if (name && name.indexOf(pointPrefix)==0) {
					var rpIndex = parseInt(name.substring(pointPrefix.length, name.length));
					if (!isNaN(rpIndex) && rpIndex <= num) {
						var lIndex = -1;
						var oldSrc = Element.readAttribute(imgElems[i], 'src');
						for (var j = 0; j < locRPSrcList.length; ++j)
							if (oldSrc == locRPSrcList[j]) lIndex = isOver ? j+2 : j-2;
						if (lIndex > -1 && lIndex < locRPSrcList.length)
							imgElems[i].src = locRPSrcList[lIndex];
					}
				}
			}
		}
	}
}

// PRIVATE ==================================================================================================

/*
 * Callback function for a slider click:
 * - All toggle images of the toggleSrcList will be enabled.
 * - Form submit with the silder value.
*/
function genericSliderClick(val, sortingParam, toggleSrcList) {
	enableAllToggleImage(toggleSrcList);
	sendFormSubmit(null, val, sortingParam);
}

/*
 * Callback function for a slider value change:
 * - The active slider value element retrieves an extra style class "active".
 */
function genericSliderValueChanged(val, div_id) {
	var sliderValues = Element.select($(div_id), '.sliderValue');
	for (var i = 0; i < sliderValues.length; ++i) {
		if(sliderValues[i].innerHTML == val) {
			sliderValues[i].addClassName('active');
		} else {
			sliderValues[i].removeClassName('active');
		}
	}
}

/* Activates the ranking point images up to number "num" for all rating point bars.
 * (This is hypothetical, as only one bar makes sense, but theoretically more bars can be loaded).
*/
function activateRankingPoints4all(num, imgSrcList) {
	if (imgSrcList) {
		imgSrcList.each(function(pair) {
			activateRankingPoints(num, pair.value, pair.key);
		});
	}
}

/* Activates the ranking point images up to number "num".
*/
function activateRankingPoints(num, locImgSrcList, rbId) {
	var pointPrefix = 'rating_point_';
	var ratingBarDiv = $(rbId);
	if (ratingBarDiv) {
		var imgElems = Element.select(ratingBarDiv, 'img');
		if (imgElems) {
			for (var i = 0; i < imgElems.length; i++) {
				var name = Element.readAttribute(imgElems[i], 'name');
				if (name && name.indexOf(pointPrefix)==0) {
					var rpIndex = parseInt(name.substring(pointPrefix.length, name.length));
					if (!isNaN(rpIndex)) {
						if (rpIndex <num) {
							imgElems[i].src = locImgSrcList[0];
						} else {
							imgElems[i].src = locImgSrcList[1];
						} 
					}
				}
			}
		}
	}
}

/* Toggles the Toggle-Image from enable to disable and vice versa. Returns the index of the new image src in
 * the local Img-Src-List (locImgSrcList).
 * If no toggle could be performed, -1 is returned. 
*/
function toggleToggleImage(locImgSrcList, imgEle) {
	var lIndex = -1;
	if (imgEle && locImgSrcList && locImgSrcList.length >=2) {
		var oldSrc = Element.readAttribute(imgEle, 'src');
		for (var i = 0; i < locImgSrcList.length; i++) {
			if (oldSrc == locImgSrcList[i]) {
				lIndex = (i==0) ? 1 : 0;
				break;
			}
		}
		if (lIndex >= 0 && lIndex < locImgSrcList.length) {
			imgEle.src = locImgSrcList[lIndex];
		}
	}
	return lIndex;
}

/*
 * Enables all toggle images in the list.
*/
function enableAllToggleImage(imgSrcList) {
	if (imgSrcList) {
		imgSrcList.each(function(pair){
			var tEle = $(pair.key);
			if (tEle) {
				var imgEles = Element.select(tEle, 'img.filterTime_boxOnOff');
				if (imgEles && imgEles.length > 0) {
					var imgEle = imgEles[0];
					imgEle.src = pair.value[0];
				}
			}
		});
	}
}

/*
 * Adds the sorting param to the form.
 * If the field is not yet present, a hidden field is generated.
 * If it already exists, the value will be set to teh new value. But only a hidden field or a select
 * box is supoorted (where the value must exist).
*/
function addSortingParam(sortingParam) {
	var paramKey = 'orderby';
	var allEles = $(recipeSearchForm).getElements();
	if (allEles && allEles.length > 0) {
		var sortEle = null;
		for (var i = 0; i < allEles.length; i++) {
			if (allEles[i].name == paramKey) {
				sortEle = allEles[i];
				break;
			}
		}
		if (sortEle && (sortEle.type != 'hidden')) {
			if (sortEle.type == 'select-one') {
				var index = -1;
				for (var i = 0; i < sortEle.options.length; i++) {
					if (sortEle.options[i].value == sortingParam) {
						index = i;
						break;
					}
				}
				if (index >= 0 && i < sortEle.options.length) {
					sortEle.selectedIndex = index;
				}
			}
		} else {
			setHiddenInput(paramKey, sortingParam);
		}
	}
}


/* 
*/
function sendFormSubmit(ratingParam, maxTimeParam, sortingParam) {
	if ($(recipeSearchForm)) {
		if (ratingParam != null) setHiddenInput('minrating', ratingParam);
		if (maxTimeParam != null) setHiddenInput('maxtime', maxTimeParam);
		if (sortingParam && sortingParam != '') {
			addSortingParam(sortingParam);
		}
		$(recipeSearchForm).submit();
	}
}

/* Sets the value of the forms hidden field. If the hidden field does not exist, it will be
 * generated. 
*/
function setHiddenInput(key, value) {
	var elems = $(recipeSearchForm).getInputs('hidden', key);
	var field = null;
	if (elems.length > 0) {
		field = elems[0];
	} else {
		field = document.createElement('input');
		field.type = 'hidden';
		field.name = key;
		$(recipeSearchForm).appendChild(field);
	}
	field.value = value;
}

