var current_live;  //Boolean for if Benny is live right NOW
trunc_length = 500;

jQuery(document).ready(function() {
	
	jQuery(".beskjeder").hide();
	
	//Benny Admin: Hide all question content and forms
	jQuery("tr.question_content").hide();
	jQuery("tr.answer_form").hide();
	
	//Hide search box in Forums
	jQuery("tr.search_content").hide();
	
	
	//Clear all textareas
	jQuery("textarea.svar-textarea").val("");
	
	
	//Benny admin: live checkbox toggle
	if (jQuery("#liveonoff:checked").length != 0) {
		toggle_live_dropdown();
	}
	
	//Pagination (Bennys ubesvarte liste)
	jQuery(".bennys-pagination a.page").click(function() {
		adminBennyPagination(this);
	});
	
	
	//INIT
	init_help_benny_questions();
	
	//Benny-admin. Lagre live-status
	jQuery("#benny-admin-lagre-live-button").click(function() {
		benny_admin_lagre_live();
	});
	
});


//Pagination (Benny admin ubesvarte liste)
function adminBennyPagination(elem) {
	var pageClicked = jQuery(elem).attr('title');
	//ajax-kall
	jQuery.ajax({
		url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/benny-admin-stream-ubesvarte.php',
		data: { side: pageClicked },
		success: function(msg) {
			jQuery("#benny_admin_ubesvarte_liste").html(msg);
			//Så må vi kjøre init, fordi vi putter nytt innhold og jquery(ready) ikke funker...
			init_help_benny_questions();
		},
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Det skjedde noe galt! "+xhr.status+"\n"+thrownError);
		}
	});
}


//Hjelp Benny: Truncate too long questions, and adds a "... (link to see whole)"
function my_truncate(text) {
	tmp = text.substring(0, trunc_length);
	tmp = tmp.replace(/\w+$/, '');  //don't cut in the middle of a word, go back 1 word
	return tmp;
}


function init_help_benny_questions() {
	//Expand/hide rows with forum post content	
	jQuery("h6.i-can-answer").click(function() {
		var container = jQuery('#'+ jQuery(this).attr('id') +'_container');
		if (jQuery(container).hasClass("expanded-hjelpbenny")) {
			jQuery(container).hide();  //Hide container
			jQuery(container).removeClass("expanded-hjelpbenny").addClass("collapsed-hjelpbenny");
			jQuery(this).children('img').removeClass("expanded-hjelpbenny").addClass("collapsed-hjelpbenny");
		} else {
			jQuery(container).show();  //Show container
			jQuery(container).addClass("expanded-hjelpbenny").removeClass("collapsed-hjelpbenny");
			jQuery(this).children('img').addClass("expanded-hjelpbenny").removeClass("collapsed-hjelpbenny");
			jQuery(container).children('form').children('label').children('textarea').focus(); //Place cursor
		}
	});	
	
	hjelpbenny_truncate_all();
	
	//Benny Admin: Hide all question content and forms
	jQuery("tr.question_content").hide();
	jQuery("tr.answer_form").hide();
	
	//Clear all textareas
	jQuery("textarea.svar-textarea").val("");
	
	//Pagination (Bennys ubesvarte liste)
	jQuery(".bennys-pagination a.page").click(function() {
		adminBennyPagination(this);
	});
	
	
	//Expand/hide rows with forum post content	(BENNY-ADMIN)
	jQuery("tr.question_row a.show_question_content").click(function() {
		if (jQuery(this).parent().parent().hasClass("expanded")) {
			jQuery(this).parent().parent().next('tr').hide();  //Hide next row (post content)
			jQuery(this).parent().parent().next('tr').next('tr').hide();  //Hide next row after that (form)
			jQuery(this).parent().parent().removeClass("expanded").addClass("collapsed");  //add class to a instead
			//jQuery(this).removeClass("expanded").addClass("collapsed");
		} else {
			jQuery(this).parent().parent().next('tr').show();  //Show next row (post content)
			jQuery(this).parent().parent().next('tr').next('tr').show();  //Show next row after that (form)
			jQuery(this).parent().parent().addClass("expanded").removeClass("collapsed");  //add class to a instead
			//jQuery(this).addClass("expanded").removeClass("collapsed");
			jQuery(this).parent().parent().next('tr').next('tr').children('td').children('form').children('label').children('textarea').focus(); //Place cursor
			//Scroller ned til starten av sp�rsm�lraden
			jQuery('html,body').animate({scrollTop: jQuery(this).parent().parent().offset().top-2});
		}
	});
		
}

//Helper function, truncates ubesvarte + besvarte texts
function hjelpbenny_truncate_all() {
	//Check and run truncate on too long questions, add "see more"-link
	jQuery(".questionText").each(function() {
		var qtext = jQuery(this).html();
		if (qtext.length > trunc_length) {
			var newtext = my_truncate(qtext);
			//add "see more" link
			newtext += '... <em class="showmore-link">(<a class="read-full makelink" onclick="this.parentNode.parentNode.innerHTML='+
			'unescape(\''+escape(qtext)+'\');return false;" title="Klikk for &aring; vise hele sp&oslash;rsm&aring;let">' + 
			'Vis hele sp&oslash;rsm&aring;let<\/a>)</em>';
			jQuery(this).html(newtext);  //replace html with new text
		}
	});
	
	
	//truncate answers as well
	jQuery(".answquestionText").each(function() {
		var qtext = jQuery(this).html();
		if (qtext.length > trunc_length) {
			var newtext = my_truncate(qtext);
			//add "see more" link
			newtext += '... <em class="showmore-link">(<a class="read-full makelink" onclick="this.parentNode.parentNode.innerHTML='+
			'unescape(\''+escape(qtext)+'\');return false;" title="Klikk for &aring; vise hele sp&oslash;rsm&aring;let">' + 
			'Vis hele sp&oslash;rsm&aring;let<\/a>)</em>';
			jQuery(this).html(newtext);  //replace html with new text
		}
	});
	jQuery(".answersnippet").each(function() {
		var qtext = jQuery(this).html();
		if (qtext.length > trunc_length) {
			var newtext = my_truncate(qtext);
			//add "see more" link
			newtext += '... <em class="showmore-link">(<a class="read-full makelink" onclick="this.parentNode.parentNode.innerHTML='+
			'unescape(\''+escape(qtext)+'\');return false;" title="Klikk for &aring; vise hele svaret">' + 
			'Vis hele svaret<\/a>)</em>';
			jQuery(this).html(newtext);  //replace html with new text
		}
	});
}


function toggle_live_dropdown() {
	if (jQuery("input[name='liveonoff']").is(':checked')) {
		jQuery("select[name='select_klokkeslett']").removeAttr('disabled');
		jQuery("select[name='select_klokkeslett_halvtime']").removeAttr('disabled');
	} else {
		jQuery("select[name='select_klokkeslett']").attr('disabled', true);
		jQuery("select[name='select_klokkeslett_halvtime']").attr('disabled', true);
	}
}

//Benny Admin, Benny vil lagre live options
function benny_admin_lagre_live() {
	
	var liveToggle = 0;
	if (jQuery("#liveonoff:checked").length != 0) { liveToggle = 1; }
	
	//var dato = jQuery("#nextlivedate").val();
	var heltime = jQuery("select[name='select_klokkeslett']").val();
	var halvtime = jQuery("select[name='select_klokkeslett_halvtime']").val();
	
	//alert(liveToggle + ", "+heltime+", "+halvtime);
	//send med ajax
	jQuery.ajax({
		type: "POST",
		url: "http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/benny-admin-lagre-liveoptions.php",
		data: {
			live: liveToggle,
			//dato: dato,
			heltime: heltime,
			halvtime: halvtime
		},
		success: function(msg) {
			jQuery(".beskjeder").empty().html("Endringene er lagret!").show('slow');
			setTimeout(function(){
				jQuery('.beskjeder').hide('slow');
			},3000);
			//jQuery(".beskjeder").empty().html("Endringene er lagret!").show();
		},
		error: function(msg) {
			alert("Uh oh. Det skjedde noe feil "+msg);
		}
	});
}


//Knapp: T�m tekstfeltet (for Bennys svar)
function emptyinput(e) {
	jQuery(e).parent().children('label').children('textarea').val("");
}

//Benny har svart p� sp�rsm�l i admin, "Ubesvarte sp�rsm�l"
function benny_har_svart(e, id, parentid) {
	//Hent verdier fra inputs
	var tittel = jQuery(e).parent().children('input[name=tittel]').val();
	var svar = jQuery(e).parent().children().children('textarea').val();
	
	if (svar == "") {
		alert("Vennligst fyll inn et svar");
		jQuery(e).parent().children().children('textarea').focus();
	} else {
		//Send med ajax
	
		jQuery.ajax({
			type: "POST",
			url: "http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/benny-admin-send-svar.php",
			//contentType: "application/x-www-form-urlencoded; charset=utf-8",
			data: {
				tittel: tittel,
				svar: svar,
				post_id: id,
				parent_id: parentid
			},
			success: function(msg) {
				jQuery("#beskjeder").empty().html(msg).show('slow');
				setTimeout(function(){
					jQuery('#beskjeder').hide('slow');
				},3000);
				antall = parseInt(jQuery(".countQuestions").html());  //trekk fra 1 fra antall sp�rsm�l
				jQuery(".countQuestions").html(antall-1);
			},
			error: function(msg) {
				alert("Det skjedde noe feil");
			}
		});
	
		//Slett alle 3 radene
		jQuery(e).parent().parent().parent().prev().prev().remove(); //Slett sp�rsm�let
		jQuery(e).parent().parent().parent().prev().remove(); //Slett question content
		jQuery(e).parent().parent().parent().remove(); //Slett form
		
	}
	
}

//Benny vil slette tr�d
function benny_vil_slette(e, id, parentid) {
	if (confirm("Er du sikker p" + unescape('%E5') + " at du vil slette dette sp" + unescape('%F8') + "rsm" + unescape('%E5') + "let?")) {
		jQuery.ajax({
			type: "POST",
			url: "http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/benny-admin-slett-spml.php",
			data: {
				'postid': id,
				'threadid': parentid
			},
			success: function(msg) {
		    	//alert?
		    	//jQuery("#beskjeder").empty().html(msg).show();	//T�m, skriv og vis beskjed
				
				jQuery("#beskjeder").empty().html(msg).show('slow');
				setTimeout(function(){
					jQuery('#beskjeder').hide('slow');
				},3000);
				antall = parseInt(jQuery(".countQuestions").html());  //trekk fra 1 fra antall sp�rsm�l
				jQuery(".countQuestions").html(antall-1);
			},
			error: function(msg) {
				//alert("Uh oh. Det skjedde noe feil");
			}
		});
		
		//Fjern sp�rsm�lradene. Jeg f�r ikke til � bruke remove p� form og q-content, s� de ligger skjult til page reload
		if (jQuery(e).parent().parent().hasClass("expanded")) {
			jQuery(e).parent().parent().next('tr').next('tr').hide();
			jQuery(e).parent().parent().next('tr').hide();
		}
		jQuery(e).parent().parent().remove();
	}
}

//Svart på spørsmål i Hjelp Benny
function jeg_vil_svare(e, threadId) {
	//Hent verdier fra inputs
	var tittel = jQuery(e).parent().children('input').val();
	var svar = jQuery(e).parent().children('textarea').val();
	
	if (svar == "") {
		alert("Vennligst fyll inn et svar");
		jQuery(e).parent().children().children('textarea').focus();
	} else {
		//Send med ajax
		jQuery.ajax({
			type: "POST",
			url: "../wp-content/themes/broom/benny-admin-send-svar.php",
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			data: {
				tittel: tittel,
				svar: svar,
				thread_id: threadId
			},
			success: function(msg) {
				jQuery('#fs_thread_'+threadId).remove();
				jQuery('#answerlist').empty();
				var params = '';
				if (jQuery('#bennybilmodeller').is(":visible") == true) {
					params = {'rand':Math.random(),'bilmerkeid':jQuery('#bennybilmerker').val(), 'bilserieid':jQuery('#bennybilmodeller').val()};
				} else {
					params = {'rand':Math.random(),'bilmerkeid':jQuery('#bennybilmerker').val()};
				}
				jQuery.ajax({
					url: '../wp-content/themes/broom/hjelp-benny-stream-answers.php',
					data : params,
					success: function(data) {
						jQuery('#answerlist').html(data);							
					}
				});
				
				//Pagination (Hjelp Benny besvarte)
				jQuery("ul#answerlist a.page").click(function() {
					hjelpBenny_answers_pagination(this);
				});
				/*jQuery("#beskjeder").empty().html(msg).show('slow');
				setTimeout(function(){
					jQuery('#beskjeder').hide('slow');
				},7000);
				antall = parseInt(jQuery(".countQuestions").html());  //trekk fra 1 fra antall sp�rsm�l
				jQuery(".countQuestions").html(antall-1);*/
			},
			error: function(msg) {
				alert("Det skjedde noe feil");
			}
		});
	
	}
	
}

var EonbitApi = {
	getCarmodels : function (select) {
		if (jQuery(select).val() > 0) {
			jQuery.getJSON('http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/carmodels.php', {'make_id':jQuery(select).val()}, function(data) {
				jQuery('#bennybilmodeller').empty();
				jQuery('#bennybilmodeller').append('<option value="0">Alle modeller</option>');
				jQuery.each(data, function(i, item) {
					jQuery('#bennybilmodeller').append('<option value="'+item.id+'">'+item.name+'</option>');
				});
				
				jQuery('#questionlist').empty();
				jQuery.ajax({
					url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/hjelp-benny-stream-questions.php',
					data : {'bilmerkeid':jQuery(select).val()},
					success: function(data) {
						jQuery('#questionlist').html(data);
						init_help_benny_questions();
						hjelpbenny_truncate_all();
					}
				});
				jQuery('#answerlist').empty();
				jQuery.ajax({
					url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/hjelp-benny-stream-answers.php',
					data : {'bilmerkeid':jQuery(select).val()},
					success: function(data) {
						jQuery('#answerlist').html(data);
						hjelpbenny_truncate_all();				
					}
				});
				jQuery('#bennybilmodeller').show();
			});
		} else {
			jQuery('#bennybilmodeller').empty();
			jQuery('#bennybilmodeller').hide();
			jQuery('#questionlist').empty();
			jQuery.ajax({
				url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/hjelp-benny-stream-questions.php',
				data : {},
				success: function(data) {
					jQuery('#questionlist').html(data);	
					init_help_benny_questions();
					hjelpbenny_truncate_all();
				}
			});
			jQuery('#answerlist').empty();
			jQuery.ajax({
				url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/hjelp-benny-stream-answers.php',
				data : {},
				success: function(data) {
					jQuery('#answerlist').html(data);
					hjelpbenny_truncate_all();							
				}
			});
		}
	}, 
	updateStream : function (select) {
		if (jQuery(select).is(":visible") == true) {
			jQuery('#questionlist').empty();
			jQuery.ajax({
				url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/hjelp-benny-stream-questions.php',
				data : {'bilmerkeid':jQuery('#bennybilmerker').val(), 'bilserieid':jQuery(select).val()},
				success: function(data) {
					jQuery('#questionlist').html(data);
					init_help_benny_questions();
					hjelpbenny_truncate_all();
				}
			});
			jQuery('#answerlist').empty();
			jQuery.ajax({
				url: 'http://tv2-wordpress.eonbit.com/benny/wp-content/themes/broom/hjelp-benny-stream-answers.php',
				data : {'bilmerkeid':jQuery('#bennybilmerker').val(), 'bilserieid':jQuery(select).val()},
				success: function(data) {
					jQuery('#answerlist').html(data);					
				}
			});
		}
	}
}

