/**
 * site JS
 */
var map;
var localSearch;
var markers = [];
var info;
var local = {};
var closeTimer = null;

$(document).ready(function (){
	$('body').addClass('js');
	initMap();
	initTabs();
	initCountrySwitcher();
	initFormProductList();
	initGlobalMap();
});

function initMap(){
	if($('#globalMap').length > 0){ 
		//centre map.
		var latlng = new google.maps.LatLng(42.9, -7.9);
	    var mapOpts = {
	      zoom: 1,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    
	    map = new google.maps.Map(document.getElementById("globalMap"), mapOpts);
	    
	    //set up single info window
	    info = new google.maps.InfoWindow({content: ''});
	    
	    populateOffices();
	}
}

function populateOffices(){
	for(var o in offices){
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(offices[o].lat, offices[o].lng),
            map: map,
            title: offices[o].name
        });
        
        marker.content = '<h4>' + offices[o].name + '</h4>';
        if(offices[o].description){
        	marker.content += '<p>' + offices[o].description + '</p>';  
        }
        google.maps.event.addListener(marker, 'click', function() {
      		//set content
        	info.setPosition(this.getPosition());
        	info.setContent(this.content);
        	info.open(map,this);
        });
        markers.push(marker);
	}
}

function initTabs(){
	$("div.tabs").tabs(".campaign > div", {

		// enable "cross-fading" effect
		effect: 'fade',
		fadeOutSpeed: "slow",
		event:'mouseover',
		// start from the beginning after the last tab
		rotate: true
		
	// use the slideshow plugin. It accepts its own configuration
	}).slideshow({autoplay:false,interval: 6000});
}

function initCountrySwitcher(){
	if($('#countrySelectContainer').length > 0){
		//country switcher
		$('#countrySelect').change(function (){
			window.location = this.value;
		});
		//hide button
		$('#btnCountrySelect').hide();
		$('#countrySelectContainer').addClass('js');
	}
}

function initFormProductList(){
	$(".productList").tabs(".productGroup", {tabs: 'span', effect: 'slide', initialIndex: 0});

	
	$('.productGroup input:checkbox').click(function (){
		updateViewedProducts(this.id, this.checked);
		updateLists(this);
	});
	
	$('.otherViewedProducts input:checkbox').click(function (){
		updateMainCheckboxes(this);
	});
	
	//initialise any checked products
	if($('.productGroup').length > 0){
		$('.productGroup input:checked').each(function (){
			updateLists(this);
		});
	}
	
	$('.selectedProducts .delete').live('click', function (){
		//remove the associated item and uncheck it too
		var id = this.rel;
		removeElement(id);
		
		//uncheck associated checkbox
		origId = createId(this.rel, true);
		if($('#' + origId).length > 0){
			$('#' + origId).attr('checked', false);
		}
		//update any potential other viewed product
		if($('#v' + origId).length > 0){
			$('#v' + origId).attr('checked', false);
		}
		return false;
	});
}

function updateLists(el){
	var pVal = $(el).parents('.productGroup').prev('span').text();
	var eVal = el.value;
	var eId = el.id;
	
	if(el.checked){
		//add product to selected list
		addToList(pVal, eVal, eId);
	} else {
		//ensure product is removed from selected list
		removeFromList(eId);
	}
}

function updateViewedProducts(eId, checked){
	var id = 'v' + eId;
	$('#' + id).attr('checked', checked);
}

function updateMainCheckboxes(el){
	var id = el.id.replace(/v/, '');
	var main = $('#' + id)[0];
	main.checked = el.checked;
	updateLists(main);
}

function addToList(pVal, eVal, eId){
	var id = createId(eId);
	addElement(id, '<span>' + pVal + '</span> ' + eVal);
	removePlaceholder();
}

function removeFromList(eId){
	var id = createId(eId);
	removeElement(id);
}

function createId(id, reverse){
	var target = 'product';
	var replace = 'selected';
	if(reverse){
		target = 'selected';
		replace = 'product';
	}
	
	var regex = new RegExp(target, 'g');
	return id.replace(regex, replace);
}

function addElement(id, txt, noDelete){
	if($('#' + id).length == 0){
		var del = '<a href="#" class="delete" rel="' + id + '" title="remove product">delete</a>';
		if(noDelete){
			del = '';
		}
		var p = '<li id="' + id + '">' + txt + del + '</li>';
		$('.selectedProducts ul').append(p);
	}
}

function removeElement(id){
	if($('#' + id).length > 0){
		$('#' + id).fadeOut('fast', function (){
			$('#' + id).remove(); 
			if($('.selectedProducts ul li').length == 0){
				addPlaceholder();
			}
		});
	}
}

function addPlaceholder(){
	addElement('noSelectedProducts', 'There are no selected products', true);
}

function removePlaceholder(){
	removeElement('noSelectedProducts');
}

function initGlobalMap(){
	if($('#FChomeMap').length > 0){
		getGlobalOverlay();
		$('#FChomeMap area').each(function (idx){
			$(this).hover(
				//mouse over
				function (e){
					var id = this.href.split(/#/)[1];
					if($('#' + id).length > 0){
						closeOverlay(true);
						$('#OverlayContent').html($('#' + id).clone());
						showOverlay(e, this);
					}
				},
				//mouse out
				function (){
					setCloseTimer();
				}
			);
		});
		
	}
}

function getOverlayDimensions(e, sts){
	var hOffset = 55;
	var wOffset = 18;
	
	if(sts){
		hOffset = 5;
		wOffset = 5;
		$('#GlobalOverlay').addClass('sts');
	} else {
		$('#GlobalOverlay').removeClass('sts');
	}
	
	var h = $('#GlobalOverlay').height();
	var w = $('#GlobalOverlay').width();

	var res = {};
	res.top = (e.pageY - (h+hOffset)) + 'px';
	res.left = (e.pageX - ((w /2) + wOffset)) + 'px';
	return res;
}

function showOverlay(e, el){
	//position the overlay
	//work out where we need to put the overlay
	var dim = getOverlayDimensions(e, $('#OverlayContent > div').hasClass('sts'));
	//setup overlay
	$('#GlobalOverlay').css({top: dim.top, left: dim.left}).fadeIn('2000');
	
	//if the mouse moves over the overlay, cancel any timeout, reinstating it on mouseout
	$('#GlobalOverlay').hover(
		//mouse in
		function (){clearCloseTimer();},
		//mouse out
		function (){setCloseTimer();}
	);
	
	/*
	 * IE6 strikes again - need to make the whole overlay clickable for our favourite browser
	 * due to the png fix rendering any links in the overlay unclickable......
	 */
	if($.browser.msie && $.browser.version == 6){
		var href = false;
		if($('#OverlayContent address .overlayEmail').length > 0){
			href = $('#OverlayContent .overlayEmail')[0].href; //why attrib() isn't working, not sure
			$('#GlobalOverlay').wrap('<a id="ie6Wrapper" href="' + href + '" title="Send an email"></a>');
			$('#ie6Wrapper').css('cursor', 'pointer');
		} 
	}
	
}

function setCloseTimer(){
	closeTimer = setTimeout(closeOverlay, 1000);
}

function clearCloseTimer(){
	if(closeTimer){
		clearTimeout(closeTimer);
		closeTimer = null;
	}
}

function closeOverlay(im){
	if(im){
		//hide immediately
		clearCloseTimer();
		$('#GlobalOverlay').hide();
		$('#OverlayContent').html('');
	} else {
		$('#GlobalOverlay').fadeOut('fast', function (){
			$('#OverlayContent').html(''); 
			//remove IE6 link wrapper, if present
			if($('#ie6Wrapper').length > 0){
				$('#GlobalOverlay').unwrap();
			}
		});
	}
}

function getGlobalOverlay(){
	var overlay = '<div id="GlobalOverlay"><div id="OverlayContent"></div></div>';
	$('body').append(overlay);
}
