/*******************************************

              Johnson & Laird
	         ~~~~~~~~~~~~~~~~~
            built by Seven 2008

*******************************************/

/* CONSTANTS
 */
var rollovers = { 
	nav_actors: { xpos: -10, ypos: -10, xover: -147 },
	nav_voices: { xpos: -10, ypos: -57, xover: -147 },
	nav_presenters: { xpos: -10, ypos: -104, xover: -147 },
	nav_mcs_entertainers: { xpos: -10, ypos: -151, xover: -147 },
	nav_shortlist: { xpos: -10, ypos: -198, xover: -147 },
	
	nav_actor: { xpos: -10, ypos: -392, xover: -147 },
	nav_voice: { xpos: -10, ypos: -439, xover: -147 },
	nav_presenter: { xpos: -10, ypos: -486, xover: -147 },
	nav_mc_entertainer: { xpos: -10, ypos: -533, xover: -147 },
	
	but_start: { xpos: -10, ypos: -839, xover: -304 },
	but_refine: { xpos: -10, ypos: -275, xover: -304 },
	but_send: { xpos: -10, ypos: -557, xover: -304 },
	but_forward: { xpos: -10, ypos: -1027, xover: -304 },
	but_clear: { xpos: -10, ypos: -980, xover: -304 },
	
	but_back_actors: { xpos: -10, ypos: -322, xover: -304 },
	but_back_voices: { xpos: -10, ypos: -369, xover: -304 },
	but_back_presenters: { xpos: -10, ypos: -416, xover: -304 },
	but_back_mcs_entertainers: { xpos: -10, ypos: -463, xover: -304 },
	but_back_talent_homepage: { xpos: -10, ypos: -886, xover: -304 },
	but_back_news: { xpos: -10, ypos: -933, xover: -304 },
	but_back_shortlist: { xpos: -10, ypos: -510, xover: -304 },
	but_back_submission: { xpos: -10, ypos: -1074, xover: -304 },
	but_back_profile: { xpos: -10, ypos: -604, xover: -304 },
	
	but_back_about: { xpos: -10, ypos: -651, xover: -304 },
	but_back_news: { xpos: -10, ypos: -698, xover: -304 },
	but_back_contact: { xpos: -10, ypos: -745, xover: -304 },
	but_back_home: { xpos: -10, ypos: -792, xover: -304 },
	
	but_download_bio: { xpos: -10, ypos: -345, xover: -147 }
};
var ageranges = ['Any Age Range', '0 &ndash; 10', '10 &ndash; 15', '16 &ndash; 20', '20 &ndash; 25', '25 &ndash; 30', '30 &ndash; 35', '35 &ndash; 40', '40 &ndash; 45', '45 &ndash; 50', '50 &ndash; 55', '55 &ndash; 60', '60 &ndash; 65', '65+'];


/* VARIABLES
 */
var currentAudioClip;
var shortlistTotals = { "total":0, "d1":-1, "d2":-1, "d3":-1, "d4":-1 };


/* FUNCTIONS
 */
// Is a valid email address
function isEmail($email) {
	var filter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	return !filter.test($email);
}

// Add to Shortlist
function addToShortlist($id) {
	// Add to shortlist
	$.post("/shortlist/add", { talent: $id }, function(total){
		// Make display changes
		$('#nav-shortlist').html('Shortlist <span>(' +total+ ')</span>');
	});
}
// Remove from Shortlist
function removeFromShortlist($id) {
	// Remove to shortlist
	$.post("/shortlist/remove", { talent: $id }, function(total){
		// Make display changes
		$('#nav-shortlist').html('Shortlist <span>(' +total+ ')</span>');
	});
}

// Checks the Shortlist Form is ready to send
function checkShortlistForm() {
	var errmsg = '';
	
	// Name of Shortlist
	if ($('#sen-name').val() == '') errmsg += "- Please enter a name for the Shortlist \n";
	// Your Email
	if (isEmail($('#sen-email').val())) errmsg += "- Please enter a valid email address for you \n";
	// Recipients
	if ($('#sen-recipients').val() == '') errmsg += "- Please enter some Recipients to send this Shortlist to \n";
	
	if (errmsg != '') { alert(errmsg); }
	else {
		// Remove to shortlist
		$.post("/shortlist/send", { name: $('#sen-name').val(), email: $('#sen-email').val(), recipients: $('#sen-recipients').val(), message: $('#sen-message').val(), talent: $('#sen-talent').val() }, function(status) {
			$('#send-form').prev().attr('class','title-sent');
			$('#send-form').prev().attr('title','Sent Shortlist');
			$('#send-form').prev().html('Sent Shortlist');
			$('#send-form').html('');
			//alert('status:' + status);
		});
	}
}

// Checks the Submission Form is ready to send
function checkSubmissionForm() {
	var errmsg = '';
	
	// Name of Submission
	if ($('#sen-name').val() == '') errmsg += "- Please enter a name for the Submission \n";
	// Your Email
	if (isEmail($('#sen-email').val())) errmsg += "- Please enter a valid email address for you \n";
	// Recipients
	if ($('#sen-recipients').val() == '') errmsg += "- Please enter some Recipients to forward this Submission to \n";
	
	if (errmsg != '') { alert(errmsg); }
	else {
		// Remove to shortlist
		$.post("/submission/forward", { id: $('#submission-id').val(), title: $('#submission-title').val(), character: $('#submission-character').val(), name: $('#sen-name').val(), email: $('#sen-email').val(), recipients: $('#sen-recipients').val(), message: $('#sen-message').val(), talent: $('#sen-talent').val() }, function(status) {
			$('#send-form').prev().attr('class','title-forwarded');
			$('#send-form').prev().attr('title','Submission Forwarded');
			$('#send-form').prev().html('Submission Forwarded');
			$('#send-form').html('');
			//alert('status:' + status);
		});
	}
}

// Pauses any current playing Flash players
function pauseCurrentAudioClip($newid) {
	var tempAudioClip = "PreviewPlayer-" + $newid;
	if ((currentAudioClip) && (tempAudioClip != currentAudioClip)) {
		var swf = swfobject.getObjectById(currentAudioClip);
		if (swf) {
			swf.pausePlayback();
		}
	}
	currentAudioClip = tempAudioClip;
}
// Replaces image with Flash element and loads audio
function loadAudioClip($fullid, $type) {
	// Stop current audio
	pauseCurrentAudioClip($fullid);
	
	// Play this audio
	var flashvars = { talentid: $fullid.split('-')[0], type:$type };
	//alert('flasvars { fullid: ' +$fullid+ ', talentid:' +flashvars.talentid+ ', type:' +flashvars.type+ ' }');
	var params = { menu: "false" };
	var attributes = { id: currentAudioClip, name: currentAudioClip };
	swfobject.embedSWF("/swf/PreviewPlayer.swf", "preview-"+$fullid, "125", "43", "8", "/swf/expressInstall.swf", flashvars, params, attributes);
}

// Encodes a string to URL-safe
function URLEncode($str) {
	var output = '';
	var x = 0;
	$str = $str.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < $str.length) {
		var match = regex.exec($str.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if ($str[x] == ' ')
				output += '+';
			else {
				var charCode = $str.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}
// Decodes a URL-safe string
function URLDecode($str) {
	var output = $str;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') {
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
	return output;
}

// Submits a search
function submitSearchForm() {
	var page = $('#form-type').val();
	var querystring = '';
	
	// Build query string
	var name = $('#pri-name').val();
	if ((name != '') && (name != $('#pri-name').attr('title'))) {
		querystring = '&name=' + URLEncode(name);
	}
	
	// Add query select options
	$('#search-form select').each(function() {
		var id = $(this).attr('id');
		var formid = id.substr(id.indexOf('-') + 1);
		
		var val = $('option:selected', this).val();
		if (val != '') querystring += '&' +formid+ '=' +URLEncode(val);
	});
	if (querystring != '') querystring = '?' + querystring.substr(1);
	
	// Search
	location.href = page + querystring;
	
	return false;
}
function submitQuickSearchForm() {
	var division = $('#pri-division option:selected').val();
	if (division == '') {
		alert('- Select a Division to search within');
	} else {
		var querystring = '';
		var searchname = $('#pri-name').val();
		if ((searchname != '') && (searchname != $('#pri-name').attr('title'))) querystring = '?name=' + searchname;
		location.href = '/' + division + querystring;
	}
	return false;
}
// Rebuilds the search age range select box options
function buildAgeRangeOptions($gen) {
	var agerange = $('#pri-agerange');
	if ($(agerange).html()) {
		var html = '';
		for(var i=0; i < ageranges.length; i++) {
			var val = i;
			var sel = '';
			if (i == 0) {
				val = '';
				sel = ' selected="selected"';
			}
			if (($gen == 'adults') && (i > 0) && (i < 3)) {}
			else if (($gen == 'kids') && (i > 2)) {}
			else {
				html += '<option value="' +val+ '"' +sel+ '>' +ageranges[i]+ '</option>';
			}
		}
		$(agerange).html(html);
		$(agerange).prev().html(ageranges[0]);
		$(agerange).prev().removeClass('sel');
	}
}
// Clear entries check first!
function clearShortlist($div) {
	var title = "all " + $div.substr(0, 1).toUpperCase() + $div.substr(1) + "?";
	if ($div == "all") title = "All Talent?";
	else if ($div == "mcs") title = "MC&rsquo;s / Entertainers?";
	
	var reply = confirm("Clear this Shortlist of " +title);
	if (reply) {
		clearShortlistConfirmed($div);
	}
}
// Clear all entries from Shortlist
function clearShortlistConfirmed($div) {
	var shortlist_html = $('#nav-shortlist span').html();
	var shortlist_total = parseInt(shortlist_html.substr(1, shortlist_html.length-2));
	var talent_arr = [];
	
	// For each division on this page...
	$("#results .division").each(function() {
		var type = $(this).find("h3").attr("class").substr(6);
		if (($div == type) || ($div == "all")) {
			// Close this section on screen
			$(this).slideUp('slow');
			// Add to a list of talent to remove from shortlist
			$(this).find("li.profile").each(function() {
				talent_arr.push($(this).attr("id"));
			});
		}
	});
	
	// If there are talent to remove...
	if (talent_arr.length > 0) {
		// Remove all from session variable
		$.post("/shortlist/removeall", { talent_all: talent_arr.join("&") }, function(total){
			// Once complete, updated tally top right of page
			$('#nav-shortlist').html('Shortlist <span>(' +total+ ')</span>');
		});
		// Remove sidebar if all talent have just been removed from shortlist
		if (talent_arr.length >= shortlist_total) {
			$('#send-container').slideUp('slow');
			$('#clear-container').slideUp('slow');
		}
	}
}
// Shows the Voices shortcut menu
function displayVoicesMenu() {
	// Add overlay
	$('body').append('<div class="TB_overlayBG" id="TB_overlay"></div><div id="JLM_voices"><div class="sec1"><h1 title="Johnson &amp; Laird">Johnson &amp; Laird</h1></div><div class="sec2"><a href="#">Close</a></div><div class="sec3"><h3 title="Search Voices">Search Voices</h3></div><div class="options"><ul><li class="opt1"><a href="http://www.johnsonlaird.com/voices?gender=m&generation=adults"><span title="Male Voices">Male</span></a></li><li class="opt2"><a href="http://www.johnsonlaird.com/voices?gender=f&generation=adults"><span title="Female Voices">Female</span></a></li><li class="opt3"><a href="http://www.johnsonlaird.com/voices?generation=kids"><span title="Kids Voices">Kids</span></a></li></ul></div></div>');
	
	// Events
	$('#TB_overlay, #JLM_voices .sec2 a').click(function() {
		$('#TB_overlay').remove();
		$('#JLM_voices').remove();
		return false;
	});
}


/* EVENTS
 */

// On Window Load
$(document).ready(function() {
	// Menu Rollovers
	$('#header li a').each(function() {
		var id = $(this).attr('id').replace(/-/g, '_');
		if ($(this).parent().attr('class').indexOf('sel') == -1) {
			$(this).mouseover(function() { $(this).css({ backgroundPosition: rollovers[id].xover+ 'px ' +rollovers[id].ypos+ 'px' }) });
			$(this).mouseout(function() { $(this).css({ backgroundPosition: rollovers[id].xpos+ 'px ' +rollovers[id].ypos+ 'px' }) });
		}
	});
	// Alt Menu Rollovers
	$('.talent-homepage .details li a').each(function() {
		var id = $(this).attr('id').replace(/-/g, '_');
		if ($(this).parent().attr('class').indexOf('sel') == -1) {
			$(this).mouseover(function() { $(this).css({ backgroundPosition: rollovers[id].xover+ 'px ' +rollovers[id].ypos+ 'px' }) });
			$(this).mouseout(function() { $(this).css({ backgroundPosition: rollovers[id].xpos+ 'px ' +rollovers[id].ypos+ 'px' }) });
		}
	});
	
	// Search Fields: Input Text
	$('.textfield input').focus(function() { $(this).css({ backgroundPosition: '-304px -9px' }) });
	$('.textfield input').blur(function() { $(this).css({ backgroundPosition: '-10px -9px' }) });
	
	// Search Fields: Input Text with default values
	$('input.input-default').each(function() {
		$(this).focus(function() {
			if ($(this).val() == $(this).attr('title')) {
				$(this).addClass('sel');
				$(this).val('');
			}
		});
		$(this).blur(function() {
			if ($(this).val() == '') {
				$(this).removeClass('sel');
				$(this).val($(this).attr('title'));
			}
		});
	});
	
	// Search Fields: Select
	$('.selectfield select').change(function() {
		var id = $(this).attr('id');
		var sel = $(this).children('option:selected');
		var val = $(sel).val();
		
		// All Select boxes
		if ((val == '') || (val == 'all')) {
			$(this).prev().removeClass('sel');
		}
		else {
			$(this).prev().addClass('sel');
		}
		$(this).prev().html($(sel).html());
		
		// Age Range Select box
		if (id == 'pri-generation') {
			buildAgeRangeOptions(val);
		}
	});
	
	// Search Fields: Textarea
	$('.textfield textarea').focus(function() { 
		$(this).css({ backgroundColor: '#fafafa' });
		$(this).parent().css({ backgroundPosition: '-304px -117px' }) 
	});
	$('.textfield textarea').blur(function() { 
		$(this).css({ backgroundColor: '#ffffff' });
		$(this).parent().css({ backgroundPosition: '-10px -117px' }) 
	});
	
	// Search Form: Main Button	
	$('a.button').each(function() {
		var id = $(this).attr('id').replace(/-/g, '_');
		$(this).mouseover(function() { $(this).css({ backgroundPosition: rollovers[id].xover+ 'px ' +rollovers[id].ypos+ 'px' }) });
		$(this).mouseout(function() { $(this).css({ backgroundPosition: rollovers[id].xpos+ 'px ' +rollovers[id].ypos+ 'px' }) });
		if (id == 'but_refine') {
			$(this).click(submitSearchForm);
		} else if (id == 'but_start') {
			$(this).click(submitQuickSearchForm);
		}
	});
	
	
	// General Results
	var container = $('#container').attr('class');
	$('li.profile').each(function() {
		$(this).css({ background: '#f2f2f2 url(img/graphics/profile-bg.gif) left bottom' });
		// Hover events
		$(this).mouseover(function() { 
			$(this).css( { background: '#ffffff' } );
			$('h5 a', this).css( { color: '#222' } );
		});
		$(this).mouseout(function() { 
			$(this).css( { background: '#f2f2f2 url(img/graphics/profile-bg.gif) left bottom' } );
			$('h5 a', this).css( { color: '#808080' } );
		});
		
		// Click event
		var list = $(this).parent().attr('class');
		var link = $('h5 a', this).attr('href');
		$('div.details', this).click(function() { 
			location.href = link;
			return false;
		});
		
	});
	
	// Audio Results
	$('.audio-clip a').each(function() {
		$(this).mouseover(function() { $(this).css({ backgroundPosition: '-147px -292px' }) });
		$(this).mouseout(function() { $(this).css({ backgroundPosition: '-10px -292px' }) });
		$(this).click(function() {
			var fullid = $(this).parent().attr('id').substr(8);
			var type = $(this).attr('class');
			loadAudioClip(fullid, type);
			return false;
		});
	});
	
	// Shortlist: Add
	$('li.profile a.add').click(function() {
		var id = $(this).parents('.profile').attr('id');
		addToShortlist(id);
		$(this).parent().html('<strong>Added</strong> to Shortlist');
		return false;
	});
	$('#profile-title a.add').click(function() {
		var id = $('#talent-id').val();
		addToShortlist(id);
		$(this).parent().html('<p><strong>Added</strong> to Shortlist</p>');
		return false;
	});
	
	// Shortlist: Remove
	$('li.profile a.remove').click(function() {
		// Remove from Shortlist
		var id = $(this).parents('.profile').attr('id');
		removeFromShortlist(id);
		
		// Fade out profile panel
		var element = $(this).parents('.profile');
		var division = $(this).parent().attr('class');
		if (shortlistTotals[division] < 0) {
			shortlistTotals[division] = $(element).siblings().length;
		}
		if (shortlistTotals[division] == 0) {
			// Slide up division
			$(element).parents('.division').slideUp('slow');
			var divtotal = $('#division-total').val() - 1;
			$('#division-total').val(divtotal);
			
			// No more divisions left
			if (divtotal == 0) {
				$('#send-form').slideUp('slow');
				$('.title-send').slideUp('slow');
			}
		} else {
			$(element).fadeOut(400);
		}
		shortlistTotals[division]--;
		
		return false;
	});
	
	// Shortlist: Send
	$('#but-send').click(function() {
		checkShortlistForm();
		return false;
	});
	
	// Shortlist: Clear
	$('#but-clear').click(function() {
		clearShortlist($('#clear-division option:selected').val());
		return false;
	});
	
	// Submission: Forward
	$('#but-forward').click(function() {
		checkSubmissionForm();
		return false;
	});
	
	// Download Bio
	$('li.profile a.bio').click(function() {
		window.open($(this).attr('href'), '_blank');
		return false;
	});
	
	// Download Track
	$('li.profile a.track').click(function() {
		window.open($(this).attr('href'), '_blank');
		return false;
	});
	
	// Voices Select Menu
	$('#nav-voices').click(function() {
		displayVoicesMenu();
		return false;
	});
	
});