var stdFade = 0.25;
var standardlistfade = 1;

var ProductGuide = {
	'answer1': null,
	'answer2': null,
	'answer3': null,
	'answer4': null,
	'answer5': null,
	'answer6': null
}


$.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});


function showContact() {
	$('#z11').show();
	$('#z12').show();
	$('#z13').show();
	$('#z1').hide();
	$('#z2').hide();
	$('#z3').hide();
	$('#z4').hide();
	$('#z5').hide();
	$('#z6').hide();
	$('#z8').hide();
}

function showForm() {
	$('#z1').show();
	$('#z2').show();
	$('#z3').show();
	$('#z4').show();
	$('#z5').show();
	$('#z6').show();
	$('#z8').show();
	$('#z11').hide();
	$('#z12').hide();
	$('#z13').hide();
}

function showList() {
	$('#list').show();
	$('#single').hide();
}

function showSingle(uid) {
	$.getJSON(
		getDialogLink(),
		{zone: 'single', uid: uid},
		function(data){
			if (data.noerror) {
				$('#single > div > h1').html(data.name);
				$('#single > p > img').attr('src', data.imgsrc);
				$('#single > p > img').attr('alt', data.name);
				$('#single > div > h1').next().html(data.html);
				$('#list').hide();
				$('#single').show();
			}
		}
	);
}

function reset() {
	cleanQ2_Q6();
	cleanQ7() ;
	$('#q1 input').attr('value', '');
	$('#list img').fadeTo('fast', standardlistfade);
	showList();
}

// Produktliste
function initList(){
	$.getJSON(
		getDialogLink(),
		{zone: 'list', action: 'init'},
		function(data) {
			if (data.noerror) {
				var i = 0;
				$.each(data.products, function(idx, prod) {
					i++;
					var pnr = '#prod'+i;
					$(pnr).attr('src', prod.imgsrc);
					$(pnr).attr('alt', prod.name);
					$(pnr).attr('name', prod.id);
					$(pnr).attr('title', 'Produktdetail');
				});
			}
		}
	);
}

// Fragen und Hilfetexte laden
function initHelp(){
  $.getJSON(
    getDialogLink(),
    {zone: 'form', action: 'inithelp'},
    function(list) {
      //alert('noerror: ' + list.noerror);
      if (list.noerror) {
        $.each(list.elements, function(idx, elem){
          nr = parseInt(elem.pos) + 1;
          //alert('#loadme' + nr + "\n"+ elem.help +"\n" + '#q' + nr + ' > div.label'+"\n"+elem.quest);
          $('#loadme' + nr).html(elem.help);
          $('#q' + nr + ' div.label').html(elem.quest);
        });
      }
    }
  );
}

// Frage1: Anwortmöglichkeiten und Status
function initQ1(){
	$.getJSON(
		getDialogLink(),
		{zone: 'form', action: 'initQ1'},
		function(list) {
			if (list.noerror) {
				str = '';
				$('#was').html(str);
				$.each(list.elements, function(idx, elem) {
					str += '<option value="'+elem.uid+'">'+elem.title+'</option>';
				});
				$('#was').html(str);
			}
		}
	);
}

// Fragen 2 bis 6: Anwortmöglichkeiten und Status
function initQ2_Q6(qx){
  $.getJSON(
    getDialogLink(),
    {zone: 'form', action: 'initQN', qx: qx},
    function(list) {
      //alert('qx: ' + qx + ', debug: ' + list.debug);
      switch (list.render * 1) {

        case 2:
          if (list.options) renderQ2(list);
          break;

        case 3:
          if (list.options) renderQ3(list);
          break;

        case 4:
          if (list.options) renderQ4(list);
          break;

        case 5:
          if (list.options) renderQ5(list);
          break;

        case 6:
          if (list.options) renderQ6(list);
          break;

        case 7:
          $('#q7').fadeTo('fast', 1);
          $('#z7 img').fadeTo('fast', 1);
          ableProducts();
          break;

        default:
          break;

      }
    }
  );
}

function renderQ2(list) {
	cleanQ3() ;
	cleanQ4() ;
	cleanQ5() ;
	cleanQ6() ;
	cleanQ7() ;
	
	var str = '';
	$.each(list.elements, function(idx, elem){
		str +=
			'<input onclick="submitQ2(this.value)" value="'+elem.uid+'" type="radio" id="rA'+elem.uid+'" name="radioA" />' +
			'<label for="rA'+elem.uid+'">'+elem.title+'</label>';
	});
	$('#radioA').html(str);
	$("#radioA").buttonset();
	$('#q2').fadeTo('fast', 1);
	$('#z2 img').fadeTo('fast', 1);
}

function renderQ3(list) {
	if (ProductGuide.answer2 == null) ProductGuide.answer2 = -1 ;
	
	cleanQ4() ;
	cleanQ5() ;
	cleanQ6() ;
	cleanQ7() ;
	
	str = '';
	$.each(list.elements, function(idx, elem){
		str += '<option value="'+elem.uid+'">'+elem.title+'</option>';
	});
	$('#trocken').html(str);
	$('#q3').fadeTo('fast', 1);
	$('#z3 img').fadeTo('fast', 1);
}

function renderQ4(list) {
	if (ProductGuide.answer2 == null) ProductGuide.answer2 = -1 ;
	if (ProductGuide.answer3 == null) ProductGuide.answer3 = -1 ;
	
	cleanQ5() ;
	cleanQ6() ;
	cleanQ7() ;
	
	str = '';
	$.each(list.elements, function(idx, elem){
		str +=
			'<input onclick="submitQ4(this.value)" value="'+elem.uid+'" type="radio" id="rB'+elem.uid+'" name="radioB" />' +
			'<label for="rB'+elem.uid+'">'+elem.title+'</label>';
	});
	$('#radioB').html(str);
	$("#radioB").buttonset();
	$('#q4').fadeTo('fast', 1);
	$('#z4 img').fadeTo('fast', 1);
}

function renderQ5(list) {
	if (ProductGuide.answer2 == null) ProductGuide.answer2 = -1 ;
	if (ProductGuide.answer3 == null) ProductGuide.answer3 = -1 ;
	if (ProductGuide.answer4 == null) ProductGuide.answer4 = -1 ;
	
	cleanQ6() ;
	cleanQ7() ;
	
	str = '';
	$.each(list.elements, function(idx, elem){
		str +=
			'<input onclick="submitQ5(this.value)" value="'+elem.uid+'" type="radio" id="rC'+elem.uid+'" name="radioC" />' +
			'<label for="rC'+elem.uid+'">'+elem.title+'</label>';
	});
	$('#radioC').html(str);
	$("#radioC").buttonset();
	$('#q5').fadeTo('fast', 1);
	$('#z5 img').fadeTo('fast', 1);
}

function renderQ6(list) {
	if (ProductGuide.answer2 == null) ProductGuide.answer2 = -1 ;
	if (ProductGuide.answer3 == null) ProductGuide.answer3 = -1 ;
	if (ProductGuide.answer4 == null) ProductGuide.answer4 = -1 ;
	if (ProductGuide.answer5 == null) ProductGuide.answer5 = -1 ;
	
	cleanQ7() ;
	
	str = '';
	$.each(list.elements, function(idx, elem){
		str +=
			'<input onclick="submitQ6(this.value)" value="'+elem.uid+'" type="radio" id="rD'+elem.uid+'" name="radioD" />' +
			'<label for="rD'+elem.uid+'">'+elem.title+'</label>';
	});
	$('#radioD').html(str);
	$("#radioD").buttonset();
	$('#q6').fadeTo('fast', 1);
	$('#z6 img').fadeTo('fast', 1);
}

function cleanQ2_Q6() {
	ProductGuide.answer2 = null ;
	ProductGuide.answer3 = null ;
	ProductGuide.answer4 = null ;
	ProductGuide.answer5 = null ;
	ProductGuide.answer6 = null ;
	
	cleanQ2() ;
	cleanQ3() ;
	cleanQ4() ;
	cleanQ5() ;
	cleanQ6() ;

}

function cleanQ2() {
	$('#q2').fadeTo('fast', stdFade);
	$('#z2 img').fadeTo('fast', stdFade);
	var str =
		'<input value="" type="radio" id="rA1" name="radioA" />' +
		'<label for="rA1">-</label>'+
		'<input value="" type="radio" id="rA2" name="radioA" />' +
		'<label for="rA2">-</label>';
	$('#radioA').html(str);
	$("#radioA").buttonset();
}

function cleanQ3() {
	$('#q3').fadeTo('fast', stdFade);
	$('#z3 img').fadeTo('fast', stdFade);
	str = '<option value=""> </option>';
	$('#trocken').html(str);
	$('#q3 input').attr('value', '');
}

function cleanQ4() {
	$('#q4').fadeTo('fast', stdFade);
	$('#z4 img').fadeTo('fast', stdFade);
	str =
		'<input value="" type="radio" id="rB1" name="radioB" />' +
		'<label for="rB1">-</label>'+
		'<input value="" type="radio" id="rB2" name="radioB" />' +
		'<label for="rB2">-</label>'+
		'<input value="" type="radio" id="rB3" name="radioB" />' +
		'<label for="rB3">-</label>';
	$('#radioB').html(str);
	$("#radioB").buttonset();
}

function cleanQ5() {
	$('#q5').fadeTo('fast', stdFade);
	$('#z5 img').fadeTo('fast', stdFade);
	str =
		'<input value="" type="radio" id="rc1" name="radioC" />' +
		'<label for="rc1">-</label>'+
		'<input value="" type="radio" id="rc3" name="radioC" />' +
		'<label for="rc3">-</label>'+
		'<input value="" type="radio" id="rc2" name="radioC" />' +
		'<label for="rc2">-</label>';
	$('#radioC').html(str);
	$("#radioC").buttonset();
}

function cleanQ6() {
	$('#q6').fadeTo('fast', stdFade);
	$('#z6 img').fadeTo('fast', stdFade);
	str =
		'<input value="" type="radio" id="rD1" name="radioD" />' +
		'<label for="rD1">-</label>'+
		'<input value="" type="radio" id="rD2" name="radioD" />' +
		'<label for="rD2">-</label>';
	$('#radioD').html(str);
	$("#radioD").buttonset();
}

function cleanQ7() {
	$('#q7').fadeTo('fast', stdFade);
	$('#z7 img').fadeTo('fast', stdFade);
	$('#q7 input').attr('value','Ihre PLZ') ;
}


function submitQ2(v) {
	ProductGuide.answer2 = v ;
	ProductGuide.answer3 = null ;
	ProductGuide.answer4 = null ;
	ProductGuide.answer5 = null ;
	ProductGuide.answer6 = null ;
	
	initQ2_Q6(3);
	ableProducts();
}

function submitQ4(v) {
	ProductGuide.answer4 = v ;
	ProductGuide.answer5 = null ;
	ProductGuide.answer6 = null ;
	
	initQ2_Q6(5);
	ableProducts();
}

function submitQ5(v) {
	ProductGuide.answer5 = v ;
	ProductGuide.answer6 = null ;
	
	initQ2_Q6(6) ;
	ableProducts() ;
}

function submitQ6(v) {
	ProductGuide.answer6 = v ;
	
	$('#q7').fadeTo('fast', 1);
	$('#z7 img').fadeTo('fast', 1);
	ableProducts();
}

function ableProducts() {
	$('#single').hide();
	
	// If Text, show text, else ableProducts
	var infotextRes = $.ajax({
		url: getDialogLink(),
		data: {zone: 'infotext'},
		async: false
	}).responseText ;
	
	if (infotextRes == '') {
		$('#productguide-infotext').hide() ;
		$('#list').show();
		
		$.getJSON(
			getDialogLink(),
			{zone: 'get_products'},
			function(data2) {
				$.each(data2.able, function(i, val) {
					name = '#list img[name="' + i + '"]';
					if (val) $(name).fadeTo('fast', 1);
					else $(name).fadeTo('fast', stdFade);
				});
			}
		);
	} else {
		$('#productguide-infotext').html(infotextRes) ;
		$('#productguide-infotext').show() ;
		$('#list').hide();
	}
}


// autocomplete Combobox Frage1
$.widget("ui.combobox1", {
	_create: function() {
		var self = this;
		var select = this.element.hide();
		
		var input = $("<input>")
			.insertAfter(select)
			.autocomplete({
				source: function(request, response) {
					var matcher = new RegExp(request.term, "i");
					response(select.children("option").map(function() {
						var text = $(this).text();
						if (!request.term || matcher.test(text))
							return {
								id: $(this).val(),
								label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
								value: text
							};
					}));
				},
				delay: 0,
				select: function(e, ui) {
					if (!ui.item) {
						// remove invalid value, as it didn't match anything
						$(this).val("");
						return false;
					}
					$(this).focus();
					select.val(ui.item.id);
					self._trigger("selected", null, {
						item: select.find("[value='" + ui.item.id + "']")
					});
					
					ProductGuide.answer1 = ui.item.id ;
					ProductGuide.answer2 = null ;
					ProductGuide.answer3 = null ;
					ProductGuide.answer4 = null ;
					ProductGuide.answer5 = null ;
					ProductGuide.answer6 = null ;
					
					cleanQ2_Q6();
					$('#list img').fadeTo('fast', standardlistfade);
					$('#q7').fadeTo('fast', stdFade);
					$('#z7 img').fadeTo('fast', stdFade);
					
					ableProducts();
					initQ2_Q6(2);
				},
				minLength: 0
			})
			.addClass("ui-widget ui-widget-content ui-corner-left");
		
		$("<button>&nbsp;</button>")
			.insertAfter(input)
			.button({
				icons: {
					primary: "ui-icon-triangle-1-s"
				},
				text: false
			})
			.removeClass("ui-corner-all")
			.addClass("ui-corner-right ui-button-icon")
			.position({
				my: "left center",
				at: "right center",
				of: input,
				offset: "-1 0"
			}).
			css("top", "")
			.click(function() {
				// close if already visible
				if (input.autocomplete("widget").is(":visible")) {
					input.autocomplete("close");
					return;
				}
				// pass empty string as value to search for, displaying all results
				input.autocomplete("search", "");
				input.focus();
			});
		}
});

// autocomplete Combobox Frage3
$.widget("ui.combobox2", {
	_create: function() {
		var self = this;
		var select = this.element.hide();
		
		var input = $("<input>")
			.insertAfter(select)
			.autocomplete({
				source: function(request, response) {
					var matcher = new RegExp(request.term, "i");
					response(select.children("option").map(function() {
						var text = $(this).text();
						if (!request.term || matcher.test(text))
							return {
								id: $(this).val(),
								label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
								value: text
							};
					}));
				},
				delay: 0,
				select: function(e, ui) {
					if (!ui.item) {
						// remove invalid value, as it didn't match anything
						$(this).val("");
						return false;
					}
					$(this).focus();
					select.val(ui.item.id);
					self._trigger("selected", null, {
						item: select.find("[value='" + ui.item.id + "']")
					});
					
					ProductGuide.answer3 = ui.item.id ;
					ProductGuide.answer4 = null ;
					ProductGuide.answer5 = null ;
					ProductGuide.answer6 = null ;
					
					initQ2_Q6(4);
					ableProducts();
				},
				minLength: 0
			})
			.addClass("ui-widget ui-widget-content ui-corner-left");
		
		$("<button>&nbsp;</button>")
			.insertAfter(input)
			.button({
				icons: {
					primary: "ui-icon-triangle-1-s"
				},
				text: false
			})
			.removeClass("ui-corner-all")
			.addClass("ui-corner-right ui-button-icon")
			.position({
				my: "left center",
				at: "right center",
				of: input,
				offset: "-1 0"
			})
			.css("top", "")
			.click(function() {
				// close if already visible
				if (input.autocomplete("widget").is(":visible")) {
					input.autocomplete("close");
					return;
				}
				// pass empty string as value to search for, displaying all results
				input.autocomplete("search", "");
				input.focus();
			});
	}
});

function openDialog() {
	$("select#was").combobox1(); // Frage 1
	$("select#trocken").combobox2(); // Frage 2
	
	// Buttons
	$("#reset").button().click(function(){
		reset();
	});
	
	$("#start").button().click(function(){
		showForm();
	});
	
	$("#produkte").button().click(function(){
		showList();
	});
	
	$("#radioA").buttonset(); // Frage 2
	$("#radioB").buttonset(); // Frage 4
	$("#radioC").buttonset(); // Frage 5
	$("#radioD").buttonset(); // Frage 6
	
	// Frage 7
	$('input#plz').focus(function(){
		$(this).val("");
	}).change(function(){
		$.getJSON(
			getDialogLink(),
			{zone: 'contact', plz: $(this).val()},
			function(data){
				if (data.noerror){
					$('#z11 > td > h1').html(data.name);
					$('#z11 > td > p > img').attr('src', data.imgsrc);
					$('#z11 > td > p > img').attr('alt', data.name);
					$('#z11 > td > h1').next().html(data.html);
					showContact();
				}
			}
		);
	});
	
	// Produkt single
	$('td.list > img').click(function() {
		showSingle($(this).attr('name'));
	});
	
	// TooTip (clueTip)
	$('a.load-local').cluetip({
		local:true,
		cursor:'pointer',
		arrows:true,
		width:280,
		showTitle:false,
		leftOffset:50,
		hoverIntent: {
			sensitivity:  1,
			interval:     150,
			timeout:      150
		}
	});
	
	// Dialog
	$('#dialog').dialog({
		width: 940,
		title: '<h1><span class="addcon-dialog-title">ADDCON</span> Product Guide</h1>',
		position: ['center', 25], // geändert: 25px von oben
		draggable: false,         // neu: Fenster nicht verschiebbar
		autoOpen: false,
		modal: true,
		resizable: false,
		zIndex: 50,
		close: function(event, ui) {
			// Layer entfernen
			$('div.tx-addconproductsview-pi1').remove();
			$('ul.ui-autocomplete').remove();
			$('#cluetip-waitimage').remove();
			$('#cluetip').remove();
			$('div.ui-widget-overlay').remove();
			$('div.ui-dialog').remove();
			$('div#dialog').remove();
		}
	});
	
	initList();
	cleanQ2_Q6();
	initQ1();
	$('#q7').fadeTo('fast', stdFade);
	$('#z7 img').fadeTo('fast', stdFade);
	initHelp();
	
	$('#dialog').dialog('open');
	showForm();
	showList();
	
	$('#was').focus();
}
