var map;

var is_browser = {
	webkit: jQuery.browser.webkit,
	ie6: (jQuery.browser.msie && jQuery.browser.version.substr(0,1)<7),
	ie: (jQuery.browser.msie)
};


var app = {
	initialise: function() {
		app.log('initialised');
		app.classyfy_inputs();
		$('.news_item:last').addClass('last');
	},
	
	log: function(message) {
		if(typeof console != 'undefined') console.log(message);
	},
	
	classyfy_inputs: function() {
		$('input[type=text]').addClass('input_text');
		$('input[type=password]').addClass('input_text');
		$('input[type=button]').addClass('input_button');
		$('input[type=submit]').addClass('input_button submit_button');
		$('input[type=checkbox]').addClass('input_checkbox');		
		if (is_browser.webkit) { $('input[type=button], input[type=submit]').addClass('webkit_input_button'); }
	}

};

var newsletter_subscribe_form = {
	initialise: function() {
		var submit_newsletter_subscription_link = $('#submit_newsletter_subscription_link');
		submit_newsletter_subscription_link.show();
		submit_newsletter_subscription_link.click( function(){
			$(this).closest('form').submit();
			return false;
		});
		$('#submit_newsletter_subscription').hide();
		
		//label hiding
		var your_email_label = "Email Address";
		var your_email_input = $('#your_email');
		your_email_input.val(your_email_label);
		your_email_input.focus(function(){
			if($('#your_email').val() == your_email_label){
				$('#your_email').val('');
			}
		});
		your_email_input.blur(function(){
			if($('#your_email').val() == ""){
				your_email_input.val(your_email_label);
			}
		});
		
	}
};

var maps = {
	initialise: function() {
	
		$('a.map_move').click(function(){
			maps.move_map($("form#map_form_"+$(this).attr('href')));
			return false;
		});
		
		var markers_info= $('.maps_data');
		var myLatlng = new google.maps.LatLng(54,-4);
		var latBoundHighest = 0;
		var latBoundLowest = 0;
		var lngBoundHighest = 0;
		var lngBoundLowest = 0;

	    var myOptions = {
	      zoom: 4,
	      center: myLatlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP,
		  panControl: false,
		  mapTypeControl: false,
		  scaleControl: false,
		  streetViewControl: false,
		  zoomControl: true
		};
		
		map = new google.maps.Map(document.getElementById("map"), myOptions);
		
		$('#zoom_map').click(function(){
			map.setZoom(map.zoom+1);
		});
		
		$('#unzoom_map').click(function(){
			map.setZoom(map.zoom-1);
		});
		
		for (i=0;i<markers_info.length;i++)
		{
			var Lat = $(markers_info[i]).children('input[name="lat"]')[0].value;
			var Lng = $(markers_info[i]).children('input[name="Lng"]')[0].value;
			var myLatlng = new google.maps.LatLng(Lat,Lng);
		
			var marker = new google.maps.Marker({
	        	position: myLatlng, 
	        	map: map,
	        	title:""
	    	});
	
			markersArray[i] = marker;

			if($('#show_case_study_page').length == 0){
				if(Lat>latBoundHighest)
				{
					latBoundHighest = Lat;
				}

				if(Lat<latBoundLowest||latBoundLowest==0)
				{
					latBoundLowest = Lat;
				}

				if(Lng>lngBoundHighest||lngBoundHighest==0)
				{
					lngBoundHighest= Lng;
				}

				if(Lng<lngBoundLowest)
				{
					lngBoundLowest = Lng;
				}
			}else{
				map.setCenter(myLatlng);
			}
			
			
			maps.add_info_box(marker,markers_info[i],map);
			
		}

		if($('#show_case_study_page').length == 0){
			var darwin = new google.maps.LatLng(54, -4);
			map.setCenter(darwin);
			map.setZoom(4);
		}else{
			map.setZoom(6);
		}
		
	},
	close_all_info_windows: function(markersArray) {
		$.each( markersArray, function ( i, interpreter ){
			if(markersArray[i].infowindow){
				markersArray[i].infowindow.close();
			}
		});
	},
	move_map: function(form){
		var Lat = form.children('input[name="lat"]')[0].value;
		var Lng = form.children('input[name="Lng"]')[0].value;
		
		var myLatlng = new google.maps.LatLng(Lat, Lng);

		map.setCenter(myLatlng);
		map.setZoom(10);
		
		maps.clearOverlays();
		
		var new_myLatlng = new google.maps.LatLng(Lat,Lng);
	
		var marker = new google.maps.Marker({
        	position: new_myLatlng, 
        	map: map,
        	title:""
    	});

		maps.add_info_box(marker,form,map);

		markersArray[0] = marker;
	},
	
	clearOverlays: function() {
	  if (markersArray) {
	    for (i in markersArray) {
	      markersArray[i].setMap(null);
	    }
	  }
	},
	
	add_info_box: function(marker,marker_info,map) {
		if($.browser.msie){
			var margin_right = "0px";
		}else{
			var margin_right = "-10px";
		}
		
		
		var myOptions = {
			 content: '<div class="maps_info"><span class="title">' + $(marker_info).children('input[name="name"]')[0].value + '</span><a href=\"/'+$(marker_info).children('input[name="slug"]')[0].value+'\">View case study &raquo;</a></div>'
			,disableAutoPan: false
			,maxWidth: 0
			,pixelOffset: new google.maps.Size(-50, 0)			
			,zIndex: null
			,boxStyle: { 
			  opacity: 1
			  ,width: "100px"
			 }
			,closeBoxMargin: "0px "+margin_right+" 0px 0px"
			,infoBoxClearance: new google.maps.Size(20, 20)
			,isHidden: false
			,pane: "floatPane"
			,enableEventPropagation: false
		};
		
		google.maps.event.addListener( marker , 'click', function() {
			maps.close_all_info_windows(markersArray);
			marker.infowindow.open(map,marker);	

		});
		
		marker.infowindow = new InfoBox(myOptions);
	}
	
};

var hero_slideshow = {
	
	initialise_width: function() {
		
		var largest = 0;
		
		if($('.multipul_titles').length > 0){
			
			$('.multipul_titles').each(function(index){
				app.log($(this).width());
				if($(this).width() > largest){
					largest = $(this).width();
				}
			});
			
			$('.multipul_titles').each(function(index){
				app.log($(this).width());
				if($(this).width() > largest){
					largest = $(this).width();
				}
				
				if(index != 0){
					$(this).hide();
				}
				
			});
			
			
			$('#slideshow_holder').width(largest + 153);
			
		}
		
	},
	
	initialise: function(){
		$('.letterbox_crop:eq(0)').addClass('on');
		$('#slides div').hide();
		
		$('.details .maximaise_button').hide();
		$('.details .maximaise_button:eq(0)').show();
		
		$('#slideshow_numbers a').each(function(index) {
			$(this).mouseover(function(){
				hero_slideshow.show_slide(index);
			});
		});
		
		$('#slideshow_numbers a').each(function(index) {
			$(this).mouseout(function(){
			//	hero_slideshow.hide_slide(index);
			});
		});
		
		$('#slideshow_numbers a').each(function(index) {
			$(this).click(function(){
				$('.maximaise_button:eq(' + index + ')').click();
				return false;
			});
		});
		
		$('#slides a').each(function(index) {
			$(this).click(function(){
				$('.maximaise_button:eq(' + index + ')').click();
				return false;
			});
		});
		
		$('#slides .letterbox').each(function(index) {
			$(this).click(function(){
				hero_slideshow.switch_letterbox(index);
				return false;
			});
		});
		
		//run switch letterbox...
		
	},
	
	start_interval_timer: function() {
		if($('.letterbox_crop').length > 0){
			setInterval("hero_slideshow.auto_next_slide()", 4500)
		}
	},
	
	auto_next_slide: function() {
		
		var next_index = 0;
		
		$('.letterbox_crop').each(function(index){
			if($(this).hasClass('on')){
				next_index = (index + 1);
			}
		});

		
		if(next_index == $('.letterbox_crop').length){
			next_index = 0;
		}
		
		hero_slideshow.switch_letterbox(next_index);
		
	},
	
	show_slide: function(index) {
		$('#slideshow_numbers li').removeClass('on');
		$('#slideshow_numbers li:eq('+index+')').addClass('on');
		
		$('#slides div').each(function(inner_index){
			if(inner_index == index){
				$(this).fadeIn();
			}else{
				$(this).hide();
				$(this).fadeOut();
				$(this).stop(true, true);
			}
		});
	},
	
	hide_slide: function(index) {
		$('#slideshow_numbers li').removeClass('on');
		$('#slides div').hide();
	},
	
	switch_letterbox: function(index){
		$('.letterbox_crop').each(function(inner_index){
			if(inner_index == index){
				$(this).addClass('on');
				$(this).fadeIn();
			}else{
				$(this).removeClass('on');
				$(this).fadeOut();
			}
		});
		$('.details .maximaise_button').hide();
		$('.details .maximaise_button:eq('+index+')').show();
		$('.multipul_titles').hide();
		$('.multipul_titles:eq('+index+')').show();
	}
	
};

var case_study_titles_and_ps = {
	initialise: function() {
		var case_study_category_headline = $('.case_study_category_headline');
		case_study_category_headline.append('<span class="step_one"></span>');
		case_study_category_headline.append('<span class="step_two"></span>');
		case_study_category_headline.append('<span class="step_three"></span>');

		case_study_category_headline.each(function(index) {
			var title_width = $(this).find('.title').width();
			app.log(title_width);
			$(this).find('.step_one').width(title_width);
			$(this).find('.step_two').width(title_width + 37);
			$(this).find('.step_three').width(title_width + 37 + 57);
		});
	}
};

var lightbox = {
	initialise: function() {
		$('#lightbox_bg').fadeTo(0,0);
		$('#lightbox_bg').hide();
		
		lightbox_links.click(function(){
			
			caption_to_add = $('#' + $(this).attr('id') + '_cap').text();
			app.log(caption_to_add);
			
			
			if(is_overlay_open){
				lightbox.load_in_previous_check( $(this).attr('href') );
			}else{
				lightbox.open( $(this).attr('href') );
			}
			return false;
		});
		
		$('#out_of_how_many').text( $('a[rel^=lightbox]').length );
		
		//lightbox.open('/images/lb_one.png');
		
		$('.next_lightbox').click(function(){
			if(lightbox_next){
				lightbox.open(lightbox_next);
			}
			return false;
		});
		
		$('.previous_lightbox').click(function(){
			if(lightbox_previous){
				lightbox.open(lightbox_previous);
			}
			return false;
		});
		
		$('#close_box .close').click(function() {
			lightbox.close();
			return false;
		});
		
		$('.maximaise').click(function(){
			lightbox.open( $(lightbox_links[0]).attr('href') );
			return false;
		});
		
	},
	
	open: function(href) {
		$('#lightbox_bg').show();
		$('#lightbox_bg').css('height', '100%');
		$('#lightbox_bg').fadeTo(333,0.3, function(){
			lightbox.load_in_previous_check( href );
		});
		$('#lightbox_overlay').show();
	},
	
	close: function(href) {
		$('#lightbox_bg').fadeTo(333,0, function(){
			$('#lightbox_bg').hide();
		});
		$('#lightbox_overlay').hide();
	},
	
	load_in_previous_check: function( href ) {
		if($('#image_holder img').length > 0){
			$('#image_holder img').fadeTo(333,0,function(){
				lightbox.hide_info_box( href );
			});
		}else{
			lightbox.hide_info_box( href );
		}
	},
	
	hide_info_box: function(href) {
		$('#info_panel').slideUp(333, function(){
			lightbox.load_in(href);
		});		
	},
	
	load_in: function(href) {
		
		var img = new Image();
		
		img.onload = function() {
			
			$('#loader').hide();
			
			$('#info_panel').width(img.width);
			$('#close_box .previous_lightbox').css('top', (img.height / 2) + 'px');
			$('#close_box .next_lightbox').css('top', (img.height / 2) + 'px');
			
			img.style.display = 'none';
			var target = $('#target_box');
			var image_holder = $('#image_holder');
			image_holder.empty();
			image_holder.append(img);
			lightbox.set_next_previous_slide_numbers(href);
			target.animate({
				width: img.width,
				height: img.height
			}, 500, function (){
				$( img ).fadeIn( 'normal', function() {
					$('#info_panel').slideDown(333);
					$('#caption_area').text(caption_to_add);
				});
			});
			
			$('#close_box').animate({
				width: img.width
			}, 500);
			
		};
		
		$('#loader').show();
		img.src = href;
	},
	
	set_next_previous_slide_numbers: function(href) {
		
		lightbox_links.each(function(index) {
		    if( $(this).attr('href') == href ){
				//current number
				$('#current_number').text((index + 1));
				
				//prevous
				if(index == 0){
					$('#info_panel .title_row .previous').fadeTo(0, 0.3);
					$('#info_panel .title_row .previous').addClass('disabled');
					$('#close_box .previous_lightbox').hide();
				}else{
					$('#info_panel .title_row .previous').fadeTo(0, 1);
					$('#info_panel .title_row .previous').removeClass('disabled');
					$('#close_box .previous_lightbox').show();
				}
				
				//next
					if((index + 1) == lightbox_links.length){
						$('#info_panel .title_row .next').fadeTo(0, 0.3);
						$('#info_panel .title_row .next').addClass('disabled');
						$('#close_box .next_lightbox').hide();
					}else{
						$('#info_panel .title_row .next').fadeTo(0, 1);
						$('#info_panel .title_row .next').removeClass('disabled');
						$('#close_box .next_lightbox').show();
					}
				if(is_browser.ie6){
					$('#close_box .next_lightbox').hide();
					$('#close_box .previous_lightbox').hide();
				}
				
				
				//set next link
				lightbox_next = $(lightbox_links[index + 1]).attr('href');
				lightbox_previous = $(lightbox_links[index - 1]).attr('href');
				caption_to_add = $('.a_caption:eq('+index+')').text();
			}
		});
		
		
	}
	
};

var full_stop_new = {
	initialise: function() {
		String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

		$('.news_item .post').each(function(index) {
			var str = $(this).find('p:last').html();
			str = str + "";
			str = str.trim(str);
			var newStr = str.substring(0, str.length-1);
			$(this).find('p:last').html(newStr);
			$(this).find('p:last').append('<span class="end_box" ></a>');

		});
	}
};

$(document).ready(function(){
	
	hero_slideshow.initialise_width();
	
	app.initialise();
	newsletter_subscribe_form.initialise();
	hero_slideshow.initialise();
	case_study_titles_and_ps.initialise();
	full_stop_new.initialise();
	
	//lightbox
	lightbox_links = $('a[rel^=lightbox]');
	lightbox_next = "";
	lightbox_previous = "";
	is_overlay_open = false;
	lightbox.initialise();
	
	if($('#failed_to_signup').length > 0){
		$('#your_email').focus();
	}
	
	
	$('.expander').each(function(index) {
		
		var expander = $(this);
		expander.click(function(){
			expander.parent().toggleClass('on');
			expander.parent().find('ul li').fadeTo(0,0);
			expander.parent().find('ul').slideToggle(333, function(){
				expander.parent().find('ul li').fadeTo(333,1);
			});	
		});
		
	});
	
	
	$('.print a').click(function(){
		window.print();
		return false;
	});
	
});

$(window).load(function(){
	
	hero_slideshow.start_interval_timer();
	
	if($('#map').length > 0){
		markersArray = [];
		maps.initialise();
	}
});


// register keypresses
$(document).keyup(function(e) {
  if (e.keyCode == 27) { lightbox.close(); }   // esc closes confirm window
});

