/**
* initializes carrousels
*
* @author Lowen, <lowen@efocus.nl>
* @version jun 2011
* @returns void
*/

function initCarrousel() {
	jQuery('div.carrousel_holder').each(function (index, el) {

		var thisCarrousel = new Carrousel(
			jQuery(el).find('ul.carrousel'),
			jQuery(el).find('a.btn_next'),
			jQuery(el).find('a.btn_prev')
		);
	});
}

/**
* Switches language
*
* @author Phi Son Do <phison.do[AT]efocus.nl>
* @version june 2011
* @returns void
*/
function switchLanguage(){
	jQuery("#lang").bind("change", function() { 
		jQuery("#lang option:selected").each(function(i, selected){ 
			this[i] = jQuery(selected).val();
			document.location.href = this[i];
		});
	});
}

/**
* Initializes googlemaps
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @version june 2011
* @returns void
*/

function initGoogleMaps() {

	if (jQuery('#map').length == 0) { return false }

	var defaultInput = jQuery('div.bg_map fieldset span.default').text();

	if (jQuery('div.bg_map fieldset select').val()) {
		var inputText;
		if (defaultInput != jQuery('div.bg_map fieldset input').val()) {
			inputText = jQuery('div.bg_map fieldset input').val();
		}
		showDealers(jQuery('div.bg_map fieldset select').val(), inputText);
	}

	// search form
	jQuery('div.bg_map fieldset input, div.bg_map fieldset select').keypress(function (e) {
		if (e.which == 13) {
			e.preventDefault();
			var inputText;
			if (defaultInput != jQuery(this).parent().find('input').val()) {
				inputText = jQuery(this).parent().find('input').val();
			}
			showDealers(jQuery(this).parent().find('select').val(), inputText);
		}
	});

	jQuery('div.bg_map fieldset a.button').click(function (e) {
		e.preventDefault()
		var inputText;
		if (defaultInput != jQuery(this).parent().find('input').val()) {
			inputText = jQuery(this).parent().find('input').val();
		}
		showDealers(jQuery(this).parent().find('select').val(), inputText);
	});

	jQuery('div.bg_map fieldset input').click(function (e) {
		jQuery(this).val('');
	});

}

/**
* show dealers on map
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @version june 2011
* @returns void
*/

function showDealers(country, query) {

	
	if (country && !query) {

		eFocus.Thetford.Thetford.webservices.Thetford.wsDealers.GetDealersByCountry(country, function (result) {
			if (result.length > 0) {
				createMap(result, country);
			} else {
				jQuery('div#map p.choose_map').css('display', 'none');
				jQuery('div#map p.error_map').css('display', 'block');
			}
		});

	} else if (query) {
	eFocus.Thetford.Thetford.webservices.Thetford.wsDealers.GetDealersByQuery(query, 50, '', country, function (result) {
		
		if (result.length > 0) {
			createMap(result, country);
		} else {
			jQuery('div#map p.choose_map').css('display', 'none');
			jQuery('div#map p.error_map').css('display', 'block');
		}
	});
}

}

/**
* create map
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @version june 2011
* @returns void
*/

function createMap(result, country) {

	var options = {
		'mapContainer': jQuery('#map')[0],
		'customIcon': '/img/Thetford/marker.png',
		'mapCenter': { lat: 36.116579, lng: 0 },
		'mapZoom': 2,
		'mapMarkerData': result,
		'showResultsInList': true,
		'showListContainer': jQuery('.list_map'),
		'selectedCountry': country
	}

	var thisMap = new Googlemaps(
		options
	);

}


/**
 * inputPlaceholder fallback for IE
 * 
 * @author Phi son Do, <phisondo@efocus.nl>
 * @version 1.0, june, 2011
 * @return false
 */
function inputPlaceholder(){
	jQuery('input').focus(function() {
		  var input = jQuery(this);
		  if (input.val() == input.attr('placeholder')) {
		  input.val('');
		  input.removeClass('placeholder');
	}
	}).blur(function() {
		var input = jQuery(this);
		if (input.val() == '' || input.val() == input.attr('placeholder')) {
		input.addClass('placeholder');
		input.val(input.attr('placeholder'));
	}
	}).blur();
	jQuery('[placeholder]').parents('form').submit(function() {
	  jQuery(this).find('[placeholder]').each(function() {
		  var input = jQuery(this);
		  if (input.val() == input.attr('placeholder')) {
			  input.val('');
		  }
	  });
	});
}

/**
* sets the rating in stars
* 
* @author Lowen, <lowen@efocus.nl>
* @version 1.0, june, 2011
* @return void
*/

function setRating() {
	var arrRating = jQuery('.star_rating');

	if (jQuery(arrRating).length != 0) {
		jQuery('.star_rating').each(function (index, elRating) {
			var strRatingClass = Math.round(parseFloat(jQuery(elRating).prop('title').split(' ', 3)[0].replace(',', '.')) * 2);
			jQuery(elRating).addClass('rating' + strRatingClass);
		});	
	}
}

/**
* rate a product
* 
* @author Lowen, <lowen@efocus.nl>
* @version 1.0, june, 2011
* @return void
*/

function rateProduct() {

	jQuery('dl.ratings_holder dd').each(function () {
		var elRatingHolder = jQuery(this).find('.review_rating');
		var arrStars = jQuery(elRatingHolder).find('li');

		if (jQuery(arrStars).length == 0) return false;

		var arrRatings = ['rating_1', 'rating_2', 'rating_3', 'rating_4', 'rating_5'];

		//set variables to empty strings, if undefined jQuery(.removeClass) will remove all classes instead
		var hoverRating = '';
		jQuery(elRatingHolder).data('currentRating', '');

		jQuery(arrStars).each(function (index, elStar) {
			jQuery(elStar).bind({
				mouseenter: function () {
					jQuery(elRatingHolder).removeClass(jQuery(elRatingHolder).data('currentRating'));
					jQuery(elRatingHolder).removeClass(hoverRating);
					hoverRating = arrRatings[index];
					jQuery(elRatingHolder).addClass(hoverRating);
				},
				click: function () {
					jQuery(elRatingHolder).data('currentRating', arrRatings[index]);
					jQuery(elRatingHolder).addClass(arrRatings[index]);
					jQuery(elRatingHolder).prev().val(index + 1);
				},
				mouseout: function () {
					jQuery(elRatingHolder).removeClass(hoverRating);
					jQuery(elRatingHolder).addClass(jQuery(elRatingHolder).data('currentRating'));
				}
			});
		});

	});
}

/**
* closes lightbox
* 
* @author Lowen, <lowen@efocus.nl>
* @version 1.0, june, 2011
* @return void
*/

function closeLightbox() {
	jQuery('.lightbox_close').click(function () {
		window.parent.parent.Shadowbox.close();
	});
}


/**
* initializes tabs and linking to tabs from text links
* 
* @author Lowen, <lowen@efocus.nl>
* @version 1.0, june, 2011
* @param elTabHolder holder of tabs 
* @return void
*/

function initTabs(elTabHolder) {
	
	jQuery(elTabHolder).tabs({
		show: function(event, ui) { 
			equalizeHeight(jQuery('div.col_sub, div.col_content, div.col_content_large, div.col_side'));  
		}
	});
	
	// link to specific tab
	jQuery('.tab_link').each(function (index, elLink) {
		jQuery(elLink).click(function () {
			
			var tab = jQuery(elLink).prop('href').split('#')[1];

			switch (tab) {
				case 'reviews':
					jQuery(elTabHolder).tabs('select', 3);
					break;
				case 'service':
					jQuery(elTabHolder).tabs('select', 2);
					break;
				case 'technical_specifcation':
					jQuery(elTabHolder).tabs('select', 1);
					break;
				case 'general_info':
					jQuery(elTabHolder).tabs('select', 0);
					break;
			}

		});
	});
}

/**
* submits form using javascript on hyperlinks with class submit
* 
* @author Lowen, <lowen@efocus.nl>
* @version 1.0, june, 2011
* @return void
*/
function submitForm() {
	var arrSubmit = jQuery('.submit');
	if (arrSubmit.length != 0) {
		jQuery(arrSubmit).click(function (event) {
			event.preventDefault();
			jQuery(arrSubmit).parents('form').submit();
		});
	}
}

/**
* Equalizes the height of elements in array
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @param arrElements, array of elements to equalize
* @version june 2011
* @returns void
*/
function equalizeHeight(arrElements) {
	if (jQuery(arrElements).length == 0) return false;
	
	var elParent;
	var intIndexCounter = intLength = 0;
	var intHeight = intMaxHeight = 0;
	var arrCurrentRow = [];

	// Calculate the number of columns per row:
	var intParentWidth = jQuery(jQuery(arrElements)[0]).parent().width();
	var intWidth = 0;
	var blnCountColumns = true;
	jQuery(arrElements).each(function(index) {
		if (intWidth >= intParentWidth) blnCountColumns = false;
		if (blnCountColumns) {
			intWidth += jQuery(this).innerWidth() + parseInt(jQuery(this).css('margin-left')) + parseInt(jQuery(this).css('margin-right'));
			if (intWidth <= intParentWidth) intColumns = index + 1;
		}
	});

	// Measure the maximum height of the items on a row:
	jQuery(arrElements).each(function(index, item) {
		// Checks if the parent element differs and thus occurs more than once on the page and thus the equalizing needs to be reset:
		if (jQuery(this).parent()[0] != jQuery(elParent)[0]) {
			elParent = jQuery(this).parent();
			intMaxHeight = 0;
			arrCurrentRow = [];
			intIndexCounter = 0;
			intLength = jQuery(elParent).children().length;
		}
		intIndexCounter++;

		jQuery(item).css('min-height', 0);
		intHeight = jQuery(item).height();

		if (intHeight > intMaxHeight) intMaxHeight = intHeight;
		arrCurrentRow.push(item);
		
		if (intIndexCounter % intColumns == 0 || intIndexCounter == intLength) {
			jQuery(arrCurrentRow).css('min-height', intMaxHeight);
			jQuery(jQuery(arrCurrentRow)[0]).addClass('left'); // Optional class for left aligned elements
			if (intIndexCounter % intColumns == 0) jQuery(jQuery(arrCurrentRow)[intColumns - 1]).addClass('right'); // Optional class for right aligned elements
			if (intIndexCounter == intLength) jQuery(arrCurrentRow).addClass('last'); // Optional class for last elements
			intMaxHeight = 0;
			arrCurrentRow = [];
		}
	});
}


/**
* Equalizes elements within other elements to be equalized.
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @version may 2011
* @param arrListItems, array with list items
* @param arrElementsToMeasure, array with elements to measure
* @param intElementsPerRow, integer
* @returns void
*/
function equalizeHeightWithin(arrListItems, arrElementsToMeasure, intElementsPerRow) {
	jQuery(arrListItems).addClass('measure');
	jQuery(arrListItems).each(function (index, el) {
		if (jQuery(el).hasClass('hidden')) {
			jQuery(el).removeClass('hidden');
			jQuery(el).data('washidden', true);
		}
	});

	// Measure the maximum height of the items:
	var intIndexCounter = intLength = 0;
	var intHeight = intMaxHeight = 0;
	var arrCurrentRow = [];
	var intLength = jQuery(arrListItems).length;

	jQuery(arrListItems).find(arrElementsToMeasure).each(function(index, item) {
		intIndexCounter++;
		
		jQuery(item).css('min-height', 0);
		intHeight = jQuery(item).height();
		
		if (intHeight > intMaxHeight) intMaxHeight = intHeight;
		arrCurrentRow.push(item);
		
		if (intIndexCounter % intElementsPerRow == 0 || intIndexCounter == intLength) {
			jQuery(arrCurrentRow).css('min-height', intMaxHeight);
			intMaxHeight = 0;
			intIndexCounter = 0;
			arrCurrentRow = [];
		}
	});

	jQuery(arrListItems).each(function (index, el) {
		if (jQuery(el).data('washidden')) {
			jQuery(el).addClass('hidden');
		}
	});
	jQuery(arrListItems).removeClass('measure');
}

/**
* Equalizes the height of downloads elements in a hidden panel
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @version aug 2011
* @returns void
*/
function equalizeHeightOfDownloads(){
	var elDownloadPanel = jQuery('ul.downloads').parent('.ui-tabs-hide');

	jQuery(elDownloadPanel).addClass('measure');
	equalizeHeight(jQuery('ul.downloads > li'));
	jQuery(elDownloadPanel).removeClass('measure');
}

/**
* Puts FAQ categories in an accordion and enables toggling of answers.
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @since jun 2011
*/
function faqAccordion() {
	jQuery('ul.faq').accordion({
		collapsible: true,
		active: false,
		change: function(){
			jQuery('ul.faq dt, ul.faq dd').removeClass('active');
			equalizeHeight(jQuery('div.col_sub, div.col_content, div.col_content_large, div.col_side'));
		}
	});
	
	jQuery(jQuery('ul.faq div.panel')[0]).css('height', jQuery(jQuery('ul.faq div.panel')[0]));

	var alreadyOpen = false;

	if (jQuery('ul.faq dt').length == jQuery('ul.faq dd').length) {
		jQuery('ul.faq dt').each(function(index, item){
			jQuery(this).click(function(){
				if (jQuery(this).hasClass('active')) alreadyOpen = true;

				jQuery(jQuery(item).parents('div.panel')[0]).css('height', 'auto');

				jQuery('ul.faq dt, ul.faq dd').removeClass('active');
				if (!alreadyOpen) {
					jQuery(jQuery('ul.faq dt')[index]).addClass('active');
					jQuery(jQuery('ul.faq dd')[index]).addClass('active');
				}
				alreadyOpen = false;
				
				equalizeHeight(jQuery('div.col_sub, div.col_content, div.col_content_large, div.col_side'));
			});
		});
	}
}


/**
* Adds interaction to the practice pushbox toggling a sliding box when clicking on hotspots.
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @since jun 2011
*/
function practicePushbox() {
	if (jQuery('.practice_pushbox').length == 0) return false;

	var arrHotspots = jQuery('ol.practice_hotspots > li');
	var arrIndicators = jQuery('ol.practice_indicators > li');
	var arrDetails = jQuery('ol.practice_details > li');
	var intDetailHiddenPosX = parseInt(jQuery(jQuery(arrDetails)[0]).css('left'));
	var intActiveIndex = null;
	
	var activateDetail = function(index){
		jQuery(jQuery(arrDetails)[index]).animate({'left': -30}, {'easing': 'easeOutBack'});
		jQuery(arrIndicators).removeClass('active');
		jQuery(jQuery(arrIndicators)[index]).addClass('active');
	}

	jQuery(arrHotspots).each(function(index, el){
		jQuery(this).find('a').click(function(){
			jQuery(arrHotspots).removeClass('active');
			jQuery(jQuery(arrHotspots)[index]).addClass('active');

			jQuery(arrDetails).each(function(index, el){
				if (parseInt(jQuery(this).css('left')) > intDetailHiddenPosX) intActiveIndex = index;
			});
			
			if (intActiveIndex != null) {
				jQuery(jQuery(arrDetails)[intActiveIndex]).animate({
						'left': intDetailHiddenPosX
					}, {
						'easing': 'easeOutExpo',
						'complete': function(){
							activateDetail(index);
						}
					}
				);
			} else {
				activateDetail(index);
			}
		});
	});
}

/**
* Opens links with the deprecated target attribute externally in a new window.
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @since aug 2011
*/
function deprecatedExternalLinks() {
	jQuery('a[target=_blank]').each(function(){
		jQuery(this).removeAttr('target');
		jQuery(this).click(function(e){
			e.preventDefault();
			window.open(jQuery(this).attr('href'));
		});
	});
}

/**
* Resize the header image
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @version aug 2011
* @returns void
*/
function resizeHeaderImage() {

	jQuery('img.header_visual_resize').parent().css('height', jQuery('img.header_visual_resize').height());
	
	jQuery(window).resize(function () {
		jQuery('img.header_visual_resize').parent().css('height', jQuery('img.header_visual_resize').height());
	});

}
