/////////////////////////////////////////// BASIC FUNCTIONS, DON'T EDIT ///////////////////////////////////////////

/*
 * domready
 * Starts executing the initializing functions when the DOM structure of the page has been loaded.
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses Mootools 1.2 JavaScript Library
 */
window.addEvent('domready', function() {
	initExternalLinks();
	initCustomFunctions();
});

/*
 * load
 * Starts executing the initializing functions when the entire page has been loaded.
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses Mootools 1.2 JavaScript Library
 */
window.addEvent('load', function() {
	fixLogoTransparencyForIE6();
});



/*
 * initExternalLinks
 * Used in order for certain links to open in a new window without the direct target attribute (so it validates properly).
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses <a href="http://www.efocus.nl/" rel="external">eFocus site</a>
 */
function initExternalLinks() {
	if (!document.getElementsByTagName) return; 
	var arrAnchors = document.getElementsByTagName("a"); 
	for (var i=0; i<arrAnchors.length; i++) { 
		var elAnchor = arrAnchors[i]; 
		if (elAnchor.getAttribute("href") && elAnchor.getAttribute("rel") == "external") {
			elAnchor.target = "_blank";
		}
	}
}



/////////////////////////////////////////// CUSTOM CLIENT-SIDE FUNCTIONS ///////////////////////////////////////////

/*
 * initCustomFunctions
 * Add all your custom function which need to be initialized to this function.
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @todo: add custom functions
 */
function initCustomFunctions() {
//	headFontReplacement(); // Because of a bug in IE6 the function is now being called at the end of the DOM in the HTML.
	headerVisualHome();
//	headerVisualConceptBathroom(); // Function gets called from within the HTML page itself.
	homeSubNavCarrousel();
	showroomsMultiMap();
	showroomMap();
	formFocusInteraction();
	groepDetailSlideshow();
}



/*
 * headFontReplacement
 * sIFR font replacement for the H1 tags.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function headFontReplacement() {
	var arrHeadsLevel1 = $$('h1');
	if (arrHeadsLevel1.length == 0) return;
	
	var objHelveticaNeue45Light = {
		src: '/flash/helvetica_neue_45_light.swf'
	};
	
	sIFR.useStyleCheck = true;
	sIFR.activate(objHelveticaNeue45Light);
	
	sIFR.replace(objHelveticaNeue45Light, {
		selector: 'h1'
		,css: {
			'.sIFR-root': { 'background-color': '#000000', 'color': '#cdcac5' }
		}
	});
	
	sIFR.replace(objHelveticaNeue45Light, {
		selector: 'p#footer_slogan'
		,css: {
			'.sIFR-root': { 'background-color': '#000000', 'color': '#cdcac5', 'text-align': 'center' }
		}
	});
}



/*
 * loads JW player into page via swiff (mootools)
 * 
 * @since 2.0, 20 jan 2010
 * @author Ralph Meeuws <ralph.meeuws@efocus.nl>
 * @author Rocco Janse <rocco@efocus.nl>
 */
function headerVisualHome() {
	
	if (($('page').className != 'home') || (!$('header_visual'))) return;

	var elHeaderVisual = $('header_visual');
	elHeaderVisual.getElement('p').setStyle('display','none');	

	var objHeaderVisualHomeSwiff = new Swiff('/flash/video/player-licensed.swf', {
		'id': 'videoplayer',
		'width': 940,
		'height': 400,
		'container': elHeaderVisual,
		'params': {
			'allowfullscreen': 'false',
			'allowscriptaccess': 'always',
			'wmode': 'opaque',
			'bgcolor': '#000000'
		},
		'vars': {
			'file': '/flash/video/SaniStream.flv',			
			'bufferlength': 2,
			'skin': '/flash/video/modieus.swf',
			'autostart': 'true',
			'frontcolor': '888888',
			'controlbar': 'none',
			'repeat': 'always'
		}
	});

}

/*
 * headerVisualConceptBathroom
 * Loads the Flash Swiff for the header visual on the conceptbathroom page.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function headerVisualConceptBathroom(bathroom_number) {
	if (($('page').className != 'conceptbadkamer') || (!$('header_visual'))) return;
	
	var elConceptVisual = $('concept_visual');
	var strXmlLink = $('specific_xml_link').innerHTML;
	//console.log(strXmlLink);
	elConceptVisual.getElement('p').setStyle('display','none');
	
	var objHeaderVisualHomeSwiff = new Swiff('/flash/header_visual.swf', {
		id: 'header_visual_swiff',
		width: 940,
		height: 360,
		container: elConceptVisual,
		params: {
			wmode: 'opaque',
			bgcolor: '#000000'
		},
		vars: {
			bathroom_xml: strXmlLink, //'/flash/header_visual.xml',
			bathroom_menu: 'false',
			bathroom_selection: bathroom_number
		}
	});
}



/*
 * homeSubNavCarrousel
 * Defines the carrousel on the homepage using the subnav buttons.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function homeSubNavCarrousel() {
	if ($('page').className != 'home') return;
	
	var elHomeSubNav = $('sub_nav');
	var arrHomeSubNavLinks = elHomeSubNav.getElements('a');
	var arrHomeContainerBlocks = $$('.col_center_right');
	
	arrHomeSubNavLinks.each(function(elHomeSubNavLink, i){
		elHomeSubNavLink.addEvent('click', function(){
			arrHomeSubNavLinks.each(function(elHomeSubNavLinkInstance, j){
				if (arrHomeSubNavLinks[j] != elHomeSubNavLink) {
					elHomeSubNavLinkInstance.removeClass('active');
				} else {
					elHomeSubNavLink.addClass('active');
				}
			});
			
			arrHomeContainerBlocks.each(function(elHomeContainerBlock){
				if (arrHomeContainerBlocks[i] != elHomeContainerBlock) {
					elHomeContainerBlock.addClass('hidden');
				} else {
					elHomeContainerBlock.removeClass('hidden');
				}
			});
		});
	});
}


/*
 * showroomsMultiMap
 * Loads multiple markers of showrooms om a single map using Google Maps.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function showroomsMultiMap() {
	if (!$('showrooms_map')) return;
	
	if (GBrowserIsCompatible()) { 
		var elShowroomsMap = $('showrooms_map');
		
		arrListShowrooms = $$('ul.showrooms_list li');
		arrShowroomSpans = arrListShowrooms.getElements('span');
		
		gmaps = new GMap2(document.getElementById("showrooms_map"));
		gmaps.addControl(new GLargeMapControl());
		
		geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode("nl");
		
		var baseIcon = new GIcon();
	
		for (var i=0; i<arrListShowrooms.length; i++) {

			var showroomName = arrShowroomSpans[i][0].innerHTML;
			var showroomStreet = arrShowroomSpans[i][2].innerHTML;
			var showroomZip = arrShowroomSpans[i][3].innerHTML;
			var showroomCity = arrShowroomSpans[i][1].innerHTML;
			
			var showroomLon = arrShowroomSpans[i][4].innerHTML;
			var showroomLat = arrShowroomSpans[i][5].innerHTML;

			var showroomBalloonHTML = "<div class=\"showroom_logo\"><img src=\"/siteimg/icon_sanidrome.gif\" alt=\"Sanidr\&otilde\;me\"></div>\n";
			showroomBalloonHTML += "<div class=\"showroom_details\">\n";
			showroomBalloonHTML += "<h4>" + showroomName + "</h4>\n";
			showroomBalloonHTML += "<p>" + showroomStreet + "<br>\n";
			showroomBalloonHTML += showroomZip + ", " + showroomCity + "<br><br>\n";
			showroomBalloonHTML += "<a href=\"" + arrListShowrooms[i].getElement('a').getProperty('href') + "\" title=\"" + "Naar " + showroomName + " pagina" + "\">" + "Naar " + showroomName + " pagina" + "</a>\n";											
			showroomBalloonHTML += "</p></div>";

			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			baseIcon.infoShadowAnchor = new GPoint(18, 25);

			if (parseFloat(showroomLon) == 52.3572 && parseFloat(showroomLat) == 6.49148) // Sanidrõme Disselhorst Nijverdal
			{
				baseIcon.iconSize = new GSize(19, 19);
				sanidromeIcon = new GIcon(baseIcon);
				sanidromeIcon.image = "/siteimg/icon_sanidrome_small.gif";
			}
			else
			{
				baseIcon.iconSize = new GSize(28, 28);
				sanidromeIcon = new GIcon(baseIcon);
				sanidromeIcon.image = "/siteimg/icon_sanidrome.gif";	
			}
			
			loadShowroomMarker(gmaps, geocoder, showroomLat, showroomLon, showroomBalloonHTML, sanidromeIcon);
			
		}
	
	}
}



/*
 * loadShowroomMarker
 * Loads a Google Maps point from an address by geolocation:
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function loadShowroomMarker(map, geocoder, lat, lon, html, icon) {
		//geocoder.getLatLng(address, function(point) {
	
		point = new GLatLng(lon, lat); 
		
		if (!point) {
			//alert("Adres " + address + " is niet gevonden");
		} else {
			var centerpoint = new GLatLng(52.150000, 5.300000);
			map.setCenter(centerpoint, 7, G_NORMAL_MAP);

			var marker = createShowroomMarker(point, html, icon);
			map.addOverlay(marker);
			map.addControl(new GMapTypeControl());
		}
		//});
}


/*
 * createShowroomMarker
 * Creates a Google Maps marker:
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function createShowroomMarker(point, html, icon) {
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}



/*
 * showroomMap
 * Loads multiple markers of showrooms om a single map using Google Maps.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function showroomMap() {
	if (!$('showroom_map')) return;
	
	if (GBrowserIsCompatible()) {
		elShowroomMap = $('showroom_map');
		var elShowroomRouteZip = $('showroom_route_zip');
		var elShowroomRouteBtn = $('showroom_route_submit');
		var strShowroomName = $('showroom_name').innerHTML;
		var strShowroomStreet = $('showroom_street').innerHTML;
		var strShowroomCity = $('showroom_city').innerHTML;
		var strShowroomAddress = strShowroomStreet + ', ' + strShowroomCity;
		locale = 'nl_NL';
		
		showroomMarkerMsg = '<strong>' + strShowroomName + '</strong><br>' + strShowroomStreet + '<br>' + strShowroomCity;
		
		gmap = new GMap2(document.getElementById("showroom_map"));
		var geocoder = new GClientGeocoder();
		geocoder.getLocations(strShowroomAddress, showroomLoadGoogleMaps);
	}

	elShowroomRouteBtn.addEvent('click', function(){
		strStartPointZipValue = elShowroomRouteZip.value;
		gdir.load('from: ' + strStartPointZipValue + ' to: ' + strShowroomAddress, { 'locale': locale });
	});
	
	elShowroomRouteZip.addEvent('keydown', function(event){
		if (event.key == 'enter') {
			strStartPointZipValue = elShowroomRouteZip.value;
			gdir.load('from: ' + strStartPointZipValue + ' to: ' + strShowroomAddress, { 'locale': locale });
		}
	});
}

/*
 * showroomLoadGoogleMaps
 * Loads a Google Maps point from an address by geolocation:
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function showroomLoadGoogleMaps(response) {
	var place = response.Placemark[0];
	var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
	gmap.setCenter(point, 13, G_NORMAL_MAP);

	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(28, 28);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	
	var sanidromeIcon = new GIcon(baseIcon);
	sanidromeIcon.image = "/siteimg/icon_sanidrome.gif";
	markerOptions = { icon:sanidromeIcon };
	var marker = new GMarker(point, markerOptions);
	
	gmap.addOverlay(marker);
	gmap.addControl(new GLargeMapControl());
	gmap.addControl(new GMapTypeControl());
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(showroomMarkerMsg);
	});

	var elShowroomDirections = $('showroom_directions');

	gdir = new GDirections(gmap, elShowroomDirections);
//	GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);
}

// Standard Google Maps errorhandling:
function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
   else alert("An unknown error occurred.");
}



/*
 * formFocusInteraction
 * Changes the bottom border when focussing on an inputfield of a standard form.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function formFocusInteraction() {
	var arrStandardForms = $$('.standard_form');
	
	if (arrStandardForms.length == 0) return;
	
	var elFirstStandardForm = arrStandardForms[0];
	var arrFocusInputs = elFirstStandardForm.getElements('input');
	var arrFocusTextareas = elFirstStandardForm.getElements('textarea');
	var arrFocusAreas = new Array;
	arrFocusAreas.extend(arrFocusInputs).extend(arrFocusTextareas);
	
	arrFocusAreas.each(function(elFocusArea){
		elFocusArea.addEvent('focus', function(){
			elFocusArea.addClass('focus');
		});
		elFocusArea.addEvent('blur', function(){
			elFocusArea.removeClass('focus');
		});
	});
}



/**
 * groepDetailSlideshow
 * initializes images+descriptions crossfader on product&brand detail pages
 *
 * set interval in milliseconds in variable 'intSlideInterval'
 * 
 * @author Klaas Dieleman
 */
function groepDetailSlideshow() {
	if (!$('slideshow')) return;
	
	intSlideInterval = 5000;
	
	arrSlides = $$('div#slideshow div.slide');
	intNextSlide = 0;
	if (arrSlides.length < 1) return;
	
	arrSlides.each(function(elSlide) {
		elSlide.setStyle('opacity', '0');
	});
	arrSlides[0].setStyle('opacity', '1');
	
	setTimeout('nextDetailSlide()', intSlideInterval);
}



/**
 * nextDetailSlide
 * crossfades images+descriptions on product&brand detail pages with a timer, set in function groepDetailSlideshow
 * 
 * @author Klaas Dieleman
 */
function nextDetailSlide() {
	intCurrSlide = intNextSlide;
	intNextSlide ==  arrSlides.length - 1 ? intNextSlide = 0 : intNextSlide++;

	arrSlides[intCurrSlide].set('morph', {duration: 1500});
	arrSlides[intNextSlide].set('morph', {duration: 1500});
	arrSlides[intCurrSlide].morph({ opacity: 0 });
	arrSlides[intNextSlide].morph({ opacity: 1 });
	
	setTimeout('nextDetailSlide()', intSlideInterval);
}



/*
 * fixLogoTransparencyForIE6
 * Fixes the transpaency of the logo as an inline PNG-24 image for IE6.
 * 
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 */
function fixLogoTransparencyForIE6() {
	if (!$('logo') || !Browser.Engine.trident4) return;
	
	var elLogoLink = $('logo');
	var elLogo = elLogoLink.getElement('img');
	var strLogoSrc = elLogo.src;
	var strLogoSrcExt = strLogoSrc.substring(strLogoSrc.length-3, strLogoSrc.length);
	
	if (strLogoSrcExt == 'png') {
		elLogo.setStyles({
			paddingTop: 50,
			filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader (src=' + strLogoSrc + ', sizingMethod=image)'
		});
	}
}



/////////////////////////////////////////// CUSTOM DEVELOPMENT FUNCTIONS ///////////////////////////////////////////

/**
 * goTo
 * 
 * @author Vincent <vincent.poulissen[AT]efocus.nl>
 */
function goTo(href){
	if(href != ''){
		location.href=href;
	}	
}


