$(window).load(function () {
	$('#options').css('width', (890 - $('#logo').outerWidth()) );
});
$(document).ready(function () {
	var search_xhr;
	var question_xhr;
	loadAudio();
	dyn_init();
	dyn_select();
	window.scrollTo(0,1);
	$('.chart table tr.conjugations:odd').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_light_gray.png")');
	$('.chart table tr.conjugations:even').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_white.png")');
	$('.credit_history tr:odd td').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_light_gray.png")');
	$('.credit_history tr:even td').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_white.png")');
	$('.glossary:odd').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_light_gray.png")');
	$('.glossary:even').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_white.png")');
	$('.phrase:even').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_light_gray.png")');
	$('.side_question:odd').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_light_gray.png")');
	$('.point_history tr:odd').css('background-image','url("http://www.onlinelanguagehelp.com/media/images/transparent_light_gray.png")');
	
	
	$('.lesson_row.premium').live('mouseover', function () { $(this).fadeTo(0,0.3) });
	$('.lesson_row.premium').live('mouseout', function () { $(this).fadeTo(0,1) });
	$('.lesson_row.premium').wTooltip({ className:'toolTip', style:false, fadeIn:0, timeOut:0 });
	
	$('#tut').bind('mouseover',function() {
		$(this).siblings('.streak_small').html('1st<br/>FREE');
	});
	$('#tut').bind('mouseout',function() {
		$(this).siblings('.streak_small').html('$12.99<br/>/class');
	});
	
	$('.question .answer_count').live('mouseover',function (){
		$(this).fadeTo(0,0.8);
	});
	$('.question .answer_count').live('mouseout',function (){
		$(this).fadeTo(0,1);
	});
	$('.turn_off').hide();
	$('.turn_off_toggle').live('click',function() {
		$('.turn_off_toggle').fadeOut("slow",function () {
			$('.turn_off_toggle').remove();
			$('.turn_off').fadeIn("slow");
		});
		return false;
	});
	var countdown = function (time) {
		if (time) {
			var min = Math.floor(time / 60);
			var sec = (time % 60);
			if (time == 60) {
				$('.countdown').parents('.info').append('<b> Hurry up!</b>');
			}
		} else {
			var min = 0;
			var sec = 0;
			$('.countdown').parents('.info').fadeOut();
		}
		$('.min').text(min+' min ');
		$('.sec').text(sec+' sec ');
		setTimeout( function () { countdown(time - 1); },1000);
	}
	
	if ($('.countdown').length) {
		if (!$('.countdown .sec').length) {
			var time = parseInt( $('.countdown').text() );
			$('.countdown').text('');
			$('.countdown').append($('<span class="min"/>')).append( $('<span class="sec"/>') );
		}
		countdown(time);
		$('.drop_down').hide();
	}
	
	$('.edit_question').live('click', function () {
		$.get('/question/edit_form/'+$('#question_id').val(), function(data) {
			$('.question_header').after('<div class="section_container"><h2>Edit Question</h2><div class="section">'+data+'</div></div>');
			$('.question_search_results').hide();
			dyn_select();
			dyn_init();
		});
		return false;
	});

	loading_img = $('<img src="http://www.onlinelanguagehelp.com/media/images/loading.gif" alt="Loading..." class="loading" />');
	$('img.flag').wTooltip({ className:'toolTip', style:false, fadeIn:340, timeOut:550 });
	$('.phrase_xml a').wTooltip({ className:'toolTip', style:false, fadeIn:340, timeOut:550 });
	$('.drop_down').hide();
	$('.options').bind('mouseenter', function () {
		$(this).children('.drop_down_container').children('.drop_down').fadeIn('fast');
	});
	$('.options').bind('mouseleave', function () {
		var container = $(this);
		setTimeout( function () { container.children('.drop_down_container').children('.drop_down').fadeOut('fast') }, 130);
	});
	$('.zero').first().attr('id','unanswered');
	/* Site Search */
	$('.search_results').hide();
	$('#search').focusout( function () {
		setTimeout( function () { $('.search_results').fadeOut() }, 210);
		if ($(this).val() == '') { $(this).val('Search Words and Phrases'); }
	});
	$('#search').bind('keyup', function () {
		search();
	});
	$('#search').focus( function () {
		if ($(this).val() == 'Search Words and Phrases') { $(this).val(''); }
		search();
	});
	var search = function () {
		if ($('#search').val().length > 2) {
			$('.search_results').fadeIn();
			if (search_xhr) {
				search_xhr.abort();
			}
			$('.search_results .loading').remove();
			$('.search_results').append('<img src="http://www.onlinelanguagehelp.com/media/images/loading.gif" alt="Loading..." class="loading" />');
			search_xhr = $.ajax({
				type: 'get',
				url: $('#search_form').attr('action'),
				data: $('#search_form').serialize(),
				success: function (data) {
					if (data) {
					
						$('.search_results').empty();
						if (data.glossary.length || data.questions.length) {
							if (data.glossary.length) {
								$('.search_results').append('<div class="section_title">Glossary Search</div>');
								for (i in data.glossary) {
									$('.search_results').append( $('<div/>').html($('<a/>').attr('href','/word/'+data.glossary[i].id+'/'+data.glossary[i].original).text(data.glossary[i].original+" - "+data.glossary[i].translation)) );
								}
							}
							if (data.questions.length) {
								$('.search_results').append('<div class="section_title">Question Search</div>');
								for (j in data.questions) {
									$('.search_results').append( $('<div/>').html($('<a/>').attr('href','/how_to_say/'+data.questions[j].id+'/'+data.questions[j].question).text(data.questions[j].question)) );
								}
							}
						} else {
							$('.search_results').fadeOut();
						}
							
					}
				},
				dataType: "json"
			});
		} else {
			$('.search_results').empty();
			$('.search_results').hide();
		}
	}
	/* Add Answer */
	$('#add_answer').validate({
		submitHandler:function(form) {
			$('#add_answer input[type=submit]').after(loading_img);
			$('#add_answer input[type=submit]').attr('disabled','disabled');
			$.ajax({
				type: 'post',
				url: $(form).attr('action'),
				data: $(form).serialize(),
				success: function (data) {
					if (data.message == 'success') {
						displayAnswer(data);
						$('#answer').val('');
					} else if (data.message == 'not_logged_in') {
						alert(data);
					} else {
						alert(data.message);
					}
					$(loading_img).remove();
					$('#add_answer input[type=submit]').removeAttr('disabled');
				},
				dataType: "json"
			});
			return false;
		},
		messages: {
			answer: {
				required: 'Required' }
		},
		rules: {
			answer: {
				required: true }
		}
	});
	var displayAnswer = function (json) {
		$('.answers p').remove();
		like = $('<a class="like lever" />').html( $('<span class="indicator"/>') ).attr('href','/answer/like/'+json.answer_id );
		dontLike = $('<a class="dontLike lever" />').html( $('<span class="indicator"/>') ).attr('href','/answer/dontLike/'+json.answer_id );
		result = $('<span class="result"/>');
		votes = $('<span class="votes" />').html('<span class="number">0</span>');
		votes.prepend(like);
		votes.append(dontLike);
		votes.append(result);
		user = $('<a/>').text(json.user_name).attr('href','/profile/'+json.user_id);
		photo = $('<a/>').html('<img src="'+json.user_photo+'" alt="'+json.user_name+'" class="small_user" /> ').attr('href','/profile/'+json.user_id);
		date = $('<span class="date"/>').text(json.datetime+' ');
		info = $('<div class="info"> answered </div>').prepend(user).prepend(photo).prepend(date);
		answer = $('<div class="answer">').html('<div class="text">'+json.answer+'</div>').append(info).prepend(votes);
		$('.answers').append(answer);
		$('.question_header .answer_count').removeClass('zero');
		answer.hide();
		if ($('.question_header .answer_count b').text() == 0) {
			$('.question_header .answer_count b').text('1');
		} else {
			$('.question_header .answer_count b').text( parseInt($('.question_header .answer_count b').text())+1 );
		}
		answer.slideDown();
	};
	/* Ask Form */
	$('.question_search_results').hide();
	$('#question').live('focusout', function () {
		$('.question_search_results').fadeOut();
	});
	$('#question').live('keyup', function () {
		searchQuestions();
		var charsLeft = 100 - $('#question').val().length;
		$('#qlen').text(charsLeft);
		if (charsLeft < 10) {
			$('#qlen').css('color','red');
		} else {
			$('#qlen').css('color','#999');
		}
	});
	$('#question').live('focus', function () {
		searchQuestions();
	});
	var searchQuestions = function () {
		if ($('#question').val().length > 2) {
			if (question_xhr) { question_xhr.abort(); }
			question_xhr = $.ajax({
				type: 'post',
				url: '/question/search',
				data: $('#ask').serialize(),
				success: function (data) {
					if (data) {
						if (data.length) {
							$('.question_search_results').empty();
							$('.question_search_results').fadeIn();
							for (i in data) {
								$('.question_search_results').append( $('<div/>').html($('<a/>').attr('href','/how_to_say/'+data[i].id+'/'+data[i].question).text(data[i].question)) );
							}
						} else {
							$('.question_search_results').empty();
							$('.question_search_results').fadeOut();
						}
					}
				},
				dataType: "json"
			});
		} else {
			$('.question_search_results').empty();
		}
	}
	$('#ask').submit( function (form) {
		$('.question_search_results').fadeOut();
		if ($('#question').val().length < 2 || $('#question').val().length > 100) {
			$('#question').focus();
		} else if ($('#to_language').val() == '') {
			$('#to_language').siblings('.dyn_picker_selected').focus();
		} else if ($('#from_language').val() == '') {
			$('#from_language').siblings('.dyn_picker_selected').focus();
		} else if ($('#from_language').val() == $('#to_language').val()) {
			$('#to_language').val('');
			$('#to_language').siblings('.dyn_picker_selected').val('');
			$('#to_language').siblings('.dyn_picker_selected').css('background-image','');
			$('#to_language').siblings('.dyn_picker_selected').focus();
		} else {
			$('#ask input[type=submit]').attr('disabled','disabled');
			$('#ask input[type=submit]').fadeTo("slow",0.3);
			$.ajax({
				type: 'post',
				url: $('#ask').attr('action'),
				data: $('#ask').serialize(),
				success: function (data) {
					if (data.message == 'success') {
						$('#question').val('');
						displayQuestion(data,false);
						var a = $('<a>').text('Edit Question').attr('href',$('#recent .question:first .title').attr('href'));
						$('#recent .question:first .info').append(a)
					} else if (data.message == 'not_logged_in') {
						$('.login_message').remove();
						result = $('<div class="login_message" />').html(data.result);
						$('#ask_question').after(result);
						result.fadeTo(890,1);
					//	setTimeout( function () { $('.result').fadeTo(890,0) }, 5500);
					} else if (data.message == 'already_asked') {
						question = $('#question').val('');
						window.location = '/how_to_say/'+data.id+'/'+question
					} else {
						alert(data.message);
					}
					$('#ask input[type=submit]').removeAttr('disabled');
					$('#ask input[type=submit]').focus();
					$('#ask input[type=submit]').fadeTo("slow",1);
				},
				dataType: "json"
			});
		}
		return false;
	});
	var displayQuestion = function (json,append) {
		if ($('#recent').length) {
			link = "/how_to_say/"+json.id+"/"+escape(json.question);
			answer_count = $('<a class="answer_count">answers</a>').prepend( $('<b/>').text(json.answer_count) ).attr('href',link);
			if (json.answer_count == 0) {
				answer_count.addClass('zero');
				verb = ' asked ';
			} else {
				verb = ' answered ';
			}
			from_language = $('<img class="flag" />').attr('src','http://www.onlinelanguagehelp.com/media/images/flags/'+json.from_language.toLowerCase()+'.png').attr('alt',json.from_language);
			to_language = $('<img class="flag" />').attr('src','http://www.onlinelanguagehelp.com/media/images/flags/'+json.to_language.toLowerCase()+'.png').attr('alt',json.to_language);
			arrow = $('<img class="arrow" />').attr('src','http://www.onlinelanguagehelp.com/media/images/arrow.png').attr('alt','&rarr;');
			languages = $('<span class="languages"/>').prepend(from_language).append(arrow).append(to_language);
			title = $('<a class="title"/>').attr('href',link).html(json.question+' ').append(languages);
			user = $('<a/>').text(json.user).attr('href','/profile/'+json.user_id);
			date = $('<span class="date"/>').text(json.date+' ');
			info = $('<div class="info"/>').text(verb).prepend(user).prepend(date);
			question = $('<div class="question">').append(answer_count);
			question.hide()
			question.append(title).append(info);
			if (append) {
				$('#see_more_questions').before(question);
			} else {
				$('#recent').prepend(question);
			}
			question.slideDown();
		} else {
			window.location = '/how_to_say/'+json.id+'/'+escape(json.question);
		}
	};
	$('#see_more_questions').live('click', function () {
		return browseQuestions(this);
	});
	var browseQuestions = function (a) {
		see_more_text = $('#see_more_questions').html();
		$('#see_more_questions').html('<img src="http://www.onlinelanguagehelp.com/media/images/loading.gif" alt="Loading..." class="loading" />');
		$.ajax({
			type: 'get',
			url: $('#see_more_questions').attr('href'),
			data: 'limit=20&offset='+$('.question').length,
			success: function (data) {
				for (i in data.questions) {
					displayQuestion(data.questions[i],true);
				}
				if (data.count <= $('.question').length) {
					$('#see_more_questions').remove();
					$('.question:last').css('border','0px');
				} else {
					$('#see_more_questions').html(see_more_text);
				}
			},
			dataType: "json"
		});
		return false;
	}
	if ($('.question').length < 20) {
		$('#see_more_questions').remove();
	}
	$('.switch_languages').live('click', function () {
		to_language = $('#to_language').val();
		to_language_dyn_picker = $('#to_language').siblings('.dyn_picker_selected').val();
		to_language_dyn_picker_style = $('#to_language').siblings('.dyn_picker_selected').attr('style');
		if (!to_language_dyn_picker_style) {
			to_language_dyn_picker_style = ' ';
		}
		$('#to_language').val($('#from_language').val());
		$('#to_language').siblings('.dyn_picker_selected').val(  $('#from_language').siblings('.dyn_picker_selected').val() );
		$('#to_language').siblings('.dyn_picker_selected').attr('style', $('#from_language').siblings('.dyn_picker_selected').attr('style') );
		$('#from_language').val(to_language);
		$('#from_language').siblings('.dyn_picker_selected').val(to_language_dyn_picker)
		$('#from_language').siblings('.dyn_picker_selected').attr('style',to_language_dyn_picker_style);
		return false;
	});
	/* Voting */
	$('.lever').live('click', function () {
		var a = $(this);
		a.siblings('.number').fadeTo(340,0);
		a.siblings('.result').fadeTo(0,0);
		$.ajax({
			type: 'post',
			url: $(this).attr('href'),
			success: function (data) {
				if (data.message == 'success') {
					a.siblings('.number').text(data.votes);
					a.siblings('.number').fadeTo(550,1);
					a.siblings('.result').css('display','inline');
					a.siblings('.result').html(data.result);
					a.siblings('.result').fadeTo(890,1);
					setTimeout( function () { a.siblings('.result').fadeTo(890,0) }, 3400);
				} else {
					alert(data.message);
				}
			},
			dataType: "json"
		});
		return false;
	});
	/* Report Inappropriate */
	$('.report_inappropriate a').bind('click', function () {
		var a = $(this);
		a.siblings('.result').fadeTo(0,0);
		$('.report_inappropriate a').unbind('click');
		$.ajax({
			type: 'post',
			url: $(this).attr('href'),
			success: function (data) {
				if (data.message == 'success') {
					a.parents('.report_inappropriate').css('display','inline');
					a.parents('.report_inappropriate').html(data.result);
					a.parents('.report_inappropriate').fadeTo(890,1);
				} else {
					alert(data.message);
				}
			},
			dataType: "json"
		});
		return false;
	});
	
	/* Lesson Embed */
	$('.embed h3').hide();
	$('.embed textarea').hide();
	$('.embed a').click( function () {
		$('.embed a').hide();
		$('.embed h3').show();
		$('.embed textarea').show();
		$('.embed textarea').focus();
		$('.embed textarea').select();
		return false;
	});
	$('.embed textarea').click( function () {
		$('.embed textarea').focus();
		$('.embed textarea').select();
	});
});
var loadAudio = function () {
	$('object').remove();
	$("span.audio").each( function(index, elem) {
		if ($(elem).text()) {
			autoplay = "no";
			if ( $(elem).hasClass('autoplay')) {
				autoplay = "yes";
				$('.autoplay').removeClass('autoplay');
			}
			flashembed(elem,{
				src:"http://www.onlinelanguagehelp.com/media/flash/audio.swf",
				wmode: 'transparent'
				}, {
					audioFile: $(elem).text(),
					autoplay: autoplay
				});
		} else {
			$(elem).remove()
		}
	});
};
/* Dynamic Pickers */
var dyn_init = function () {
	$('.dyn_picker_options').hide();
	$('.dyn_picker_selected').bind('focus',function () {
		$(this).siblings('.dyn_picker_options').fadeIn();
		$('.hovering').removeClass('hovering'); 
	});
	$('.dyn_picker_selected').bind('focusout',function () {
		dyn_select();
		$(this).siblings('.dyn_picker_options').fadeOut();
		$('.hovering').removeClass('hovering'); 
	});
	$('.dyn_picker_selected').bind('keydown',function (event) {
		if ($('.hovering').length == 0 && (event.keyCode == 40 || event.keyCode == 38)) {
			$(this).siblings('.dyn_picker_options').children('.dyn_picker_option').first().addClass('hovering');
		} else {
			if (event.keyCode == 40) {
				$('.hovering').next('.dyn_picker_option').addClass('hovering').prev('.dyn_picker_option').removeClass('hovering');
			} else if (event.keyCode == 38) {
				$('.hovering').prev('.dyn_picker_option').addClass('hovering').next('.dyn_picker_option').removeClass('hovering');
			} else if (event.keyCode == 13 || event.keyCode == 9) {
				$('.dyn_picker_selected').blur();
				dyn_select();
			}
		}
		return false;
	});
	$('.dyn_picker_option').bind('mouseenter',function () {
		$('.hovering').removeClass('hovering');
		$(this).addClass('hovering');
	});
	$('.dyn_picker_option').bind('mouseleave',function () {
		$('.hovering').removeClass('hovering');
	});
}
var dyn_select = function () {
	$('.hovering').each( function () {
		src = '';
		if ($(this).children('img').length != 0) {
			src = $(this).children('img').attr('src');
			$(this).parents().children('.dyn_picker_selected').css('padding-left','30px'); 
			$(this).parents().children('.dyn_picker_selected').css('padding-right','3px'); 
		}
		text = $(this).children('.name').text();
		id = $(this).children('.id').text();
		$(this).parents().children('.dyn_picker_selected').css('background-image','url('+src+')').val(text);
		$(this).parents().children('input[type=hidden]').val(id);
		$(this).parents().children('.dyn_picker_selected').change();
	});
	$('.hovering').removeClass('hovering');
}