var gallery;

function stopscrolly( str ){
	if (str == 'true'){
		gallery.stopPauseOnHover();
		gallery.stopAutoProgress();
	}else{
		gallery.startPauseOnHover();
		gallery.startAutoProgress();
	}	
}



//// Provides the proper address for the movie depending on browser
//function getFlashMovie(movieName) {
//	var isIE = navigator.appName.indexOf("Microsoft") != -1;
//	return (isIE) ? window[movieName] : document[movieName];
//}
//
//function sendTextToFlash()
//{
//	getFlashMovie("white-player").getTextFromJavaScript();
//	//console.log(getFlashMovie("videoplayer6"));
//}


$(function(){
    var workspaceBind = function(){
	$('#cms-workspace').bind('editing-enabled', function(){
	    if (typeof afeature !== 'undefined'){
		afeature.disable();
	    }

	    $('.workintro div.morecopy').show();

	    $("div.projectthumbnail").unbind('mouseenter').unbind('mouseleave');

	    $('#projects div.cms-component').show();
	    $('#pagination').html('');

	}).bind('editing-disabled', function(){
	    if (typeof afeature !== 'undefined'){
		afeature.enable();
	    }
	    $('.workintro div.morecopy').hide();

	    //get href value for blocks
	    $("div.projectthumbnail").hover(function () {
		$(this).find('.projectinfo').stop(true, true).fadeIn('fast');
		$(this).find('.projectinfo').css( 'cursor', 'pointer' );
	    },
	    function () {
		$(this).find('.projectinfo').stop(true, true).fadeOut('fast');
	    }
	    ).click(function (){
		location = $(this).find('a').attr('href');
	    });

	    initPagination();
	}).bind('block-updated', function(e, selector){
	    sifrUpdate();
	    initializeMap();
	});

    }

    function initializeMap() {

	$('.googlemap').each(function(){

	    var location1=$('.latitude', this).val(),
		location2=$('.longtitude', this).val(),
		latlng = new google.maps.LatLng(location1, location2),
		myOptions = {
		    zoom: 15,
		    center: latlng,
		    mapTypeId: google.maps.MapTypeId.ROADMAP,
		    floatShadow:null,
		    mapTypeControl: false
		},
		map = new google.maps.Map($('.map', this)[0], myOptions),
		marker = new google.maps.Marker({
			position: latlng,
			map: map,
			flat: true
		}),
		infowindow = new google.maps.InfoWindow({
			position: latlng,
			content: "<h3>"+$('.infowindowcontent', this).val()+"</h3>",
			flat: true
		});

	    infowindow.open(map,marker);
	});
    }

    
    initializeMap();

    var afeature;

    $('div.afeature').scrolly
    ({
	selectors:
	{
	    container: '.cms-anchor',
	    items: '.cms-component'
	},
	before: function()
	{

	    var li = '';
	    for(var i = 1; i <= this.total(); i++){
		li += '<li><a href="#" class="scrolly-opt">'+i+'</a></li>';
	    }
	    $('div.afeature ul').html(li);
	    this.container().append('<div class="mask"/>');

	    this.items().find('.item').show();
	},
	total: function()
	{
	    return $(this.selectors.container, this.el).find(this.selectors.items).length;
	},
	after: function()
	{
	    var self = this;
				
	    // bind the buttons
	    $('.navigation ul li a', this.el).click(function(e){
		self.move($(this).parent().prevAll().length + 1);
		return false;
	    });	   

	    this.container().mouseenter(function()
	    {
		if (self.is_enabled())
		{

		    self.mask().stop(true, true).fadeIn(500);
		}
	    })
	    .mouseleave(function()
	    {
		if (self.is_enabled())
		{
		    self.mask().stop(true, true).fadeOut(300);
		}
	    });
					
	    this.mask().click(function(){


		self.stopPauseOnHover();
		var active = self.active();
		location = $(active).find('a').attr('href');

	    });

	    afeature = this;
								
	},
	videoContent: function(){
	    return $('#video-content');
	},
	container: function()
	{
	    return $(this.selectors.container, this.el);
	},
	
	mask :function()
	{
	    return $('.mask', this.container());
	},

	autoscroll: 5000,

	moved: function ()
	{
	    this.highlight(this.current() -1);

	    this.mask().removeClass('maskimage1 maskimage2');

	    var maskClass = this.active().children('.homelink').hasClass('alternatelink') ? 'maskimage2' : 'maskimage1';

	    this.mask().addClass(maskClass);
	},

	highlight: function(index)
	{
	    // Update the buttons
	    $('.navigation ul li a').removeClass('selected').eq(index).addClass('selected');
	},

	is_enabled: function(){
	    return this.el.hasClass('scrolly-enabled');
	}

    });
		
    workspaceBind();
		
    //subpage image gallery
    $('div.imagewrapper').scrolly({
	selectors: {
	    container: '.image',
		items: '.largeimage'
	},
	after: function(){
	    var self = this;
	    // bind the buttons
	    $('.thumbnails a', this.el).click(function(){
		self.move($(this).attr('title'));
		return false;
	    });
	},
	autoscroll: 5000,
	moved: function (){
		var active = this.current()-1,
		speed  = 400;
		// Update the text
		$('.title h3').stop(true,true).hide().eq(active).fadeIn(speed).removeClass('selected').eq(active).addClass('selected');
		$('.copy p').stop(true,true).hide().eq(active).fadeIn(speed).removeClass('selected').eq(active).addClass('selected');
		// Update the buttons
		$('.thumbnails a').removeClass('selected').eq(active).addClass('selected');
	}

    });

	//to display the view case study alpha image for four thumbnail gallery
	$('div.imagewrapper .image').hover(
		function() {
			$('div.imagewrapper').find('.addoverlay').fadeIn();
		},
		function() {
			$('div.imagewrapper').find('.addoverlay').fadeOut(300);
		}
	);
		
	//to allow above overlay to be clicked
	$('div.imagewrapper .image .addoverlay').click(function(){
		location = $('div.imagewrapper .image').find('a.active').attr('href');
	});

		
    // project page style image scroller
    $('div.gallery').scrolly({
	selectors: {
	    container: '.image'
	},
	before: function()
	{
		gallery = this;

		if (this.total() < 2){
			$('#play-pause').css("visibility","hidden");
			$('.navigation').html('');
		}

	},
	after: function(){
	    var self = this;
	    // bind the buttons
		
	    $('.navigation ul li a', this.el).click(function(){
			try{jsStopVideo('stop');}
				catch(err){
				//return false;
			}
			self.move($(this).attr('title'));
			self.startPauseOnHover();
			
			
			return false;
	    });
	},
	autoscroll: 5000,
	moved: function (){
	    var active = this.current()-1,
	    speed  = 400;
	    // Update the buttons
	    $('.navigation ul li a').removeClass('selected').eq(active).addClass('selected');
		
	},
	beforeAutoProgress: function()
	{
		$('#play-pause').css("background-position","0 0");
	},
	beforeStopAutoProgress:function()
	{
		$('#play-pause').css("background-position","0 -25px");
	}
 });		
		
    //allows ie6 the dropdown nav
    $('#mainnav li').hover(
	function () {
	    $(this).addClass('rollover');
	},
	function () {
	    $(this).removeClass('rollover');
	}
	);
    	
    //fancy box for showreel video

    $('.call-showreel').fancybox({
	padding:0,
	frameWidth:765,
	frameHeight:430,
	hideOnOverlayClick:false,
	hideOnContentClick:false
    });

    $('.watch-showreel').fancybox({
	padding:0,
	frameWidth:765,
	frameHeight:430,
	hideOnOverlayClick:false,
	hideOnContentClick:false,
	callbackOnClose:function(){afeature.startPauseOnHover();afeature.startAutoProgress();}
    });

	$('.call-image').fancybox({
	padding:0,
	frameWidth:765,
	frameHeight:430,
	hideOnOverlayClick:false,
	hideOnContentClick:false
    });

	$('.call-video').fancybox({
	padding:0,
	frameWidth:765,
	frameHeight:430,
	hideOnOverlayClick:false,
	hideOnContentClick:false
    });

    // readmore slider
    $('.workintro div.intro p:last').append(' <a href="#" class="readmore">Read More »</a>');
    $('.workintro div.morecopy').toggle();
    
    $(".readmore").click(function () {
	$(this).html(($(this).text()==='Read More »') ? '« Hide' : 'Read More »');
	$(".morecopy").slideToggle('slow');
	return false;
    });


    function pageselectCallback(page_index, jq){
	var start = page_index * 6,
	    end   = start + 6,
	    items = $('#projects div.cms-component .projectthumbnail');

	items.hide();

	for(var i = start; i < end; i++ ) {
	    items.eq(i).show();
	}

	return false;
    };


    function initPagination() {
                var num_entries = $('#projects div.cms-component .projectthumbnail').length;
                // Create pagination element
                $("#pagination").pagination(num_entries, {
                    num_edge_entries: 2,
                    num_display_entries: 6,
                    callback: pageselectCallback,
                    items_per_page:6,
		    next_text:'Next projects »',
		    prev_text:'« Previous projects',
		    prev_show_always: true,
		    next_show_always: true
                });
             }

	initPagination();


    //get href value for blocks
    $("div.projectthumbnail").hover(function () {
	$(this).find('.projectinfo').stop(true, true).fadeIn('fast');
	$(this).find('.projectinfo').css( 'cursor', 'pointer' );
    },
    function () {
	$(this).find('.projectinfo').stop(true, true).fadeOut('fast');
    }
    ).click(function (){
	location = $(this).find('a').attr('href');
    });
		
		
    // news home page featured article control
    $("div.featurednews").hover(function () {
	$(this).find('.featurednews-rollover').stop(true, true).fadeIn('fast');
	$(this).css( 'cursor', 'pointer' ).click(function(){
	    location = $(this).find('a').attr('href');
	});
    },
    function () {
	$(this).find('.featurednews-rollover').stop(true, true).fadeOut('fast');
    }
    );
		
    // hover state for news articles on news home page
    $("div.newsarticle").hover(function () {
	heightRequired = $(this).find('img').outerHeight();
	$(this).find('.newshighlight').css('height',heightRequired).stop(true, true).fadeIn('fast');
	$(this).css( 'cursor','pointer');
    //$(this).find('p').css('color','#fff' );
    },
    function () {
	$(this).find('.newshighlight').stop(true, true).fadeOut('fast');
    }
    ).click(function (){
	location = $(this).find('a').attr('href');
    });
		
    // fancybox embed box
    $('.openembed').live('click', function(){
	$(this).next('.embedblock-fancy').addClass('embedblock-fancy-show');
	//$('.embedcode-fancy').attr('value', $('#video-content').html());
	return false;
    });
		
    $('.closeinput').live('click', function(){
	$('.openembed').next('.embedblock-fancy').removeClass('embedblock-fancy-show');
	return false;
    });


    // fancybox email box
    $('.openemail').live('click', function(){
	$(this).next('.emailblock-fancy').addClass('emailblock-fancy-show');
	return false;
    });

    $('.closefancyemail').live('click', function(){
	$('.openemail').next('.emailblock-fancy').removeClass('emailblock-fancy-show');
	return false;
    });


    // show video pop-up on page load
    var id	= window.location.href.match(/\?block=(\d+)/);

    if(id !== null) {
		if(id[1] == 82) {
			$('.call-showreel').click();
		} else {
			var watch_link = $('.watch-showreel', '#cms-component-'+id[1]);

			if(watch_link.length !== 0) {
			watch_link.attr('href', 'showreel/index/'+id[1]+'?link='+encodeURIComponent(document.location.href)).click();
			afeature.stopAutoProgress();
			afeature.stopPauseOnHover();
			}

		}
    }

	//case studies more, home and next and allow news articles
	$('.caseprev').hover(
		function(){
				$('.prev-tip').fadeIn();
		},function(){
				$('.prev-tip').fadeOut('fast');
		});

	$('.casenext').hover(
		function(){
				$('.next-tip').fadeIn();
		},function(){
				$('.next-tip').fadeOut('fast');
		});

	$('.casehome').hover(
		function(){
				$('.home-tip').fadeIn();
		},function(){
				$('.home-tip').fadeOut('fast');
		});

	//to open the send to a friend pop up
	$('.share-email').click(function(){
		$('#emailbox')
			.html('<iframe frameborder="0" id="emailframe" />')
			.find('iframe')
			.attr('src', $('#email-window').attr('title'));

		$('#email-window').fadeIn();
	});

	//to close the send to a friend pop up and remove the iframe
	$('.close-email').click(function(){		
		$('#email-window').hide().find('iframe').remove();
	});

    
});

			
