// cufon font conversions
//Cufon.replace('div#slogan', { fontFamily: 'helvetica-neue-53' });
Cufon.replace('#page_navigation ul li a', { fontFamily: 'helvetica-neue-53' });
Cufon.replace('#video_playlist ul li a.media', { fontFamily: 'helvetica-neue-53' });
Cufon.replace('.helvetica-neue-53', { fontFamily: 'helvetica-neue-53' });
Cufon.replace('h1.post-title, h2.post-title', { fontFamily: 'helvetica-neue-23' });
Cufon.replace('div.studio-content h3.heading', { fontFamily: 'helvetica-neue-63' });
Cufon.replace('div.home-content', { fontFamily: 'helvetica-neue-43' });

// jquery address
$.address.change(function(e){
	page = e.value.substr(1).toLowerCase();

	var ignore = false;
	
	var ignore_reg = /(demo-archives)/;
	if ( ignore_reg.test( window.location.pathname ) ) {
		ignore = true;
		console.log('ignore this shit');
	}
	
	
	// if we're on a new article, we will not do any ajax calls
	var more_reg = /more\-[0-9]+/;
	if ( more_reg.test( e.path ) ) {
		ignore = true;
		
		selectPage('news');
	}
	
	if (ignore == true) {
		return;
	}
	
	// if we're on the / page (root page), set the page to home
	if ($.address.path() == '/') {
		return;
	}
	
	// loading animation
	$('div#content').html('<div id="loading"><img src="http://www.christopherkent.co.uk/assets/images/loading.gif" alt="Loading..." /></div>');
	updateShadows();

	// load page content
	$.get('/ajax.php', { pg : page }, function(data) {
		$('div#content').hide().html(data).slideDown(250);

		// update the shadows 10 times per second then stop after 3 seconds
		var interval = setInterval(updateShadows, 100);
		setTimeout(function(){ clearInterval(interval); }, 3000);
		
		selectPage(page);

		// contact form script
		if (page == 'contact') {
			contactForm();
		}

		// cufon fonts
		Cufon.replace('.helvetica-neue-53', { fontFamily: 'helvetica-neue-53' });
		Cufon.replace('h1.post-title, h2.post-title', { fontFamily: 'helvetica-neue-23' });
		Cufon.replace('div.studio-content h3.heading', { fontFamily: 'helvetica-neue-63' });
		Cufon.replace('div.home-content', { fontFamily: 'helvetica-neue-43' });
		Cufon.now();
	});
	
});

// get the video id
function getID() {
	var me;
	if (navigator.appName.indexOf("Microsoft") != -1) {
		me = window['vid'];
	} else {
		me = document['vid'];
	}
	return me;
}

$(document).ready(function() {
	$('#page_navigation a, #footer .nav').click(function(){
		// if we're on the demo-archive page, then go back to home before changing the page
		var demo_reg = /(demo-downloads|demo-archives)/;
		var news_reg = /[0-9]{4,4}\/[0-9]{2,2}\/[0-9]{2,2}\/[a-z\-_\+]+/;
		if ( demo_reg.test( window.location.href ) || news_reg.test( window.location.href ) ) {
			window.location.href = '/#/' + $(this).attr('id').toLowerCase();
			return false;
		}
		
		// send current page to jquery address
		$.address.value( $(this).attr('id').toLowerCase() );
		return false;
	});
	
	$('#client-login-btn').mouseover(function(){
		$(this).attr('src', 'http://www.christopherkent.co.uk/assets/images/client-login-over.gif');
		return false;
	});
	$('#client-login-btn').mouseout(function(){
		$(this).attr('src', 'http://www.christopherkent.co.uk/assets/images/client-login.gif');
		return false;
	});
	
	
	// when we get the files for the last 3 videos, update them in this array
	var mp4s 		= ['03_Trailer.mp4', '05_Commercial.mp4', '02_Promo.mp4', '04_Documentary.mp4', '01_Narration.mp4', 'video.mp4', 'video.mp4'];
	var screenshots = ['qt_trailer.jpg', 'qt_commercial.jpg', 'qt_promo.jpg', 'qt_documentary.jpg', 'qt_narration.jpg', 'black.jpg', 'black.jpg'];
	var folders		= ['videos', 'videos', 'videos', 'videos', 'videos', 'audio', 'audio'];
	var appleProduct = false;
	
	$('#video_playlist').delegate('a.media', 'click', function(){
		// show the appropriate 'download' button
		$('#video_playlist ul li').each(function(){
			$(this).removeClass('selected');
		});
		$(this).parent().addClass('selected');
		
		var id = $(this).attr('rev');
		
		// call a function from within flash to play the video and pass the url
		if (appleProduct == true) {
			highlightCurrentVideo(id);
			
			var new_vid = '';
			new_vid += '<object type="video/mp4" data="http://www.christopherkent.co.uk/assets/videos/' + screenshots[id] + '" width="480" height="270">';
			new_vid += '<param name="controller" value="false" />';
			new_vid += '<param name="src" value="http://www.christopherkent.co.uk/assets/videos/' + screenshots[id] + '" />';
			new_vid += '<param name="href" value="http://www.christopherkent.co.uk/assets/' + folders[id] + '/' + mp4s[id] + '" />';
			new_vid += '<param name="target" value="myself" />';
			new_vid += '</object>';
			$('#vid').html( new_vid );
			
		} else {
			var me = getID();
			me.playVideoByID(id);
		}

		return false;
	});

	// embed flash video player
	var flashvars = {};
	var params = { wmode:'transparent', allowscriptaccess:'always' };
	var attributes = { id:'vid', name:'vid' };
	swfobject.embedSWF("http://www.christopherkent.co.uk/assets/swf/ckuk-player.swf?xml_file=http://www.christopherkent.co.uk/assets/xml/ckvo.xml", "vid", "480", "270", "9.0.0", false, flashvars, params, attributes, swfcallback);
	
	function swfcallback(e) {
		//console.log( e.success );
		if (e.success == false) {
			appleProduct = true;
			$('#vid object').attr('data', 'http://www.christopherkent.co.uk/assets/videos/black.jpg');
			$('#vid object param[name="src"]').attr('value', 'http://www.christopherkent.co.uk/assets/videos/black.jpg');
			$('#vid object param[name="href"]').attr('value', 'http://www.christopherkent.co.uk/assets/videos/' + mp4s[0]);
		} else {
			appleProduct = false;
		}
		
		// reset cookie info
		$.cookie('ckuk_media_visited', null);
		
		// auto start video if first-time visitor
		if ( $.cookie('ckuk_media_visited') != 'true' ) {
			// automatically play the first video
			var id = 0;
			
			var me = getID();
			var interval = setInterval(function()
			{
				try {
					if ( me.playVideoByID(id) == undefined ) {
						clearInterval( interval );
					}
				} catch(e) {
					//console.log(e);
				}
			}, 500 );
			
			// set cookie to true so that it doesn't play automatically next time
			$.cookie('ckuk_media_visited', 'true', { expires:180 }); // set to expire in 6 months
		} else {
			// don't auto play, do nothing
		}
		
	}
	
	updateShadows();
	
	
	// if we're on the contact page, initialise the form
	if ( $('.contact-form').length ) {
		contactForm();
	}
});

function highlightCurrentVideo(id) {
	// show the appropriate 'download' button
	$('#video_playlist ul li a.download').fadeOut(500);
	
	$('#video_playlist ul li').each(function(){
		$(this).removeClass('selected');
		
		if ( $(this).children('a.media').attr('rev') == id ) {
			$(this).addClass('selected');
			$(this).children('a.download').fadeIn(500);
		}
	});
}


// remove 'selected' attribute from the current nav button, and put it on the newly selected page
function selectPage(page) {
	// reset all links and set clicked item as selected page
	$('#page_navigation ul li').each(function(i) {
		$(this).attr('class', '');

		var page_parts = page.split('/');
		
		if (page_parts[0] == 'news') {
			page = 'news';
		}
		
		if ( $(this).children('a').text().replace(' ','-').toLowerCase() == page) {
			$(this).attr('class', 'selected');
		}
	});
}

function updateShadows() {
	//console.log('updating shadows');
	$('#shadow-left, #shadow-right').height( $('#container').height() );
}


// contact form
function contactForm() {
	$('.wide, textarea').clearField();
	
	$('#scriptfile').uploadify({
		'uploader'		: '/assets/js/uploadify/uploadify.swf',
		'script'		: '/assets/js/uploadify/uploadify.php',
		'cancelImg'		: 'http://www.christopherkent.co.uk/assets/js/uploadify/cancel.gif',
		'buttonImg'		: 'http://www.christopherkent.co.uk/assets/images/browse-file.gif',
		'buttonText'	: '',
		'width'			: 131,
		'height'		: 34,
		'auto'			: true,
		'onSelect'		: fileselected,
		'onComplete'	: fileuploaded,
		'onCancel'		: fileCancelled
	});
	
	function fileselected(e,q_id,file_obj) {
		$('#send_btn').attr({ 'disabled':'disabled', 'src':'http://www.christopherkent.co.uk/assets/images/send-btn-disabled.jpg' });
		
		// update the shadows 10 times per second then stop after 2 seconds
		var interval = setInterval(updateShadows, 100);
		setTimeout(function(){ clearInterval(interval); }, 2000);
		
		return true;
	}
	
	function fileCancelled(e,q_id,file_obj,data) {
		$('#send_btn').attr({ 'disabled':null, 'src':'http://www.christopherkent.co.uk/assets/images/send-btn.jpg' });
		
		// update the shadows 10 times per second then stop after 2 seconds
		var interval = setInterval(updateShadows, 100);
		setTimeout(function(){ clearInterval(interval); }, 2000);
		
		return true;
	}
	
	function fileuploaded(e,q_id,file_obj,response,data) {
		var url = response + ',';
		var orig_value = $('#attachments').val();
		$('#attachments').val( orig_value + url );
		
		$('#send_btn').attr({ 'disabled':null, 'src':'http://www.christopherkent.co.uk/assets/images/send-btn.jpg' });
		
		$('#scriptfileQueue .cancel').fadeOut(250);
		
		return false;
	}
	
	var errorCount = 0;
	$('#requestquote_form').submit(function(){
		//console.log('submit');
		var valid = validateFields();
		
		if (valid == false) {
			errorCount++;
			if (errorCount >= 2) {
				$('#form-errors').fadeOut(50);
				$('#form-errors').fadeIn(100);
				$('#form-errors').fadeOut(50);
				$('#form-errors').fadeIn(100);
			} else {
				$('#form-errors').text('Please check the highlighted fields above.').fadeIn();
			}
		} else {
			$('#form-errors').fadeOut();
			sendEmail();
		}

		return false;
	});
}

function validateFields() {
	var valid = true;
	
	// trim name field
	$('#name').val( $.trim($('#name').val()) );
	if ( $('#name').val() == 'Name *' || $('#name').val().length < 3 ) {
		highlightField('#name', 'error');
		valid = false;
	} else {
		highlightField('#name');
	}
	
	$('#email').val( $.trim($('#email').val()) );
	if ( validateEmail($('#email').val()) == false ) {
		highlightField('#email', 'error');
		valid = false;
	} else {
		highlightField('#email');
	}
	
	$('#telephone').val( $.trim($('#telephone').val()) );
	if ( $('#telephone').val() == 'Telephone *' || $('#telephone').val().length < 3 ) {
		highlightField('#telephone', 'error');
		valid = false;
	} else {
		highlightField('#telephone');
	}
	
	$('#lengthofscript').val( $.trim($('#lengthofscript').val()) );
	if ( $('#lengthofscript').val().length < 1 ) {
		highlightField('#lengthofscript', 'error');
		valid = false;
	} else {
		highlightField('#lengthofscript');
	}
	
	// trim
	$('#company').val( $.trim($('#company').val()) );
	$('#comments').val( $.trim($('#comments').val()) );

	return valid;
}

function validateEmail(address) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(address) == false) {
		return false;
	}

	return true;
}

function sendEmail() {
	var data = new Object();
	data.send_btn = 'Send';
	data.name = $('#name').val();
	data.company = $('#company').val();
	data.email = $('#email').val();
	data.telephone = $('#telephone').val();
	data.comments = $('#comments').val();
	data.attachments = $('#attachments').val();

	($('#vertising').attr('checked') == true) ? data.advertising = 'on' : null;
	($('#filmvideo').attr('checked') == true) ? data.filmvideo = 'on' : null;
	($('#multimedia').attr('checked') == true) ? data.multimedia = 'on' : null;
	($('#other').attr('checked') == true) ? data.other = 'on' : null;

	data.lengthofscript = $('#lengthofscript').val();
	data.lengthradio = $("input[name='lengthradio']:checked").val();

	($('#broadcast').attr('checked') == true) ? data.broadcast = 'on' : null;
	($('#corporate').attr('checked') == true) ? data.corporate = 'on' : null;
	($('#publicexhibition').attr('checked') == true) ? data.publicexhibition = 'on' : null;
	($('#internet').attr('checked') == true) ? data.internet = 'on' : null;
	($('#otherusage').attr('checked') == true) ? data.otherusage = 'on' : null;

	$.post("/requestquote.php", data, function(res){
		if (res == 'success') {
			$('.uploadifyQueueItem').hide();
			$('#form-message').show().addClass('success').html('Thank you - your request was sent successfully.');
			$('#send_btn').attr({ 'disabled':'disabled', 'src':'http://www.christopherkent.co.uk/assets/images/send-btn-disabled.jpg' });
		} else {
			$('#form-message').show().addClass('error').html('Your request was not sent, please try again.');
		}
	});
}

function highlightField(field_id, error_type) {
	switch (error_type) {
		case 'error':
			$(field_id).css('border-color','#FF9900');
			$(field_id).css('background-color','#FFFFFD');
			break;
		default:
		case null:
			$(field_id).css('border-color','#ABADB3');
			$(field_id).css('background-color','#FFFFFF');
			break;
	}
}


