$(document).ready(function()
{
	$('a[@rel=external]').bind('click', function()
	{
		$(this).attr('target', '_blank');
	});
});


function bid(btn, id)
{
	btn.blur();
	btn.hideFocus = true;
	btn.style.outline = 'none';

	var token = $('#token').val();

	$.getJSON('/auctions/offer/' + id + '/' + token + '/', function(data)
	{
		if (data.code == 0)
			document.location.href = '/prisijungimas/';
		else if (data.code == -1)
			document.location.href = '/papildyti-saskaita/';
		else if (data.code == -2)
			alert(data.message);
		else if (data.code == -3)
		{
			//
		}
		else
			$('span.account').html(data.credits);
	});
}

function bid2(btn, id)
{
	btn.blur();
	btn.hideFocus = true;
	btn.style.outline = 'none';

	var token = $('#token').val();
	var code = $('#code' + id).val();

	$.getJSON('/auctions/offer2/' + id + '/' + token + '/' + code + '/', function(data)
	{
		if (data.code == 0)
			document.location.href = '/prisijungimas/';
		else if (data.code == -2 || data.code == -4)
			alert(data.message);
		else if (data.code == -3)
		{
			//
		}
		$('#code_' + id + ' img').attr('src', '/code.php?a=' + Math.random() + '&auction=' + id);
	});
}


var valid = new validator();

function validator()
{
	error = 'error';
	field = 'Užpildykite visus privalomus laukus.';
	phone = 'Neteisingas telefono numeris.';
	email = 'Neteisingas el. pašto adresas.';
	rules =  'Būtina sutikti su taisyklėmis.';
	password = 'Jūsų įvesti slaptažodžiai nesutampa.';
	too_long = 'Jūsų prisijungimo vardas per ilgas.';
	wrong = 'Neleistinas vartotojo vardas.';
	msg = '';

	this.check = function(form)
	{
		var id = form.id;
		var failed = false;

		$('form#'+id+' .required').each(function()
		{
			var id = $(this).attr('id');
			var label = $('label[@for=' + id + ']');

			label.removeClass('error');
			if ($(this).val() == '')
			{
				label.addClass('error');
				failed = true;
				msg = field;
			}
			else if (id == 'username')
			{
				if ($(this).val().length > 25)
				{
					label.addClass('error');
					failed = true;
					msg = too_long;
				}
				else if (username($(this).val()))
				{
					label.addClass('error');
					failed = true;
					msg = wrong;
				}
			}
		});

		if (!failed && $('form#'+id+' #phone').val() && ($('form#'+id+' #phone').val().length != 8 || $('form#'+id+' #phone').val() != parseInt($('form#'+id+' #phone').val())))
		{
			$('label[@for*=phone]').addClass('error');
			failed = true;
			msg = phone;
		}

		if (!failed && $('form#'+id+' .email').val() && !checkEmail($('form#'+id+' .email').val()))
		{
			$('label[@for*=email]').addClass('error');
			failed = true;
			msg = email;
		}

		if (!failed && $('form#'+id+' #pass1').val() != $('form#'+id+' #pass2').val())
		{
			$('label[@for*=pass1]').addClass('error');
			$('label[@for*=pass2]').addClass('error');
			failed = true;
			msg = password;
		}

		if (!failed && $('form#' + id + ' #agree').val() == '1' && $('form#' + id + ' #agree').attr('checked') != true)
		{
			$('label[@for*=agree]').addClass('error');
			failed = true;
			msg = rules;
		}

		if (failed)
		{
			$('div.'+error).html(msg);
			$('div.message').hide();
			$('div.'+error).fadeIn(400);
		}

		return !failed;
	}
}

function checkEmail(str)
{
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,4}(?:\.[a-z]{2})?)$/i;
	return filter.test(str);
}

function username(str)
{
	var filter = /\s/;
	return filter.test(str);
}


function uploaded(data)
{
	data = data.split('|');
	$('#user_img').attr('src', '/data/users/' + data[0]);
	$('#user_img_small').attr('src', '/data/users/s' + data[0]);
	$('div.success').html(data[1]).fadeIn('slow');
	$('#user_img_default').css('display', 'none');
	$('#user_img_own').css('display', 'block');

	$.get('/users/uploaded/' + $('#token').val() + '/');
}

function deleteImage()
{
	$.getJSON('/users/delete/' + $('#token').val() + '/', function(data)
	{
		if (data.code == 'ok')
		{
			$('#user_img').attr('src', '/images/user_big.gif');
			$('#user_img_small').attr('src', '/images/user_small.gif');
			$('div.success').html(data.message).fadeIn('slow');
			$('#user_img_default').css('display', 'block');
			$('#user_img_own').css('display', 'none');
		}
		else
		{
			$('div.success').fadeOut('slow');
			$('div.error').html(data.message).fadeIn('slow');
		}
	});
}


function banks()
{
	if ($('input[@name*=bank_name][checked]').val() == undefined)
	{
		$('div.error').html('Pasirinkite banką.').fadeIn('slow');
		return false;
	}
	return true;
}

function num(inp)
{
	inp.value = amount(inp.value);
}

function amount(val)
{
	var amount = parseFloat(val.replace(/,/, '.'));
	if (isNaN(amount) || amount < 10.00)
		amount = 50.00;

	var present = amount * 0.2;
	present = present.toFixed(2).replace('.', ',');
	$('#present').html(present + ' ' + $('#currency').html());

	return amount.toFixed(2).replace('.', ',');
}


function timer(place, stamp, now)
{
	var diff = new Number(stamp) - new Number(now);
	now = new Number(now) + 1;

	var days = Math.floor(diff / 24 / 60 / 60);
	var hours = Math.floor((diff / 3600) % 24);
	var minutes = Math.floor((diff / 60) % 60);
	var seconds = diff % 60;

	days = (days <= 0)? '': days + 'd ';
	hours = (hours <= 0)? '': hours + 'val ';
	minutes = (minutes <= 0)? '': minutes + 'min ';

	if (days == '' && hours == '' && minutes == '' && seconds <= 0)
		document.location.href = document.location.href;

	$('#' + place).html(days + hours + minutes + seconds + 'sek');

	setTimeout("timer('" + place + "', '" + stamp + "', '" + now + "');", 1000);
}

function timer_(stamp, now)
{
	var diff = new Number(stamp) - new Number(now);
	now = new Number(now) + 1;

	if (diff <= 0)
		document.location.href = document.location.href;

	setTimeout("timer_('" + stamp + "', '" + now + "');", 1000);
}


function credits()
{
	var offers = parseInt($('#offers').val());
	if (offers != $('#offers').val() || offers <= 0)
	{
		alert('Neleistinas siūlymų kiekis');
		$('#credits').html('-');
	}
	else
	{
		var cr = offers * 3;
		$('#credits').html(cr);
	}
}

function autopilot(auction, user, n)
{
	var token = $('#token_').val();
	if (n == undefined) n = '';

	var offers = parseInt($('#offers').val());
	if (offers != $('#offers').val() || offers <= 0)
		alert('Neleistinas siūlymų kiekis');
	else
	{
		$.get('/products/autopilot'+n+'/' + auction + '/' + user + '/' + offers + '/' + token + '/', function(data)
		{
			if (data == '1')
			{
				$('#a_offers').html(offers);
				$('#a_bids').html('0');
				$('#a_credits').html('0');

				$('#off').hide();
				$('#on').show();
			}
			else
				alert(data);
		});
	}
}

function autopilot_cancel(auction, user, n)
{
	var token = $('#token_').val();
	if (n == undefined) n = '';

	$.get('/products/autopilot_cancel'+n+'/' + auction + '/' + user + '/' + token + '/', function(data)
	{
		if (data == '1')
		{
			$('#off').show();
			$('#on').hide();
		}
		else
			alert(data);
	});
}


function timer2(id)
{
	setInterval(function()
	{
		var t = $('#t' + id).attr('title');

		if (t == '' || isNaN(t) || t < 0)
		{
			$('#t' + id).text('00:00');
			return true;
		}

		if (t == '0')
		{
			$('#t' + id).attr('title', '0');
			$('#t' + id).text('Tikrinama');
			$('#w1' + id).hide();
			$('#auto' + id).hide();
		}
		else
		{
			t = parseInt(t) - 1;
			if (t < 0)
				return true;

			$('#t' + id).attr('title', t);
			var t2 = t;
			if (t2 < 10)
				t2 = '0' + t2;
			t2 = '00:' + t2;
			$('#t' + id).text(t2);
			$('#w1' + id).show();
			$('#auto' + id).show();
		}

		if (t <= 30)
			$('#t' + id).addClass('soon_end');
		else
			$('#t' + id).removeClass('soon_end');

	}, 1000);
}

function timer3(id)
{
	setInterval(function()
	{
		var t = $('#t_' + id).attr('title');

		if (t == '' || isNaN(t) || t < 0)
		{
			$('#t_' + id).text('00:00');
			return true;
		}

		if (t == '0')
		{
			$('#t_' + id).attr('title', '0');
			$('#t_' + id).text('Tikrinama');
			$('#w1_' + id).hide();
			$('#auto_' + id).hide();
		}
		else
		{
			t = parseInt(t) - 1;
			if (t < 0)
				return true;

			$('#t_' + id).attr('title', t);
			var t2 = t;
			if (t2 < 10)
				t2 = '0' + t2;
			t2 = '00:' + t2;
			$('#t_' + id).text(t2);
			$('#w1_' + id).show();
			$('#auto_' + id).show();
		}

		if (t <= 30)
			$('#t_' + id).addClass('soon_end');
		else
			$('#t_' + id).removeClass('soon_end');

	}, 1000);
}


function wishlist()
{
	var wish = $('#wish').val();
	if (wish != '')
	{
		$.post('/pages/wishes/', { message: wish }, function(data)
		{
			if (data == '1')
			{
				$('#wishlist fieldset').hide();
				$('#wishlist span').show();
				$('#wish').val('');
			}
		});
	}
}

function showForm()
{
	$('#wishlist fieldset').show();
	$('#wishlist span').hide();
}

function vote()
{
	var token = $('#token').val();

	$.get('/auctions/vote/' + token + '/', function(data)
	{
		if (data == '0')
			document.location.href = '/prisijungimas/';
		else
		{
			if (data == '10000')
				document.location.href = document.location.href;

			$('#free_auctions_votes').html(data);

			$('#free_auctions_content a').hide();
			$('#free_auctions_voted').show();

			$('#second_box').hide();
			$('#second_box2').show();

			$('#third_box').hide();
			$('#third_box2').show();
		}
	});
	return false;
}