/*

	Unibroue main.js
	Date created: 18/02/2010
	Author: Antoine Girard (antoine.girard@gmail.com)

*/

/*
	Describe me
*/
  
site = {
	
	init : function() {

		// init drop down menus
		dropdown.init('ul#nav > li');		
		 
		site.position_footer();
		
		// attach on resize events
		window.onresize = function() { 
			site.position_footer();
		};  
		
		// init scroll bars
    this.content_to_scroll();  
		 	
		// font init
		Cufon.replace('body.splash h2, body.splash p, body.splash ul li, ul#nav > li > a, .content-sub-nav a, ul.beers-list li h3, #page-header h2, ul.page-nav li a, h3.section-title, #page-content a.cufon, .two-cols-container .inner h4, #footer p.copyrights, #footer ul li a', { 'hover' : true });		
		
    // add target blank to rel=blank
    $("a[rel='blank']").attr('target', "_blank");
    
    // hack beers menu item link to actually use its first child's href
    var beer_section_a = $('ul#nav li.beers > a');
    var first_beer_category = $(beer_section_a).next().find('li a')[0];
    $(beer_section_a).attr('href', $(first_beer_category).attr('href'));
    
		// add .last class to some nav elements
		$("ul.page-nav li:last").addClass('last');
		// alert($(".page-nav li:last"));

    // abbr pop in
    abbr_overlay.init();
    
	}, 
	
	content_to_scroll : function() {
		$('.to-scroll').jScrollPane({scrollbarWidth: 22, dragMaxHeight: 40, dragMinHeight: 40, topCapHeight: 32});		  
	},	
	
	// Add a fixed position to footer if browser window height
	// is higher than the (#header + #main) total height
	// Some values are *hardcoded* here: precise design require precision pixels
	position_footer : function() {
	  var height = $("#header").height() + $("#main").height();
	  var window_height = $(window).height(true) - $("#footer").height() - $("#footer .decoration").height() - 50;
                       
	  if(window_height > height) {
	    $("#footer").addClass('fixed');
			$("#footer").css('width', $('#wrapper').innerWidth() - 34);
	  } else {
	    $("#footer").removeClass('fixed').css('width', 'auto');  
	  }
	},
	
	preload_backgrounds : function() {
	  
	} 	
		
}

  
abbr_overlay = {
  
  init : function() {
    $('abbr').removeAttr('title').each(function() {
      var text = $(this).text();
      abbr_overlay.search(this, text);
    });  
  },
  
  search : function(e, word) {
    var url = "/" + LANGUAGE_CODE + "/unibroue/glossary/";    
    // build params for ajax call
		params = { 'is_ajax_search': 1, "word": word }

		$.getJSON(url, params,
			function(data) {            
				// clear all markers before inserting new ones
        definition = $.parseJSON(data.definition);
        
        // if no difinition was found, remove class and tool-tip event
        if(definition[0]) {        
          $(e).attr('rel', definition[0].fields.text);  
          abbr_overlay.show(e, definition[0]);
          $(e).addClass('abbr_overlay')
        }      
        
			}
		);
    
  },
  
  show : function(e, definition) {
		$(e).qtip({ 
			content: {
				text: definition.fields.text
			},
			style: { 
				width: 200,
				padding: 5,
				background: '#5D5145',
				color: '#fff',
				border: {
					width: 7,
					radius: 5,
					color: '#5D5145'
				},
				tip: 'topleft'
      }
    });
  
  }
    
}


/*
	Main navitation drop down system
	Selected with : ul#nav > li
*/

dropdown = {
	
	init : function(sel) {
	
		$(sel).mouseenter(
			function() { dropdown.over(this); }
		);	             
		
		$(sel).mouseleave(
			function() { dropdown.out(this); } 
		);
		
	},
	
	over : function(e) {
		content = $(e).find('ul');
		content.css('opacity', 0).show();
		content.animate({'opacity': 1}, 300);		
	},
	
	out : function(e) {
		content = $(e).find('ul');
		content.fadeOut(100);
		
		// refreshing Cufon's rendering engine on mouseLeave
		Cufon.refresh();
	}	
}



/*
	Page sub-navitation system
	Dependency: jQuery Address 
*/
sub_menu = {
	
	init : function(sel, target) {                            
		var autoload = AUTOLOAD_SUBMENU_FIRST_ELEMENT;		
		
		this.sel = sel;
		this.markup_container = target;	                       	

		$(this.sel).address();
	                                   
		// handle #hash address
		// will trigger click event on link if a hash is found
		$.address.change(function(event) {             
			// do nothing if no path is found
			if(event.pathNames.length > 0) {
				e = $.find('a[rel=address:'+event.pathNames[0]+']');
				sub_menu.open(e);				
			} else if (autoload == true) {           
				// no #hash found, open first element in selection
				e = $(sel)[0];
				sub_menu.open(e);
			}			
		});
		
	},
	
	open : function(e) {
		url = $(e).attr('href');
		params = { is_ajax: 1 };

		// do nothing if element has .active class
		if(!$(e).hasClass('active')) {
			
			$.get(url, params,
				function(data){ 					
					$(sub_menu.markup_container).html(data);
					sub_menu.activate_section(e);
					site.content_to_scroll();
				}
			);			
			
		}   
	},
	
	activate_section : function(e) {
		$(sub_menu.sel).removeClass('active');
		$(e).addClass('active');
		Cufon.refresh();
		abbr_overlay.init();
	}	
}  


/*
	Page content-sub-nav functions
*/ 

content_sub_nav = {
                 
  init : function(sel) { 			
		var content = $(sel).find('ul');
				
		$(content).css('opacity', 0);
		    
    $(sel).mouseenter(function() {
      content_sub_nav.over(this, content);
   	});    

  	$(sel).mouseleave(function() {
      content_sub_nav.out(this, content);
  	}); 

    if(BEER_CATEGORY_CLASS) {
    	var active_category = $('.content-sub-nav li' + BEER_CATEGORY_CLASS).find('a');
    } else {
      var active_category = $('.content-sub-nav li:last').find('a');
    }                                                       
    
   	var current_category_text = $(active_category).html();    
   	$('a#current-category').html(current_category_text);      
    
  },
  
  over : function(e, content, ie) {
	  // calculate total height for animation
    var totalHeight = parseInt($(content).outerHeight()) + 35;
    $(content).children().each(function() {
       totalHeight += $(this).height()
    });
	
		$(content).animate({ 'height': totalHeight, 'opacity': 100}, 250);    			
  },
  
  out : function(e, content) {
		$(content).animate({'height': 0, 'opacity': 0}, 250);    
  }
  
}

/*
	Videos sub-navigation
	Dependency: jQuery Address 
*/

videos_navigation = {
	
	init : function(sel) {		
		this.sel = sel;
		
		$(this.sel).address();
	                                   
		// handle #hash address
		// will trigger click event on link if a hash is found
		$.address.change(function(event) {
			// do nothing if no path is found
			if(event.pathNames.length > 0) {
				e = $.find('a[rel=address:'+event.pathNames[0]+']');
			} else {           
				// no #hash found, open first element in selection
				e = $(sel)[0];
			}			
			
			// find target video
			var id = $(e).attr('data-target');
			target = $(id);
			
			// start video
			video_player.init(target, 630, 354);
			
			// handle active link className
			$(videos_navigation.sel).removeClass('active');
			$(e).addClass('active');
		});
		
	}
}



/* ---------------------------------------------------------------------------
	Class: Video player
	Description: 
------------------------------------------------------------------------------ */

video_player = {
	
	init : function(sel, width, height) {

    // reset all players before doing anything
    this.clear_all_players();
		
		$(sel).each(function() {		

			var a = $(this).find('a');
			var flv = a.attr('href');
			var preview = a.html();
			      
      // hide a element
			a.hide();

			// insert video player
			$(this).flash({
					swf: MEDIA_URL + 'swf/video_player.swf',
					params: {
						wmode: 'transparent',
						allowfullscreen: "true"
					},  
					flashvars : {
						path_video : flv,                        
						video_preview: preview,
						lang: LANGUAGE_CODE,
						autoplay: 0,
						swf_base: MEDIA_URL + "swf/",
						img_base: MEDIA_URL,
					 	color: "#FFEFBC",
						color_default: "#9A8C80"
					},          
					width: width,
					height: height
				}
			);

		});
		
	},
	
	clear_all_players : function() {
    videos = $('div.video');
    
    videos.each(function() {
      var player = $(this).find('embed, object');
      // console.log(player);
      $(player).remove();      
    });              
    
	}
	
}


/* ---------------------------------------------------------------------------
	Class: ImageGallery
	Description: 
------------------------------------------------------------------------------ */
                     
gallery = {
	
	settings: {		
		mask_markup : '<div class="inner-mask-top"></div>',
		nav_markup: '<ul class="gallery-nav"><li><a href="#" id="prev">prev</a></li><li id="pages"><span id="pager"></span> - <span id="total"></span></li><li><a href="#" id="next">next</a></li></ul>'
	},
	
	init : function(sel) {
		var n = $(sel).children().length;
		
		if(n > 0) { 		 
	                      
			// insert top  mask for gallery
			$(sel).before(gallery.settings.mask_markup);
	
			// insert nav
			$(sel).after(gallery.settings.nav_markup);
      
			// start cycle only if more than 1 picture
			if(n > 1) { 
				// start gallery 
				$(sel).cycle({ 
				    prev: '#prev', 
				    next: '#next',
				 		fx: 'scrollHorz',
						speed: 300,
				    timeout: 0,
						pager: "#pager"
				});
				                                                
				//
				$("ul.gallery-nav li").css('display', 'inline-block');

				// nomber of item
				$('#total').text($(sel).find('li').length);				
			}  			
		}  		
	}
	
};


/* ---------------------------------------------------------------------------
	Class: Backgrounds
	Description: insert background image and streching within browser viewport
------------------------------------------------------------------------------ */

backgrounds = {			

	settings : {
		max_width: 1440,
		random: 7
	},
	 	
	init : function(src) {			
		
		if(src != 'random') {
			// insert image
			backgrounds.insert_image(src);			
		} else {
			rand = Math.round(Math.random() * this.settings.random) + 1;
			image = MEDIA_URL + 'img/backgrounds/background_'+rand+'.jpg';
			backgrounds.insert_image(image);
		}
		
		// init resizing and position with jQuery.supersized plugin
		$.fn.supersized.options = {
			startwidth: 1440,
			startheight: 900,
			minsize: .5,
			slideshow: 0
		};
    $('#supersize').supersized();		
	},
 
  // preload all random background images
	preload : function() {
	  for (var i=1; i <= backgrounds.settings.random; i++) {
			img = new Image(); 
			img.src = MEDIA_URL + 'img/backgrounds/background_'+i+'.jpg';
	  };
	},
		
	insert_image : function(src) {
		// create div, append an image into it (unclean ie6 solution)
		div = $("<div/>").addClass('bg-image').attr("id", "supersize");
		img = $("<img/>").attr('src', src);
		$(img).appendTo(div);
		return $(div).appendTo('body');
	}

};  


/* ---------------------------------------------------------------------------
	Class: GMaps
	Description: various snippets for interacting with Google Maps API
------------------------------------------------------------------------------ */
gmaps = {

	settings : {
		default_lat: 46.164614,
		default_lng: -72.202148,
		zoom_level: 6,
		zoom_level_search: 12,
		container: 'gmap'
	},

	init_map : function(settings) {
		// extend settings
		jQuery.extend(gmaps.settings, settings);						
				
		// init map object and center to the mountain
		this.map = new GMap2(document.getElementById(gmaps.settings.container), { size: new GSize(373,445) });
		this.map.addControl(new GSmallZoomControl3D());
		this.map.enableScrollWheelZoom();	        
		                                        
		// maps cache
		this.map_cache = new GFactualGeocodeCache();
		
		// create geocoder
		this.geocoder = new GClientGeocoder(this.map_cache);

		// set to default position
		var center = new GLatLng(this.settings.default_lat, this.settings.default_lng);
		this.map.setCenter(center, this.settings.zoom_level);

		// add loader
		$("<div id='gmap-loader'></div>").appendTo("#" + gmaps.settings.container).css('opacity', 0);		
	}, 
	
	attach_events: function() {
	  gmaps.move_event = GEvent.addListener(gmaps.map, "moveend", function() {
			if(!$("body").hasClass('info-window-open')) {
			  var center = gmaps.map.getCenter();
				gmaps.search_outlets(center.lat(), center.lng());				
			}                                                  
		});	 

		GEvent.addListener(gmaps.map, "infowindowclose", function() {
			$("body").removeClass('info-window-open');
		});		
	}, 
	
	search_current_map: function() {
	  var center = gmaps.map.getCenter();
		gmaps.search_outlets(center.lat(), center.lng());
	},
	
	search_address : function(address) {
		gmaps.geocoder.getLatLng(address, function(result) { gmaps.search_outlets(result.lat(), result.lng(), true, gmaps.settings.zoom_level_search) });
	},
	
	search_outlets : function(lat, lng, pan, zoom) {
		var pan = pan || false;                    
		var zoom = zoom || gmaps.settings.zoom_level;                    		
		var geo_location = new GLatLng(lat, lng);
				
		// pan and zoom except for onPanEvent
		if(pan) {
			gmaps.map.setCenter(geo_location);
			gmaps.map.setZoom(zoom);			
		}                                     
		
		var dist = gmaps.calculate_search_distance();
		var distance_offset = 100; // in km.

		// empty search results
		$('#outlets-list').empty();
		
		// show loader
		// $("#gmap-loader").css('display', 'block').animate({'opacity': 100}, 250);

		// build params for ajax call
		params = { 'is_ajax': 1, "lat": lat, "lng": lng, 'dist': dist + distance_offset, 'limit': 100 }

		// show loader
		gmaps.toggle_loader('show');

		$.getJSON('/fr/buy/', params,
			function(data) {            
				// clear all markers before inserting new ones
				gmaps.map.clearOverlays();
				gmaps.place_markers(data);
				
				// hide loader
				gmaps.toggle_loader('hide');
				
			}
		);
		
	},
	
	calculate_search_distance : function() {
		// get positions
		var bounds = gmaps.map.getBounds();
		var northEast = bounds.getNorthEast();
		var center = gmaps.map.getCenter();
		                     
		// create points from center to NorthEast
		var ne = new GLatLng(northEast.lat(), northEast.lng());
		var ce = new GLatLng(center.lat(), center.lng());		

		// calculate distance
	 	var distance = ne.distanceFrom(ce);	

		// round distance in KM
		return Math.round(distance / 1000);
	},
	
	place_markers : function(data) { 
	
		outlets = $.parseJSON(data.outlets);
		
		if(outlets.length > 1) {

			$(outlets).each(function() {
				var data = this;                          

				var i = gmaps.create_icon();
				var markerLatLng = new GLatLng(data.fields.lat, data.fields.lng);
				var marker = new GMarker(markerLatLng, {icon: i, title: data.fields.name});

				gmaps.map.addOverlay(marker); 

				// register click event on marker
				GEvent.addListener(marker, "click", function() {
					$("body").addClass('info-window-open');
					gmaps.display_info_window(marker, data);				
				});

				// create link element in outliet list
				var ul = $('#outlets-list');
				var li = $("<li/>");
				var a = $("<a/>").text(data.fields.name.toLowerCase()).attr('href', '#');
				a.mousedown(function() {
					$("body").addClass('info-window-open');
					gmaps.display_info_window(marker, data);				
				});

				a.appendTo(li);			
				li.appendTo(ul);						
			});		                        

			$('.outlets').jScrollPane({scrollbarWidth: 21, dragMaxHeight: 40});			
		} else {			
			// alert('nothing found');
			gmaps.map.setZoom(10);						
			$('#outlets-list').html('<li>'+ _NOTHING_FOUND +'</li>');
		}			
		
	},
	
	display_info_window : function(marker, data) {
		var html = '';
		
		// build html
		html += "<div class='gmap-infowindow'>";
		html += "<h4>"+data.fields.name.toLowerCase()+"</h4>";
		html += "<p class='address'>"+data.fields.address.toLowerCase()+", "+data.fields.city.toLowerCase()+"</p>";
		html += "<p><a href='http://"+data.fields.website+"' target='_blank'>"+data.fields.website+"</a></p>";
    html += "<p>"+format_phone(data.fields.phone)+"</p>";
    html += "<p><strong><a href='http://maps.google.com/maps?z=16&q="+data.fields.lat+","+data.fields.lng+"("+data.fields.name+")' target='_blank'>"+_SEE_ON_GOOGLE_MAPS+"</a></strong></p>"
		html += "</div>";
				
		// open infoWindow
		gmaps.map.openInfoWindowHtml(marker.getPoint(), html, { maxWidth: 150 });	
	},
	
	create_icon : function() {	
		var i = new GIcon();
		i.image = MEDIA_URL + "/img/content/map-icn.png";			
    i.iconSize = new GSize(20, 20);
    i.iconAnchor = new GPoint(10, 10);
    i.infoWindowAnchor = new GPoint(10, 10);
		i.zIndex = 10000;
		return i;
	}, 
	
	toggle_loader : function(action) {
		if(action == 'show') {
			$("#gmap-loader").css('opacity', 0).show().animate({opacity: 0.5}, 250);
		}
		if(action == 'hide') {
			$("#gmap-loader").animate({opacity: 0}, 250, function(){ $(this).hide(); });
		}
	}

	
};   



//  misc
function format_phone(phone) {
  if(phone.length == 10) {
		var p = "";
	  p += "(" + phone.substr(0,3) + ") ";
	  p += phone.substr(3,3) + "-";
	  p += phone.substr(5,4);  
	  return p;	
	} else {
		return phone;
	}  
}

