
$(function() {

		if($('#bannerwrapper').length > 0)
		{
			$('#bannercontrols').removeClass('nojs');
			bindSlideShow(false);
			
			$(window).resize(
				function()
				{
					bindSlideShow(true);
				}
			);
		}
		
		if($('.imagegallery').length>0)		
		{
			setupGallery();
		}
		
		if($('#get-in-touch').length > 0)
		{
			scrollContact();
		}
		
		if($('#callbackScroller').length > 0)
		{
			scrollCallbackScroller();
		}

		if($('#scrollquote').length > 0)
		{
			scrollQuote();
		}
		
		if($('.casestudydetailcaption').length > 0)
		{
			showCaseStudyDetailCaption();
		}
		
		if ($('#googlemap').length > 0) {
			$('#googlemap').text(' ');
				var map = new GMap2(document.getElementById("googlemap"));
		        map.setCenter(new GLatLng(53.341251,-6.262164), 16);
		        map.setUIToDefault();
		        
		        // Create our "tiny" marker icon
		        var customIcon = new GIcon(G_DEFAULT_ICON);
		        customIcon.image = "http://www.iqcontent.com/themes/iqcontent/images/map.png";

                customIcon.shadow = "http://www.iqcontent.com/themes/iqcontent/images/none.png";
				customIcon.iconSize = new GSize(220, 108);
				customIcon.shadowSize = new GSize(0,0);
				customIcon.iconAnchor = new GPoint(52, 86);
    
				// Set up our GMarkerOptions object
				markerOptions = { icon:customIcon };
		
		        // Add 10 markers to the map at random locations
		        var bounds = map.getBounds();
		        var southWest = bounds.getSouthWest();
		        var northEast = bounds.getNorthEast();
		        var lngSpan = northEast.lng() - southWest.lng();
		        var latSpan = northEast.lat() - southWest.lat();
		        var latlng = new GLatLng(53.341251,-6.262164);
		         map.addOverlay(new GMarker(latlng, markerOptions));
  
		}
		
		if ($('#carousel').length > 0) {
			// Set up carousel
			setupCarousel();
		 }
		 
		 // Case studies carousel
		 if ($('#casestudy-carousel').length > 0) {
		 	setupCaseStudyCarousel();
		 }
		
		// Listen for half-sections and match heights
		$('.halfsection.left').each(function() {
			
			if ($(this).next('.halfsection').height() > $(this).height()) {
				$(this).height($(this).next('.halfsection').height());
			}
		});
		
		// services page
		$('.first-inner-column .services_section').each(function(index) 
		{
			var n_child_index = index + 1;
			var n_child = $('.last-inner-column .services_section:nth-child(' + n_child_index + ')');
			var max_height = n_child.height();
			
			if(max_height < $(this).height()) 
			{
				max_height = $(this).height();
			}
			
			$(this).height(max_height);
			n_child.height(max_height);
		});
		
		
		// faux columns (TODO create a plugin)
		// Commented out - was causing issues with carousel and page height
		/*
		var max_height = 0;
		
		$('.content-frame > .column-1col-wrapper, .content-frame > .column-2col-wrapper').each(function(i) 
		{
			if($(this).height() > max_height) 
			{
				max_height = $(this).height();
			}
		});
		
		$('.content-frame > .column-1col-wrapper, .content-frame > .column-2col-wrapper').each(function(i) 
		{
			$(this).height(max_height);
		});	
		*/
		$(".lightbox").fancybox({
			'modal' : true
		});
		
		if ($('#Form_CallbackForm').length > 0) {
			observeCallbackForm();
		}
		
		
});

function bindSlideShow(unbind)
{
	if(unbind)
	{
		$('#bannerwrapper').cycle('destroy');
		$('.banner, #bannerwrapper').attr('style', '');
	}

	$('#bannerwrapper').cycle({
		fx: 	'scrollHorz',
		next:   '#bannernext',
		prev:   '#bannerprev',
		timeout:  0
	});
}

// Gallery on the case studies page

function setupGallery()
{
	var mainimage = $('.imagegallery .thumbs a:first').attr('href');
	var maintext  = $('.imagegallery .thumbs a:first').find('img').attr('alt');
	
	$('.imagegallery').prepend('<div class="mainimage"><img src="'+mainimage+'" alt="'+maintext+'" /></div>'); 
	
	$('.imagegallery .thumbs a').click(
		function() 
		{
			var newimage = $(this).attr('href');
			var newtext  = $(this).find('img').attr('alt'); 
			slideInImage(newimage, newtext, this);
			return false; 
		}
	);
}

function slideInImage(image, text, thumb)
{
	if($('.mainimage img:animated').length==0)
	{
		var width = $('.mainimage').width();
		var currentimage = $('.mainimage img');
	
		$('.mainimage').append('<img src="'+image+'" alt="'+text+'" style="right: -'+width+'px;" />');
		$('.mainimage img').animate({"left": "-="+width}, "slow", function() {$(currentimage).remove();});
		
		$('.imagegallery .thumbs a').removeClass('selected');
		$(thumb).addClass('selected');
	}
}

function scrollContact()
{
	// scroll get in touch after a certain point
	// this is only for test purposes and does not represent the final version
	var el = $("#get-in-touch");
	
	var el_top = el.offset().top;
	var el_height = el.height();
	var el_width = el.width();

	$(window).scroll(function() 
	{
		var pos = el_top - el_height + 87;
		if($(window).scrollTop() >= pos) 
		{
			el.css({ position: "fixed", top: "20px", width: el_width});
		}
		else 
		{
			el.css({ position: "relative" });
		}
	});
}

function scrollCallbackScroller() {
	// scroll call back after a certain point
	// this is only for test purposes and does not represent the final version
	var el = $("#callbackScroller");
	
	var el_top = el.offset().top;
	var el_height = el.height();
	var el_width = el.width();

	$(window).scroll(function() 
	{
		var pos = el_top - el_height + 340;
		if($(window).scrollTop() >= pos) 
		{
			el.css({ position: "fixed", top: "0", width: el_width});
		}
		else 
		{
			el.css({ position: "relative" });
		}
	});
}

function scrollQuote()
{
	// scroll get in touch after a certain point
	// this is only for test purposes and does not represent the final version
	var el = $("#scrollquote");
	
	var el_top = el.offset().top;
	var el_height = el.height();
	var el_width = el.width();

	$(window).scroll(function() 
	{
		var pos = el_top - el_height + 134;
		if($(window).scrollTop() >= pos) 
		{
			el.css({ position: "fixed", top: "20px", width: el_width});
		}
		else 
		{
			el.css({ position: "relative", top: 0 });
		}
	});
}

function setupCarousel() {

	// Make sure first slide is the correct height
	var firstHeight = $('#image-1').height();
	$('#carousel-content').height(firstHeight);
	$('#carousel').height(firstHeight + 84);
	$('#carousel-content').width(585);

	// Initiate slideshow
    $('#carousel-content').cycle({ 
    	fx:      		'scrollHorz',
		timeout: 		 0,
		prev:    		'#prev',
		next:    		'#next',
		containerResize:	1,
        easing:  'easeInOutBack',
		onPrevNextEvent:	function (isNext, zeroBasedSlideIndex, slideElement) {
			
			// Update the current number
			var currentSlide = zeroBasedSlideIndex + 1;
			var numberOfSlides = $('#carousel-content li').length;
			$('span#carousel-number').text(currentSlide + ' of ' + numberOfSlides);
			
			// Update the title
			var thisImageAlt = $('#image-'+currentSlide).attr('alt');
			$('#carousel .title h3').fadeOut('fast', function() {
			
				if (!thisImageAlt) {
					thisImageAlt = '&nbsp;';
				}
			
				$('#carousel .title h3').html(thisImageAlt);
				$('#carousel .title h3').fadeIn('fast');
			});
			

			// Change ul to correct height
			var newULHeight = $('#image-'+currentSlide).height();
			$('#carousel-content').stop().delay(50).animate({height:newULHeight}, 500);
			
			// Change container to correct height
			var newContainerHeight = $('#image-'+currentSlide).height() + 84;
			$('#carousel').stop().delay(50).animate({height:newContainerHeight}, 500);
		}
	});
    
}

function setupCaseStudyCarousel() {


	// Initiate slideshow
    $('#casestudy-carousel-content').cycle({ 
    	fx:      		'scrollHorz',
		timeout: 		 0,
		prev:    		'#prev-casestudy',
		next:    		'#next-casestudy',
		width:          597,
		height:			300,
        easing:  'easeInOutBack'
	});
    
}


function showCaseStudyDetailCaption() {

	$('.casestudyoverlay').hover(
		function () {
			$(this).parent().find('.casestudydetailcaption').stop(true, true).show("slide", {direction: 'down', easing: 'easeOutExpo'}, 500);
		}, 
		function () {
			$(this).parent().find('.casestudydetailcaption').stop(true, true).hide("slide", {direction: 'down', easing: 'easeOutExpo'}, 500);
		}
	);
}

function observeCallbackForm() {
	// If fields are blank, put their labels in as greyed out text

	$('.text').each(function() {
		if ($(this).val().length == 0) {
			$(this).addClass('grey');
			var textToAdd = $(this).parent().parent().find('label').text();
			$(this).val(textToAdd);
		}
	});
	
	$('.text').focus(function() {
		var compareText = $(this).parent().parent().find('label').text();
		if ($(this).val() == compareText) {
			$(this).val('');
			$(this).removeClass('grey');
		}
	});
	$('.text').blur(function() {
		var replaceText = $(this).parent().parent().find('label').text();
		if ($(this).val() == '') {
			$(this).val(replaceText);
			$(this).addClass('grey');
		}
	});
	
	// Check required fields
	// #Form_CallbackForm
	$('#Form_CallbackForm').submit(function() {
		
		if ($('#Form_CallbackForm_Name').val() == $('#Form_CallbackForm_Name').parent().parent().find('label').text()) {
			$('#Form_CallbackForm_error').text('Please provide a name.');
			$('#Form_CallbackForm_error').show();
			event.preventDefault();
		} else if ($('#Form_CallbackForm_Phone').val() == $('#Form_CallbackForm_Phone').parent().parent().find('label').text()) {
			$('#Form_CallbackForm_error').text('Please provide a phone number.');
			$('#Form_CallbackForm_error').show();
			event.preventDefault();
		} else {
			$('#Form_CallbackForm_error').hide();
		}
	});

}


/**
 * @author Alexander Farkas
 * v. 1.02
 */
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);

