var clicks = 0;
var amount = 0;
var _test = '';

var data = Array();
var map = "";
var markers = [];
var infowindows = [];
var iterator = 0;

var all_dealers = [
	["301","Trybou Staden","Diksmuidestraat 120","8840","Staden","+32(0)51 70 34 71","+32(0)51 70 12 68","info@trybou.com","","Staden","50.983581","3.005329"],
	["307","Trybou Oostkamp","Brugsestraat 196","8020","Oostkamp","+32(0)50 35 29 65","+32(0)50 35 50 45","info@trybou.com","","Oostkamp","51.166774","3.234164"],
];

$(document).ready(function() {
	
	$('a[rel=external]').attr('target', '_blank');
	
	/* TOOLTIP */
	$('#galleryarrows img').tooltip({delay: 0, track: true, showURL: false, fade:100});
	
	$('.readMore').bind('click', function(){
		$(this).hide();
		$(this).parent().parent().parent('.textitem').find('.moreInfo').show('fast', function(){
			$(this).css('display', 'inline');
		});		
	})
	$('.readLess').bind('click', function(){
		$(this).parent().parent('div.moreInfo').hide('fast', function(){
			$(this).css('display', 'none');
		});		
		$(this).parent().parent('div.moreInfo').parent().parent('.textitem').find('.button').find('.readMore').show();
	})
	
	/* YOUTUBE */
	$(".video").click(function() {
		$.fancybox({
			'autoScale'		: false,
			'title'			: false,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
			'wmode'				: 'transparent',
			'allowfullscreen'	: 'true',
			helpers	: {
				overlay		: {
							opacity : 0.8,
							css : {
								'background-color' : '#fefefe'
							}
					}
				}
			}
		});

		return false;
	});
	
	/* INITIALIZE BACKSTRETCH */
	if($('#map_holder').length > 0 || $('.splash').length > 0){
		
	}else
	{
		if($('#galleryimages').length > 0){
			$('#galleryimages li:first').addClass('active');
			var bg = $('#galleryimages li:first').text();
			$.backstretch("/media/img/pics/_background/"+bg, {speed: 150});
			
			if($('#center').length > 0){
				$('#center a:first').addClass('active');
			}
			
		}else{
			$.backstretch("/media/img/test.jpg", {speed: 150});
		}
	}
	
	/* GOOGLE MAPS */
	if($('#map_holder').length > 0){
		initialize();
	}
	
	$('#menu li').hover(function() {
		$(this).find('ul').show();
    },function() {
		$(this).find('ul').hide();
	});
	
	/* CYCLE */
	$('.cycle').cycle({
		fx: 'scrollHorz', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		speed: 500,
		timeout: 0,
		next: '#next_page',
		prev: '#prev_page',
		after: setHeight
	});
	
	/* ASSIGN CUFON TO TITLES */
	Cufon.replace('.textitem h1, #menu > li > a, .title_left h1, .notification h1', {hover:true});
	
	/* MAKING SURE THERE ARE NO TEXT PROBLEMS AFTER OPACITY ANIMATION */
	if ($.browser.msie  && parseInt($.browser.version) == 8) {
	  //alert('IE8'); 
	  $('#contentholder').removeClass('startOpacity').addClass('stopOpacity');
	} else {
	  //alert('Non IE8');
	}
	
	if($('#center').length > 0){
		/* COUNT IMAGES TO GET THE CORRECT WIDTH SO WE CAN CENTER BULLETS */
		$('#center a').each(function() {
			amount++;
		});
		
		/* CENTER BULLETS BY AMOUNT OF IMAGES */
		$('#center').css({'width':(amount*50)+'px'});
		
		if(amount >= 18){
			$('.center-wrap').css({'width':'890px', 'overflow':'hidden', 'display':'block','position':'relative', 'float':'auto'});
		}else{
			$('.center-wrap').css({'width':(amount*50)+'px'});
		}
		
		/* CHANGE BACKGROUND BY BULLETS */
		$('#center a').click(function() {
	
			if(!$('#backstretch img').is(':animated')){
				var newB = $(this).index();
				
				$('#galleryimages li.active').removeAttr('class');
				$('#galleryimages li:nth('+newB+')').addClass('active');
				
				$('#center a.active').removeAttr('class');
				$('#center a:nth('+newB+')').addClass('active');
				
				var newBack = $('#galleryimages li:nth('+newB+')').text();
		
				//$('#backstretch').remove();
				//$.backstretch("/media/img/pics/_large/"+newB, {speed: 150});
				
				var curW = $('#backstretch img').css('width');
				var curH = $('#backstretch img').css('height');
				var curT = $('#backstretch img').position().top;
				
				$('#backstretch').append('<img src="/media/img/pics/_background/'+newBack+'" alt="" title="" style="display:block;position:absolute;z-index:-9990;top:'+curT+'px;left:0;width:'+curW+';height:'+curH+';" />');
				
				setTimeout(function() {
					$('#backstretch img:eq(0)').css({'z-index':'-9900'}).fadeTo('slow',0, function() {
						$('#backstretch img:eq(0)').addClass('test');
						$('#backstretch img:eq(1)').css({'position':'relative','z-index':'-9900'});
						$('#backstretch img.test').remove();
					})
				},10);
				
			}
			
		});
		
		/* NAVIGATE THROUGH BACKGROUND IMAGES WITH ARROWS */
		$('#prev_image').click(function() {
			
			if(!$('#backstretch img').is(':animated')){
				
				var newB = $('#center a.active').index() - 1;
				//var newB = $('#galleryimages li.active').index() - 1;
				
				if(newB < 0){
					newB = $('#galleryimages li').length -1;
					$('#center').css({'margin-left':'-'+(Math.floor(newB/18)*900)+'px'});
				}
				
				if(((newB+1) % 18) == 0){
					$('#center').css({'margin-left':'-'+((Math.floor((newB+1)/18)-1)*900)+'px'});
				}
				
				$('#galleryimages li.active').removeAttr('class');
				$('#galleryimages li:nth('+newB+')').addClass('active');
				
				$('#center a.active').removeAttr('class');
				$('#center a:nth('+newB+')').addClass('active');
				
				var newBack = $('#galleryimages li:nth('+newB+')').text();
		
				//$('#backstretch').remove();
				//$.backstretch("/media/img/pics/_background/pics/_large/"+newB, {speed: 150});
				
				var curW = $('#backstretch img').css('width');
				var curH = $('#backstretch img').css('height');
				var curT = $('#backstretch img').position().top;
				
				$('#backstretch').append('<img src="/media/img/pics/_background/'+newBack+'" alt="" title="" style="display:block;position:absolute;z-index:-9990;top:'+curT+'px;left:0;width:'+curW+';height:'+curH+';" />');
				
				setTimeout(function() {
					$('#backstretch img:eq(0)').css({'z-index':'-9900'}).fadeTo('slow',0, function() {
						$('#backstretch img:eq(0)').addClass('test');
						$('#backstretch img:eq(1)').css({'position':'relative','z-index':'-9900'});
						$('#backstretch img.test').remove();
					})
				},10);
				
			}
			
		});
		
		$('#next_image').click(function() {
			
			if(!$('#backstretch img').is(':animated')){
				
				var newB = $('#center a.active').index() + 1;
				//var newB = $('#galleryimages li.active').index() + 1;
				
				if(newB+1 > $('#galleryimages li').length){
					newB = 0;
					$('#center').css({'margin-left':'0px'});
				}
				
				if((newB % 18) == 0){
					$('#center').css({'margin-left':'-'+(Math.floor(newB/18)*900)+'px'});
				}
				
				$('#galleryimages li.active').removeAttr('class');
				$('#galleryimages li:nth('+newB+')').addClass('active');
				
				$('#center a.active').removeAttr('class');
				$('#center a:nth('+newB+')').addClass('active');
				
				var newBack = $('#galleryimages li:nth('+newB+')').text();
		
				//$('#backstretch').remove();
				//$.backstretch("/media/img/pics/_background/pics/_large/"+newB, {speed: 150});
				
				var curW = $('#backstretch img').css('width');
				var curH = $('#backstretch img').css('height');
				var curT = $('#backstretch img').position().top;
				
				$('#backstretch').append('<img src="/media/img/pics/_background/'+newBack+'" alt="" title="" style="display:block;position:absolute;z-index:-9990;top:'+curT+'px;left:0;width:'+curW+';height:'+curH+';" />');
				
				setTimeout(function() {
					$('#backstretch img:eq(0)').css({'z-index':'-9900'}).fadeTo('slow',0, function() {
						$('#backstretch img:eq(0)').addClass('test');
						$('#backstretch img:eq(1)').css({'position':'relative','z-index':'-9900'});
						$('#backstretch img.test').remove();
					})
				},10);
				
			}
			
		});
		
	}
	
	
	
	
	/* SHOW IMAGE THUMBS */
	/*if($('.open-nav').length > 0){
		$('.open-nav').hover(function() {
			//clearInterval(_test);
			$('#gallerynav').slideToggle('slow');
		}, function() {
			
		});
		
		$('#gallerynav').hover(function() {
			clearInterval(_test);
		}, function() {
			_test = setTimeout(function() {
				$('#gallerynav').slideToggle('slow');
			}, 1000);
		});
	}*/
	
	/* CODE TO CLOSE AND OPEN TEXTBLOCK */
	//var originalh = $('#container').height();
	var originalh = $('.container-large').height();
	$('.container-large .button a').click(function() {
		
		var newtext = $('.button a').attr('rel');
		var oldtext = $('.button a').text();
		
		if(!$('.container-large').is(':animated') && !$('.contentholder-large').is(':animated')){
		
			if(clicks % 2){
				
				/*$('#container').animate({width:350}, function() {
				});*/
				$('#logo').animate({'width':'239px','height':'56px'});
				
				$('.container-large').animate({width:560, height:originalh}, function(){
						$('.contentholder-large').css({'display':'block'});
						$('.contentholder-large').animate({opacity:1});
						$('.button').show();
						$('.button img').show();
					});
					
				$(this).removeClass('open');
				$(this).addClass('closed');
				$('.button a').attr('rel',oldtext).text(newtext);
				$('.button').hide();
			}else{
				
				//var w = 239;
				//var h = 83;
				
				var w = 30;
				var h = 20;
				
				$('.contentholder-large').animate({opacity:0}, function(){
					
					//$('#logo').animate({'width':'119px','height':'28px'});
					
					$('.container-large').animate({height:(h)+'px', width:(w)+'px'}, function(){
						
						$('.contentholder-large').css({'display':'none'});
						
							$('.button img').hide();
							$('.button').show();
							
						/*$('#container').animate({width:(w)+'px'}, function() {
							$('.button').show();
						});*/
					});
					
				});
				
				$(this).removeClass('closed');
				$(this).addClass('open');
				$('.button a').attr('rel',oldtext).text(newtext);
				$('.button').hide();
			}
			
			clicks++;
		}
		
	});
	
	//set arrows
	$('#menu li ul li a, #menu li ul li span').prepend('&rsaquo; ');
	
	
});

function setHeight(curr, next, opts){
	//get the height of the current slide
        var $ht = $(this).height() + 30;
        //set the container's height to that of the current slide
        $(this).parent().animate({'height': $ht});
		$(this).parent().parent().animate({'height': $ht+90});
}

function initialize() {
    var myLatlng = new google.maps.LatLng(50.983581,3.005329);
    var myOptions = {
      zoom: 10,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
	  scrollwheel: false,
	  panControl: true,
	  panControlOptions: {
		position: google.maps.ControlPosition.TOP_RIGHT  
	  },
	  zoomControl: true,
	  zoomControlOptions: {
		style: google.maps.ZoomControlStyle.SMALL,
		position: google.maps.ControlPosition.TOP_RIGHT
	  },

	  mapTypeControl: false,
	  mapTypeControlOptions: {
		  style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
		  position: google.maps.ControlPosition.TOP_RIGHT
		},
	  scaleControl: false,
	  streetViewControl: false,
	  overviewMapControl: true
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	google.maps.event.addListener(map, 'zoom_changed', function() {
     if (map.getZoom() < 3) map.setZoom(3);
   });

    
    setMarkers(map, all_dealers, false);
}

function setMarkers(map, locations, bool) {
  iterator = 0;
  if(!bool){
	  for (var i = 0; i < locations.length; i++) {
		setTimeout(function() {
			addMarker(map,locations,iterator);
			var info = '<h1 style="font-size:14px; color:#000000;">'+locations[iterator][1]+'</h1><p style="font-size:11px; color:#000000;"><br />'+locations[iterator][2]+'<br />'+locations[iterator][3]+' '+locations[iterator][4]+'<br /><br />T '+locations[iterator][5]+'<br />F '+locations[iterator][6]+'<br /><a href="mailto:'+locations[iterator][7]+'">'+locations[iterator][7]+'</a><br /><a href="http://'+locations[iterator][8]+'">'+locations[iterator][8]+'</a></p>';
			addInfoWindow(info);
			google.maps.event.addListener(infowindows[iterator], "closeclick", stopBouncers);
			eval('google.maps.event.addListener(markers[iterator], "click", function(){toggleBounce(this);closeInfoWindows();infowindows['+iterator+'].open(map,this);});');
			iterator++;
		}, 1000+(i*20));
	  }
  } else {
	for (var i = 0; i < locations.length; i++) {
		addMarker(map,locations,iterator);
		var info = '<h1 style="font-size:14px; color:#000000;">'+locations[iterator][1]+'</h1><p style="font-size:11px; color:#333333;"><br />'+locations[iterator][2]+'<br />'+locations[iterator][3]+' '+locations[iterator][4]+'<br /><br />T '+locations[iterator][5]+'<br />F '+locations[iterator][6]+'<br /><a href="mailto:'+locations[iterator][7]+'">'+locations[iterator][7]+'</a><br /><a href="http://'+locations[iterator][8]+'">'+locations[iterator][8]+'</a></p>';
		addInfoWindow(info);
		google.maps.event.addListener(infowindows[iterator], "closeclick", stopBouncers);
		eval('google.maps.event.addListener(markers[iterator], "click", function(){toggleBounce(this);closeInfoWindows();infowindows['+iterator+'].open(map,this);});');
		iterator++;
	}
  }
  
}

function addMarker(map, locations, m) {
	
	var location = locations[m];
	// Add markers to the map
 
	// Marker sizes are expressed as a Size of X,Y
	// where the origin of the image (0,0) is located
	// in the top left of the image.

	// Origins, anchor positions and coordinates of the marker
	// increase in the X direction to the right and in
	// the Y direction down.
	var shape = {
		  coord: [0, 5, 0, 32, 32, 32, 32 , 5],
		  type: 'poly'
		};

		var latTemp = location[10];
		var lonTemp = location[11];
		latTemp = latTemp.replace(',','.');
		if(!lonTemp){
			alert(location[1]);
		}
		lonTemp = lonTemp.replace(',','.');
		var myLatLng = new google.maps.LatLng(latTemp, lonTemp);
		markers.push(new google.maps.Marker({
			position: myLatLng,
			map: map,
			draggable: false,
			//animation: google.maps.Animation.DROP,
			shape: shape,
			autoclick: true,
			title: location[1]
		}));
	
}

function addInfoWindow(contentString){
	infowindows.push(new google.maps.InfoWindow({
		content: contentString,
		maxWidth: 150
	}));
}

function toggleBounce(marker) {
	//stop other bouncing markers
	stopBouncers();
	//toggle
	if (marker.getAnimation() != null) {
		marker.setAnimation(null);
	} else {
		marker.setAnimation(google.maps.Animation.BOUNCE);
	}
}

function stopBouncers(){
	for(i=0; i<markers.length; i++){
		markers[i].setAnimation(null);
	}
}

function closeInfoWindows(){
	for(i=0; i<infowindows.length; i++){
		infowindows[i].close();
	}
}

function resizeMap(){
	var curW = $(window).width();
	var curH = $(window).height();
	
	document.getElementById("map_canvas").style.width = '100%';
    document.getElementById("map_canvas").style.height = '100%';
    google.maps.event.trigger(map, 'resize');
}
