var Y2W = {
	map: null,
	icon: null,
	directions: null,
	init: function(){
		jQuery('ul#clients').find('li:nth-child(3n)').addClass('third').end().find('li img').each(
			function(){
				var t = jQuery(this);
				t.after('<span class="tooltip">'+t.attr('alt')+'</span>').hover(
					function(e){
						t.next().show();
					},
					function(e){
						t.next().hide();
					}
				);
			}
		);
		
		jQuery('#left-content-column').addClass('searchtarget');
		// accordion
		var elementToTransform = ".accordion", accordionTitleCass = "accordionTitle", currentClass = ".currentPanel", textRotatePath = "path/to/rotateText.php", bgColor = "72A8CF", fontColor = "FFFFFF";
		
		jQuery(elementToTransform).each(function() {
			var title = jQuery(this).attr("title");
			
			jQuery(this).before('<div class="'+accordionTitleCass+'"><a title="'+title+'" /></div>');
		});
		jQuery(elementToTransform).hide();
		jQuery(currentClass).show();
		disableAccordion = false;
		jQuery("."+accordionTitleCass).click(function() {
			if(disableAccordion != true) {
				disableAccordion = true;
				jQuery(elementToTransform+":visible").hide(400);
				jQuery(this).next(elementToTransform).show(400, function() {
					disableAccordion = false;
				});
			}
		});
		
		jQuery('form').submit(function(){return Y2W.validateForm(this);});
		
		if(jQuery.browser.msie){
			jQuery('button').hover(
				function(){
					jQuery(this).addClass('hover');
				}, 
				function(){
					jQuery(this).removeClass('hover');
				}
			);
		}
		Map.initMap();
		
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))){
			jQuery('#wrapper_dock').remove();
		}else if (!jQuery.browser.msie || jQuery.browser.version.substr(0,1) != 6){
			jQuery('#headline').removeClass('IE6');
			var dock2 = jQuery('#dock2');
			if (dock2.size() > 0){
				dock2.Fisheye({
					maxWidth: 50,
					items: 'a',
					itemsText: 'em',
					container: '.dock-container2',
					itemWidth: 75,
					proximity: 80,
					alignment : 'left',
					valign: 'bottom',
					halign : 'center'
				});
			}
			jQuery('#dock2').mouseover(function(event){
				el = event.target;
				if(el.tagName == 'IMG'){
					jQuery('#wrapper_dock').attr('class', jQuery(el).attr('alt'));
				}
			}).mouseout(function(){
				jQuery('#wrapper_dock').removeClass(jQuery(el).attr('alt'));
			});
		  }
	},
	validateMailingList: function(form){
		var f = jQuery('form#mailinglist');
		if(Y2W.validateEmail(f.find('input#sEmail').val()) !== false){
			jQuery.post('/submit.php', f.serialize(), function(data){
				if(data == '1'){
					jQuery('#mailinglist').empty().append('<strong class="feedback">Bedankt voor uw aanmelding</strong>');
				}else{
					Y2W.showWarning(data);
				}
			});
		}else{
			Y2W.showWarning('Ongeldig e-mailadres');
		}
		return false;
	},
	showWarning: function(msg){
		jQuery('#mailinglist').find('.feedback').remove().end().append('<strong class="feedback"><br/>'+msg+'</strong>');
	},
	validateForm: function(form){
		var err = false, f = jQuery(form), el;
		jQuery('#feedback').remove();
		f.find('.required').each(function(){
			var t = jQuery(this);
			t.removeClass('error');
			if(Y2W.validateField(this) == false){
				t.addClass('error');
				err = true;
			}
		});
		if(form.id == 'search') return false;
		else if(f.attr('id') == 'mailinglist') return Y2W.validateMailingList(this);
		else if(!err) return true;
		else f.prepend('<p id="feedback" style="display: none;">Vul aub alle verplichte velden in.</p>').find('#feedback').fadeIn();
		return false;
	},
	validateField: function(el){
		el = jQuery(el), v = el.val(), n = el.attr('name');
		return 	v != '' && 
				(n != 'email' || Y2W.validateEmail(v) != false) && 
				(n != 'email-phone' || Y2W.validateEmail(v) != false || Y2W.validatePhone(v) != false);
	},
	validateEmail: function(v){
		var r = new RegExp('^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$');
		return r.test(v);
	},
	validatePhone: function(v){
		var r = new RegExp('^(\\+[0-9]{2}|\\+[0-9]{2}\\s{0,1}\\(0\\)|\\(\\+[0-9]{2}\\)\\s{0,1}\\(0\\)|00[0-9]{2}|0)([0-9]{9}|[0-9\\-\\s]{10,16})$');
		return r.test(v);
	}
}, Map = {
	curPostal: null,
	directions: null,
	icon: null,
	instance: null,
	showAddress: function(){
		var map = Map.instance,
			y2w = new GLatLng(51.9030011, 4.4586422), // Schiehavenkade
			party = jQuery('p#y2party');
		/* party map */
		if(party.get(0)){
			y2w = new GLatLng(51.996495,4.370048);
			}
		map.clearOverlays();
		jQuery('#directions').empty();
		map.setCenter(y2w, 15);
		map.setMapType(G_NORMAL_MAP);
		m = new GMarker(y2w, Map.getIcon());
		map.addOverlay(m);
		GEvent.addListener(m, 'click', function(){
			if(party.get(0)){
				m.openInfoWindow('Lijm en Cultuur Fabriek<br/>Rotterdamseweg 270<br />2628 Delft, Nederland<br />');
			}else{
				m.openInfoWindow('Schiehavenkade 100<br/>3025EZ  Rotterdam <br/>T +31 (0)10‐8200140<br/>');
			}
		});
		if(Map.directions){
			Map.directions = null;
		}
	},
	catchError: function(el){/*
		if (el.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: " + el.getStatus().code);
		else if (el.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: " + el.getStatus().code);
		else if (el.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: " + el.getStatus().code);	   
		else if (el.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: " + el.getStatus().code);
		else if (el.getStatus().code == G_GEO_BAD_REQUEST)
			alert("A directions request could not be successfully parsed.\n Error code: " + el.getStatus().code);
		else alert("An unknown error occurred.");*/
	},
	calculateDirections: function(){
		var bEnglish = window.location.href.indexOf(".com") !== -1,
		locale = bEnglish ? "en" : "nl";
		var p = jQuery('#sPostal').val(), r = new RegExp(/^[0-9]{4}[\s]?[a-zA-Z]{0,2}$/);
		if(r.test(p)){
			Map.curPostal = p;
			if(Map.directions){
				Map.directions.clear() 
			}
			var div = jQuery('#directions').empty().get(0);
			if(!div){
				div = jQuery('#map').after('<div id="directions"/>').parent().find('#directions').get(0)
			}
			var d = new GDirections(Map.instance, div);
			GEvent.addListener(d, 'load', Map.directionsLoaded);
			GEvent.addListener(d, 'error', Map.catchError);
			Map.directions = d;
			if(jQuery('#y2party').get(0)){
				Map.directions.load("from: "+p+", Nederland to: Rotterdamseweg 270, 2628AT, Delft", {"setGetPolyline": true, "setGetSteps": true, "locale": locale});
			}else{
				Map.directions.load("from: "+p+", Nederland to: Schiehavenkade 100, 3025EZ, Rotterdam", {"setGetPolyline": true, "setGetSteps": true, "locale": locale});
			}
		}
		return false;
	},
	copyPolyline: function(p){
		var arr = [], i;
		for(i = 0 ; i < p.getVertexCount() ; i++){
			arr.push(p.getVertex(i));
		}
		return new GPolyline(arr, '#FF0000');
	},
	directionsLoaded: function(){
		setTimeout(function(){
			var map = Map.instance;
			map.clearOverlays();
			map.setMapType(G_NORMAL_MAP);
			var div = jQuery('#directions').get(0), ih = div.innerHTML, img = '/images/yes2web/icons/yes2you2.png', img2 = '/images/yes2web/icons/yes2maps.png';
			ih = ih.replace('http://maps.google.com/intl/en_ALL/mapfiles/icon_greenA.png', img).replace('http://maps.google.com/intl/en_ALL/mapfiles/icon_greenB.png', img2);
			ih = ih.replace('http://maps.google.com/intl/nl_ALL/mapfiles/icon_greenA.png', img).replace('http://maps.google.com/intl/nl_ALL/mapfiles/icon_greenB.png', img2);
			ih = ih.replace('http://maps.google.com/intl/en_ALL/mapfiles/icon_greenA_graybg.png', img).replace('http://maps.google.com/intl/en_ALL/mapfiles/icon_greenB_graybg.png', img2);
			ih = ih.replace('http://maps.google.com/intl/nl_ALL/mapfiles/icon_greenA_graybg.png', img).replace('http://maps.google.com/intl/nl_ALL/mapfiles/icon_greenB_graybg.png', img2);
			div.innerHTML = ih;
			var d = Map.directions, p = d.getPolyline(), m;
			if(div){
				jQuery('body').addClass(' directions');
			}
			
			if(p){
				var newP = Map.copyPolyline(p);
				map.addOverlay(newP);
			}
			m = d.getMarker(1);
			if(m){
				m.hide();
				map.addOverlay(new GMarker(m.getPoint(), Map.getIcon()));
			}
			m = d.getMarker(0);
			if(m){
				m.hide();
				var icon = new GIcon();
				icon.image = '/images/yes2web/icons/yes2you2.png';
				icon.shadow = '/images/yes2web/icons/yes2mapsshadow.png';
				icon.iconSize = new GSize(70, 70);
				icon.shadowSize = new GSize(160, 70);
				icon.iconAnchor = new GPoint(0, 70);
				map.addOverlay(new GMarker(m.getPoint(), icon));
			}
		}, 0);
	},
	getIcon: function(){
		if(!Map.icon){
			var icon = new GIcon();
			icon.image = '/images/yes2web/icons/yes2maps.png';
			/* party map */
			if(jQuery('p#y2party').get(0)){
				icon.image = '/images/yes2web/icons/yes2partymap.png';
			}
			icon.shadow = '/images/yes2web/icons/yes2mapsshadow.png';
			icon.iconSize = new GSize(70, 70);
				icon.shadowSize = new GSize(160, 70);
				icon.iconAnchor = new GPoint(0, 70);
			icon.infoWindowAnchor = new GPoint(35, 2);
			Map.icon = icon;
		}
		return Map.icon;
	},
	initMap: function(){
		var m = jQuery('#map').get(0),
		bEnglish2 = window.location.href.indexOf(".com") !== -1,
		locale2 = bEnglish2 ? '<p><a href="#" id="resetMap">Show on map</a></p>' : '<p><a href="#" id="resetMap">Toon op kaart</a></p>';
		if (m && GBrowserIsCompatible()){
			var map = new GMap2(m);
			map.addMapType(G_PHYSICAL_MAP);
			map.addControl(new GMapTypeControl());
			map.addControl(new GSmallMapControl());
			Map.instance = map;
			Map.showAddress();
			if(jQuery('form#route').get(0) && jQuery('#right-content-column .block-b:nth-child(1)').get(0)){
				jQuery('form#route').submit(Map.calculateDirections);
				if(jQuery('#y2party').size() === 0){
					jQuery('#right-content-column .block-b:nth-child(1)').append(locale2).find('#resetMap').click(function(){Map.showAddress(); jQuery('body').removeClass(' directions'); return false;});
				}
			}
			jQuery(window).unload(GUnload);
		}
	}
}
jQuery(Y2W.init);