//establish the namespace
var ultrabold = window.ultrabold || {};
ultrabold.claryl = window.ultrabold.claryl || {};

ultrabold.claryl.homepage = 'http://www.claryl.com/';
ultrabold.claryl.dsmpage = 'http://www.dsm.com/';

ultrabold.claryl.templates_dir = '/templates/';
ultrabold.claryl.browser;

$(document).ready(function() {
	$.fn.colorbox.init(); //lightbox plugin
	
	//mark IE browsers for CSS fixes
	if(jQuery.browser.msie == true) {
		$('html').addClass('ie');
		ultrabold.claryl.browser = 'ie';
		if(jQuery.browser.version == '6.0') {
			$('html').addClass('ie6');
			ultrabold.claryl.browser = 'ie6';
		} else if(jQuery.browser.version == '7.0') {
			$('html').addClass('ie7');
			ultrabold.claryl.browser = 'ie7';
		} else if(jQuery.browser.version == '8.0') {
			$('html').addClass('ie8');
			ultrabold.claryl.browser = 'ie8';
		}
	}
	
	//fix column widths for IE
	if($('html').hasClass('ie')) {
		var ele = $('#teasers .teaser:last-child');
		var current_width = $(ele).css('width');
		$(ele).css('width', parseInt(current_width)-2+'px');
	}
	
	$('.lightbox').colorbox({
		maxHeight: '500px',
		opacity: 0.15
	});
	
	$('#dsm-logo').click(function() {
		window.location.href = ultrabold.claryl.dsmpage;
	});
	$('#logo').click(function() {
		window.location.href = ultrabold.claryl.homepage;
	});
	$('.thankyou').click(function() {
		$(this).fadeOut('slow');
	});
	
	//make form buttons submit the form
	$('form').each(function() {
		var form = $(this);
		$(this).find('.submit').click(function() {
			$(form).submit();
			return false;
		});
	});
	
	$('#country-select').change(function() {
		//window.location.href = ultrabold.claryl.homepage+ultrabold.claryl.language+'/localdealers/?country='+$(this).val();
	});
	
	//init popover behavior for dealer material requests
	var offset_x = 80;
	var offset_y = -200;
	$('#request-material-leaflets+label').hover(function(e) {
		if($('#popover').length == 0) {
			$('body').append('<div id="popover"></div>');
		}
		var htmltext = '<img src="/images/forframers_material_productflyer.jpg" alt="" />';
		$('#popover').html(htmltext).css({top: (e.pageY+offset_y)+'px', left: (e.pageX+offset_x)+'px'}).show();
	}, function() {
		$('#popover').hide();
	});
	$('#request-material-tester+label').hover(function(e) {
		if($('#popover').length == 0) {
			$('body').append('<div id="popover"></div>');
		}
		var htmltext = '<img src="/images/forframers_material_testframe.jpg" alt="" />';
		$('#popover').html(htmltext).css({top: (e.pageY+offset_y)+'px', left: (e.pageX+offset_x)+'px'}).show();
	}, function() {
		$('#popover').hide();
	});
	$('#request-material-indicator+label').hover(function(e) {
		if($('#popover').length == 0) {
			$('body').append('<div id="popover"></div>');
		}
		var htmltext = '<img src="/images/forframers_material_calculator.jpg" alt="" />';
		$('#popover').html(htmltext).css({top: (e.pageY+offset_y)+'px', left: (e.pageX+offset_x)+'px'}).show();
	}, function() {
		$('#popover').hide();
	});
	
	//claryl effect toggle
	$('#toggle-effect').click(function() {
		$('#claryl-effect img').toggle();
		return false;
	});
	
	$('#nav li').hover(function() {
		if($(this).hasClass('active') != true) {
			$(this).addClass('active-hover').css('opacity', 0.5).animate({ 
				opacity: 1.0
			}, 400);
		}
	}, function() {
		
		//remove the hover state if nav entry has not been clicked
		if($(this).hasClass('active') != true) {
			$(this).removeClass('active-hover').css('opacity', 1.0);
		}
	});
	$('#nav li').click(function() {
		//deactivate all active buttons
		/*
		$('#nav li').each(function() {
			$(this).removeClass('active');
			this.is_active = 0;
		});
		$(this).addClass('active');
		this.is_active = 1;
		*/
		var target = $(this).find('a').attr('href');
		window.location.href = target;
		return false;
	});
	
	
	$('.compartment').hover(function() {
		$(this).addClass('active');
	}, function() {
		$(this).removeClass('active');
	});
	
	
	/* slideshow */
	ultrabold.claryl.init_slideshow = function() {
		if($('#slideshow').length > 0) {
			var currentPosition = 0;
			var slideWidth = 720;
			var slides = $('.slide');
			var numberOfSlides = slides.length;
			var show_controls = false;

			slides.wrapAll('<div id="slideInner"></div>').css({
				'float' : 'left',
				'width' : slideWidth
			});

			$('#slideInner').css('width', slideWidth * numberOfSlides);
			//$('#slideshow').prepend('<span class="control" id="left-control">previous</span>').append('<span class="control" id="right-control">next</span>');
			
			//avoid a weird bug that showed duplicate controls (A.R. 26.11.09)
			if($('#left-control').length == 0 && $('#right-control').length == 0) {
				$('#slideshow').before('<div class="control" id="left-control">previous</div>').after('<div class="control" id="right-control">next</div>');
			
				var y = parseInt($('#slideshow').get(0).offsetTop);
				var x = parseInt($('#slideshow').get(0).offsetLeft);
				var width = parseInt($('#slideshow').css('width'));
				var height = parseInt($('#slideshow').css('height'));
				var control_height = parseInt($('#left-control').css('height'));
				
				if($('html').hasClass('ie')) { var offset = 4; } else { var offset = 20; }
				
				$('#left-control').css({position: 'absolute', top: (y+height*0.5-control_height*0.5)+'px', left: (x-35)+'px'});
				$('#right-control').css({position: 'absolute', top: (y+height*0.5-control_height*0.5)+'px', left: (x+offset+width)+'px'});
			}
			//manageControls(currentPosition);

			//create event listeners for .controls clicks
			
			$('.control').unbind();
			$('.control').bind('click', function() {
				currentPosition = ($(this).attr('id')=='right-control') ? currentPosition+1 : currentPosition-1;
				manageControls(currentPosition);
				$('#slideInner').animate({
					'marginLeft': slideWidth*(-currentPosition)
				});
			});
			

			function manageControls(position) {
				if(show_controls == true) {
					//hide left arrow if position is first slide
					if(position == 0){ $('#left-control').hide();
					} else { $('#left-control').show(); }
					//hide right arrow if position is last slide
					if(position == numberOfSlides-1){ $('#right-control').hide();
					} else { $('#right-control').show(); }
				} else {
					$('.control').hide();
				}
			}
		    
			if(ultrabold.claryl.browser != 'ie7') { //IE7 you are killing me!
				$('#slidesContainer').css('overflow', 'hidden');
			}
			
			if(jQuery.browser.mozilla == true) {
				$('#right-control').css('margin-left', '-16px');
			}

		    //hide the controls when they're not needed
		    show_controls = true;
		    manageControls(currentPosition);
		    /*
		    $('#slideshow').hover(function() {
				show_controls = true;
				manageControls(currentPosition);
			}, function() {
				show_controls = false;
				manageControls(currentPosition);
			});
			*/
			/* end slideshow */
		}
	}
	
	ultrabold.claryl.init_slideshow();
	
	/* ajax gallery functions */
	$('.ajax').click(function() {
		var rel = $(this).attr('rel');
		var ajax_site = ultrabold.claryl.templates_dir+'ajax_'+rel+'_'+ultrabold.claryl.language+'.tpl.php';
		
		
		$.ajax({
			url: ajax_site,
			success: function(html) {
				$("#slidesContainer").html(html);
				
				ultrabold.claryl.init_slideshow();
			
				$('.lightbox').colorbox({
					maxHeight: '500px',
					opacity: 0.15
				});
			},
			error: function(request, error) {
				alert('This site could not be included. Maybe it doesn\'t exist yet or the connection timed out.');
			}
		});
		
		return false;
	});
	
	
	ultrabold.claryl.map_init = function() {
		
		/*
		if($('#haendler-detail').length <= 0) {
			$('div[rel*=haendler]').after('<div id="haendler-detail" rel="haendler" class="compartment">click on a marker to view the details. double click to zoom the map.</div>');
		}
		*/
		
		ultrabold.claryl.map = new google.maps.Map($('#map').get(0), {
			zoom: ultrabold.claryl.zoom,
			center: ultrabold.claryl.latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			navigationControl: true,
			scaleControl: true,
			mapTypeControl: false
		});
		$('#map').css('background', '#e8e8e8');
		
		//activate the navigation
		$('#maplink-germany a').click(function() { ultrabold.claryl.map.set_center(new google.maps.LatLng(50.833698,9.558105)); ultrabold.claryl.map.set_zoom(6); return false; });
		$('#maplink-netherlands a').click(function() { ultrabold.claryl.map.set_center(new google.maps.LatLng(52.442618,5.740356)); ultrabold.claryl.map.set_zoom(7); return false; });
		$('#maplink-norway a').click(function() { ultrabold.claryl.map.set_center(new google.maps.LatLng(61.02637,8.833008)); ultrabold.claryl.map.set_zoom(5); return false; });
		$('#maplink-austria a').click(function() { ultrabold.claryl.map.set_center(new google.maps.LatLng(47.279229,12.963867)); ultrabold.claryl.map.set_zoom(7); return false; });
		$('#maplink-switzerland a').click(function() { ultrabold.claryl.map.set_center(new google.maps.LatLng(46.841407,8.404541)); ultrabold.claryl.map.set_zoom(8); return false; });
		$('#maplink-belgium a').click(function() { ultrabold.claryl.map.set_center(new google.maps.LatLng(50.712113,4.42749)); ultrabold.claryl.map.set_zoom(7); return false; });
		
		
		//do geocoder stuff
		ultrabold.claryl.geocoder = new google.maps.Geocoder();
		
		//load the markers
		ultrabold.claryl.marker_active = '/images/marker_active.gif';
		ultrabold.claryl.marker_inactive = '/images/marker_inactive.gif';
		ultrabold.claryl.all_markers = {};
		
		$.getJSON("/sites/json_locations.php", {}, function(json) {
			
			var total_markers = json.length-1;
			var j = 0;

			$(json).each(function(i, item) {
				var id = item.haendler_id;
				var name = item.haendler_name;
				var lat = item.haendler_lat;
				var lng = item.haendler_lng;
				var address = item.haendler_street+', '+item.haendler_zip+' '+item.haendler_city+', '+item.haendler_country;
				var status = item.haendler_status;
				
				if(lat == 0 && lng == 0 && address != '' && status != 'fail') {
					//try to determine an address for the first marker
					
					if(j < 1) {
						ultrabold.claryl.geocode(name, address, id);
						j++;
					}
				} else {
					//place the marker on the map if coordinates exist
					if(status != 'fail') {
						var marker = new google.maps.Marker({
							position: new google.maps.LatLng(lat, lng),
							map: ultrabold.claryl.map,
							title: name,
							icon: ultrabold.claryl.marker_inactive
						});
						
						ultrabold.claryl.all_markers[id] = marker;
						
						marker.haendler_id = id;
						marker.haendler_title = name;
						marker.coords = new google.maps.LatLng(lat, lng);
						
						google.maps.event.addListener(marker, 'click', function() {
							ultrabold.claryl.map.set_center(this.coords);
							
							ultrabold.claryl.location_detail(this.haendler_id);
						});
						
						
						
					}
				}

				//update the loading progress indicator
				var percent_loaded = Math.ceil((100/total_markers)*i);
				$('#marker-loader-indicator').html(i).css('width', percent_loaded+'%');
				if(i == total_markers) {
					$('#marker-loader').fadeOut('slow');
				}
			});
		});

	}

	ultrabold.claryl.geocode = function(name, address, id) {
		ultrabold.claryl.geocoder.geocode( { address: address}, function(results, status) {
			if(status == google.maps.GeocoderStatus.OK && results.length) {
				if(status != google.maps.GeocoderStatus.ZERO_RESULTS) {
					//ultrabold.claryl.map.set_center(results[0].geometry.location);
					
					var marker = new google.maps.Marker({
						position: results[0].geometry.location,
						map: ultrabold.claryl.map,
						title: name,
						icon: ultrabold.claryl.marker_inactive
					});
					
					ultrabold.claryl.all_markers[id] = marker;
					
					marker.haendler_id = id;
					marker.haendler_title = name;
					marker.coords = results[0].geometry.location;
					
					google.maps.event.addListener(marker, 'click', function() {
						ultrabold.claryl.map.set_center(this.coords);
						
						ultrabold.claryl.location_detail(this.haendler_id);
					});
					
					var coords = results[0].geometry.location;
					
					//save these coordinates to the database
					$.get("/sites/xml_save_coordinates.php", { id: id, latlng: coords }, function(result) {
					});
					
					return true;
				} else {
					//no results
					alert('found no results for : '+address);
					return false;
				}
			} else {
				alert('Geocode was unsuccessful for "'+address+'" due to: ' + status);
				//mark for manual correction
				$.get("/sites/xml_save_coordinates.php", { id: id, fail: 'true' }, function(result) {
					//the result was marked as not identified
				});
				return false;
			}
		});
	}
	
	ultrabold.claryl.location_detail = function(id) {
		$('#haendler-detail').html('<p>loading &hellip;</p>');
		
		//den letzten aktiven marker inaktiv setzen
		if(ultrabold.claryl.active_marker) {
			ultrabold.claryl.active_marker.set_icon(ultrabold.claryl.marker_inactive);
		}
		
		//den neuen aktivieren
		ultrabold.claryl.all_markers[id].set_icon(ultrabold.claryl.marker_active);
		ultrabold.claryl.active_marker = ultrabold.claryl.all_markers[id];
		
		$.getJSON("/sites/json_location.php", {id: id}, function(json) {
			$(json).each(function(i, item) {
				$('#haendler-detail').empty();
				$("<ul></ul>").appendTo("#haendler-detail");
				$("<li></li>").html(item.haendler_name).appendTo("#haendler-detail ul");
				$("<li></li>").html(item.haendler_partner).appendTo("#haendler-detail ul");
				$("<li></li>").html(item.haendler_street).appendTo("#haendler-detail ul");
				$("<li></li>").html(item.haendler_zip+' '+item.haendler_city).appendTo("#haendler-detail ul");
				$("<li></li>").html(item.haendler_country).appendTo("#haendler-detail ul");
				
				if(ultrabold.claryl.language == 'de') {
					var str_phone = 'Telefon';
					var str_fax = 'Fax';
					var str_email = 'Email';
					var str_url = 'URL';
				} else if(ultrabold.claryl.language == 'nl') {
					var str_phone = 'Telefon';
					var str_fax = 'Fax';
					var str_email = 'E-mail';
					var str_url = 'URL';
				} else {
					var str_phone = 'Phone';
					var str_fax = 'Fax';
					var str_email = 'Email';
					var str_url = 'URL';
				}
				
				if(item.haendler_phone != null && item.haendler_phone != '') { $("<li></li>").html(str_phone+': '+item.haendler_phone).appendTo("#haendler-detail ul"); }
				if(item.haendler_fax != null && item.haendler_fax != '') { $("<li></li>").html(str_fax+': '+item.haendler_fax).appendTo("#haendler-detail ul"); }
				if(item.haendler_email != null && item.haendler_email != '') { $("<li></li>").html(str_email+': <a href="'+item.haendler_email+'">'+item.haendler_email+'</a>').appendTo("#haendler-detail ul"); }
				if(item.haendler_url != null && item.haendler_url != '') { $("<li></li>").html(str_url+': '+item.haendler_url).appendTo("#haendler-detail ul"); }
				
				//permalink
				$("<li></li>").html('<br /><a href="'+ultrabold.claryl.site_url+ultrabold.claryl.language+'/localdealers/'+item.haendler_id+'/">Permalink</a>').appendTo("#haendler-detail ul");
			});
		});
		return false;
	}
	
	//build the map if a map container is present on the site
	if($('#map').length > 0) {
		
		//set the info image according to the site language
		if(ultrabold.claryl.language == 'en') {
			$('#map').css('backgroundImage','url(/images/map_loading_en.gif)');
		} else if(ultrabold.claryl.language == 'nl') {
			$('#map').css('backgroundImage','url(/images/map_loading_nl.gif)');
		}
		
		ultrabold.claryl.map;
		ultrabold.claryl.geocoder;
		ultrabold.claryl.active_marker;
		ultrabold.claryl.latlng = new google.maps.LatLng(49.5, 8.4); //(default lat and lng)
		if(ultrabold.claryl.language == 'en') {
			ultrabold.claryl.latlng = new google.maps.LatLng(49.5, 8.4); //(default EN)
		} else if(ultrabold.claryl.language == 'nl') {
			ultrabold.claryl.latlng = new google.maps.LatLng(52.140231, 5.300903); //(default NL)
		}
		ultrabold.claryl.zoom = 6;
		
		if($('.map-detail').length > 0) {
			//show a single marker on the map
			
			var lat = parseFloat($('#map-lat').html());
			var lng = parseFloat($('#map-lng').html());
			ultrabold.claryl.latlng = new google.maps.LatLng(lat, lng);
			ultrabold.claryl.zoom = 15;
			
			if(lat == 0 || lng == 0) {
				//set a default in case the coordinates suck
				ultrabold.claryl.latlng = new google.maps.LatLng(49.5, 8.4);
			}
			
			ultrabold.claryl.map = new google.maps.Map($('#map').get(0), {
				zoom: ultrabold.claryl.zoom,
				center: ultrabold.claryl.latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				navigationControl: true,
				scaleControl: true,
				mapTypeControl: false
			});
			$('#map').css('background', '#e8e8e8');
			
			var marker = new google.maps.Marker({
				position: ultrabold.claryl.latlng,
				map: ultrabold.claryl.map,
				title: $('#map-name').html(),
				icon: '/images/marker_inactive.gif'
			});
			
			$('#marker-loader').fadeOut('slow');
			
		} else {
		
			if(jQuery.browser.msie == false) {
				//non-ie sachen machen
				
				if(google && google.gears && google.gears) {
					//falls google gears installiert ist
					var geo = google.gears.factory.create('beta.geolocation');

					function updatePosition(position) {
						ultrabold.claryl.latlng = new google.maps.LatLng(position.latitude, position.longitude);
						ultrabold.claryl.zoom = 12;
						ultrabold.claryl.map_init();
					}

					function handleError(positionError) {
						//position auf default festlegen oder mit was anderem versuchen
						ultrabold.claryl.map_init();
					}

					geo.getCurrentPosition(updatePosition, handleError);
				} else {
					//wenn nicht
					if(navigator && navigator.geolocation && navigator.geolocation.getCurrentPosition) {
						navigator.geolocation.getCurrentPosition(function(position) {
							//only use the data if it really succeeded (firefox bug?)							
							if(position.latitude != undefined && position.longitude != undefined) {
								ultrabold.claryl.latlng = new google.maps.LatLng(position.latitude, position.longitude);
								ultrabold.claryl.zoom = 12;
							}
							ultrabold.claryl.map_init();
						}, function() {
							ultrabold.claryl.map_init();
						});
					} else {
						//Mac OSX
						ultrabold.claryl.map_init();
					}
				}
			} else {
				//alternative default location fuer IE ist eh schon definiert
				ultrabold.claryl.map_init();
			}
		}
	}
	
	//track with analytics if active
	if(ultrabold.claryl.ga_account != '') {
		ultrabold.claryl.tracker = _gat._getTracker(ultrabold.claryl.ga_account);
		ultrabold.claryl.tracker._trackPageview();
	}
});
