var loadGallery = false;

$(function() {

	// Stuff to do as soon as the DOM is ready;
    
	// Also setup the positions of the items to be undernearth their
    // parent menu items
    $('div#masthead_cars ul li').each(function (i) {
    	var menuitem_pos = $(this).position();
    	var model = $(this).attr('class');
    	var starting_position = $('#main').position();
    	$('#'+model).appendTo($(this));
    	$('#'+model).css({
    		left: starting_position['left'],
    		top: starting_position['top']
    	});
    	$('#'+model).hide();
	});    
	var prev_menu_pos = 0;	
    $('div#masthead_cars ul li').bind("mouseenter", function(){
    	var menu_dropout = $('div.slide-model', $(this));
    	var new_menu_pos = $(this).position();
    	new_menu_pos = new_menu_pos['left'];    	
    	if(prev_menu_pos != 0){
    		menu_dropout.css({
	    		left: prev_menu_pos
	    	});
    	}; 
		$('a:first', this).addClass('hover');
    	menu_dropout.show().animate({
    		opacity: 1.0,
    		left: new_menu_pos
    	}, 250, 'easeInOutQuad');
    	prev_menu_pos = new_menu_pos;
    });
    
    $('div#masthead_cars ul li').bind("mouseleave", function(){
    	$('div.slide-model', $(this)).hide();
		$('a:first', this).removeClass('hover');
    });
    
    // --------------------
    // Services popup
    $('#book-service').click(function(){
    	window.open($(this).attr('href'), "bookService", "status=0, height=625, width=450, resizable=0");
    	return false;
    });
    
    
    // ------------
	// SPECS PAGES
	// ------------
	$('ul#variantNav a').click(function(){
		
		var targetSpecs = $(this).parent().attr('id');		
		$('div.spec-option:visible').fadeOut(250);
		$('ul#specNav').fadeOut(250);
		$('#specs-loader').fadeIn(350);
		
		$('div.'+targetSpecs).load('_'+targetSpecs+'.php', function(){
			$('#specs-loader').fadeOut(350);
			$('ul#specNav').fadeIn(150);
			$(this).fadeIn(350);
		});
			
		$('ul#variantNav li.active').toggleClass('active');
		$(this).parent().toggleClass('active')		
		
		return false;
	});
	
	
    
    
    /*
    // Fix heights of popups
    $('.slide-model a img').each(function(index) {
    	var imageHeight = $(this).attr('height');
    	$(this).parent().height(imageHeight);
    });
    */

	// ---------------
	// IMAGE GALLERY
	// -------------
	
	// load a selected gallery
	loadGallery = function(galleryName) {
		if (galleryName == 'undefined' || galleryName == '') $('#model').val();
		$('#galleryHeader li').removeClass('selected');
		$('#galleryHeader li.'+galleryName).addClass('selected');
		galleryName = '/gallery/'+galleryName+'.html';
		// console.log(galleryName);
		$('#galleryContent').load(galleryName, {}, function(){
			intializeImageView();
		});
		return false;
	};
	
	// show the gallery popup 
	var galleryLoaded = false;
	var showGallery = function(initGallery) {
		$('#mb_overlay').css('height', $(document).height());
		$('#mb_overlay').show();
		$('#mb_overlay').animate({ opacity: 0.5 }, 250 );
		$('#mb_overlay').click(hideGallery);
		setTimeout("$('#mb_center').fadeIn(250);", 250);
		$('div.slide-model').hide();
		initGallery = initGallery.replace(/hover/,'').replace(/(^\s*)|(\s*$)/g, '');;
		// load the gallery content
		if (!galleryLoaded) {
			$('#mb_contents').load('/gallery/gallery.html', {}, function() {
				gallerySelectReplace(initGallery);
				$('#galleryHeader #close').click(hideGallery);
				$('#galleryHeader #model').change(function() { loadGallery($(this).val()); });
				loadGallery(initGallery);
				galleryLoaded = true;
			});
		} else {
			loadGallery(initGallery);
		}
		return false;
	}
	
	// hide the gallery popup
	var hideGallery = function() {
		$('#mb_overlay').show().animate({ opacity: 0.0 }, 250, function() {$(this).hide();} );
		$('#mb_center').hide();
		$('#mb_overlay').click(function() {});
	};	
	
	// replace the standard select box with a nicer one...
	var gallerySelectReplace = function(initGallery) {
		$('#galleryHeader select').each(function(i) {
			if ((!this.options) || (this.options.length <= 0)) return;
			$(this).addClass('replaced');
			replacement = $('<ul class="selectReplacement"></ul>');
			// workout the selected index
			for (var i = 0; i < this.options.length; i++) {
				var selectedOpt;
				if (this.options[i].selected) {
					selectedOpt = i; break;
				} else {
					selectedOpt = 0;
				}
			}
			// add list items for each option
			for (var i = 0; i < this.options.length; i++) {
				li = $('<li>'+this.options[i].text+'</li>');
				if (i == selectedOpt) $(li).addClass('selected');
				$(li).addClass(this.options[i].value);
				replacement.append(li);
			}
			// hover and click handlers
			$('li', replacement).mouseover(function(){ $(this).addClass('hover');});
			$('li', replacement).mouseout(function(){ $(this).removeClass('hover');});
			$('li', replacement).click(function(){ 
				if ($(this).hasClass('selected')) {
					$(this).parent().addClass('selectOpen');
				} else {
					selectMe(this); 
				}
				return false;
			});
			$(this).before(replacement);
		});
	};
	
	// handle changes to the replaced select box
	var selectMe = function(element) {
		$('li', $(element).parent()).each(function(i) {
			if (this != element) {
				$(this).removeClass('selected');
			} else {
				var selIndex = i
				$('#galleryHeader select').each(function() {
					this.selectedIndex = selIndex;
				});
				$('#galleryHeader select').change();
				$(this).addClass('selected');
				$(this).parent().removeClass('selectOpen');
			}	
		});
	}
	
	// add the modal gallery container
	$('body').append('<div id="mb_overlay"></div>');
	$('body').append('<div id="mb_center"><div id="mb_contents"></div></div>');
	$('#mb_center').css('left', ($('body').width() / 2) - ($('#mb_center').width() / 2));
	$('#mb_center').hide();
	$('#mb_overlay').animate({ opacity: 0.0 }, 1, function() {$(this).hide();} );
	
	// add click handler to the menu
	$('li.view-gallery a').click(function() {
		showGallery($(this).attr('class'));
		return false;
	});	
	// add click handler to the gallery items per page
	$('div.gallery-preview-images a').click(function() {
		showGallery($(this).attr('class'));
		return false;	});
	// add click handler to the gallery item for the right hand list
	$('ul#model-nav li.item-9 a').click(function() {
		showGallery($(this).attr('class'));
		return false;	});
	
	// Image Viewer
	var intializeImageView = function() {
		$('div.ImageViewer').remove();
		$('body').append('<div class="ImageViewer"></div>');
		$('div.ImageViewer').hide();
		$('div.ImageViewer').load('/gallery/imageview.html', {}, function(){
			$('div.ImageViewer').click(function() { $('div.ImageViewer').hide(); });
		});
		$('#galleryContent img').each(function(){
			$(this).click(function() { 
				clickImageView(this); 
				return false;
			});
		});
	}
	var clickImageView = function(img) {
		$('div.ImageViewer').css('left',($(window).width()-850)/2);
		$('div.ImageViewer').show();
		$('div.ImageViewer img').attr('src', $(img).attr('src').replace('/small/','/large/'));
	}
	
	var intializeImagePopup = function() {
		$('div.ImageViewer').remove();
		$('body').append('<div class="ImageViewer"></div>');
		$('div.ImageViewer').hide();
		$('div.ImageViewer').load('/gallery/imageview.html', {}, function(){
			$('.popup-image').each(function(){
				$(this).click(function() { 
					popImage(this);
					return false;
				});
			});
			$('div.ImageViewer').click(function() { $('div.ImageViewer').hide(); });
			return false;
		});
	}
		
	var popImage = function(img) {		
		$('div.ImageViewer').css('left',($(window).width()-850)/2);
		$('div.ImageViewer').show();
		$('div.ImageViewer img').attr('src', $(img).attr('href'));
		return false;
	}
	
	intializeImagePopup();
	
});