/*
MUK dealers general JS - permanent functionality
Dependencies: jquery 1.3.1, swfObject 2.0
Aurthor: Tim Leung
*/

// page initialisation
if(!location.host) {
	document.writeln('\n\t<link rel="stylesheet" href="css/js_main.css" type="text/css" media="all" />');
}
else {
	document.writeln('\n\t<link rel="stylesheet" href="/css/js_main.css" type="text/css" media="all" />');
}

// iPhone browser condition
if (/AppleWebKit.*Mobile/.test(navigator.userAgent)) {
    document.documentElement.className += " iphone ";
}


$(document).ready(function() {
	ie6navHack();
	ieLabelHack();
	linksToggle();
	dealerContact();
	aboutDealerToggle();
	modelSelector();
	offerSelector();
	addPrintEvents();
	if ($('#map').length > 0) {
		initGmap();
		
	}
});

// IE6 hack - Top navigation hover
function ie6navHack() {
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		var nav = $('#nav li');
		nav.hover(function () {
			$(this).addClass('sfhover');
		}, function () {
			$(this).removeClass('sfhover');
		});
		// IE6 png transparent images fix
		$('img[src$=".png"],#mainContent,#leftColumn').ifixpng();
	}
};
// END: IE6 hack - Top navigation hover

function ieLabelHack () {
	if(jQuery.browser.msie) {
	    var label = $('label');
	    label.each(function() {
	    	var labelImg = $(this).children('img');
	    	if (labelImg[0]) {
				labelImg[0].forid = this.htmlFor;
		        labelImg.click(function() {
					var e = $('#'+this.forid);
					switch(e.attr('type')) {
						case 'radio':
							e.checked = true;
						break;
						case 'checkbox': 
							e.click();
						break;
						case 'text':
						case 'password':
						case 'textarea':
							e.focus();
						break;
					}
	        	});
        	}
		});
	}
};

function linksToggle() {
	var transitionTime = {show: 300, hide: 200};
	var links = $('a.collapse');
	links.each(function() {
		var eachLink = $(this);
		var relativeNode = eachLink.next(0);
		// Links toggle function apply for each relative nodes
		eachLink.click(function(e) {
			var clickedLink = $(this);
			var hours = clickedLink.parent('.hours');
			e.preventDefault();
			clickedLink.blur();
			if (hours) {
				// Opening hours links reset
				hours.children('a.collapse').not(clickedLink).next('div').slideUp(transitionTime.hide,function(){$(this).removeClass('on');});
			};
			relativeNode.slideToggle(transitionTime.show,function(){$(this).toggleClass('on');});
		});
	});
};

// Hiding dealer contact details onload when reaching set max dealer numbers
function dealerContact() {
	// Set max dealer number
	var largeGroup = 3;
	var transitionTime = 200;
	var dealerContact = $('#leftColumn .contact');
	var opening_hours = dealerContact.find('div.hours div.hours_table');
	if (opening_hours.length < 2) opening_hours.show();
	
	if (dealerContact.length > largeGroup) {
		var viewHours = dealerContact.find('.viewHours a');	
		viewHours.each(function() {
			var eachLink = $(this);
			eachLink.parent().show();
			var hoursTable = eachLink.parent().siblings('.hours');
			/*
				TODO js_main.css
			*/
			hoursTable.hide();
			// Hours Links Toggle
			eachLink.click(function(e) {
				var clickedLink = $(this);
				var content = clickedLink.parent().prev('div');
				var hoursLinks = hoursTable.find('a.collapse');
				e.preventDefault();
				clickedLink.hide();
				viewHours.not(clickedLink).show().parent().siblings('.hours').slideUp(transitionTime);
				hoursLinks.next('div').slideUp(transitionTime,function(){$(this).removeClass('on');});
				hoursLinks.eq(0).next('div').slideDown(transitionTime,function(){$(this).addClass('on');});
				hoursTable.slideToggle(transitionTime);
			});
		});
	};
};

/*function dealerContact() {
	// Set max dealer number
	var largeGroup = 3;
	var transitionTime = 200;
	var dealerContact = $('#leftColumn .contact');
	if (dealerContact.length > largeGroup) {
		var viewContact = dealerContact.find('.viewContact a');
		var viewHours = dealerContact.find('.viewHours a');
		
		viewContact.each(function() {
			var eachLink = $(this);
			eachLink.parent().show();
			// hide all dealer details apart from dealer name and address
			var content = $(eachLink.parent().prev('div'));
			content.hide();
			// Toggle content when h1 being clicked
			eachLink.click(function(e) {
				var clickedLink = $(this);
				var hoursLinks = clickedLink.parent().next('div.viewHours').find('a');
				e.preventDefault();
				clickedLink.blur();
				// Other dealer links reset
				viewContact.not(clickedLink).parent().prev('div').slideUp(transitionTime);
				viewHours.not(hoursLinks).parent().siblings('.hours').slideUp(transitionTime);
				// Opening hours links reset
				content.slideToggle(transitionTime);
			});
		});
		viewHours.each(function() {
			var eachLink = $(this);
			eachLink.parent().show();
			var hoursTable = eachLink.parent().siblings('.hours');
			hoursTable.hide();
			// Hours Links Toggle
			eachLink.click(function(e) {
				var clickedLink = $(this);
				var content = clickedLink.parent().prev('div');
				var hoursLinks = hoursTable.find('a.collapse');
				var contactLinks = clickedLink.parent().prev('div.viewContact').find('a');
				e.preventDefault();
				clickedLink.blur();
				viewHours.not(clickedLink).parent().siblings('.hours').slideUp(transitionTime);
				if (hoursLinks.length == 1) {
					hoursLinks.next().slideDown(transitionTime);
				} else {
					hoursLinks.next().slideUp(transitionTime);
				};
				viewContact.not(contactLinks).parent().prev('div').slideUp(transitionTime);
				hoursTable.slideToggle(transitionTime);
			});
		});
	};
};*/

function aboutDealerToggle () {
	var transitionTime = {show: 300, hide: 200};
	var dealerLink = $('#about.toggle div.header a');
	var expandLink = dealerLink.filter('.expand');
	expandLink.fadeIn(transitionTime.show);
	// Hiding relative nodes when js initialise
	var relativeNode = dealerLink.parent().next('.aboutContent');
	var closeLink = dealerLink.filter('.collapse');
	// Link toggle function
	dealerLink.click(function(e) {
		e.preventDefault();
		relativeNode.slideToggle(transitionTime.hide, function() {
			expandLink.toggle();
			closeLink.toggle();			
		});
	});
	/*
	closeBtn.click(function(e) {
			e.preventDefault();
			closeBtn.blur();
			relativeNode.slideUp(transitionTime.hide);
			closeBtn.hide();
		});
		// apply links toggle function
		dealerLink.click(function(e) {
			e.preventDefault();
			$(this).blur();
			relativeNode.slideToggle(transitionTime.show, function () {
				if (relativeNode.is(':visible')) {
					closeBtn.fadeIn(transitionTime.show);
				} else {
					closeBtn.hide();
				};
			});
		});*/
};

// mousehover function for the Model Selector in New Mazda page
function modelSelector () {
	var modelImgs = $('.model_select img, .offer_select img');
	var transitionTime = 200;
	var offers_link = $('#expand_model a.next');
	var model_list = $('ul.offer_select');
	offers_link.click(function(e) {
		e.preventDefault();
		$(this).blur();
		model_list.slideToggle(transitionTime);
	});
	$(".offer_select :checked").prev().find('img').addClass('selected');
	modelImgs.each(function() {
		var thumb = $(this);
		var src = thumb.attr('src');
		// get mouseout images path
		var mouseover = getValueFromParams('hover', src);
		// set images to mouseout status
		//thumb.attr('src', mouseout);
		// add hover effect to each image
		thumb.hover(function() {
			if (!thumb.hasClass('selected')) thumb.attr('src', mouseover);
		}, function() {
			if (!thumb.hasClass('selected')) thumb.attr('src', src);
		});
		offerSelector(thumb,src,mouseover);
	});
};

// model offer selector checkbox function
function offerSelector (thumb,src,mouseover) {
	var img = $(thumb);
	var modelOffer = img.parent(0).siblings(':checkbox');
	img.attr('src', img.hasClass('selected') ? mouseover : src);
	modelOffer.click(function() {
		img.toggleClass('selected');
		img.attr('src', img.hasClass('selected') ? mouseover : src);			
	});
};

// Print buttons function for promotions offers
function addPrintEvents() {
	var print_buttons = $('a.promo_print');
	print_buttons.each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			$(this).blur();
			window.print();
		});
	});
};

function initGmap() {

	//is gmaps enabled?
	if (gmap2.isEnabled()) { 
		
		//set map behaviours (if you need any)
		var behaviours = {
			//beforeRenderMap: function () { console.log('beforeRenderMap'); },
			//afterRenderMap: function () { console.log('afterRenderMap'); }
		};

		//add map behaviours
		gmap2.addBehaviours(behaviours);
		
		//initialize the gmaps, placeholder element, optional width, height
		gmap2.init($('#map')); 
		
		//get map location
		var loc = gmap2.getGmapParams($('#mapLocation')); 
		
		//create marker with letter S
		var point = gmap2.createPoint(loc.lat, loc.lng, ''); 
		
		//attach click event to the marker
		gmap2.click(point, function() { 
			//open window on mouse click
			var dealerContact = '<h3>' + $('#dealer-contact').children('h1').text() + '</h3>';
			dealerContact += $('#dealer-address').html();
			dealerContact += '<br />' + $('#dealer-tel').html();
			dealerContact += '<br />' + $('#dealer-email').html();
			gmap2.windowOpen(gmap2.getGmapPoint(loc.lat, loc.lng), dealerContact);
		});
		
		// Google map event tracking
		//GEvent.addListener(gmap2.map, 'dblclick', function() { pageTracker._trackEvent('Google Map', 'Double Click - Zoom In'); });
		//GEvent.addListener(gmap2.map, 'dragstart', function() { pageTracker._trackEvent('Google Map', 'Drag Start'); });
		//GEvent.addListener(gmap2.map, 'dragend', function() { pageTracker._trackEvent('Google Map', 'Drag End'); });
		GEvent.addListener(gmap2.map, 'infowindowopen', function() { pageTracker._trackEvent('Google Map', 'Info Window Open'); });
		//GEvent.addListener(gmap2.map, 'infowindowclose', function() { pageTracker._trackEvent('Google Map', 'Info Window Cloae'); });
		
/*		gmap2.click(point, function() { 
			//open window on mouse click
			gmap2.windowOpen(gmap2.getGmapPoint(loc.lat, loc.lng), 'You just clicked the <b>MARKER</b>.');
		});
		
		//draw a circle
		var circle = gmap2.drawCircle(loc.lat, loc.lng, 40, "#000000", 1, 0.5, '#dd0000', 0.6); 
		
		//open window on mouse click
		gmap2.click(circle, function(){
			gmap2.windowOpen(gmap2.getGmapPoint(loc.lat, loc.lng), 'You just clicked the <b>CIRCLE</b>.');
		});
		
		var point2 = gmap2.createPoint(53.479874, -2.246704, 'M');
		
		gmap2.click(point2, function() { 
			//get distance between points
			var d = point.getLatLng().distanceFrom(point2.getLatLng());
			
			gmap2.windowOpen(point2.getLatLng(), 'Distance to point S is ' + Math.round(d/1000) + ' km');
			
		});*/

	}
};


function getValueFromParams (name, params) {
	var res = params.match(new RegExp('[\\?&]'+ name +'=([^&#]*)'));
	return (res !== null)? res[1] : '';
};