$(document).ready(function(){
	
	if (getUrlVarsFrom(document.location.href, false)['testmode'] == '1') {
		maintenanceMode();
	} else {
		//Clear cache
		//$('link#custom-css').attr('href', $('link#custom-css').attr('href') + '?version=' + Math.floor(Math.random() * 1000))
	}
	
	// change logo for ie
	if ( $.browser.msie ) ieHacks();
	
	// Make the html5 placeholder attr work on lesser browsers
	fixPlaceHolderCompatibility();
	
	// highlight the menu items that point to the current page
	highlightCurrentMenuItems();
	
	// Call specific functions to each page
    switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
	case undefined:
		initHome();
		break;
    case '1':
		initHome();
		break;
	case '4':
		initObjectDetails();
		break;
	case '14':
		hideInvisible();
		initConfirmationMessage();
		initContactPage();
		break;
	case '148':
		initNewsletterList();
		break;
    }
	
	appendSecondaryMenu();
	
	
})

function initNewsletterList(){
	$('div.post-template').each(function(index,domEle){
		$('div.post-content', domEle).wrap('<a href="' + $('h2.blog-title a', domEle).attr('href') + '" />');
		
	})
	
	
}

function appendSecondaryMenu() {
	
	$('#small-screen-menu').append($('nav.bottom-menu').clone());
	
	$('#small-screen-menu nav.bottom-menu').hide();

	$('#small-screen-menu a.button-toggle-menu').click(function(){
	
		$('#small-screen-menu nav.bottom-menu').slideToggle();
	
	})
}


//MENU FUNCTIONS

function nrKeys(a) {
	var i = 0;
	for (key in a) {
		i++;
	}
	return i;
}

function compareAssociativeArrays(a, b) {
	if (a == b) {
		return true;
	}
	if (nrKeys(a) != nrKeys(b)) {
		return false;
	}
	for (key in a) {
		if (a[key] != b[key]) {
			return false;
		}
	}
	return true;
}

// Highlight current menu item
function highlightCurrentMenuItems() {
    //check for matches on menu
    $("nav a").each(function (index, domEle) {
        if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($(domEle).attr('href'), 1))) {
            $(domEle).addClass('active');
			
        }
    })


}

function initObjectDetails(){
	
	if (
	
	navigator.userAgent.match(/iPad/i) != null ||
	navigator.userAgent.match(/iPod/i) != null ||
	navigator.userAgent.match(/iPhone/i) != null 
	
	) {
		
		$('object.object-for-screen').removeClass('image-1')
		
	}
}


// Make the confirmation notification of the contact page appear in a light box
function initConfirmationMessage() {
	if ($('.confirmation').html()!='') {
		$.fancybox.init();
		$.fancybox({
			'padding'		: 20,
			'autoScale'		: false,
			'opacity'		: true,
			'overlayShow'	: true,
			'hideOnOverlayClick' : 'true',
			'overlayColor' : '#ffffff',
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'content' : $('span.confirmation').html()
			
		});
	}
}

// Hide invisible 'required' messages
function hideInvisible() {
	
	$('.req').each(function(index, domEle){
		
		if ($(domEle).css('visibility') == 'hidden') $(domEle).hide();
		
	})
	
}



// Front Page
var frontPageSlideshowTimer;

function frontPageSlideSwitch(direction) {
	if (frontPageSlideshowTimer) clearTimeout(frontPageSlideshowTimer);
	
    var $active = $('section.slideshow figure.active');

    if ( $active.length == 0 ) $active = $('section.slideshow figure:last');

    if (direction == 'next') {
	// pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('section.slideshow figure:first');
	} else if (direction == 'previous') {
	// pull the images in the reverse order
    var $next =  $active.prev().length ? $active.prev()
        : $('section.slideshow figure:last');
	}

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        //.animate({opacity: 1.0}, 1500, function() {
		.animate({opacity: 1.0}, 2500, function() {
            $active.removeClass('active last-active');
			frontPageSlideshowTimer = setTimeout("frontPageSlideSwitch('next')", 5500);
        });
}



function initHome() {
	
	$("a.open-swf").fancybox({
		'padding'		: 20,
		'autoScale'		: false,
		'scrolling'		: 'no',
		'width'			: 736,
		'height'		: 400,
		'opacity'		: true,
		'overlayShow'	: true,
		'hideOnOverlayClick' : 'true',
		'overlayColor' : '#ffffff', 
		'titlePosition' : 'inside',
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'type' : 'inline'
	});
	
	$('article.highlights > ul > li').each(function(index, domEle) {
		
		if ($('figure img', domEle).length == 0)
		$(domEle).remove();
	})
	
	$('.slideshow figure').each(function(index, domEle) {
		
		$(domEle).prepend('<div class="menu-overlay" />');
	})
	
	frontPageSlideshowTimer = setTimeout("frontPageSlideSwitch('next')", 5500);
	
}


// Contact page
var contactSlideshowTimer;

function contactSlideSwitch(direction) {
	if (contactSlideshowTimer) clearTimeout(contactSlideshowTimer);
	
    var $active = $('.contact .street-view-show .slides a.active');

    if ( $active.length == 0 ) $active = $('.contact .street-view-show .slides a:last');

    if (direction == 'next') {
	// pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('.contact .street-view-show .slides a:first');
	} else if (direction == 'previous') {
	// pull the images in the reverse order
    var $next =  $active.prev().length ? $active.prev()
        : $('.contact .street-view-show .slides a:last');
	}

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        //.animate({opacity: 1.0}, 1500, function() {
		.animate({opacity: 1.0}, 2500, function() {
            $active.removeClass('active last-active');
			contactSlideshowTimer = setTimeout("contactSlideSwitch('next')", 4500);
        });
}




// Contact page

function initContactPage(){
	
	$.fancybox.init();
	$('.street-view-show a').fancybox({
		'padding'		: 20,
		'width'			: '90%',
		'height'		: '90%',
		'opacity'		: true,
		'overlayShow'	: true,
		'hideOnOverlayClick' : 'true',
		'overlayColor' : '#ffffff',
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'type' : 'iframe'
		
	});
	
	// Init street-view slide
	contactSlideshowTimer = setTimeout("contactSlideSwitch('next')", 4500);
	
	
	initSlideButtons();
	
	
	function initSlideButtons() {
		$('img.nav')
		.css('opacity',0.6)
		.hover(
		function(){
			$(this).css('opacity',0.9);
		},
		function(){
			$(this).css('opacity',0.6);
		}
		)
		.click(function(){
		
			if ($(this).hasClass('next')) {
			
				contactSlideSwitch('next')
			
			}
			if ($(this).hasClass('previous')) {
			
				contactSlideSwitch('previous')
			
			}	
		
		})
	}
	
}

function maintenanceMode() {
	
	document.styleSheets[0].disabled = true;
	$('a').each(function(index,domEle){
		
		if ($(domEle).attr('href') != null)
		
		if ($(domEle).attr('href').indexOf('?')==-1) {
			$(domEle).attr('href', $(domEle).attr('href') + '?testmode=1');
		} else {
			$(domEle).attr('href', $(domEle).attr('href') + '&testmode=1')
		}
	})

}

// hacks for old browsers
function ieHacks() {
	
	// add reduced logo
	if ( $.browser.msie && parseInt($.browser.version, 10) < 8 ) {
		$('a.logo img').attr('src', 'media/trevor-philip-media/image/misc/Trevor-Philip-and-Sons-Ltd-logo-ie.png');
	}

	
}

// Make the html5 placeholder attribute work in lesser browsers
function fixPlaceHolderCompatibility() {
	if(!Modernizr.input.placeholder){

		$('[placeholder]').focus(function() {
		  var input = $(this);
		  if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		  }
		}).blur(function() {
		  var input = $(this);
		  if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		  }
		}).blur();
		$('[placeholder]').parents('form').submit(function() {
		  $(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
			  input.val('');
			}
		  })
		});
	
	}	
}



// Get variables from the url
function getUrlVarsFrom(url, preventUnwantedVars) {
    var vars = [],
        hash;
    var hashes = url.split('#')[0].slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (preventUnwantedVars == 1) {
            if (hash[0] != 'lg' && hash[0] != 'objectid' && hash[0] != 'tabindex' && hash[0] != 'page' && hash[0] != 'keyword' && hash[0] != 'mediaid') {
                if (hash[0] == 'categoryid' && hash[1] == 0) {} else {
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
            }
        } else {
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}

