// Fallback from the CDN if necessary
window.jQuery || document.write('<script src="/_files/js/jquery.js">\x3C/script>')

// Add the tipsy and cycle plugin after the main script has loaded
document.write('<script src="/_files/tipsy/js/jquery.tipsy.js">\x3C/script>')
document.write('<script src="/_files/js/cycle.js">\x3C/script>')

// Add reinvigorate
document.write('<script src="http://include.reinvigorate.net/re_.js">\x3C/script>')


// Google Analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-23167981-1']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// Phone
var adiInit ="663";
(function() {
	var adiSrc = document.createElement("script"); adiSrc.type = "text/javascript";
	adiSrc.async = true;
	adiSrc.src = ("https:" == document.location.protocol ? "https://" : "http://") + "static.adinsight.eu/static/scripts/adiTrack.min.js";
	var s = document.getElementsByTagName("script")[0];
	s.parentNode.insertBefore(adiSrc, s);
})();
// ReInv
try { reinvigorate.track("6i3u9-4sb6z4lrq5"); } catch(err) {}


if (document.referrer.search('http://www.sehbac.com') >= 0)
{
	// Add the "You came from SEHBAC.com" banner
	var d = document.createElement('div');
	d.setAttribute('id', 'notice');
	d.style.position = 'absolute';
	d.style.width = '100%';
	d.style.top = '0';
	d.style.background = '#fffaaf';
	d.style.borderBottom = '1px solid #ffc05c';
	document.body.appendChild(d);
	d.innerHTML = '<p style="padding:5px 10px; text-align: center;">You\'ve left our home improvement site for our dedicated solar site. <a href="http://www.sehbac.com/">To return to the home improvement site click here</a>. <a href="#" onclick="d.style.display=\'none\'; document.body.style.paddingTop = \'0\'; return false;" style="position: absolute; right: 10px; color: #666; border: 1px solid #ccc; padding: 1px 4px 3px 4px; line-height: 1; top: 5px; background: #fefbca; text-decoration: none">x</a></p>';
	document.body.style.paddingTop = '25px';
}

// Add the google maps API if necessary
if (document.getElementById('gmap-holder')) { document.write('<script src="http://maps.googleapis.com/maps/api/js?sensor=false&region=GB">\x3C/script>'); }

// Add the flowplayer script if necessary
if (document.getElementById('player')) { document.write('<script src="/_files/js/flowplayer-3.2.6.min.js">\x3C/script>'); }

// Only used in a slideshow but typing in the postcode always sets it. It's easier that way.
var manual = false;

// Tipsy, menu and slideshow logic
$(function(){

	if (document.getElementById('player')) {
		flowplayer("player", {
			src: "http://builds.flowplayer.netdna-cdn.com/89231/49650/flowplayer-3.2.7-0.swf",
			wmode: 'opaque'
		}, 
		{
			clip: { url: 'http://www.sehbacsolar.co.uk/assets/videos/solar-pv.mp4' }
		});
	}

	// Map logic
	if (document.getElementById('gmap-holder'))
	{
		var geocoder = new google.maps.Geocoder();
		var map = {
			options : {
				zoom : 7,
				center : new google.maps.LatLng(51.85613885029435, -0.4888916015625),
				mapTypeId : google.maps.MapTypeId.SATELLITE
			},
			marker : new google.maps.Marker(),
			postcode : null,
			object : null
		};
		map.object = new google.maps.Map(document.getElementById("gmap-holder"), map.options);
		google.maps.event.addListener(map.object, 'click', function(evt) {
			map.marker.setMap(null);
			map.marker = new google.maps.Marker({
				position: evt.latLng, 
				map: map.object,
				animation: google.maps.Animation.DROP,
				icon: '/_files/images/my-house.png'
			});
			map.object.setCenter(evt.latLng);
			document.getElementById('latlong').value = evt.latLng;
			if (document.getElementById('hint'))
			{	
				document.getElementById('hint').innerHTML = 'If this isn\'t your home, simply click to reposition the pointer';
			}
			else
			{
				$("#yes, #no").css("display", "block");
				document.getElementById('caption').innerHTML = 'If this isn\'t your home, simply click to reposition the pointer';
			}

		});

		$('#postcode-input').submit(function(a){
			var postcode = document.getElementById("gmap-postcode").value;
			if (postcode.length < 6)
			{
				$("#gmap-heading").fadeOut(100, function() {
					document.getElementById('gmap-heading').innerHTML = 'Please type your whole postcode!';
					$("#gmap-heading").fadeIn(100);
				});
				return false;
			}
			manual = true;
			map.postcode = postcode;
			geocoder.geocode({ 'address': map.postcode, "region" : "uk" }, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.object.setCenter(results[0].geometry.location);
					map.object.setZoom(18);
					$("#gmap-overlay").fadeOut(500);
					if (document.getElementById('hint'))
					{
						$("#hint").fadeIn(500);
					}
					else
					{
						document.getElementById('caption').innerHTML = '<span>Click and drag to find your home, then click on it to select it. &nbsp; <a href="#" id="retype">Click here to re-type your postcode</a></span>';
					}

					try { document.getElementById("skip").innerHTML = 'Alternatively, if you can\'t find your home, fill in the form on the right to get your quote.'; } catch(e) {}
					document.getElementById('address').value = results[0]['formatted_address'];
				} else {
					alert("We could not find your postcode. Could you try your street name and town please?");
				}
			});
			return false;
		});
		$("#gmap-postcode").blur(function(){
			manual = true;
			map.postcode = this.value;
			document.getElementById('address').value = this.value;
		});
		$("#retype").live('click', function(){
			$("#hint").hide();
			$("#gmap-overlay").fadeIn(500);
			if (document.getElementById("skip"))
			{
				document.getElementById("skip").innerHTML = 'Alternatively, if you can\'t find your home, type in your postcode and fill in the form on the right to get your quote.';
			}
			return false;
		});

		$("#no").click(function(){
			map.marker.setMap(null);
			$("#yes, #no").hide();
			return false;
		});

		$("#yes").click(function(){
			$("#yes, #no").hide();
			$("#gmap").append("<div id='gmap-loading'><img src='/_files/images/loading.gif' alt='' />Loading...</div>");
			window.setTimeout(function(){
				document.getElementById('gmap-loading').style.display = 'none';
				document.getElementById('gmap-holder').style.display = 'none';
				document.getElementById('gmap-form').style.display = 'block';
				document.getElementById('caption').innerHTML = '';
			}, Math.floor(Math.random() * (1000 - 500 + 1) + 500));

			return false;
		});
	}

	// Check for IE6
	var nav = navigator.userAgent.match(/; MSIE (\d+.\d+)/);
	if(((nav) ? nav[1] : '') === '6.0') {
		// Add the event listeners
		$('nav li').hover(function(e) {
			if(!$(e.target).hasClass('selected')) {
				$(e.target).style('background', 'transparent url(/_files/images/navigation-main.jpg) no-repeat center 0');
			}
		},function(e) {
			if(!$(e.target).hasClass('selected')) {
				$(e.target).style('background', 'none');
			}
		});
	}

	$('input[type="text"], input[type="phone"]').tipsy({
		fade: true,
		gravity: 'w',
		trigger: 'focus'
	});

	if (document.getElementById('slideshow') && $("#items").children().length > 1)
	{
		var timer = window.setInterval(slideshow, 4000);

		// Have we manually clicked a selector?

		// Ensure hovering stops the fading
		$("#slideshow").hover(function(){
			window.clearInterval(timer);
		},
		function(){
			if (manual == false)
				timer = window.setInterval(slideshow, 4000);
		});

		// Make our controls work
		$("#controls a").click(function(){
			// First, clear the interval
			timer = window.clearInterval(timer);
			manual = true;

			$("#items").children().each(function(c,e){
				$(e).removeClass("fading");
			});

			var current = $("#items .selected");

			if (current.index() == $(this).index())
			{
				// This is already selected
				return false;
			}

			$("#items .selected").stop(true, true).removeClass('selected').addClass('fading');

			$("#items").children(":nth-child(" + ($(this).index() + 1) + ")").stop(true, true).hide().addClass('selected').fadeIn(1000);
			
			$("#controls a").css('color', '#999');
			$(this).css('color', '#444');

			return false;
		});

	}

	$("form").submit(function(){
		var success = true;
		$(this).children("input").each(function(c,e){
			// Skip submit values
			if (e.getAttribute('type') == 'submit')
				return;

			if (e.value.length < 1)
			{
				$(e).css('border', '1px solid red');
				success = false;
			}
		});

		if ( ! success)
		{
			alert("Please fill out all of the fields");
            return false;
		}

	});

	$("input").keypress(function(){
		$(this).css('border', '1px solid #AEAEAE');
	});
    
    $("#slideshow-overlay").click(function(){
        $(this).fadeOut(500);
    });
});

function slideshow()
{
	if (manual == true)
	{
		// We've filled in a map, just unset this
		window.clearInterval(timer);
		return;
	}

	var current = $("#items .selected");
	var next = current.next();

	if (next.length == 0)
	{
		// Loop through back to the beginning
		next = $("#items").children(":first");
	}

	// Add fading which ensures this stays just below 'selected'
	current.removeClass('selected').addClass('fading');

	next.hide().addClass('selected').fadeIn(1000, function(){
		// Remove 'fading' class from the previous one once fading is complete
		$("#items .fading").removeClass('fading');
	});

	// Sort out player control colours
	$("#controls a").css('color', '#999');
	$("#controls a:nth-child(" + (next.index() + 1) + ")").css('color', '#444');
	$("#caption").html("&uarr; &nbsp;" + next.attr("data-caption"));
}


