var sb_cleared = false;
var qb_cleared = false;
var timer = false;
var lastLoad = false;
var introText = "Please describe your problem, or ask a question here";
var suggestText = "Please enter your suggestion for a how to article here";
var formElement = false;
var specialNoticeOpen = false;
var specialNoticeText;

var postLBFunc = function() {
	$$('textarea.suggestion').each(function(el,i) {
		sb_cleared = false;
		$$('textarea.suggestion').set('value',suggestText);
	  $$('textarea.suggestion').setStyle('color','#525053');
	  $$('textarea.suggestion').setStyle('font-style','italic');
		
		$$('textarea.suggestion').addEvent('focus',function() {
			$$('textarea.suggestion').setStyle('color','#000');
	    $$('textarea.suggestion').setStyle('font-style','inherit');
			if (sb_cleared) return;
			$$('textarea.suggestion').set('value','');
			sb_cleared = true;
		});
	});
	
	$$('#TB_ajaxContent form.suggestion_form').addEvent('submit', function(e) {
		new Event(e).stop();
		formElement = this.parentNode;
		var formRequest = new Form.Request(this, false, {
			onSend: function(e) {
				formElement.parentNode.tween('height','50px');
				formElement.set('html','We\'re submitting your suggestion. Please wait.');
			},
			onFailure: function(response) {
				formElement.set('html','An error occurred during submitting. Please try again later.');
			},
			onSuccess: function(response) {
				formElement.set('html','Your suggestion has been received and will be considered shortly');
			}
		});
		formRequest.send();
	});
}

window.addEvent('domready',function() {
	var value = $('question_box').get('value');
	if (value != "" && value != introText) {
		ajaxLoad();
	} else {
		resetQuestionBox();
	}
	
	$('question_box').addEvent('focus',function() {
		if (qb_cleared) return;
		$('question_box').set('value','');
		$('question_box').setStyle('color','inherit');
    $('question_box').setStyle('font-style','inherit');
		qb_cleared = true;
	});
	
	$('question_box').addEvent('keyup',function(e) {
		if (timer !== false) window.clearTimeout(timer);
		if (e.code == 13) {
			var val = $('question_box').value;
			$('question_box').value = val.replace(/^\s+|\s+$/g,"");
			ajaxLoad();
			return;
		}
		var val = $('question_box').get(value);
		if (val == "") return;
		timer = window.setTimeout(ajaxLoad,500);
	});
	
	$('question_form').addEvent('submit',function(e) {
		e.preventDefault();
		if (timer !== false) window.clearTimeout(timer);
		ajaxLoad();
	});
	
	specialNotice();
	
});

function getProtocol() {
	if (document.location.protocol == "https:") return "https://"; else return "http://";
}

function specialNotice() {
	if ($('special_notice')) {
		//Hide the special notice as the browser supports JS.
		$('special_notice_details').setStyle('height','0px');
		$('special_notice_details').setStyle('display','none');
		$('open_special_notice').setStyle('display','block');
		
		$('open_special_notice').addEvent('click', function() {
			if (specialNoticeOpen) {
				specialNoticeOpen = false;
				$('open_special_notice').set('html',specialNoticeText);
				$('special_notice_details').tween('height','0px');
				var func = function() {
					$('special_notice_details').setStyle('display','none');
				}.delay(500);
			} else {
				specialNoticeOpen = true;
				specialNoticeText = $('open_special_notice').get('html');
				$('open_special_notice').set('html','Close');
				$('special_notice_details').setStyle('display','block');
				$('special_notice_details').tween('height','205px');
			}
		});
	
	}
}

function initLightbox() {
	TB_init();
}

function ajaxLoad() {
	var val = $('question_box').get('value');
	if (val.trim() == "" || val == introText) return;
	if (lastLoad != false && lastLoad == val) return;
	lastLoad = val;
	$('load_spinner').setStyle('display','block');
	
	var jsonRequest = new Request.JSON({
		url: getProtocol()+window.location.hostname+'/ajax_search.php',
		onFailure: function() {
			handleFailure();
		},
		onSuccess: function(data, text) {
			handleSuccess(data);
		}
	}).post({'search': val});
}

function handleFailure() {
	$('load_spinner').setStyle('display','none');
	$('results').setStyle('display','block');
	var replace_html = '<div class="ajaxerror">An error occurred while loading your search results</div>';
	replace_html += '<div id="suggesthowto"><a href="#TB_inline?height=130&width=670&inlineId=proposeHowTo" title="Suggest a How To topic" class="smoothbox">Would you like to suggest a how to topic?</a></div>';
	resultsTween(replace_html);
};
	
function handleSuccess(data) {
	$('load_spinner').setStyle('display','none');
	$('results').setStyle('display','block');
	if (data != null && typeof(data.state) == "string") {
		if (data.state == "ok") {
			$('results').setStyle('display','block');
			var result_type = false;
			var replace_html = "";
			var altClass = " altRow";
			var total = data.results.length - 1;
			data.results.each(function(result,i){
				var newhtml = "";
				if (result_type == false || result_type != result.type) {
					var useclass = "section_title";
					if (result_type == false) var useclass = "section_title first";
					result_type = result.type;
					if (result.type == "howto") {
						newhtml += "<div class='"+useclass+"'>How To Articles</div>";
					} else if (result.type == "faq") {
						newhtml += "<div class='"+useclass+"'>Frequently Asked Questions</div>";
					} else {
						newhtml += "<div class='"+useclass+"'>"+result.type.toUpperCase()+"s</div>";
					}
				}
				if (altClass == " altRow") {
					altClass = " normRow";
				} else {
					altClass = " altRow";
				}
				newhtml += "<div class='search_result"+altClass;
				if (total == i || data.results[i+1].type != result.type) newhtml += " finalRow";
				newhtml += "' ";
				if (result.type == "faq") {
					newhtml += "alt='http://"+window.location.hostname+"/"+result.faqloc+"/faq#"+result.id+"'>";
				} else {
					newhtml += "alt='http://"+window.location.hostname+"/support/howto/article/"+result.id+"'>";
				}
				if (result.type == "faq") {
					newhtml += "<a class='support_link' href='http://"+window.location.hostname+"/"+result.faqloc+"/faq#"+result.id+"'>";
				} else {
					newhtml += "<a class='support_link' href='http://"+window.location.hostname+"/support/howto/article/"+result.id+"'>";
				}
				newhtml += result.text+"</a></div>";
				replace_html += newhtml;
    	});
			replace_html += '<div id="suggesthowto"><a href="#TB_inline?height=130&width=670&inlineId=proposeHowTo" title="Suggest a How To topic" class="smoothbox">Would you like to suggest a how to topic?</a></div>';
    	resultsTween(replace_html);
    	register_mouseovers();
    } else {
    var replace_html = '<div class="ajaxerror">'+data.error+'</div>';
		replace_html += '<div id="suggesthowto"><a href="#TB_inline?height=130&width=670&inlineId=proposeHowTo" title="Suggest a How To topic" class="smoothbox">Would you like to suggest a how to topic?</a></div>';
    resultsTween(replace_html);
    }
	} else {
		//Submit the form, as we've had an AJAX error and render without Javascript
		$('question_form').submit();
	}
	initLightbox();
	step2_trigger();
}

function resetQuestionBox() {
	$('question_box').set('value',introText);
  $('question_box').setStyle('color','#525053');
  $('question_box').setStyle('font-style','italic');
	qb_cleared = false;
	lastLoad = false;
}

function step2_trigger() {
	$('supportform_step2').removeClass('inactive');
	$('supportform_step2').setStyle('cursor','pointer');
	$('step2_text').set('html','If you were unable to find the answer to your question, click here to contact support');
	$('supportform_step2').addEvent('click',function() {
		openStep2();
	});
}

function openStep2() {
	resetQuestionBox();
	$('results_container').tween('height','0px');
	clearResults.delay(500);
	$('supportform_step2').setStyle('cursor','default');
	$('supportform_step2').tween('height','275px');
	$('step2_header').tween('paddingTop','10px');
	$('step2_text').set('html','To contact support, please fill in the following form');
	$('support_form').tween('height','225px');
	step3_trigger();
}

function step3_trigger() {
	$('supportform_step3').removeClass('inactive');
	$('supportform_step3').setStyle('cursor','pointer');
	$('support_phonedetails').setStyle('height','0px');
	$('step3_header').tween('paddingTop','25px');
	$('step3_text').set('html','If you encounter an issue submitting a ticket above, you can contact us by phone<br />Click here for our telephone contact details');
	$('supportform_step3').addEvent('click',function() {
		openStep3();
	});
}

function openStep3() {
	resetStep2();
	$('supportform_step3').setStyle('cursor','default');
	$('supportform_step3').tween('height','100px');
	$('step3_header').tween('paddingTop','10px');
	$('step3_text').set('html','');
	$('support_phonedetails').tween('height','55px');
}

function resetStep2() {
	$('supportform_step2').tween('height','100px');
	$('supportform_step2').setStyle('cursor','pointer');
	$('step2_header').tween('paddingTop','28px');
	$('step2_text').set('html','If you were unable to find the answer to your question, click here to contact support');
	$('support_form').tween('height','0px');
}

function clearResults() {
	$('results').set('html','');
}

var lastColor;
function register_mouseovers() {
	$$('.search_result').setStyle('cursor','pointer');

	$$('.search_result').addEvent('mouseover',function() {
		lastColor = $(this).getStyle('backgroundColor');
		$(this).setStyle('backgroundColor','#525053');
		$(this.firstChild).setStyle('color','#fff');
	});
	
	$$('.search_result').addEvent('mouseout',function() {
		$(this).setStyle('backgroundColor',lastColor);
		$(this.firstChild).setStyle('color','#000');
	});
	
	$$('.search_result').addEvent('click',function() {
		window.location = $(this).get('alt');
	});
}

function resultsTween(html) {
	$('problem').set('value',$('question_box').get('value'));
	var el = $('results_container');
	el.setStyle('overflow','hidden');
	var current = $('results').getSize();
	$('results').set('html',html);
	var next = $('results').getSize();
	el.setStyle('height',current.y);
	el.tween('height',next.y);
}
