function openWebchat(locale) {
	if(locale == null ) {
		locale = 'en';
	}
	
	var d = new Date();
	
	$.getJSON('/support/webchat/checkHours.json?' + d.getTime(), function(data) {
		if(data.inHours == false) {
			afterHoursDialog(locale);
		} else {
			webchatDialog(locale);
		}
	});
}

function webchatDialog(locale) {
	var d = new Date();
	
	$("#webchat-dialog").load('/support/webchat/' + locale + '/form-ajax.xhtml?' + d.getTime(),
		// Anonymous function after ajax load.
		function() {
			$("#webchat-submit").button();
			$("#questions").change(checkQuestionsLength);
			$("#questions").keyup(checkQuestionsLength);
			$("#questions").keypress(checkQuestionsLength);
			$("#questions").keydown(checkQuestionsLength);
		}
	);
	$("#webchat-dialog").dialog({
		width: 500,
		minHeight: 350,
		modal:true,
		resizable: false,
		show: "fade"
		});
}

function afterHoursDialog(locale) {
	var d = new Date();
	$("#after-hours-dialog").load('/support/webchat/' + locale + '/afterhours-ajax.xhtml?' + d.getTime(),
		function() {
			$("#after-hours-button").button();
		}
	);
	
	$("#after-hours-dialog").dialog({
		width: 400,
		minHeight: 200,
		resizable: false,
		modal: true,
		show: "fade"
	});
}

function submitWebChatForm() {
	var form = document.webchatForm;
	var language = form.language.value;
	var name = encodeURIComponent(form.name.value);
	var accountNumber = encodeURIComponent(form.accountNumber.value);
	var stateSelect = form.state;
	var state = encodeURIComponent(stateSelect.options[stateSelect.selectedIndex].value);
	var questions = encodeURIComponent(form.questions.value);
	
	var url = "https://" + window.location.host + "/HPPCEnterpriseWeb/hppcwebchat?";
	url += "varUserRequest=REQ_JS_START" +
		"&varHPPCLanguage=" + language + 
		"&k_language=" + language +
		"&k_company=INFINITE" +
		"&k_name=" + name + 
		"&k_accountnumber=" + accountNumber + 
		"&k_state=" + state + 
		"&k_questions=" + questions + 
		"&k_referrer=" + encodeURIComponent(window.location);

	window.open(url,'InvWin',
			'width=600,height=500,toolbar=0,directories=0,menubar=0,status=0,resizable=0,location=0,scrollbars=0,copyhistory=0,left=100,top=50');

	destroyWebchat();
	
}

function destroyWebchat() {
	$("#webchat-dialog").dialog("destroy");
	$("#after-hours-dialog").dialog("destroy");
}

var QMAX = 150;
function checkQuestionsLength() {
	if (this.value.length > QMAX) {
		this.value = this.value.substring(0, QMAX);
		
	}
	$("#questions-length").text( (QMAX - this.value.length) );
}