var slider_width = 264;
var handle_width = 12;
var typ_selection = null;
var such_art_selection = null;
var next_page = 1;
var current_step = 'step-1';

if (!console)
	var console = {log: function() { }}

function get_post_data()
{
	var list = []
	function append_fields(fields)
	{
		fields.each(function (i, el) {
			list.push($(el));
		});
	}
	append_fields($('#wizard .post-data input:text'));
	append_fields($('#wizard .post-data input:checked'));
	append_fields($('#wizard .post-data select'));
	append_fields($('#wizard .filter-line.typ-' + typ_selection + ' .filter-weight input:checked'));
	append_fields($('#wizard .filter-select.typ-' + typ_selection + ' input:text'));
	append_fields($('#wizard .filter-select.typ-' + typ_selection + ' input:checked'));
	append_fields($('#wizard .filter-select.typ-' + typ_selection + ' select'));
	append_fields($('#wizard input:text.typ-' + typ_selection));
	append_fields($('#wizard input:checked.typ-' + typ_selection));
	append_fields($('#wizard select.typ-' + typ_selection));
	var post_data = {};
	$.each(list, function (i, el) {
		var name = el.attr('name');
		var l = name.length;
		name = name.replace(/^_+/, '');
		if (name.substr(l - 2) == '[]')
		{
			if (!post_data[name])
				post_data[name] = [];
			post_data[name].push(el.val());
		}
		else
		{
			post_data[name] = el.val();
		}
	});
	dkamera.log(post_data);
	post_data["anti_cache"] = Math.floor(Math.random()*999);
	return post_data;
}

function show_results()
{
	next_page = 1;
	$('#wizard #results-box').html($('#wizard #loading').html());
	$('#wizard #results-box').append($('<p>Ergebnisse werden geladen...</p>'));
	var post_data = get_post_data();
	$('#wizard #results-box').load('/digitalkamera-kaufberatung/ajax/results', post_data);
}

var results_counter_html = null;
function show_result_count()
{
	if (current_step != 'step-4') return;
	if (!$('#wizard #step-3 .such_art-select:checked').length) return;
	var post_data = get_post_data();
	if (!results_counter_html)
		results_counter_html = $('#wizard #results-counter').html();
	else
		$('#wizard #results-counter').html(results_counter_html);
	$('#wizard #results-counter').load('/digitalkamera-kaufberatung/ajax/count', post_data);
}

function wizard_load_next()
{
	var post_data = get_post_data();
	var loading = $('<tr><td colspan="4">' + $('#wizard #loading').html() + '</td></tr>');
	var next_row = $('#wizard #next-row');
	next_row.before(loading);
	$.post(
		'/digitalkamera-kaufberatung/ajax/page/' + next_page,
		post_data,
		function(data) {
			loading.remove();
			if (data.status != "ok")
			{
				var dialog = $('<div title="Fehler">Fehler beim Laden der Daten, bitte versuchen Sie es später nochmal.</div>');
				dialog.dialog({
						buttons: {Ok: function(e) { dialog.dialog('destroy'); }},
						modal: true,
						resizable: false,
						dialogClass: 'warning',
						height: 200,
						width: 300,
						position: [340, 'center']
				});
				return;
			}
			$.each(data.result.results, function(i, cont) {
				var row = $(cont);
				next_row.before(row);
			});
			next_page = data.result.next_page;
			if (!data.result.has_next)
				next_row.remove();
		},
		'json'
	);
}

/*
function make_bookmark()
{
	var post_data = get_post_data();
	$('#wizard #results-box').load('./wizard/bookmark', post_data);
}
*/

function changed_hersteller_or_speicherkarte()
{
	if (
		$('#wizard #step-2 #tab-2-hersteller .hersteller input:checked').length == 0 ||
		$('#wizard #step-2 #tab-2-speicherkarte .speicherkarten input:checked').length == 0
	)
	{
		$('#wizard #step-2 .next input').attr('disabled', 'disabled');
	}
	else
	{
		$('#wizard #step-2 .next input').removeAttr('disabled');
	}
}

function changed_typ()
{
	$('#wizard #step-1 .next input').attr('disabled', 'disabled');
	$('#wizard #step-1 .typ-select:checked').each(function (i, el) {
		var current_selection = $(el).val();
		if (!current_selection) return;
		typ_selection = current_selection;
		dkamera.log("Typ geändert zu: " + current_selection);
		$('#wizard .typ-kompakt').hide();
		$('#wizard .typ-bridge').hide();
		$('#wizard .typ-dslr').hide();
		$('#wizard .typ-' + current_selection).show();
		$('#wizard #step-1 .next input').removeAttr('disabled');
	});
}

function changed_typ_page()
{
	$('#wizard #step-1 .typ-select:checked').each(function (i, el) {
		wizard_step_select('step-2');
	});
}

function changed_such_art()
{
	$('#wizard #step-3 .next input').attr('disabled', 'disabled');
	$('#wizard #step-3 .such_art-select:checked').each(function (i, el) {
		var current_selection = $(el).val();
		if (!current_selection) return;
		such_art_selection = current_selection;
		dkamera.log("Such-Art geändert zu: " + current_selection);
		$('#wizard #step-4 .suche-kategorie').hide();
		$('#wizard #step-4 .suche-filter').hide();
		$('#wizard #step-4 .suche-' + current_selection).show();
		$('#wizard #step-3 .next input').removeAttr('disabled');
	});
}

function changed_such_art_page()
{
	$('#wizard #step-3 .such_art-select:checked').each(function (i, el) {
		wizard_step_select('step-4');
	});
}

function changed_kategorie_page()
{
	$('#wizard #step-4 .suche-kategorie .kategorie-select:checked').each(function (i, el) {
		wizard_step_select('results');
		show_results();
	});
}

function filter_select_to_slider(el)
{
	el = $(el);
	var select_min = el.children('.filter-min');
	var select_max = el.children('.filter-max');
	select_min.hide();
	select_max.hide();
	var type;
	if (select_min.length && select_max.length)
		type = 'range';
	else if (select_min.length)
		type = 'min';
	else if (select_max.length)
		type = 'max';
	else
		return;
	var options;
	var length;
	if (type == 'range' || type == 'min')
	{
		select_min = $(select_min.get(0));
		var min_options = select_min.children('option');
		length = min_options.length;
		var min_selection_index = 0;
		var min_slider_index = 0;
		var min_soft = $('<div class="ui-slider-soft min">');
		var min_handle = $('<div class="ui-slider-handle min">');
		options = min_options;
	}
	if (type == 'range' || type == 'max')
	{
		select_max = $(select_max.get(0));
		var max_options = select_max.children('option');
		length = max_options.length;
		var max_selection_index = length - 1;
		var max_slider_index = 1;
		var max_soft = $('<div class="ui-slider-soft max">');
		var max_handle = $('<div class="ui-slider-handle max">');
		if (type == 'max')
		{
			options = max_options;
			max_slider_index = 0;
		}
	}
	if (type == 'range' && min_options.length != max_options.length)
		return;
	var slider_options = $('<ul class="options">');
	options.each(function (i, el) {
		slider_options.append('<li class="option-' + i + '">' + $(el).text().replace("\n", "<br />\n") + '</li>');
	});
	if ($.browser.msie)
		slider_options.append('<li class="option-end"> </li>');
	var slider = $('<div class="slider"></div>');
	if (type == 'range' || type == 'min')
	{
		slider.append(min_handle);
		slider.append(min_soft);
		min_options.each(function (i, el) {
			$(el).addClass('option-' + i);
			if ((type == 'min' || i <= length) && $(el).attr('selected'))
				min_selection_index = i;
		});
	}
	if (type == 'range' || type == 'max')
	{
		slider.append(max_handle);
		slider.append(max_soft);
		max_options.each(function (i, el) {
			$(el).addClass('option-' + i);
			if ((type == 'max' || i > 0) && $(el).attr('selected'))
				max_selection_index = i;
		});
	}
	if (type != 'range')
	{
		var pseodo_range = $('<div class="ui-slider-range">');
		slider.append(pseodo_range);
	}
	var slider_box = $('<div class="slider-box num-' + length + ' filter-' + type + '">');
	slider_box.append(slider);
	slider_box.append(slider_options);

	function handle_slider_activation()
	{
		if (!slider.hasClass('disabled')) return;
		var weight_options = slider_box.parents('.filter-line').children('.filter-weight');
		if (weight_options.length)
		{
			if (weight_options.children('.ignore').children('input:checked').length)
			{
				weight_options.children('.ignore').children('input').removeAttr('checked');
				weight_options.children('.normal').children('input').attr('checked', 'checked');
				slider.removeClass('disabled');
				slider_box.removeClass('weight-light');
				slider_box.removeClass('weight-normal');
				slider_box.removeClass('weight-heavy');
				slider_box.removeClass('weight-force');
				slider_box.addClass('weight-normal');
			}
		}
	}
	function handle_change()
	{
		if (type == 'range' || type == 'min')
		{
			var min_value = slider.slider('value', min_slider_index);
			min_options.removeAttr('selected');
			min_options.filter('.option-' + min_value).attr('selected', 'selected');
			dkamera.log(select_min.attr('name') + ' gesetzt auf ' + select_min.val());
		}
		if (type == 'range' || type == 'max')
		{
			var max_value = slider.slider('value', max_slider_index);
			max_options.removeAttr('selected');
			max_options.filter('.option-' + max_value).attr('selected', 'selected');
			dkamera.log(select_max.attr('name') + ' gesetzt auf ' + select_max.val());
		}
		handle_slider_activation();
		show_result_count();
	}
	function handle_slide()
	{
		handle_slide_selected();
		handle_slide_gfx();
	}
	function handle_slide_selected()
	{
		slider_options.children('li').removeClass('selected');
		if (type == 'range' || type == 'min')
		{
			var min_value = slider.slider('value', min_slider_index);
			slider_options.children('li.option-' + min_value).addClass('selected');
		}
		if (type == 'range' || type == 'max')
		{
			var max_value = slider.slider('value', max_slider_index);
			slider_options.children('li.option-' + max_value).addClass('selected');
		}
	}
	function handle_slide_gfx()
	{
		if (type == 'range' || type == 'min')
		{
			min_soft.css('right', slider_width - parseInt(min_handle.css('left')) - (handle_width / 2));
		}
		if (type == 'range' || type == 'max')
		{
			max_soft.css('left', parseInt(max_handle.css('left')) + (handle_width / 2));
		}
		if (type == 'min')
		{
			var pseodo_range_left = parseInt(min_handle.css('left')) + (handle_width / 2);
			pseodo_range.css('left', pseodo_range_left);
			pseodo_range.css('width', slider_width - pseodo_range_left);
		}
		else if (type == 'max')
		{
			var pseodo_range_right = parseInt(max_handle.css('left')) + (handle_width / 2);
			pseodo_range.css('left', 0);
			pseodo_range.css('width', pseodo_range_right);
		}
	}

	slider.slider({
		min: 0,
		max: length - 1,
		stepping: 1,
		range: type == 'range' ? true : false//,
		//change: handle_change,
		//slide: handle_slide
	});
	slider.bind('slidechange', handle_change);
	slider.bind('slide', handle_slide);
	el.append(slider_box);
	/*
	if (type == 'range' || type == 'max')
		slider.slider('moveTo', max_selection_index, max_slider_index);
	if (type == 'range' || type == 'min')
		slider.slider('moveTo', min_selection_index, min_slider_index);
	*/
	// Workaround: slider.moveTo funktioniert nur, wenn Slider sichtbar
	if (type == 'range' || type == 'max')
	{
		slider_options.children('li.option-' + max_selection_index).addClass('selected');
		max_handle.css('left', (slider_width - handle_width) * max_selection_index / (length - 1));
		max_handle.bind('mousedown', handle_slider_activation);
	}
	if (type == 'range' || type == 'min')
	{
		slider_options.children('li.option-' + min_selection_index).addClass('selected');
		min_handle.css('left', (slider_width - handle_width) * min_selection_index / (length - 1));
		min_handle.bind('mousedown', handle_slider_activation);
	}
	handle_slide_gfx();
	if (type == 'range')
	{
		var slider_range = slider.children('.ui-slider-range');
		slider_range.css('left', (slider_width - handle_width) * min_selection_index / (length - 1) + (handle_width / 2));
		slider_range.css('width', (slider_width - handle_width) * (max_selection_index - min_selection_index) / (length - 1));
	}
}

/*
function filter_options_force_warning(el)
{
	el = $(el);
	if (el.val() == 'force')
	{
		if ($('#wizard .filter-line .filter-weight .force :checked').length > 4)
		{
			var dialog = $('<div title="Warnung">Mehr als 4 Muss-Kriterien könnten die Suche zu stark einschänken.</div>');
			dialog.dialog({
					buttons: {Ok: function(e) { dialog.dialog('destroy'); }},
					modal: true,
					resizable: false,
					dialogClass: 'warning',
					height: 200,
					width: 300,
					position: [340, 'center']
			});
		}
	}
}
*/

function filter_options_init(el)
{
	el = $(el);
	var filter_select = el.parent('.filter-line').children('.filter-select')
	var slider_box = filter_select.children('.slider-box');
	var slider = slider_box.children('.slider');
	var filter_options = filter_select.find('input:checkbox');
	var ignore_option = el.children('.ignore').children('input');
	var normal_option = el.children('.normal').children('input');
	var force_option = el.children('.force').children('input');
	var other_options = el.children(':not(.ignore)').children('input');
	ignore_option.bind('click keypress', function (e) {
		slider.addClass('disabled');
		filter_options.removeAttr('checked');
		ignore_option.parents('.filter-line').children('.filter-infos').children().remove();
		wizard_show_options_warning(e.target);
		show_result_count();
	});
	other_options.bind('click keypress', function (e) {
		slider.removeClass('disabled');
		slider_box.removeClass('weight-light');
		slider_box.removeClass('weight-normal');
		slider_box.removeClass('weight-heavy');
		slider_box.removeClass('weight-force');
		slider_box.addClass('weight-' + $(e.target).attr('value'));
		wizard_show_options_warning(e.target);
		show_result_count();
	});
	/*
	el.children('.force').children('input').bind('click keypress', function (e) {
		filter_options_force_warning(e.target);
	});
	*/
	filter_options.bind('click keypress', function (e) {
			if (filter_options.filter(':checked').length)
			{
				if (ignore_option.attr('checked'))
				{
					ignore_option.removeAttr('checked');
					force_option.attr('checked', 'checked');
				}
			}
			else
			{
				if (!ignore_option.attr('checked'))
				{
					ignore_option.attr('checked', 'checked');
					other_options.removeAttr('checked');
				}
			}
			wizard_show_options_warning(e.target);
			show_result_count();
	});
	if (ignore_option.attr('checked'))
	{
		slider.addClass('disabled');
		filter_options.removeAttr('checked');
	}
	else
		other_options.each(function (i, el) {
				el = $(el);
				if (el.attr('checked')) slider_box.addClass('weight-' + el.attr('value'));
		});
}

function wizard_step_select(step, skip_history)
{
	if (step != 'step-1')
		if (!$('#wizard #step-1 .typ-select:checked').length) return;
	if (step == 'step-4' || step == 'results')
		if (!$('#wizard #step-3 .such_art-select:checked').length) return;
	if (step == 'results' && $('#wizard #step-3 .such_art-select:checked').val() == 'kategorie')
		if (!$('#wizard #step-4 .kategorie-select:checked').length) return;
	$('#wizard .step').not('#' + step).hide();
	$('#wizard #' + step).show();
	if (!skip_history)
		$.history.add(step);
	current_step = step;
	if (step == 'step-4')
		show_result_count();
	if (step == 'results')
		show_results();
	var header_image = $('#wizard-header-image');
	if (step == 'step-1')
		header_image.attr('src', header_image.attr('src').replace(/header(_[a-z]+)?/, 'header'));
	else
		header_image.attr('src', header_image.attr('src').replace(/header(_[a-z]+)?/, 'header_' + $('#wizard #step-1 .typ-select:checked').val()));
	window.setTimeout(function () {
		window.scrollTo(0, 0);
	}, 50);
	if (typeof reload_ads != 'undefined') reload_ads();
	if (pageTracker) pageTracker._trackPageview('ajax:'+window.location.href.replace("#", ":"));
}

function wizard_history_handler()
{
	var hash = $.history.getCurrent();
	//dkamera.log('history.hash: ' + hash);
	if (!hash) return;
	var hash_parts = hash.split(';');
	if (hash_parts.length == 0) return;

	if (hash_parts[0].match(/^(step-[1-4]|results)$/g))
	{
		var step = hash_parts[0];
		wizard_step_select(step, true);
	}
}

function wizard_filter_info_show(filter_infos, info, need_append)
{
	if (need_append)
	{
		info.hide();
		filter_infos.append(info);
	}
	info.slideDown('slow');
	return info;
}

function wizard_filter_info_hide(filter_infos, info)
{
	info.remove();
}

function wizard_show_options_warning(el)
{
	el = $(el);
	var name = el.attr('name');
	if (!name) return;
	var filter_infos = el.parents('.filter-line').children('.filter-infos');
	if (!filter_infos) return;
	if (name == 'wizard[filter][bildstabilisator][value]')
	{
		if ($('#wizard #step-1 .typ-select:checked').val() == 'dslr' && el.attr('checked'))
		{
			if (!filter_infos.children('.warning').length)
				wizard_filter_info_show(
					filter_infos,
					$('<div class="warning typ-dslr"><strong>Achtung:</strong> Mit dieser Filtereinstellung schließen Sie DSLR Kameras aus, die über Objektive mit integriertem Bildstabilisator aufgewertet werden könnten.</div>'),
					true
				);
		}
		else
			wizard_filter_info_hide(
				filter_infos,
				filter_infos.children('.warning')
			);
	}
	if (name == 'wizard[filter][sensortyp][values][]')
	{
		if (el.parents('.filter-select').find('input:checked').length)
		{
			if (!filter_infos.children('.warning').length)
				wizard_filter_info_show(
					filter_infos,
					$('<div class="warning"><strong>Achtung:</strong> Die Festlegung auf bestimmte Bildsensortypen kann viele Kameras ausschließen.</div>'),
					true
				);
		}
		else
			wizard_filter_info_hide(
				filter_infos,
				filter_infos.children('.warning')
			);
	}
	if (name == 'wizard[filter][sucher][value]')
	{
		if ($('#wizard #step-1 .typ-select:checked').val() == 'kompakt' && el.attr('checked'))
		{
			if (!filter_infos.children('.warning').length)
				wizard_filter_info_show(
					filter_infos,
					$('<div class="warning typ-kompakt"><strong>Achtung:</strong> Wenige Kompaktkameras bieten zusätzlich zum LCD Display auch einen Sucher.</div>'),
					true
				);
		}
		else
			wizard_filter_info_hide(
				filter_infos,
				filter_infos.children('.warning')
			);
	}
	if (name == 'wizard[filter][raw_format][value]')
	{
		if ($('#wizard #step-1 .typ-select:checked').val() == 'kompakt' && el.attr('checked'))
		{
			if (!filter_infos.children('.warning').length)
				wizard_filter_info_show(
					filter_infos,
					$('<div class="warning typ-kompakt"><strong>Achtung:</strong> Wenige Kompaktkameras bieten die Aufnahme im RAW Format.</div>'),
					true
				);
		}
		else
			wizard_filter_info_hide(
				filter_infos,
				filter_infos.children('.warning')
			);
	}
	if (name == 'wizard[filter][alter][zukuenftig_verfuegbar]')
	{
		if (el.attr('checked'))
		{
			if (!filter_infos.children('.warning').length)
				wizard_filter_info_show(
					filter_infos,
					$('<div class="warning typ-kompakt"><strong>Achtung:</strong> Da zukünftige Digitalkameras meist keine Preisangabe haben, werden diese auf der Ergebnisseite teilweise bevorzugt bzw. benachteiligt.</div>'),
					true
				);
		}
		else
			wizard_filter_info_hide(
				filter_infos,
				filter_infos.children('.warning')
			);
	}
}

function ie_label_ids()
{
	if (!$.browser.msie) return;
	dkamera.log('Using IE label workaround');
	$('#wizard label').each(function (i, el) {
		el = $(el);
		if (el.hasClass('help')) return;
		var label_inputs = el.find('input');
		if (label_inputs.length == 1)
		{
			/*
			var id = 'ielabelid' + Math.floor(Math.random()*9999999);
			el.attr('for', id);
			label_inputs.attr('id', id);
			*/
			function handle_click(e) {
				el.unbind('click', handle_click);
				label_inputs.trigger('click');
				label_inputs.trigger('click');
				el.bind('click', handle_click);
			}
			el.bind('click', handle_click);
		}
	});
}

$(document).ready(function() {
	// Generic Init
	$('#wizard #javascript-warning').hide();
	$('#wizard #loading').hide();
	$('#wizard .tabs').tabs({
		select: function() {
			if (typeof reload_ads != 'undefined') reload_ads();
			if (pageTracker) pageTracker._trackPageview('ajax:'+window.location.href.replace("#", ":"));
		}
	});
	$('#wizard #step-1').show();

	$('#wizard .filter-line .filter-select.filter-slider').each(function (i, el) { filter_select_to_slider(el); });
	$('#wizard .filter-line .filter-weight').each(function (i, el) { filter_options_init(el); });

	// Init steps
	$('#wizard #step-1 .next input').attr('disabled', 'disabled');
	$('#wizard #step-1 .typ-select').bind('click keypress', changed_typ);
	$('#wizard #step-1 .typ-select').bind('click keypress', changed_typ_page);
	changed_typ();

	$('#wizard #step-3 .next input').attr('disabled', 'disabled');
	$('#wizard #step-3 .such_art-select').bind('click keypress', changed_such_art);
	$('#wizard #step-3 .such_art-select').bind('click keypress', changed_such_art_page);
	changed_such_art();

	//$('#wizard #step-4 .suche-kategorie .kategorie-select').bind('click keypress', changed_kategorie_page);

	$('#wizard #step-2 #tab-2-hersteller :checkbox').bind('click keypress', changed_hersteller_or_speicherkarte);
	$('#wizard #step-2 #tab-2-speicherkarte :checkbox').bind('click keypress', changed_hersteller_or_speicherkarte);

	$('#wizard #zufuenftig-verfuegbar').bind('click keypress', function (e) { wizard_show_options_warning(e.target); } );

	ie_label_ids();

	$('#wizard label .help').bind('click keypress', function(e) {
		e.preventDefault();
		e.stopPropagation();
		var el = $(e.target);
		var filter_infos = el.parents('.filter-line').children('.filter-infos');
		if (!filter_infos) return;
		dkamera.log(el);
		dkamera.log(el.children('span'));
		var text = el.children('span').html();
		var info = $('<div class="ok">');
		info.html(text);
		var cur_info = filter_infos.children('.ok');
			wizard_filter_info_hide(
				filter_infos,
				filter_infos.children('.ok')
			);
		if (cur_info.length && cur_info.html() == text) return;
		info = wizard_filter_info_show(
			filter_infos,
			$('<div class="ok">' + text + '</div>'),
			true
		);
	});

	// History
	$(document).history(wizard_history_handler);
	if (!$.history.getCurrent())
		$.history.add('step-1');
	wizard_history_handler();
	
	// test
	/*
	$('#wizard #step-1').hide();
	$('#wizard #step-4').show();
	$('#wizard #step-4 .suche-filter').show();
	document.write = function (x) { dkamera.log('document.write(' + x + ')'); }
	*/
});

