/////////////////////////////////////////// BASIC FUNCTIONS, DON'T EDIT ///////////////////////////////////////////

/**
 * Starts executing the initializing functions when either the DOM structure of the page has been loaded ('domready'), or the entire page ('load').
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses Mootools 1.2.1 JavaScript Library
 */
window.addEvents({
	'domready': function() {
		/*startProtection();*/

		/* General calls */
		initDebugger();
		initExternalLinks();
		
		/* CSD calls */
		initRatingIndicator();
		initInputSliders();
		initWineOverviewTableOddEven();
		initWineOverviewTooltips();
		initF6WineNewsTabs();
		initF24Popup();
		initF35FaqAccordion();
		initF41FormPanel();
		initF64WineShopInfo();
		
		/* Dev calls */
		initDetailInfoTabs();
		initResetButton();
		initSearchForm();
		initTips();
		initInvulhulp();
		initCancelShadowbox();
		initPrefillField();
		initPopupForm();
		initShadowboxLink();
		initPersonalRatingForm();
		initDetailFieldset();
		initTastingNote();
				
		if (document.getElements('div.actionbox li a')) {
			makeEqualHeight(document.getElements('div.actionbox li a'));
		}
		
	},
	'load': function() {
		/* CSD calls */
		initPaginatorCentering();
		initF12WineCellar();
		initF4Pushbox();
		initF16WineInfoPanel();
	}
});

function init(){
	fixErrorTooltips();
}



/**
 * initDebugger
 * In case the Firebug add-on is present in Firefox, it's console is used (only when enabled), else an alert is shown instead.
 * 
 * @author Ralph.Meeuws (ralph.meeuws[AT]efocus.nl)
 * @usage log(my_variable);
 * @return void
 */
function initDebugger() {
	log = (Browser.Engine.gecko && window.console) ? function(msg){console.log(msg)} : function(msg){alert(msg)};
}



/**
 * initExternalLinks
 * Opens external links valid in a new window without the target attribute.
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses <a href="http://www.efocus.nl/" class="external">eFocus</a>
 */
function initExternalLinks() {
	var arrExternalLinks = $$('a.external');
	if (arrExternalLinks.length == 0) return;
	
	arrExternalLinks.each(function(elExternalLink) {
		elExternalLink.addEvent('click', function(event) {
			event.stop();
			window.open(this.get('href'));   
		});
	});
}



/////////////////////////////////////////// CLIENT-SIDE JAVASCRIPT FUNCTIONS ///////////////////////////////////////////

/**
 * initRatingIndicator
 * Resizes the fill of the rating indicator depending on the number inside.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initRatingIndicator() {
	var arrRatings = $$('.rating');
	if (arrRatings.length == 0) return;
	
	arrRatings.each(function(elRating){
		intRatingValue = elRating.getElement('.rating_value').get('text');
		intRatingFillWidth = ((elRating.getElement('.rating_bg').getWidth() / 100) * intRatingValue).toInt();
		elRating.getElement('.rating_fill').setStyle('width', intRatingFillWidth);
	});
}



/**
 * initPaginatorCentering
 * Centers paginators compared against its parent.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initPaginatorCentering() {
	var arrPaginators = $$('.paginator');
	if (arrPaginators.length == 0) return;
	
	arrPaginators.each(function(elPaginator){
		var intPaginatorDivider = (!Browser.Engine.trident4) ? 2 : 4;
		var intPaginatorOffsetLeft = ((elPaginator.getParent().getWidth() - elPaginator.getWidth()) / intPaginatorDivider).toInt();
		elPaginator.setStyle('margin-left', intPaginatorOffsetLeft);
	});
}



/**
 * initInputSliders
 * Injects a slider replacing the hidden input for setting the slider value.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initInputSliders() {
	var arrSliderFields = $$('.slider_field');
	if (arrSliderFields.length == 0) return;
	
	arrSliderFields.each(function(elSliderField){
		var strSliderFieldId = elSliderField.getProperty('id');
		
		var elInputSlider = new Element('div', {'id': strSliderFieldId + '_slider','class': 'input_slider'});
		var elInputSliderKnob = new Element('div', {'id': strSliderFieldId + '_slider_knob', 'class': 'input_slider_knob'});
		var elInputSliderFeedback = new Element('p', {'id': strSliderFieldId + '_slider_feedback', 'class': 'input_slider_feedback'});
		
		elInputSliderKnob.inject(elInputSlider);
		elInputSlider.injectBefore(elSliderField);
		elInputSliderFeedback.injectAfter(elInputSlider);
		
		var objInputSlider = new Slider(elInputSlider, elInputSliderKnob, {
			offset: -1,
			onChange: function(step) {
				elSliderField.value = step;
				elInputSliderFeedback.set('text', step);
			}
		});
		
		objInputSlider.set(elSliderField.value);
	});
}



/**
 * initWineOverviewTableOddEven
 * Adds a class to the even rows of the wine overview table, but never on a row containing tableheads.
 *
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initWineOverviewTableOddEven() {
	var arrWineOverviews = $$('.wine_overview');
	if (arrWineOverviews.length == 0) return;
	
	arrWineOverviews.each(function(elWineOverview){
		elWineOverview.getElements('tr:even').each(function(elWineOverviewTableRowEven){
			if (!elWineOverviewTableRowEven.getElement('th')) elWineOverviewTableRowEven.addClass('even');
		});
	});
}

/**
 * initF4Pushbox
 * Loads the Swiff pushbox and sets flashvars and flashparams
 *
 * @author Rocco Janse (rocco[AT]efocus.nl)
 * @return void
 */

function initF4Pushbox() {
	var arrPushboxes = $$('.pushbox');
	if (arrPushboxes.length == 0) return;
	var i = 1;
	
	arrPushboxes.each(function(elPushbox) {
		
		//load Swiff
		var objPushbox = new Swiff('/fileadmin/templates/flash/pushbox.swf', {
			container: elPushbox.getElement('.pushbox_content'),
			id: 'pushbox_'+i,
			width: 576,
			height: 270,
			params: {
				wMode: 'opaque'
			},
			vars: {
				xmlurl: elPushbox.getElement('.pushbox_xml').get('text')
			}
		});
		
		i++;
	});
	
}



/**
* initF6WineNewsTabs
*
* Change tab content for 2 tabs.
*
* @author Klaas Dieleman <klaas.dieleman{AT}efocus.nl>
* @editor Rou-hun Fan <rouhun.fan{AT}efocus.nl>
* @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
* @return void
*/

function initF6WineNewsTabs() {
	if (!document.getElement('.wine_news')) return;
	
	var elWineNews = document.getElement('.wine_news');
	var arrWineNewsHeadsLinks = elWineNews.getElements('.wine_news_head_nav a');
	var arrWineNewsPanels = elWineNews.getElements('.wine_news_panel');
	
	arrWineNewsHeadsLinks.each(function(elWineNewsHeadLink, n){
		elWineNewsHeadLink.addEvent('click', function(event){
			event.stop();
			this.blur();
			
			if(this.id == 'link_interesting_wines') {
				$('interesting_wines').set('html', '<img src="fileadmin/templates/img/icon_loader_home.gif" alt="Waiting..." class="waiting_home" />');
				tx_uwc_pi50getInterestingWines();
			}
			
			arrWineNewsHeadsLinks.getParent().getParent().removeClass('active');
			this.getParent().getParent().addClass('active');
			arrWineNewsPanels.addClass('hidden');
			arrWineNewsPanels[n].removeClass('hidden');
		});
	});
	
	arrWineNewsPanels[arrWineNewsPanels.length-1].addClass('hidden');
}



/**
 * initF12WineCellar
 * Loads the Swiff movie and toggles the panel view
 *
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @return void
 */
function initF12WineCellar() {
	var arrWineCellars = $$('.virtual_winecellar');
	if (arrWineCellars.length == 0) return;

	arrWineCellars.each(function(elWineCellar){		
		//load Swiff
		var objVirtualWineCellar = new Swiff('/fileadmin/templates/flash/winerack.swf', {
			container: elWineCellar.getElement('.winecellar_content'),
			id: 'virtualWineCellar',
			width: '774',
			height: '190',
			params: {
				wMode: 'window'
			},
			vars: {
				xmlLoc: elWineCellar.getElement('.winecellar_xml').get('text')
			}
		});
		
		elWineCellarHandle = elWineCellar.getElement('.winecellar_handle'); 
		elWineCellarPanel = elWineCellar.getElement('.winecellar_panel'); 
		if (!elWineCellarHandle && !elWineCellarPanel) return;
		
		elWineCellarHandle.addEvent('click', function() {
			if (elWineCellar.hasClass('closed')) {
				elWineCellar.removeClass('closed');	
			} else {
				elWineCellar.addClass('closed');
			}
		});
		
		// toggle total value
		elLinkShowTotalValue = elWineCellar.getElement('.link_show_total_value');
		elWineCellarTotalValue = elWineCellar.getElement('.winecellar_total_value');
		
		if(elLinkShowTotalValue) {
			elLinkShowTotalValue.addEvent('click', function(){
				elLinkShowTotalValue.addClass('hidden');
				elWineCellarTotalValue.removeClass('hidden');
			});
			elWineCellar.getElement('.link_hide_total_value').addEvent('click', function(){
				elLinkShowTotalValue.removeClass('hidden');
				elWineCellarTotalValue.addClass('hidden');
			});
		}
	});
}



/**
 * initF16WineInfoPanel
 * Handles panel functionality (sliding, amount resizing)
 *
 * @author Rocco Janse <rocco[at]efocus.nl>
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @param string $handle handle to activate slider
 * @param string $element element to hide
 * @return void
 */
 
function initF16WineInfoPanel() {
	// find box(es)
	var arrWineInfoBoxes = $$('.wineinfo_box');
	if (arrWineInfoBoxes.length == 0) return;
	
	arrWineInfoBoxes.each(function(elWineInfoBox) {
		// get elements and check if present
		elWineInfoHandle = elWineInfoBox.getElement('.wineinfo_handle'); 
		elWineInfoPanel = elWineInfoBox.getElement('.wineinfo_panel'); 
		if (!elWineInfoHandle && !elWineInfoPanel) return;
		
		var fxWineInfo = new Fx.Slide(elWineInfoPanel, {
			duration: 1000,
			transition: Fx.Transitions.Pow.easeOut
		});
		
		// add event to toggle panel sliding
		elWineInfoHandle.addEvent('click', function() {
			this.blur();
			fxWineInfo.toggle();
			if (fxWineInfo.open) {
				elWineInfoBox.addClass('closed');	
			} else {
				elWineInfoBox.removeClass('closed');
			}
		});
		
		// hide the panel initially when class "closed" is present
		if (elWineInfoBox.hasClass('closed')) {
			fxWineInfo.hide();
		}
		
		// detect length of number as amount
		elWineInfoAmount = elWineInfoBox.getElement('.wineinfo_amount');
		if(elWineInfoAmount) {
			intAmountLength = elWineInfoAmount.get('text').length;
		
			if (intAmountLength == 3) {
				elWineInfoAmount.addClass('digits3');
			} else if (intAmountLength >= 4) {
				elWineInfoAmount.addClass('digits4');
			} else {
				elWineInfoAmount.removeClass('digits3');
				elWineInfoAmount.removeClass('digits4');
			}
		}
	});
}



/**
 * initWineOverviewTooltips
 * Loads the tooltip info for the wine overview and adds the events to the appropriate button.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initWineOverviewTooltips () {
	var arrWineOverviews = $$('.wine_overview');
	if (arrWineOverviews.length == 0) return;
	
	arrWineOverviews.each(function(elWineOverview){
		arrWineOverviewTooltipLinks = elWineOverview.getElements('.tooltip_link');
		if (arrWineOverviewTooltipLinks.length == 0) return;
		
		var objF31Tooltips = new WineTooltips('.tooltip_link', {
			className: 'wine_edit_tooltip',
			hideDelay: 500,
			offset: {x: -224, y: -155},
			fixed: true
		});
		
		arrWineOverviewTooltipLinks.each(function(elWineOverviewTooltipLink){
			tooltipContent = elWineOverviewTooltipLink.getParent().getParent().getElement('.tooltip_content');
			elWineOverviewTooltipLink.store('tip:title', tooltipContent.getElement('h4'));
			elWineOverviewTooltipLink.store('tip:text', tooltipContent.getElement('ul'));
		});
	});
}


/**
 * WineTooltips
 * New MooTools class based on Tips Class (MooTools 1.2.2) for creating custom wine tooltips.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
var WineTooltips = new Class({
	Extends: Tips,
	
	options: {
		onHide: null
	},
	
	initialize: function(options){
		
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		if (params.options && params.options.offsets) params.options.offset = params.options.offsets;
		this.setOptions(params.options);
		//this.container = new Element('div', {'class': 'tip'});
		//this.tip = this.getTip();
		
		//if (params.elements) this.attach(params.elements);
		
		this.parent(options);
		
		this.tipEnter(); // ADDED
		this.tipLeave(); // ADDED
		this.tipArrow(); // ADDED
	},
	
	elementEnter: function(event, element){
		$A(this.container.childNodes).each(Element.dispose);
		
		['title', 'text'].each(function(value){
			var content = element.retrieve('tip:' + value);
			if (!content) return;
			
			this[value + 'Element'] = new Element('div', {'class': 'tip-' + value}).inject(this.container);
			this.fill(this[value + 'Element'], content);
		}, this);
		
		this.timer = $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this, element);
		this.tip.setStyle('display', 'block');
		
		this.options.offset.y = -this.tip.getHeight() + 40; // ADDED
		
		this.position((!this.options.fixed) ? event : {page: element.getPosition()});
		
		this.tip.fade('in'); // ADDED
	},

	elementLeave: function(event, element){
		$clear(this.timer);
//		this.tip.setStyle('display', 'none');
		this.timer = this.hide.delay(this.options.hideDelay, this, element);
	},
	
	tipEnter: function(){
		this.tip.addEvent('mouseenter', function(){
			$clear(this.timer);
		}.bind(this));
	},
	
	tipLeave: function(){
		this.tip.addEvent('mouseleave', function(){
			this.tip.fade('out');
		}.bind(this));
	},
	
	tipArrow: function(){
		new Element('div', {'class': 'tip-arrow'}).injectInside(this.tip);
	},
	
	hide: function(el){
//		this.fireEvent('hide', [this.tip, el]);
		this.tip.fade('out');
	}

});



/**
 * initF24Popup
 * Shows a popup when clicked on the delete-link in the tooltip.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initF24Popup () {
	if ($$('.link_confirm_delete').length == 0) return;
	
	arrConfirmDeleteLinks = $$('.link_confirm_delete');
	
	arrConfirmDeleteLinks.each(function(elConfirmDeleteLink){
		var strConfirmDeleteLinkHref = elConfirmDeleteLink.getProperty('href');
		elConfirmDeleteLink.setProperty('href', 'javascript:void(0);');
		elConfirmDeleteLink.addEvent('click', function(){
			Shadowbox.open({
				player: 'html',
				content: '<div class="wishlist_popup"><p>Verwijder deze wijn van uw wishlist.</p><p><a href="#" class="button">OK</a></p></div>',
				width: 178,
				height: 78
			});
		});
	});
}



/**
 * initF35FaqAccordion
 * Adds the accordion effect to the FAQ list.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initF35FaqAccordion() {
	if (!document.getElement('.faq_list')) return;
	
	var elFaqList = document.getElement('.faq_list');
	var arrFaqListTogglers = elFaqList.getElements('h3');
	var arrFaqListPanels = elFaqList.getElements('div.panel');
	
	var objFaqAccordion = new Fx.Accordion(arrFaqListTogglers, arrFaqListPanels, {
		onActive: function(elFaqListToggler){
			elFaqListToggler.getParent().addClass('active');
		},
		onBackground: function(elFaqListToggler){
			elFaqListToggler.getParent().removeClass('active');
		}
	});
}



/**
 * initF41FormPanel
 * Enables the formpanel show/hide toggle functionality.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initF41FormPanel() {
	if (!document.getElement('.wine_search_filter_handle') || !document.getElement('.wine_search_filter')) return;
	
	var elWineSearchFilterHandle = document.getElement('.wine_search_filter_handle');
	
	var fxF41FormSlide = new Fx.Slide(document.getElement('.wine_search_filter'), {transition: Fx.Transitions.Pow.easeOut});
	
	elWineSearchFilterHandle.addEvent('click', function(){
		this.blur();
		fxF41FormSlide.toggle();
		if (fxF41FormSlide.open) {
			elWineSearchFilterHandle.getParent().addClass('closed');
		} else {
			elWineSearchFilterHandle.getParent().removeClass('closed');
		}
	});
}



/**
 * initF52ManageGeneralPersonalRating
 * Makes the rating clickable for setting its value.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initF52ManageGeneralPersonalRating() {
	if (!document.getElement('.manage_general_personal_rating')) return;
	
	elGeneralPersonalRating = document.getElement('.manage_general_personal_rating').getElement('.rating');
	
	elGeneralPersonalRatingValue = elGeneralPersonalRating.getElement('.rating_value');
	elGeneralPersonalRatingFill = elGeneralPersonalRating.getElement('.rating_fill');
	elGeneralPersonalRatingBg = elGeneralPersonalRating.getElement('.rating_bg');
	intGeneralPersonalRatingWidth = elGeneralPersonalRatingBg.getWidth();
	
	elGeneralPersonalRating.addEvent('click', function(event){
		intGeneralPersonalRatingFillX = event.page.x - elGeneralPersonalRatingFill.getPosition().x;
		if (intGeneralPersonalRatingFillX < 0) {
			intGeneralPersonalRatingFillWidth = 0;
		} else if (intGeneralPersonalRatingFillX > intGeneralPersonalRatingWidth) {
			intGeneralPersonalRatingFillWidth = intGeneralPersonalRatingWidth;
		} else {
			intGeneralPersonalRatingFillWidth = event.page.x - elGeneralPersonalRatingFill.getPosition().x;
		}
		elGeneralPersonalRatingFill.setStyle('width', intGeneralPersonalRatingFillWidth);
		elGeneralPersonalRatingValue.set('text', ((intGeneralPersonalRatingFillWidth / intGeneralPersonalRatingWidth) * 100).round());
	});
}



/**
 * initF64WineShopInfo
 * Opens and closes the wine shop info panel.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initF64WineShopInfo(){
	if (!document.getElement('.wine_shop_info')) return;
	
	var elWineShopInfo = document.getElement('.wine_shop_info');
	var elWineShopInfoPanel = elWineShopInfo.getElement('.wine_shop_info_panel');

	var fxWineShopInfo = new Fx.Slide(elWineShopInfoPanel, {
		duration: 1000,
		transition: Fx.Transitions.Pow.easeOut
	});
	
	// add event to toggle panel sliding
	elWineShopInfo.getElement('.wine_shop_info_handle').addEvent('click', function() {
		fxWineShopInfo.toggle();
		if (fxWineShopInfo.open) {
			elWineShopInfo.addClass('closed');	
		} else {
			elWineShopInfo.removeClass('closed');
		}
	});
	
	// optionally hide the panel initially when class "closed" is present
	if (elWineShopInfo.hasClass('closed')) {
		fxWineShopInfo.hide();
	}
}



/**
 * initInvulhulp
 *
 * 
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function initInvulhulp() {	
	
	$$('span.invulhulpcontainer').each(function(item) {

		item.getElement('select').addEvent('change', function() {
			if (item.getElement('select').getSelected().getProperty('value') != '_emptyvalue_') {
				item.getElement('input').setProperty('value', item.getElement('select').getSelected().get('text'));
			}			
			item.getElement('input').focus();
		});
	});
}



/**
 * fixErrorTooltips
 * fixes 'left-overs' of tooltips
 *
 * @author Rocco Janse, <rocco[at]efocus.nl>
 * @return void()
 */
function fixErrorTooltips() {	
	var errortips = $$(document.body).getElements('div.errortipcontainer');
	if (errortips == 0) return;
	errortips.each(function(tip) {
		tip.setStyle('visibility', 'hidden');
	});
}



/**
 * initTips
 *
 * attaches customly styled tooltip to form fields
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function initTips() {
	$$('.formtip').each(function(el) {
		
		if(el.get('title')){
			var content = el.get('title').split('::');   
			el.store('tip:title', content[0]);   
			el.store('tip:text', content[1]);
		}
	});
	
	$$('.errortip').each(function(el) {
		
		if(el.get('title')){
			var content = el.get('title').split('::');   
			el.store('tip:title', content[0]);   
			el.store('tip:text', content[1]);
		}
	});
	
	var formtips = new eFocusTips('.formtip', {
		className: 'formtipcontainer',
		offsets: {'x': 170, 'y': 1},
		fixed: true,
		triggerEvent: 'focus',
		fitInWindow: false
	});
	var errortips = new eFocusTips('.errortip', {
		className: 'errortipcontainer',
		offsets: {'x': 35, 'y': -8},
		fixed: true,
		triggerEvent: 'hover',
		fitInWindow: false
	});
}





/////////////////////////////////////////// DEVELOPMENT JAVASCRIPT FUNCTIONS ///////////////////////////////////////////

/**
 * initDetailInfoTabs
 * Centers paginators compared against its parent.
 * 
 * @author Richard van Yperen
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initDetailInfoTabs() {	
	if (document.getElement('.wine_vintage_info_nav')) {
		var arrExtDetailsTabNavListItems = document.getElement('.wine_vintage_info_nav').getElements('a');
		
		arrExtDetailsTabNavListItems.each(function(elExtDetailsTabNavListItem){
			elExtDetailsTabNavListItem.addEvent('click', function(){
				tx_uwc_pi75getXajaxTabdetails(this.id.replace(/link_/,''));
			});
		});
	} else if (document.getElement('.extended_details_tab_nav')) {
		var arrExtDetailsTabNavListItems = document.getElement('.extended_details_tab_nav').getElements('a');
		
		arrExtDetailsTabNavListItems.each(function(elExtDetailsTabNavListItem){
			elExtDetailsTabNavListItem.addEvent('click', function(){
				tx_uwc_pi17getXajaxTabdetails(this.id.replace(/link_/,''));
			});
		});
	}
}

/**
 * initResetButton
 * Resets the search form.
 * 
 * @author Richard van Yperen
 * @return void
 */
function initResetButton() {
	
	if($('link_reset_pi63')) {
		$('link_reset_pi63').addEvent('click', function() {
			var winetype = $('tx_uwc_pi63_wine_type').value;
			tx_uwc_pi63processForm(0, winetype);
			initSearchForm();
		});
	} 
	
	if($('link_reset_pi64')) {
		$('link_reset_pi64').addEvent('click', function() {
			tx_uwc_pi64processForm(0);
			initSearchForm();
		});
	} 
	
	if($('link_reset_pi3')) {
		$('link_reset_pi3').addEvent('click', function() {
			tx_uwc_pi3processForm(0);
			initSearchForm();
		});
	} 
	
	if($('link_reset_pi8')) {		
		$('link_reset_pi8').addEvent('click', function() {						
			tx_uwc_pi8processForm(false);
			var defaultKeyWord = document.getElement('.keywordsearch').title;
			document.getElement('.keywordsearch').value = defaultKeyWord;
			initSearchForm();
		});
	}
	
	if (document.getElement('.search_facet')) {
		var searchButton = document.getElement('.search_facet');		
		searchButton.addEvent('click', function () {
			$('search_facet').value = 1;
		});
	}	
}

/**
 * initSearchForm
 * Init Search form
 * 
 * @author Richard van Yperen
 * @return void
 */
function initSearchForm() {

	if(document.getElement('.keywordsearch')) {
		
		var defaultKeyWord = document.getElement('.keywordsearch').title;
		
		document.getElement('.keywordsearch').addEvent('click', function() {
			if(document.getElement('.keywordsearch').value==defaultKeyWord) {
				document.getElement('.keywordsearch').value = '';
			}
		});
		
	}
	
	if (document.getElements('input.search_facet')) {
		var searchButton = document.getElements('input.search_facet');	
		searchButton.each(function (el) {
			el.addEvent('click', function () {
				$('search_facet').value = 1;
			})
		});
	}	

}

/**
 * displayErrors
 * Displays errors.
 * 
 * @author Gijs Epping (gijs.epping[AT]efocus.nl)
 * @return void
 */
function displayErrors(error){
	
	/*
	 * Nog een keer aanroepen, omdat deze functie altijd met parameters aangeroepen wordt en initialiseren dus misgaat
	 * @author Aart de Bruijn (aart.de.bruijn[AT]efocus.nl)
	 * gewijzigd op 27-04-09
	 */
	
	if(!error) return;

	var myObject = JSON.decode(error);
	
		$$('.error').each(function(el){
			if(el.get('tag')!='li'){
				el.removeClass('error');
			}
		});
		
		$$('.errortip').each(function(el){
			el.setStyle('display','none');
		});
		
		myObject.each(function(obj){
			if($(obj.id) || $('error_'+obj.id) ){
				if($(obj.id)) $(obj.id).addClass('error');
				if($('error_'+obj.id)) $('error_'+obj.id).setStyle('display','block');
			}
		});
		
	
}

function isArray(obj) {
	return (obj.constructor.toString().indexOf("Array") != -1);
}

function displayErrorMessage(error) {
	if(!error) return;
	var myObject = JSON.decode(error);
	
	if($$('div.error_report').length > 0) {

		var html = '<h3>'+myObject.title+'</h3>';
		html += '<ul>';
		myObject.error.each(function(obj){			
			html += '<li>'+obj+'</li>';
		});
		html += '</ul>';
		
		$$('div.error_report').set('html', html);
		$$('div.error_report').removeClass('hidden');
	}
}

/**
 * editShadowbox
 * shows Shadowbox
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function editShadowbox(urls, classNames) {
	
	switch(classNames) {
    	case 'button shadowbox middlebox':
    	case 'shadowbox middlebox':
    		 Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '250', 'width': '550' });
    	break;
    	case 'button shadowbox addtocellar':
    		 Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '230', 'width': '550' });
    	break;
    	case 'button shadowbox smallbox':
    	case 'shadowbox smallbox':
    		 Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '150', 'width': '420' });
    	break;
    	case 'shadowbox claim':
    		 Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '300', 'width': '650' });
    	break;
    	case 'shadowbox imagepreview':
    		 Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '375', 'width': '500' });
    	break; 
    	case 'shadowbox button edit':
    		Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '430', 'width': '650' });
    	break;
    	case 'shadowbox button edittastingnote':
    		Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '570', 'width': '650' });
    	break;    	
    	default:
    		Shadowbox.open({'player': 'iframe', 'content': urls, 'height': '700', 'width': '650' });
    }
    
    return;
   
}

/**
 * initToolTips
 * replaces the links of inside the tool tips with shadowbox onclicks
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initToolTips() {

	if (document.getElements('.tooltip_content').length == 0) return;

	document.getElements('.tooltip_content').each(function(el) {
		el.getElements('.shadowbox').each(function(item) {
			var itemurl = item.href;
			var className = item.className;
			item.erase('href'); 
			item.addEvent('click', function() {
				editShadowbox(itemurl, className);
			});
		})
	});
	
}

/**
 * initCancelShadowbox
 * searches for all cancel shadowbox links/buttons and gives them an onclick to close the shadowbox
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initCancelShadowbox() {
	if ($$('.cancelshadowbox').length == 0) return;

	$$('.cancelshadowbox').each(function(el) {
		el.addEvent('click', function() {
			self.parent.Shadowbox.close();
		});			
	});
}

/**
 * initPrefillField
 * searches for all autocomplete textfields en supplies them with a autocomplete box
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initPrefillField() {
	if ($$('.autocomplete').length > 0) {
	
		$$('.autocomplete').each(function(el) {
			// Disables the autocomplete feature of the browser when a custom autocomplete is being used.
			el.setProperty('autocomplete', 'off');
			
			el.addEvent('keyup', function() {
				if(el.value.length > 3) {
					tx_uwc_pi41processKeywordSearch(el.value);
				}
			});
			
			$(el.id+'_submit').addEvent('click', function() {
				if($('form_autocompletion_wineId').value != '') {
					tx_uwc_pi41getFilledFieldset($(el.id+'_wineId').value);
				}
			});
			
			// if wineId is known, load filled fieldset
			if($(el.id+'_wineId').value > 0) {
				tx_uwc_pi41getFilledFieldset($(el.id+'_wineId').value);
			}
		});
	}
	
	if ($$('.searchfield').length > 0) {
	
		$$('.searchfield').each(function(el) {
									
			$('form_search_submit').addEvent('click', function() {
				if($('form_searchfield').value != '') {
					tx_uwc_pi41gotoSearch($('form_searchfield').value);
				}
			});			
			
		});
	}
}

/**
 * initPrefillList
 * events for the prefill search result list
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initPrefillList(listId) {
	if (!$(listId)) return;

	$(listId).removeClass('hidden');
	
	$(listId).getElements('li').each(function(el) {
		el.addEvent('click', function() {
			var id =  el.id.replace(listId+'_', '');
			var fieldId = listId.replace(/_list/, '');			
			$(fieldId).value = el.get('text');
			$(fieldId+'_wineId').value = id;
			$(listId).addClass('hidden');
			$('form_autocompletion_submit').removeClass('disabled');			
		});
	});

}

function initDetailFieldset() {
	if($('fieldset_details') && $('tx_uwc_pi3_winelabel')) {
		if($('tx_uwc_pi3_winelabel').value > 0) {
			showDetailFieldset();
		}
	}	
}

function showDetailFieldset() {
	if($('fieldset_details')) {
		$('fieldset_details').removeClass('hidden_alt');
		$('fieldset_none').removeClass('hidden_alt');
		$('fieldset_save').removeClass('hidden');	
	}
}

/**
 * initPopupForm
 * some events for popup forms
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initPopupForm() {
	// onclick for bid/sale radiobuttons
	if($$('.form_sell').length != 0) {
		// if already checked
		if($('form_sell_bid') && $('form_sell_bid').checked) {
			$('form_saledate_field').removeClass('hidden');
		}
		
		// onclick
		$$('.form_sell').each(function(el) {
			el.addEvent('click', function() {
				if(el.id == 'form_sell_bid') {
					$('form_saledate_field').removeClass('hidden');
				} else {
					$('form_saledate_field').addClass('hidden');
				}
			});
		});
	}	
}

/**
 * initShadowboxLink
 * some events links to be opened in a lightbox
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initShadowboxLink() {
	
	// to open links into a shadowbox
	if ($$('.shadowbox').length != 0) {
		$$('.shadowbox').each(function(elShadowboxLink) {			
			
			var itemurl = '/'+elShadowboxLink.getProperty('href');
			var className = elShadowboxLink.className;
			elShadowboxLink.setProperty('href', 'javascript:void(0);');
			elShadowboxLink.addEvent('click', function(event) {
				event.stop(0);
				if(this.hasClass('bidding')) {
					itemurl = itemurl+'&tx_uwc_pi58[bid]='+$('maxbid').value.replace(/,/, '.');
				}
				editShadowbox(itemurl, className);								
			});
		});
	}

	// to close a shadowbox with a given url
	if ($$('.closeShadowbox').length != 0) {
		$$('.closeShadowbox').each(function(elCloseShadowboxLink) {
			var itemlink = elCloseShadowboxLink.getProperty('href');
			elCloseShadowboxLink.setProperty('href', 'javascript:void(0);');
			elCloseShadowboxLink.addEvent('click', function() {
				window.parent.location = itemlink;
			});
		});
	}
	
}

/**
 * initPersonalRatingForm
 * save and reset function for personal rating form
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function initPersonalRatingForm() {
	if($('saverating')) {
		$('saverating').addEvent('click', function() {
			var value = $('form_rating').value;
			tx_uwc_pi39processForm('save', value);
		});
	}
	if($('resetrating')) {
		$('resetrating').addEvent('click', function() {
			tx_uwc_pi39processForm('reset', 0);
		});
	}		
}

/**
 * setPersonalRatingForm
 * action after saving or reseting personal rating form
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function setPersonalRatingForm(value, text, notavailable) {
	$('rating').innerHTML = value;
	window.parent.$('pi15_rating').set('text', value=='&nbsp;' ? notavailable :  value);
	window.parent.$('pi15_text').set('text', text);
}

/**
 * activateWaitImage
 * sets waiting image on place of 
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function activateWaitImage(plugin) {
	if(plugin=='pi7') {
		$('search_results').set('html', '<img src="fileadmin/templates/img/icon_loader_ani_footer.gif" alt="loading" />');
	} else {
		$('loading_'+plugin).removeClass('hidden');
	}
}

/**
 * deactivateWaitImage
 * removes waiting image
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function deactivateWaitImage(plugin) {
	$('loading_'+plugin).addClass('hidden');
}

/**
 * initSubscriptionForm
 * specific functions for subscription form
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function initSubscriptionForm() {
	if(document.getElements('input.accounttype').length > 0 && $('form_prefixid')) {
		document.getElements('input.accounttype').each(function(el) {
			var prefix = $('form_prefixid').value;
			switch(prefix) {
				case 'tx_uwc_pi10':
					if(el.checked) {
						tx_uwc_pi10processData(el.value, $('form_paymentperiod').value);
						/*
						if(el.value==2) {
							$('form_payment_select').addClass('hidden');
						} else {
							$('form_payment_select').removeClass('hidden');
						}*/
					}
					el.addEvent('click', function() {
						tx_uwc_pi10processData(el.value, false);
						/*if(el.value==2) {
							$('form_payment_select').addClass('hidden');
						} else {
							$('form_payment_select').removeClass('hidden');
						}*/
					});
					break;
				case 'tx_uwc_pi32':
					if(el.checked) {
						tx_uwc_pi32processData(el.value, $('form_paymentperiod').value);
					}
					el.addEvent('click', function() {
						tx_uwc_pi32processData(el.value, false);
					});
					break;				
			}			
		});
	}
}

function initTastingNote() {
	// tasting note short
	if($$('ul.tasting_notes')) {	
		$$('ul.tasting_notes').each(function(el) {
			if(el.getElements('span.delete')) {
				el.getElements('span.delete').each(function(item) {
					item.addEvent('click', function() {
						tx_uwc_pi14deleteTastingtNote(item.id.replace(/tn_/, ''));	
					});	
				});
			}
		});
	}
	
	// tasting note details
	if($$('ul.extended_details_notes_list')) {	
		$$('ul.extended_details_notes_list').each(function(el) {
			if(el.getElements('a.delete')) {
				el.getElements('a.delete').each(function(item) {
					item.addEvent('click', function() {
						tx_uwc_pi18deleteTastingtNote(item.id.replace(/tn_/, ''));	
					});	
				});
			}
		});
	}
	
}

/**
 * initTastingNoteForm
 * initiatates sliders for tasting note form
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function initTastingNoteForm() {
	if($('formtastingnote')) {
		initClassificationSlider('form_generalrating');
		initClassificationSlider('form_mouth');
		initClassificationSlider('form_nose');
		initClassificationSlider('form_eye');
	}
}

/**
 * initAddWtoWishlistForm
 * initiatates form to add wine to wishlist
 * 
 * @author Richard van Yperen (richardvy[AT]efocus.nl)
 * @return void
 */
function initAddWtoWishlistForm() {
	// removes button outsite shadowbox
	if($('addtowishlist')) {
		var wineId = $('addtowishlist').value;
		if(window.parent.$('button_addtowishlist_'+wineId)) {
			window.parent.$('button_addtowishlist_'+wineId).dispose();
		}
	}	
}

/** 
 * Gijs Epping
 * klikken bieden 
 */
 function addBid(el){
 	$('maxbid').value;
 	alert(el.href);	
 
 }
 
/**
 * starts copy protection on the site
 * disables right click and stops ctrl+c usage
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @since 1.0, 16 sept, 2009
 * @return void
 */
 
 function startProtection() {
 
 	$(document).addEvents({
 		'contextmenu': function(event) {
 			event.stop();
 		},
 		'keydown': function(event) {
 			if (event.key == 'c' && event.control) {
 				event.stop();
 			}
 		}
 	});
 
 }
 
 
/**
 * removes import record
 *
 * @author Richard van Yperen <richardvy@efocus.nl>
 * @since 1.0, 15 Mar, 2010
 * @return void
 */
 
 function removeImportRecord(uid) {
 	tx_uwc_pi65processRemoveRecord(uid);
 }
	
	
/**
* equals the height of the elements in an array
*
* @author Mirjam
* @since 1.0, dec 2010
* @param array - elements to equalize
* @param integer - optional amount of columns per row
*/

function makeEqualHeight(arrElements, intColumns) {
	
	var intMaxheight = 0;
	var arrCurrentRow = new Array();
	
	arrElements.each(function(item, index) {
		
		item.setStyle('height', 'auto');
		var intHeight = item.getSize().y;
		if (intHeight > intMaxheight) {
			intMaxheight = intHeight;
		}
		arrCurrentRow.push(item);
		
		
		if((index+1)%intColumns == 0) {
			arrCurrentRow.each(function(el) {
				el.setStyle('height', intMaxheight);
			});
			intMaxheight = 0;
			arrCurrentRow = [];
		}
		
	});
	
	arrCurrentRow.each(function(el) {
		el.setStyle('height', intMaxheight);
	});
	
}

/**
* sets waiting row and loads new row or adding a cepage
*
* @author Richard
* @since 1.0, jan 2011
*/

function addCepageRow(add) {
	
	// replace select with hidden field
	$('list').getElements('select').each(function(el) {
		
		var optName = 'unknown';
		
		el.getElements('option').each(function(opt) {
			if(opt.selected) {
				optName = opt.innerHTML
			}
		});
		
		var fieldEl = new Element('span', {
			'class': 'cepage',
			'html': optName+'<input type="hidden" name="tx_uwc_pi76[cepage][]" value="'+el.value+'" />'			
		});
		
		fieldEl.replaces(el);
		
	});
	
	$('list').getElements('input').each(function(el) {
		if (el.type == 'text') {
			var val = parseInt(el.value) > 0 ? parseInt(el.value) : 0;
			var fieldEl = new Element('span', {
				'class': 'percent',
				'html': val+'% <input type="hidden" name="tx_uwc_pi76[percentage][]" value="'+val+'" />'			
			});
			
			fieldEl.replaces(el);
		}
	});
	
	if (add) {
	
		// set waiter
		$('waiting').removeClass('hidden');	
		
		var data = xajax.getFormValues('information_edit');
		
		// load row
		tx_uwc_pi76addCepageRow(data);
			
	}
}

/**
* removes item from cepage list
*
* @author Richard
* @since 1.0, jan 2011
*/

function deleteCepageRow(row) {
	$(row).dispose();
}

function checkCepages() {
	if ($('cepage-form')) {
		var total = 0;	
		addCepageRow(false);	
		// percentages must be 100%
		$('list').getElements('input').each(function(el) {
			if (el.name == 'tx_uwc_pi76[percentage][]') {
				total += parseInt(el.value);
				
			}
		});
		if (total != 100) {
			return false;
		}
	}	
	return true;
}
