var Order = {
	filter: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,

	validate_time: function(time, day, month)
	{
		if (time.val() != '' && Order.is_time(time.val()) && day.val() > 0 && month.val().length > 5)
		{
			Order.toggle_continue('continue-order', 'enable');
		}
		else
		{
			Order.toggle_continue('continue-order', 'disable');
		}
	},
	
	validate_personal_info: function(name, phone, email)
	{
		if (name.val() != '' && Order.is_phone_number(phone.val()) && (email.val() == '' || (Order.filter).test(email.val())) )
		{
			Order.toggle_continue('continue-order', 'enable');
		}
		else
		{
			Order.toggle_continue('continue-order', 'disable');
		}
	},

	validate_notification_info: function(name, phone, email, date)
	{
		if (name.val() != '' && Order.is_phone_number(phone.val()) && date.val() != '' && (email.val() == '' || (Order.filter).test(email.val())) )
		{
			Order.toggle_continue('finish-notification', 'enable');
		}
		else
		{
			Order.toggle_continue('finish-notification', 'disable');
		}
	},

	toggle_continue: function(button, state)
	{
		if (state == 'enable')
		{
			$('#' + button)
				.removeClass('disabled')
				.removeAttr('disabled');
		} else {
			$('#' + button)
				.addClass('disabled')
				.attr('disabled', 'disabled');
		}
	},

	deactivate: function(step)
	{
		$('#progress li').each(function() {
			var _tmp_id = $(this).attr('id');

			_tmp_id.match('progress-([0-9]+)');

			if (RegExp.$1 > step)
			{
				$('#progress-' + RegExp.$1)
					.find('a').replaceWith(
						$('<strong />')
					)
					.end();
			}
		});
	},

	activate: function(step)
	{
		$('#progress-' + step)
			.find('strong').replaceWith(
				$('<a />').attr('href', '#')
			)
			.end()
			.addClass('selected');
	},

	save: function()
	{
		 var result = $.ajax(
			{
				type: 'POST',
				url: $links.order_save,
				data: ({notification : $('input#notification').is(':checked')}),
				async: false
			}).responseText;

		return (result.substr(0, 4) == 'TRUE') ? true : result;
	},

	save_notification: function()
	{
		 var result = $.ajax(
			{
				type: 'POST',
				url: $links.notification_save,
				data:
				{
					ecv : $('#notify_license_plate').val(),
					date : $('#notify_date').val(),
					name : $('#notify_name').val(),
					email : $('#notify_email').val(),
					phone : $('#notify_phone').val()
				},
				async: false
			}).responseText;

		return (result.substr(0, 4) == 'TRUE') ? true : result;
	},
	
	get_times: function(selected_time)
	{
		$.post(
			$links.order_json,
			{
				month: $('#_month').val()
				, branch: $('#_branch').val()
				, day: $('#_day').val()
			},
			function(times) {
				$('#order-form-step-3 table td')
					.removeClass('today');

				$link.parent()
					.addClass('today');
			
				var new_times = '';

				var column_width = Math.ceil(100 / times.first.length) - 1;
			
				$.each(times.first, function(i,tweet){
					new_times += '<ol style="width: ' + column_width + '%"><li class="hour">' +  tweet.hour_title + '</li>';
					
					$.each(tweet.periods, function(j, period){
						new_times += '<li><a href="#" class="time'+ (('#'+period.id == selected_time) ? ' selected' : '')+'" id="' +  period.id + '">' +  period.time + '</a></li>';
					});

					new_times += '</ol>';
				});

				$('#time-first-block').html(new_times);

				new_times = '';
				$.each(times.second, function(i,tweet){
					new_times += '<ol style="width: ' + column_width + '%"><li class="hour">' +  tweet.hour_title + '</li>';

					$.each(tweet.periods, function(j, period){
						new_times += '<li><a href="#" class="time'+ (('#'+period.id == selected_time) ? ' selected' : '')+'" id="' +  period.id + '">' +  period.time + '</a></li>';
					});

					new_times += '</ol>';
				});

				$('#time-second-block').html(new_times);

				$.fancybox.hideActivity();
			},
			'json'
		);
		
	},

	step: function(step, options)
	{
		options = options || {};

		switch (parseInt(step))
		{
			case 5:
				$.post($links.order_uri + '5/', options, function(data) {
					Order.activate(5);

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

					$('#order-form-step-5').submit(function() {
						Order.toggle_continue('finish-order', 'disable');

						var status = Order.save();

						Order.toggle_continue('finish-order', 'enable');
						
						if (status == true)
						{
							return true;
						}
						else
						{
							alert(status);
							return false;
						}
					});
				});

				break;

			case 4:
				$.post($links.order_uri + '4/', options, function(data) {
					Order.activate(4);

//					$('#_time').val($('#time').val());

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

					$('#name').focus();

					$('#order-form-step-4').submit(function() {
						return Order.step(5, {
							branch: $('#_branch').val()
							, month: $('#_month').val()
							, day: $('#_day').val()
							, time: $('#_time').val()
							, name: $('#name').val()
							, email: $('#email').val()
							, phone: $('#phone').val()
							, vehicle_type_id: $('#vehicle_type').val()
							, type_id: $('#type').val()
							, vehicle_type_text: $("#vehicle_type option[value='" + $('#vehicle_type').val() + "']").text()
							, type_text: $("#type option[value='" + $('#type').val() + "']").text()
							, license_plate: $('#license_plate').val()
							, vehicle: $('#vehicle').val()
						});
					});

					$('select').selectbox();

					Order.validate_personal_info($('#name'), $('#phone'), $('#email'));
				});

				break;

			case 3:
	
				
				break;

			case 2:
				$.post($links.order_uri + '2/',
				{
					branch: $('#_branch').val(),
					day: $('#_day').val()
				}
				, function(data) {
					var _station_name = (options.set_station_name == true)
						? ($('#branch-' + $('#_branch').val() + ' strong').text() || $('#branch-' + $('#_branch').val() + ' b').text())
						: null;

					Order.activate(2);

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

					$('#order-form-step-2').submit(function() {
						return Order.step(4, {
							branch: $('#_branch').val()
							, month: $('#_month').val()
							, day: $('#_day').val()
							, time: $('#_time').val()
							
						});
					});
								

					$('select').selectbox()
						.change(function() {
							$.fancybox.showActivity();

							$link = $(this);
							$.post(
								$links.calendar_uri,
								{
									month: $('#month').val(),
									branch: $('#_branch').val()
								},
								function(data)
								{
									$('#_month').val($('#month').val());
									$('#_day').val('');
									$('#_time').val('');
								
									$('#date').html(data);
							
									$('#time-first-block').html('');
									$('#time-second-block').html('');
									Order.toggle_continue('continue-order', 'disable');

									$.fancybox.hideActivity();
								}
							);
						});
						
	                    var selected_time = $('#_time').val();	
						
	                    if (selected_time.length > 2)
	                    {
	                        selected_time = '#' + selected_time.replace(':', '-');
	                        $(selected_time).addClass('selected');
	                    }
							
						if ($('#_day').val() > 0)
						{
							Order.get_times(selected_time);
						}
						
						Order.validate_time($('#_time'), $('#_day'), $('#_month'));

	
					if (_station_name != null)
					{
						$('span.station').text(_station_name);
					}
				});

				break;

			case 1:
			default:
				$.post($links.order_uri + '1/', {}, function(data) {
					$('#steps').html(data);

					$('#order-form-step-1').submit(function() {
						return Order.step(2, {
							branch: $('#_branch').val()
							, set_station_name: false
						});
					});
				});

				break;
		}

		return false;
	},

	validate_unsubscription: function(code)
	{
		var match = code.match('[a-z0-9]{10}');

		return (match == null) ? false : true;
	},

	is_phone_number : function(s)	{
		s = s.replace(/\s+/g, '');
		
		var match = s.match('^[+]{1}[4]{1}[2]{1}[1]{1}[0-9]{9}$');

		return (match == null) ? false : true;
	},

	is_time : function(s)	{
		var match = s.match('^[0-9]{1,2}[:]{1}[0-9]{2}$');

		return (match == null) ? false : true;
	}
}

$(document).ready(function() {
	
	$('.time').live('click', function(){

		var time = $(this);

		$('#_time').val(time.text());
		$('.time').removeClass('selected');
		time.addClass('selected');
		Order.validate_time($('#_time'), $('#_day'), $('#_month'));
		return false;
	});

	$('#keyword').focus(function() {
		if ($(this).val() == $(this).get(0).defaultValue)
		{
			$(this).val('');
		}
		else
		{
			$(this).select();
		}
	}).blur(function() {
		if ($(this).val() == '')
		{
			$(this).val($(this).get(0).defaultValue);
		}
	});

	$('#notification').fancybox({
		'titleShow'				: false,
		'autoDimensions'		: false,
		'showCloseButton'		: false,
		'showNavArrows' 		: false,
		'hideOnOverlayClick' 	: false,
		'enableEscapeButton' 	: false,
		'enableKeyboardNav' 	: false,
		'scrolling' 			: 'no',
		'width' 				: 700,
		'height' 				: 600,
		'overlayColor' 			: '#000',
		'overlayOpacity' 		: 0.7,
		'autoDimensions' 		: false,
		'autoScale' 			: false,
		'onStart' 				: function() {
			$('#notify-container').css('display', 'block');

			$.datepicker.setDefaults({
				dateFormat: 'dd.mm.yy'
				, minDate: 0
				, changeMonth: true
				, changeYear: true
			});

			$('#notify_date').datepicker();

			$('#notify-container form').submit(function() {
				Order.toggle_continue('finish-notification', 'disable');

				var status = Order.save_notification();

				Order.toggle_continue('finish-notification', 'enable');

				if (status == true)
				{
					return true;
				}
				else
				{
					alert(status);
					return false;
				}
			});
		}
	});

	$('#close-notification').live('click', function()
	{
		$.fancybox.close();

		$('#notify-container').css('display', 'none');
	});

	$('#notify-container input').live('keydown, keyup, change', function() {
		Order.validate_notification_info($('#notify_name'), $('#notify_phone'), $('#notify_email'), $('#notify_date'));
	});


	$('#order, a.order').fancybox({
		'titleShow'				: false,
		'autoDimensions'		: false,
		'showCloseButton'		: false,
		'showNavArrows' 		: false,
		'hideOnOverlayClick' 	: false,
		'enableEscapeButton' 	: false,
		'enableKeyboardNav' 	: false,
		'scrolling' 			: 'no',
		'width' 				: 700,
		'height' 				: 500,
		'overlayColor' 			: '#000',
		'overlayOpacity' 		: 0.7,
		'autoDimensions' 		: false,
		'autoScale' 			: false,
		'onStart' 				: function() {
			$('#order-container').css('display', 'block');
		},
		'onComplete' 			: function() {
			Order.step(1);
		}
	});

	$('.jump-back').live('click', function() {
		var id = $(this).attr('id');

		if (id.match('back-([0-9]+)'))
		{
			var step = RegExp.$1;

			Order.deactivate(step);

			Order.step(step);
		}

		return false;
	});

	$('#map a').live('click', function() {
		var id = $(this).attr('id');

		if ($(this).attr('class') == 'sub')
		{
			$('#map a.sub').removeClass('selected');

			// Order.toggle_continue('continue-order', 'enable');

			if (id.match('branch-([0-9]+)'))
			{
				var _tmp = RegExp.$1;
				$('#_branch').val(_tmp);
			}

			Order.step(2);
		}
		else
		{
			$('#map a').removeClass('selected');

			if (id == 'branch-ba')
			{
				$(this)
					.siblings('div').removeClass('hidden');

				$('#_branch').val('');

				// Order.toggle_continue('continue-order', 'disable');
			}
			else
			{
				$('#map div').addClass('hidden');

				// Order.toggle_continue('continue-order', 'enable');

				if (id.match('branch-([0-9]+)'))
				{
					var _tmp = RegExp.$1;
					$('#_branch').val(_tmp);
				}

				Order.step(2);
			}
		}

		$(this).addClass('selected');

		return false;
	});

	$('#order-form-step-2 table a').live('click', function() {
		$('#order-form-step-2 table td')
			.removeClass('today');

		$('#_month').val($('#month').val());
		$('#_day').val($(this).text());

		$(this).parent()
			.addClass('today');
// PRIDANE
	$.fancybox.showActivity();

	$('#_day').val($(this).text());
	
	$('#_time').val('');
	Order.toggle_continue('continue-order', 'disable');
	
	$link = $(this);

	$.post(
		$links.order_json,
		{
			month: $('#_month').val()
			, branch: $('#_branch').val()
			, day: $(this).text()
		},
		function(times) {
			$('#order-form-step-3 table td')
				.removeClass('today');

			$link.parent()
				.addClass('today');

			var new_times = '';

			var column_width = Math.ceil(100 / times.first.length) - 1;

			if (times.first.length == 0)
			{
				$('#time-first-block').html($phrases.no_free_time);
				$('#time-second-block').html('');
			}
			else
			{
				$.each(times.first, function(i,tweet){
					new_times += '<ol style="width: ' + column_width + '%"><li class="hour">' +  tweet.hour_title + '</li>';
				
					$.each(tweet.periods, function(j, period){
						new_times += '<li><a href="#" class="time" id="' +  period.id + '">' +  period.time + '</a></li>';
					});
				
					new_times += '</ol>';
				});

				$('#time-first-block').html(new_times);

				new_times = '';
				$.each(times.second, function(i,tweet){
					new_times += '<ol style="width: ' + column_width + '%"><li class="hour">' +  tweet.hour_title + '</li>';

					$.each(tweet.periods, function(j, period){
						new_times += '<li><a href="#" class="time" id="' +  period.id + '">' +  period.time + '</a></li>';
					});

					new_times += '</ol>';
				});

				$('#time-second-block').html(new_times);
			}

			$.fancybox.hideActivity();
		},
		'json'
	);

// KONIEC PRIDANE

		return false;
	});

	$('#order-form-step-4 input').live('blur', function() {
		var name = $(this).attr('name');
		var value = $(this).val();

		if (name == 'name' && value == '')
		{
			$(this).addClass('error');

			Order.toggle_continue('continue-order', 'disable');
		}
		else if (name == 'phone' && !Order.is_phone_number(value))
		{
			$('#phone').addClass('error');
			Order.toggle_continue('continue-order', 'disable');
		}
		else
		{
			$(this).removeClass('error');
		}

   
	});

	$('#order-form-step-4 input').live('keydown, keyup', function() {
		Order.validate_personal_info($('#name'), $('#phone'), $('#email'));
	});

	$('#close-order').live('click', function()
	{
		if ($('#_branch').val() != 0)
		{
			if (confirm($phrases.close))
			{
				Order.deactivate(1);

				$.fancybox.close();
			}
			else
			{
				return false;
			}
		}

		$.fancybox.close();

		$('#order-container').css('display', 'none');

		return false;
	});

	$('#progress a').live('click', function() {
		var id = $(this).parent('li').attr('id');

		id.match('progress-([0-9]+)');

		var step = RegExp.$1;

		Order.deactivate(step);

		return Order.step(step);
	});

	$('#confirmation_code').live('keydown, keyup', function() {
		if (Order.validate_unsubscription($(this).val()))
		{
			$('#continue-unsubscribe')
				.removeClass('disabled')
				.removeAttr('disabled');
		} else {
			$('#continue-unsubscribe')
				.addClass('disabled')
				.attr('disabled', 'disabled');
		}
	});

	$('#unsubscribe').submit(function()
	{
		return Order.validate_unsubscription($('#confirmation_code').val());
	});
});

