$(function(){
	$('.input-bg input')
		.each(function(){
			this.myFiller = this.nextSibling.innerHTML;
			if (!this.value)
				this.value = this.myFiller;
		})
		.focus(function() {
			if(this.value==this.myFiller) this.value='';
		})
		.blur(function() {
			if($.trim(this.value)=='') this.value=this.myFiller;
		});

    $("#menu ul.menu ul").each(function(index) {
			$(this).append("<div class=\"mnu-lt\"></div><div class=\"mnu-rt\"></div><div class=\"mnu-bl\"></div><div class=\"mnu-br\"></div>");
	});
});

jQuery.fn.center = function(dx, dy)
{
	var w = $(window);
	this.css("position","absolute");
	this.css("top",Math.max(dy||0, Math.floor((w.height()-this.height())/2+w.scrollTop())) + "px");
	this.css("left",Math.max(dx||0, Math.floor((w.width()-this.width())/2+w.scrollLeft())) + "px");
	$('body').append(this);
	return this;
}
function wheel_variant(small, big) {
	$('#current-big').html(small);
	$('#current-big-preview').html(big);
}
function wheel_preview(item) {
	wheel_preview_im($('#'+item.id+'-preview'));
}
function wheel_preview_im(im) {
	var p = $('#wheel-preview')
		.html(im.html())
		.center();
	$('#wheel-preview img')
		.css('paddingLeft', Math.floor((p.width() - im.width()) / 2))
		.css('paddingTop', Math.floor((p.height() - im.height()) / 2));
	p.fadeIn();
}
function wheel_preview_hide() {
	$('#wheel-preview').fadeOut();
}
$(function() {
	$('#wheel-preview')
		.click(wheel_preview_hide)
		.mouseleave(wheel_preview_hide);
});

// Preview engine
var image_preview;
function sub_launch_hide() {
	image_preview.fadeOut();
}
function sub_launch_fetch_url(href) {
	return href.match(/'\/content\/.*?'/)[0].replace("'", '').replace("'", '').replace(/\?.*/, '');
}
function sub_launch() {
	return sub_launch_url(this, sub_launch_fetch_url(this.href));
}
function sub_launch_url(place, url) {
	//$.preventDefault();

	previewBox.show(url);
	return false;

	// Old:

	if (!image_preview)
	{
		image_preview = document.createElement('div');
		image_preview.id = 'image-preview';
		$(document.body).append(image_preview);
		image_preview = $(image_preview);
		image_preview
			.append('<img src="'+url+'" alt="" />')
			.click(sub_launch_hide)
			.mouseleave(sub_launch_hide);
	}
	else
		image_preview.get(0).firstChild.src = url;

	var p = $(place).offset();
	image_preview.css('top', p.top-150+'px').css('left', p.left-200+'px');
	image_preview.fadeIn();

	return false;
}
$(function(){
	$("a[href^='javascript:launch(']").click(sub_launch).each(function() {
		$('#image-cache').append('<img alt="" src="'+sub_launch_fetch_url(this.href)+'" />');
	});
	$("a[href^='javascript:launch_nc(']").click(sub_launch);
});

var previewBox = {
	show: function(url) {
    	if (!this.frame) {
    		this.frame = $('#preview-modal');
    		this.img = $('#preview-modal img');
    		this.initCheckWidth();
    	}

    	this.img.attr('src', url);
    	if (this.img.width() == 0) {
    		this.origin(400, 300);
	   		setTimeout(function() {
	   			previewBox.checkWidth();
	   		}, 50);
    	}
    	else
    		this.origin(this.img.width(), this.img.height());

    	this.frame.show();
	},

	origin: function(w, h) {
		this.lastSize = { w: w, h: h };
		this.frame.css({
			width: (w*1+40)+'px',
			height: (h*1+40)+'px'
		}).center();
	},

	initCheckWidth: function() {
   		setInterval(function() {
   			previewBox.checkWidth();
   		}, 2000);
	},

	checkWidth: function() {
		var w = this.img.width(), h = this.img.height();
		if (w && this.lastSize && (w != this.lastSize.w || h != this.lastSize.h))
			this.origin(w, h);
	}
};

// Match form
var brand, model, code, years;
function initial_set(v, s, tail)
{
	var x = $('#match_'+v).html(s);
	if (window['match_'+v])
	{
		x.val(window['match_'+v]);
		window[v] = window['match_'+v];
		window['match_'+v] = '';
	}
	else if (x.val() != window[v])
		x.val(window[v]);
	if (!tail)
		x.change();
}
function reset_tail(id)
{
	var s = '<option value="">&nbsp;</option>';
	if (cars[brand] && cars[brand][model]) {
		// Codes
		var x = cars[brand][model][id.substr(0, 1)];
		for (var i in x) if (x.hasOwnProperty(i))
			s += '<option value="'+i+'">'+(x[i] == 1 ? i : x[i])+'</option>';
	}
	initial_set(id, s, true);
	$('#match_'+id).attr('disabled', !model);
}
function match_init() {
	$('#match_years').change(function(){
		years = this.value;

		if (!this.value)
			return reset_tail('code');

		var x = cars[brand][model].yc[this.value];
		if (x) {
			var s = '<option value="">&nbsp;</option>';
			for (var i in x) if (x.hasOwnProperty(i))
				s += '<option value="'+i+'">'+i+'</option>';
			initial_set('code', s, true);
		}
	});
	$('#match_code').change(function(){
		code = this.value;

		if (!this.value)
			return reset_tail('years');

		var x = cars[brand][model].cy[this.value];
		if (x) {
			var s = '<option value="">&nbsp;</option>';
			for (var i in x) if (x.hasOwnProperty(i))
				s += '<option value="'+i+'">'+cars[brand][model].y[i]+'</option>';
			initial_set('years', s, true);
			$('#match_years').attr('disabled', false);
		}
		else
		{
			x = $('#match_years');
			if (x.val() != '')
				x.val('').change();
			x.attr('disabled', true);
		}
	});
	$('#match_model').change(function(){
		model = this.value;
		years = code = '';
		reset_tail('code');
		reset_tail('years');
	});
	$('#match_brand').change(function(){
		brand = this.value;
		var s = '<option value="">&nbsp;</option>';
		if (cars[brand]) for (var i in cars[brand]) if (cars[brand].hasOwnProperty(i))
			s += '<option value="'+i+'">'+i+'</option>';
		initial_set('model', s);
	});

	// Init brand box and chain the Change event
	var s = '<option value="">&nbsp;</option>';
	for (var i in cars) if (cars.hasOwnProperty(i))
		s += '<option value="'+i+'">'+i+'</option>';
	var b = $('#match_brand');
	b.html(s);
	if (window.match_brand)
		b.val(match_brand);
	b.change();
}

// Match sizes
var sizes_map = ['h2', 'lz', 'pcd', 'et', 'dia'], sizes_fields = [],
	sizes_active = [], sizes_adapters;

function sizes_init() {
	for (var i in sizes_map) if (sizes_map.hasOwnProperty(i))
	{
		sizes_fields[i] = $('#match_'+sizes_map[i]);
		sizes_fields[i][0].matchIdx = i; // attr() does nothing
		sizes_fields[i].change(sizes_change);
	}
	$('#match_adapters').change(sizes_adapters_change);
}

function array_add_sorted(a, v) {
	for (var i = 0; i < a.length; i++)
		if (a[i] == v) return;
		else if (a[i] > v) {
			for (var j = a.length; j > i; j--)
				a[j] = a[j-1];
			a[i] = v;
			return;
		}
	a[a.length] = v;
}

function sizes_level(arr, curIdx, testOnly) {

	// Stop recursion
	if (!sizes_map[curIdx])
		return (arr == 1 || sizes_adapters);

	// Set refs
	var v = sizes_values[curIdx],
		has = false;

	// Test
	//sizes_active[curIdx] = [];
	for (var i in arr) if (arr.hasOwnProperty(i))
		if (sizes_level(arr[i], curIdx+1, testOnly || (v && v != i))) {
			if (testOnly) {
				if (!v || v == i)
					return true;
			}
			else {
				has = has || !v || v == i;
				array_add_sorted(sizes_active[curIdx], i*1);
			}
		}

	return has;
}

function sizes_change() {
	var skipIdx = this.matchIdx || -1;

	sizes_values[skipIdx] = this.value*1;

	// Fill sizes_active
	$.each(sizes_map, function(i) { sizes_active[i] = []; });
	sizes_level(sizes, 0, false);

	// Change options
	$.each(sizes_map, function(curIdx){
		if (skipIdx != curIdx) {
			var s = '<option value="0">&nbsp;</option>',
				x = sizes_active[curIdx];

			for (var i in x) if (x.hasOwnProperty(i))
				s += '<option value="'+x[i]+'">'+x[i]+'</option>';

			sizes_fields[curIdx]
				.html(s)
				.val(sizes_values[curIdx]);
		}
	});
}

function sizes_adapters_change() {
	// Store value
	sizes_adapters = this.checked;

	// Get lists
	sizes_change();

	// Detect and fix selection of the just removed value in DIA
	if (!this.checked) {
		var dia = $('#match_dia');
		if (dia.val() != sizes_values[dia[0].matchIdx])
			dia.val(sizes_values[dia[0].matchIdx]).change();
	}
}

function Filter(o) {

	$.extend(this, o);
	this.skip = o.skip ? ':gt('+(o.skip || 0)+')' : '';
	this.hSkip = o.hSkip || o.skip || 0;

	if (typeof this.table == 'string')
		this.table = $(this.table);

	var s = '<tr class="selects">', cols = this.table.find('thead tr>*').length;
	for (var i = 0; i < cols; i++)
		s += i < this.hSkip ? '<th></th>' : '<th><select></select></th>';
	s += '</tr>';

	this.table.find('thead').append(s);
	this.selectsChanged();

	this.update();
}

Filter.prototype = {

	selectsChanged: function() {
		if (this.selects) this.selects.unbind('change');
		var me = this;
		this.selects = this.table.find('thead select');
		this.selects.change(function(i) {
			me.update();
		});
	},

	getCol: function(idx, visible) {
		var r = [];
		this.table.find('tbody tr'+(visible ? ':visible' : '')+this.skip).each(function() {
			var val = $(this).children('td:eq('+idx+')').html();
	    	if ($.inArray(val, r) == -1)
	    		r[r.length] = val;
		});
		return r;
	},

	apply: function(idx, value) {
		this.table.find('tbody tr'+this.skip).each(function() {
			var row = $(this),
				show = !value || row.children('td:eq('+idx+')').html() == value;
			row[show ? 'show' : 'hide']();
		});
	},

	testRow: function(tds) {
		for (var i = 0; i < this.selects.length; i++)
			if (this.selects[i].value && this.selects[i].value != tds.eq(i).text())
				return false;
		return true;
	},

	update: function() {
		var me = this;
		this.table.find('tbody tr'+this.skip).each(function() {
			var row = $(this);
			row[me.testRow(row.children()) ? 'show' : 'hide']();
		});
		this.selects.each(function(i) {
			var v = this.value, s = '<select><option '+(v==''?'selected=selected':'')+'></option>';
			$.each(me.getCol(i, true || !v), function() {
				s += '<option value="'+this+'" '+(v==this?'selected=selected':'')+'>'+this+'</option>';
			});
			s += '</select>';
			$(this.parentNode).html(s);
		});
		this.selectsChanged();
	}
}