$(document).ready(function() {

	$('a.delete').css('color','red').click(function(){
		if (confirm('Czy napewno usunąć ten element ?'))
		{
			return true;
		}
		
		return false;
	});
	
	$('#vat-table-toggle').toggle(
		function (){
			$(this).html('Nie potrzebuję faktury VAT');
			$('#vat-table').show('slow');
			return false;
		},
		function (){
			$(this).html('Kliknij tutaj jeżeli chcesz fakturę VAT');
			$('#vat-table').hide('slow');
			return false;
		}
	);
	
	$('#i-kup-teraz').click(function(){
		
		if ($('#icolor_id').val()=='')
		{
			alert('Wybierz kolor produktu');
			return false;
		}
		
		return true;
	});
	
	$('.kup-teraz').click(function(){
		if ($(this).prev().prev().prev().prev().prev().val()=='')
		{
			alert('Wybierz kolor produktu')
			return false;
		}
		
		return true;
	});
	/**
	* rotator
	* START
	*/
		init_main_pics(); 
		function change_main_pics(to_show) {
			$('#rotator a').stop(true, true);
			$(main_pics[actual_main_pic]).fadeOut(500);
			$(main_pics[to_show]).fadeIn(500);
			actual_main_pic = to_show;
		}
		function prev_main_pics() {
			var prev = actual_main_pic == 0 ? main_pics.length - 1 : actual_main_pic - 1;
			change_main_pics(prev);
		}

		function next_main_pics() {
			var next = actual_main_pic == main_pics.length - 1 ? 0 : actual_main_pic + 1;
			change_main_pics(next);
		}
		function step_main_pic() {
			if (stop_step_main_pic == 1) return;
			next_main_pics()
		}
		function init_main_pics() {
			main_pics = $('.rotPic');
			actual_main_pic = 0;
			stop_step_main_pic = 0;
			$('#rotArrowLeft').bind('click', function (e) {
				e.preventDefault();
				prev_main_pics();
			});
			$('#rotArrowRight').bind('click', function (e) {
				e.preventDefault();
				next_main_pics();
			});
			if (main_pics.length > 1) {
				setInterval(step_main_pic, 5000);
				$('#rotator').hover(function () {
					stop_step_main_pic = 1
				}, function () {
					stop_step_main_pic = 0
				})
			}
		}
	/**
	* KONIEC
	*/
	
	
	/**
	* Kody promocyjne
	* START
	*/
	$('input[name=discount], input[name=email]').focusout(function(){


		if ( $('input[name=discount]').val().length > 0 ) {
			validator.set();
			validator.check();

		}
	});

	$('input[name=discount]').keyup(function(e){
		if ( e.keyCode == 8 ) {
			validator.set();
			validator.check();
		}






	});
	
	$('input[name=discount]').keydown(function(){
		validator.reset();
	});
	/**
	* KONIEC
	*/
	jQuery.span2input = function(){
		$('span').each(function(){
			if ( $(this).attr('name') ){
				var val = $(this).text();
				var name = $(this).attr('name');
				var clas = $(this).attr('class');
				if ( val.length > 0 ) {
					$(this).after('<input type="hidden" class="' + clas + '" name="' + name + '" value="' + val + '">');
				}
			}
		});
	}
	$(points.select).change(filterPlace); // Mapka z punktami szczepień
	$('#zipCodeBox .go').click(byZipCode);
	$('#zipCodeBox input').keyup(function(e){
		if ( e.which == 13 ) {
			byZipCode();
		}
	});
	$('#zipCodeBox p span').click(reload);
})

validator = {
	mail : '',
	code : '',
	respond : $('span.respond'),
	logo : $('span.logo'),
	set : function() {
		this.mail = $('input[name=email]').val();
		this.code = $('input[name=discount]').val();
	},
	check : function() {
		
		String.prototype.formatPrice = function () {
			str = this.replace(/,/g,'');
			price = ( Math.round ( 100 * str ) / 100 ).toString().split('.');
			if ( typeof price[1] == 'undefined' ) {
				price[1] = '00';
			}
			else if ( price[1].length == 1 ) {
				price[1] += '0';
			}
			return price.join('.');
		}
		Number.prototype.formatPrice = function () {
			str = this.toString().replace(/,/g,'');
			price = ( Math.round ( 100 * str ) / 100 ).toString().split('.');
			if ( typeof price[1] == 'undefined' ) {
				price[1] = '00';
			}
			else if ( price[1].length == 1 ) {
				price[1] += '0';
			}
			
			return price.join('.');
		}
		this.reset();
		$.ajax({
			data: 'mail=' +  this.mail + '&discount=' + this.code + '&products=' + this.getProducts(),
			url: '/panel/discounts_check.php',
			type: 'post',
			dataType: 'json',
			success: function(html){
				var msg = [];
				$r = $('span.respond');
				$l = $('span.logo');
				if ( html.status ) {
					if ( html.logo ) {
						$l.html('<img src="' + html.logo + '">');
					}
					if ( typeof discount == 'undefined' ) {
						$r.removeClass('invalid').addClass('valid').html(html.message);
					}
					else if ( typeof discount != 'undefined' && discount != validator.code ) {
						$r.removeClass('invalid').addClass('valid').html(html.message);
					}
					if ( html.reset ) {
						$('input[name=discount]').val('');
					}
					if ( html.total_discount ) {
						$('.oldPrice.total').addClass('strike');
						var val = $('.oldPrice.total').text().split(' ');	
						val = val[0].replace(/,/g,'');
						val = val - html.total_discount; 	
						$('.newPrice.total').text( val < 24.99 ? '24.99 PLN' : val.formatPrice() + ' PLN' );
					}
					else {
						for (i =0; i< html.prices.id.length; i++) {
							var id = html.prices.id[i];
							var price = html.prices.price[i];
							$('tr[data-id=' + id + ']').each(function(){
								$td = $(this).children('td:eq(2)');
								$td.find('.oldPrice').addClass('strike');
								$td.find('.newPrice').text(price.formatPrice());
							});

						}
					}
					validator.setTable();
				}
				else {
					$r.addClass('invalid').html(html.message);
				};
			}
		});
		
	},
	reset : function() {
		var defaultTxt = $('span.respond').attr('data-defaultTxt');
		if ( typeof defaultTxt == 'undefined' ) {
			defaultTxt = '';
		}
		$('span.respond').html(defaultTxt).attr('class','respond');
		$('span.logo').html('');
		$('.strike').each(function(){
			$(this).removeClass('strike');
		});
		$('span.newPrice').text('');
	},
	getProducts : function() {
		var arr = [];
		$('.productsList').find('tr').each(function(){
			var id = $(this).attr('data-id');
			if ( typeof id != 'undefined') {
				arr.push(id);
			}
		});
		return arr.join(',');
	},
	setTable : function() {
		var total = 0;
		$('.newPrice.unit').each(function(){
			var tr = $(this).parent('td').parent('tr');
			var unitPrice = $(this).text();

			var quantity = tr.find('.quantity').text();
			if ( $('input.quantity').length ) {
				quantity = tr.find('.quantity').val();

			}
			if ( unitPrice.length > 0 ) {
				$totalTd = $(this).parent('td').next('td').next('td');
				$totalTd.find('.oldPrice').addClass('strike');
				$totalTd.find('.newPrice').text( ( unitPrice * quantity ).formatPrice() + ' PLN'); 
				total += unitPrice * quantity;
			}
			else {
				total += $(this).prev().text() * quantity;

			}
		});
		if ( total > 0 ) {
			var oldPrice = $('.oldPrice.total').text().split(' ');
			oldPrice = oldPrice[0].replace(/,/g,'');
			if ( Math.round(oldPrice) != Math.round(total+24.99) && Math.round(oldPrice) != Math.round(total) ) {
				$('.total.oldPrice').addClass('strike');
				if ( $('.productsList').hasClass('cart') ) {
					total += 24.99;
				}
				$('.total.newPrice').text( total.formatPrice() + ' PLN');
			}
		}
	}
};



/**
* Mapka z punktami szczepień
* START
*/
var points = {
	wrapDiv :		'#mapNav',
	listDiv :		'#mapNav .list',
	resultDiv:		'#mapNav .result',
	districtName :	'#mapNav h3 span',
	select:			'#mapNav select'
}
function reload(id, zipCode) {
	var d;
	switch(id) {
		case 1: d = "Dolnośląskie"; break;
		case 2: d = "Kujawsko - Pomorskie"; break;
		case 3: d = "Lubelskie"; break;
		case 4: d = "Lubuskie"; break;
		case 5: d = "Łódzkie"; break;
		case 6: d = "Małopolskie"; break;
		case 7: d = "Mazowieckie"; break;
		case 8: d = "Opolskie"; break;
		case 9: d = "Podkarpackie"; break;
		case 10: d = "Podlaskie"; break;
		case 11: d = "Pomorskie"; break;
		case 12: d = "Śląskie"; break;
		case 13: d = "Świętokrzyskie"; break;
		case 14: d = "Warmińsko - Mazurskie"; break;
		case 15: d = "Wielkopolskie"; break;
		case 16: d = "Zachodnio - Pomorskie"; break;
	}
	var param = ( typeof zipCode == "undefined" ) ? "id=" + id : "zip_code=" + zipCode;
	$.ajax({
		type: 'post',
		url: '/panel/immunization_list.php',
		data: 'list=true&' + param,
		dataType: 'json',
		async: false,
		beforeSend: function(){
			$('#loader').show();
			$($(points.resultDiv).find('p')[0]).hide();
		},
		success: function(json){
			$('#loader').hide();
			var html = [];
			if ( json == 'row' ) {
				$(points.select).hide().prev('p').show();
			}
			else {
				$(points.select).children('option:gt(0)').remove();
				for ( k in json ) {
					if ( typeof json[k] == "object" ) {
						var row = json[k].row;
						html.push('<div class="place">');
						html.push('<p><strong>' + row.name + '</strong><br>');
						html.push(row.street + '<br>');
						html.push(row.postcode + ' ' + row.city + '<br>');
						html.push('tel. ' + row.phone);
						html.push('</p></div>');
						$(points.select).show();
						if ( $(points.select).html().indexOf(row.city) == -1 ) {
							$(points.select).append('<option value="' + row.city + '">' + row.city + '</option>').prev('p').hide();
						}
					}
				}
			}
			$(points.resultDiv).show('slow');
			var t = 'Wybrane województwo: <span/>';
			if ( param.indexOf('zip_code') > -1 ) {
				d = $('#zipCodeBox input').val();
				t = 'Wybrany kod pocztowy: <span/>';
			}
			else if ( typeof id == 'undefined' ) {
				t = '';
			}
			$('#chosenDistrict').html(t);
			$(points.districtName).text(d);
			$(points.listDiv).html(html.join('\n'));
			if ( typeof d == 'undefined' ) {
				$('#chosenDistrict').empty();
			}
		}
	});
	
}
function byZipCode(){
	var val = $('#zipCodeBox input').val();
	if ( val.length < 6 ) {
		alert('Nieprawidłowy format kodu pocztowego');
		return false;
	}
	else {
		reload(0, val);
	}
}
function filterPlace(){
	var txt = $(points.select).val();
	$div = $(points.listDiv).find('.place');
	$div.show();
	$div.each(function(){
		if ( $(this).html().indexOf(txt) == -1 ) {
			$(this).hide();
		}
	});
}
/**
* Mapka z punktami szczepień
* KONIEC
*/



function checkOrderForm ()
{
	var error = false;
	
	if ($('#iname').val()=='') 
	{
		$('#iname').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#iname').css('border','1px solid #009EE0');	
	}
	
	if ($('#isurname').val()=='') 
	{
		$('#isurname').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#isurname').css('border','1px solid #009EE0');	
	}
	
	if ($('#iphone').val()=='') 
	{
		$('#iphone').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#iphone').css('border','1px solid #009EE0');	
	}
	
	if ($('#iemail').val()=='') 
	{
		$('#iemail').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#iemail').css('border','1px solid #009EE0');	
	}
	
	if ($('#istreet').val()=='') 
	{
		$('#istreet').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#istreet').css('border','1px solid #009EE0');	
	}
	
	if ($('#istreet_no').val()=='') 
	{
		$('#istreet_no').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#istreet_no').css('border','1px solid #009EE0');	
	}
	
	if ($('#istreet_flat_no').val()=='') 
	{
		$('#istreet_flat_no').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#istreet_flat_no').css('border','1px solid #009EE0');	
	}
	
	if ($('#ipost_code').val()=='') 
	{
		$('#ipost_code').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#icode').css('border','1px solid #009EE0');	
	}
	
	if ($('#icity').val()=='') 
	{
		$('#icity').css('border','1px solid red');
		error = true;
	}
	else
	{
		$('#ipost_city').css('border','1px solid #009EE0');	
	}

	if ($('#ishipping:checked').val() == null) 
	{
		alert('Wybierz rodzaj dostawy');
		error = true;
	}
	
	if ($('#ishipping2:checked').val() == null) 
	{
		alert('Musisz zaznaczyć płatność 10PLN przy odbiorze');
		error = true;
	}
	
	//if ( !($('#ipayment-1:checked').val()==1 || $('#ipayment-2:checked').val()==2) )
	//{
	//	alert('Wybierz rodzaj płatności');
	//	error = true;		
	//}
	
	if ($('#iconfirm:checked').val() == null) 
	{
		alert('Musisz zaakceptować regulamin');
		error = true;
	}
	
	if (error)
	{
		return false;	
	}
	
	if ( $('span.respond').hasClass('invalid') ) {
		$('input[name=discount]').val('');
	}
	
	$.span2input()
	
	var sum = 0;
	$('tr[data-id]').each(function(){
		var val = $(this).find('td:last .newPrice').text().split(' ');
		sum += parseFloat(val[0]);
	});
	var total = $('input.newPrice.total').val().split(' '); 
	if ( (sum + 24.99).formatPrice() != total[0] && total[0].length != 0 ) {
		window.location.reload();
		return false;
	}
	
	return true;
}
