window.jQuery(window.document).ready(function ($, undefined) {


	var History = window.history;

	// Slide function o make the pages animate through each pages been called
	slide_to = function(href){

		var language = window.location.pathname.substring(0, 3);

		History.pushState({state:2}, "State 1", language + href); // logs {state:1}, "State 1", "?state=1"

		var current = 0, left = 0; 
		var pages = ['whoweare', 'whatwecando', 'howwework', 'whatwevedone', 'getaquote', 'getintouch'];
		var css_panel = ['who-we-are', 'what-we-can-do', 'how-we-work', 'what-we-done', 'get-a-quote', 'get-in-touch'];

		for (var i = 0; i < pages.length; i++) {
			if (href.indexOf(pages[i]) >= 0){
				current = i;
			}
		};

		$('.nav_menu a').each(function(){
			$('.nav_menu a').removeClass('active');
		});

		$('.nav_menu a.'+ css_panel[current]).addClass('active');

		var panelHeight = $($('.' + css_panel[current]).data('panel')).height()

		panelHeight = (panelHeight) ? panelHeight : 545;


		$(document.body).removeClass();
		$(document.body).addClass(pages[current]);

		$('.wrapper-viewport').animate({
			opacity: .3,
			height: panelHeight
		}, 'slow', function(){
			// complete function
			left = (current * -1020);
			$('.wrapper').animate({
				left: left
			}, 'medium', function(){
				$('.wrapper-viewport').animate({
					opacity: 1.0
				});	
			});
		});
	}

	var
		showing = 1,
		items = (Math.ceil($('.app-container a').length / 3)+1);

	var screens;
	var app_id;

	$('#show_more').click(function(){
		var app_container = $('.container .content .what-we-done-panel .app-container');

		if (showing >= items) {
			$('#show_more').fadeToggle('slow');
			return false;
		}

		showing++;
		
		app_container.animate({
			height: '+=200px'
		}, 'medium');

		$('.wrapper-viewport').animate({
			height: '+=200px'
		}, 'medium');



		if (showing >= items) {
			$('#show_more').fadeToggle('slow');
			return false;
		}
		return false;
	});
	
	$(function() {
		$('.app-popup').dialog({ 
			resizable: false,
			show: "fade", 
			autoOpen: false, 
			hide: "explode", 
			modal: true, 
			width: 964, 
			height: 490 
		});


  		
		$('a.app').click(function(){
			$.ajax({
				url: '/api/content/app/'+ $(this).attr('id') +'.json',
				dataType: 'json',
				success: function(data){
					var test = data.payload.app;
					app_id = data.payload.app.href;
					
					if (test.testimonial) {
						test.testimonial = {
							file: test.testimonial
						};

					} else {
						test.testimonial = false;
					}

					$.each(data.payload.stores, function(key, value){
					
						if (value.length === 0){
							data.payload.stores[key] = false;
						} else {
							data.payload.stores[key] = {
								ios: value,
								android: value,
								wp7: value,
								blackberry: value
							};
						}
					});

					var content = {
						app: test,
						about_app: data.payload.about_app,
						features: data.payload.feature,
						designs: data.payload.devices,
						stores: data.payload.stores
					}

					screens = data.payload.app.screens;
					screens = screens.replace(' ', '');
					screens = screens.split(',');
					
					var screen_count = screens.length;

					var source   = $('#mustache-content-app').html();
					var template = Handlebars.compile(source);
					$('.app-popup').html(template(content));

					var current_image = '<img data-total_images="'+ screen_count+'" src="/media/img/content/what-we-done/app/screens/'+ data.payload.app.href +'/' + screens[0]+'"/>';
					
					$('.screen').prepend(current_image);
					
					$('.app-popup').dialog( "open" );
				}
			});
			return false;
		});
	});
	 
	var current = 0;

	$('.app-popup .content .left').live('click', function(){
		current = current - 1;
		var images = [];

		$.each(screens, function(k, s){
			images.push(s.replace(' ', ''));
		});
		var image = $('.app-popup .content .phone .screen img').attr('src');
		
		var total_images = $('.app-popup .content .phone .screen img').data('total_images');

		if (current < 0){
			current = total_images - 1;
			$('.app-popup .content .phone .screen img').attr('src', "/media/img/content/what-we-done/app/screens/"+ app_id +'/' + images[total_images - 1]);
		}
		else{
			$('.app-popup .content .phone .screen img').attr('src', "/media/img/content/what-we-done/app/screens/"+ app_id +'/' + images[current]);	
		}
	});

	$('.app-popup .content .phone .right').live('click', function(){
		current = current + 1;
		var images = [];

		$.each(screens, function(k, s){
			images.push(s.replace(' ', ''));
		});

		var image = $('.app-popup .content .phone .screen img').attr('src');
		
		var total_images = $('.app-popup .content .phone .screen img').data('total_images');

		if (current > (total_images - 1)){
			current = 0;
			$('.app-popup .content .phone .screen img').attr('src', "/media/img/content/what-we-done/app/screens/"+ app_id +'/' + images[current]);
		}
		else{
			$('.app-popup .content .phone .screen img').attr('src', "/media/img/content/what-we-done/app/screens/"+ app_id +'/' + images[current]);	
		}
	});
	
	$(function(){

		var href = jQuery(location).attr('href');
		var controller = href.split('/')[4];
		var action = href.split('/')[5];

		// Check if the user is at the app section with only php
		if (controller == 'whatwevedone' && action == 'app'){
			$('.app-popup').dialog( "open" );
			$('.app-popup .close').click(function(){
				window.location.href = "/whatwevedone";
			});
			$('.app-popup a.left').click(function(){
				window.location.href = $(this).attr('href');
			});
			$('.app-popup a.right').click(function(){
				window.location.href = $(this).attr('href');
			});
		}

		$('#quote_budget').selectmenu({
			dropdown: true
		});

		$('#time_material').selectmenu({
			dropdown: true
		});

		$('.popup .content .close').live('click', function(){
			$('.app-popup').dialog('close');
			return false;
		});

		/*$('.get-a-quote-panel #quote_form').submit(function(){
			$.ajax({
				url: '/api/content/getaquote.json',
				dataType: 'json',
				type: 'POST',
				data: JSON.stringify
					({
						quote_name: $('#quote_name').val(),
						quote_company: $('#quote_company').val(),
						quote_email: $('#quote_email').val(),
						quote_telephone: $('#quote_telephone').val(),
						projects: $('#projects').val(),
						quote_budget: $('#budget').val(),
						quote_name: $('#quote_name').val(),
					}),
				processData: false,
				success: function(data){
					if (jQuery.inArray('errors', data)){
						var content = {
							errors: data.payload.errors
						}
						var source   = $('#mustache-content-error').html();

						var template = Handlebars.compile(source);
						$('.error_box').html(template(content));

						$('.error_box').animate({
							background: 'red'
						});
					}
					else{
						
					}
				}
			});

			return false;
		});*/
	});

	//Fixes the issue on the popup box that the external links doesn't go anywhere
	$('.app-popup .content a.external').live('click', function(event){
		event.preventDefault();
        event.stopPropagation();
        window.open(this.href, '_blank');
	});

	var timeout, startTimeout;

	var displayed = 0;
	var total_apps;

	startTimeout = function (time) {
		if (time === undefined) {
			time = (10 * 1000);
		}

		timeout = setTimeout(function () {
			$('.container .header .slide_panel .app_banner').animate({
				left: ('-1020' * (displayed % total_apps))
			}, 'medium', function(){
				startTimeout(5000);
			});

			displayed = displayed + 1;
		}, time)
	};
	
	$('.container .header .slide_panel .app_banner').mouseenter(function () {
		clearTimeout(timeout);
	});
	
	$('.container .header .slide_panel .app_banner').mouseleave(function () {
		startTimeout(5000);
	});

	// Code to animate the slide panel with app we've done only on the 'what we've done page 
	$('html.history .nav_menu .what-we-done').click(function(){

		$(this).addClass('active');
		$.ajax({
			url: '/api/content/appbanner.json',
			dataType: 'json',
			success: function(apps){
				var image;
				var anchor;

				// Stop it from adding a tags to the list
				if (total_apps === undefined){
					$.each(apps.payload.apps, function(app, values){
						image = $('<img />').attr('src', '/media/img/template/header/slide-panel/product_scren_banners/' + values.img);

						anchor = $('<a/>', {    //here appending `<a>` into `<li>`
	                        	'href': values.href,
	                        	'title': values.title,
	                        	'target': '_blank'
	                    	});

						$(anchor).append(image);
						$('.app_banner').append(anchor);
					});
					total_apps = apps.payload.num_apps;
				}

				$('.container .header .slide_panel .app_banner_view').show('fold', '', 'slow');
				startTimeout(5000);
			}
		});
	

	});
	
	$('html.history .nav_menu a').click(function(){
		// Only hide the app banner if it's visible
		if ($('.container .header .slide_panel .app_banner_view').is(':visible')){
			$('.container .header .slide_panel .app_banner_view').hide('fade');
		}

		if ($('.container .header .slide_panel .video-js-box').is(':visible')){
			$('.container .header .slide_panel .video-js-box').hide('fade');
		}


		clearTimeout(timeout);
		//var current = 0, left = 0;

		//var pages = ['whoweare', 'whatwecando', 'howwework', 'whatwevedone', 'getaquote', 'getintouch'];
		//var css = ['who-we-are', 'what-we-can-do-for-you', 'how-we-work', 'what-weve-done', 'get-a-quote', 'get-in-touch'];

		/*var href = $(this).attr('href');
		for (var i = 0; i < pages.length; i++) {
			if (href.indexOf(pages[i]) >= 0){
				current = i;
			}
		};*/

		var panelHeight = $($(this).data('panel')).height();

		
		panelHeight = (panelHeight ) ? panelHeight : 545;
		

		slide_to($(this).attr('href'));
		/*$('.nav_menu a').each(function(){
			$(this).removeClass('active');
		});*/

		//$('.nav_menu a.'+ $(this).data('class')).addClass('active');

		/*$('.wrapper-viewport').animate({
			opacity: .3,
			height: panelHeight
		}, 'slow', function(){
			// complete function
			left = (current * -1020);
			$('.wrapper').animate({
				left: left
			}, 'medium', function(){
				$('.wrapper-viewport').animate({
					opacity: 1.0
				});	
			});
		});*/
		return false;
	});

	$(function(){
		var latlng = new google.maps.LatLng(52.488562,-1.887444);

		 var myOptions = {
      		zoom: 16,
      		center: latlng,
      		disableDefaultUI: true,
      		mapTypeId: google.maps.MapTypeId.ROADMAP
    	};
		var map = new google.maps.Map(document.getElementById("google_map"),
        myOptions);

        addMarker(latlng, map);

        function addMarker(initalLocation, map){
        	var image = new google.maps.MarkerImage(
				'http://www.syncstudios.co.uk/media/img/content/get-in-touch/map-marker.png',
				new google.maps.Size(45,39),
				new google.maps.Point(0,0),
				new google.maps.Point(45,39)
			);

			var marker = new google.maps.Marker({
				position: initalLocation, 
				map: map,
				title: 'Sync Studios',
				icon: image
			});
        };
        
	});

	$('.container .header .slide_panel .new-panel-container a.news_button').hover(function(){
		$('.container .header .slide_panel .new-panel-container .news-panel').slideDown('slow');
		$(this).removeClass('inactive');
		$(this).addClass('active');
	});

	$('.container .header .slide_panel .new-panel-container').mouseleave(function(){
		$('.container .header .slide_panel .new-panel-container .news-panel').slideUp('slow');
		$('.container .header .slide_panel .new-panel-container a').removeClass('active');
		$('.container .header .slide_panel .new-panel-container a').addClass('inactive');
	});


	$('.container .header .slide_panel .new-panel-container a.inactive').click(function(){
		
		$('.container .header .slide_panel .new-panel-container .news-panel').slideDown('slow');
		$(this).removeClass('inactive');
		$(this).addClass('active');

		return false;
	});

	$('.container .header .slide_panel .new-panel-container .news_button.active').click(function(){
		$('.container .header .slide_panel .new-panel-container .news-panel').slideUp('slow');
		$('.container .header .slide_panel .new-panel-container a').removeClass('active');
		$('.container .header .slide_panel .new-panel-container a').addClass('inactive');
		return false;
	});	

	
	//	JS for video playing
	
	var video_added = false;

	$('.container .header .slide_panel .video').click(function(){

		$('.video_unsupport').dialog({ 
			resizable: false,
			show: "fade", 
			autoOpen: false, 
			hide: "explode", 
			modal: true, 
			width: 500, 
			height: 200,
			title: 'Video Unsupport'
		});

		var b = $.browser;

		var version = b.version;

		version = parseFloat(version);

		if (b.mozilla && version <=3){
			$('.video_unsupport').dialog( "open" );
		}
		else{
			$('.container .header .slide_panel .video-js-box').show();	

			if (video_added === false){
				$("video").VideoJS();
				video_added = true;
			}

			$("video")[0].player.play();		
		}
		
	});

});


