$(document).ajaxStart(function(){
	dialog = $("#dialog-message").dialog({
		modal: true,
		resizable: false,
		draggable: false,
		minHeight: 10,
		open: function(){
			$('.ui-dialog-titlebar').hide();
		},
		close: function(){
			$('.ui-dialog-titlebar').show();
		}
	});
})
$(document).ajaxStop(function(){
	dialog.dialog('destroy');
});

$(document).ready( function(){	
	var liSelected = $('div.menu li.selected');
	var topIconBig = $('#top_icon_big');
	
	$('.clearInput').clearingInput();
	
	$('.blank').bind("click", function(e){
		e.preventDefault();
		
		var a = $(e.target);
		while ( typeof a.attr("href") == "undefined" ) a = $(a.parent("a").get(0));

		window.open(a.attr("href"), a.attr("title"));
		return false;
	});
	
	$('.goback').bind('click', function(){
		history.go(-1);
		
		return false;
	});
	
	var icons = $('div#top div.inside div.icons img');
	icons.mousemove(function(e){
		topIconBig.css('left', e.pageX-topIconBig.width()/2);
		topIconBig.css('top', e.pageY+10);
	});
	icons.mouseenter(function(){
		topIconBig.show()
		topIconBig.attr('src', $(this).attr('src').replace(".png", "_big.png"));
		icons.stop();
		$(this).siblings().fadeTo(250, 0.3);
		$(this).fadeTo(250, 1)
	});
	icons.mouseleave(function(){
		topIconBig.hide();
		icons.stop();
		icons.fadeTo(500, 1)
	});
	
	$('div.menu li.tree > a').bind("click", function(){
		if( $(this).next('ul').css('display') == 'block' ) return false;
		
		$('div.menu li.tree ul').hide(200);
		$(this).next('ul').toggle(200);
		
		return false
	});
	
	if (liSelected.length) 
	{
		liSelected.parent('ul').css('display', 'block');
		
		var liposition = liSelected.position();
		$('div#selected_arrow').css({
			display : 'block',
			top : liposition.top+(liSelected.height()/2)-3.5,
			left : liposition.left + liSelected.width()+1
		});
		
		if ( jQuery.browser.msie )
			ie_apply_zindex('selected_arrow', 2);
	}
	
	$('#step1').animate({ top : '0' }, 1000, 'swing', function(){
		$('#step2').animate({ top : '0' }, 800, 'swing', function(){
			$('#step3').animate({ top : '0' }, 800, 'swing');
		});
	});
	
	if( jQuery.browser.msie )
		$('div#body div.sidebar div.menu > ul').corner("tl 9px");
	else
		$('div#body div.sidebar div.menu > ul > li:not(.main):first > a').corner("tl 9px");
	$('div#body div.sidebar div.menu > ul').corner("bl 9px");
	$('div#add_info.small ul').corner("bl tl 8px");
	$('div#tabs ul li').corner("top 12px");

	selected = 0;
	if( document.location.href.indexOf('/pizza/') != -1 ) selected = 1;
	else if( document.location.href.indexOf('startery') != -1 ) selected = 2;
	else if( document.location.href.indexOf('salatki') != -1 ) selected = 3;
	else if( document.location.href.indexOf('napoje') != -1 ) selected = 4;
	else if( document.location.href.indexOf('skomponuj') != -1 ) selected = 5;
	
	if( $('div#tabs ul li').length < 6 ) --selected;
	var $tabs = $('#tabs').tabs({
		'selected' : selected,
	    load: function(){			
	        $('a.tabs5').click(function() {
	            $tabs.tabs('select', $('div#tabs ul li').length-1);
				
	            return false;
	        });

			if (jQuery.browser.msie) {
				$('table.menu tbody tr.hot td:first-child, table.menu tbody tr.veg td:first-child').addClass('firstChild');
				$('table.menu thead th.prices > div, table.menu tbody td.prices > div, ol.big > li, ol.big li > div').addClass('firstLevelChild');
			}
			
			$('#print').click(function(){
				if( $(this).attr('href').indexOf('wybierzLokal') == -1 ){
					window.open('/drukuj.html', '_blank');
					
					return false;
				}
			});
			
			$('.special_popup').click(function(){
				var s_popup = $('.special_modal');
				s_popup.fadeIn(500);
				
				$('.special_modal a.close').click(function(){
					s_popup.fadeOut(500);
					
					return false;
				})
				
				return false;
			});
	    }
	});
	
	$('#accordion').accordion({
		autoHeight : false,
		change: function(event, ui) {
			document.location.hash = $(ui.newHeader).attr('href').substr(1);
			
			$(ui.newContent).find("img").each(function(){
				var self = this;
				
				if (!self.loaded) {
                    $("<img />")
                        .bind("load", function() {
                            $(self)
                                .hide()
                                .attr("src", $(self).data("img"))
                                .fadeIn(1000);
                            self.loaded = true;
                        })
                        .attr("src", $(self).data("img"));
                };
			})
		}
	});
	$('#accordion div:not(.ui-accordion-content-active) img').each(function(){
		$(this).data('img', $(this).attr('src'));
		$(this).removeAttr('src');
	});
	
	$('div#step1 select[name="city"]').bind('change', function(){
		var restaurantSelect = $('div#step1 select[name="restaurant"]');
		
		$('div#step1 select[name="restaurant"] option:not(:first)').remove();
		if ( $(this).val() == 0 )
		{
			restaurantSelect.attr('disabled', 'disabled');
		}else{
			$.ajax({
				type : "GET",
				url : '/lokale/getRestaurants/'+$(this).val(),
				success : function(data){
					var restaurants = $(data).find("restaurant");
					if (restaurants.length == 1) 
						ajaxRestaurant($(restaurants[0]).attr('id'));
					else {
						restaurants.each(function(){
							restaurantSelect.append('<option value="' + $(this).attr("id") + '">' + $(this).text() + '</option>')
						});
						restaurantSelect.attr('disabled', '');
					}
				}
			});
		}
	});
	
	if ( $('div#step1 select[name="city"]').val() != 0 && $('#step1 form').css('display') != 'none' )
		$('div#step1 select[name="city"]').change();
	
	$('div#step1 select[name="restaurant"]').bind('change', function(){
		if ( $(this).val() != 0 )
			ajaxRestaurant($(this).val());
	});
	
	$('div#step1 div.restaurant a').bind('click', function(){
		$('div#step1 select[name="city"]').val(0)
		$('div#step1 div.restaurant span:first').html('');
		$('div#step1 div.restaurant span.big').html('');
		
		$('div#step1 form').css('display', 'block');
		$('div#step1 div.restaurant').css('display', 'none');
		
		$.cookie('city_id', 0);
		$.cookie('restaurant_id', 0);
		if ( document.location.href.indexOf('lokale') != -1 || document.location.href.indexOf('promocje') != -1 || document.location.href.indexOf('menu') != -1 )
			document.location.href = document.location.href;
		
		return false;
	});
	
	$('div.map.extended select[name="city"]').bind('change', function(){
		var restaurantSelect = $('div.map.extended select[name="restaurant"]');
		
		$('div.map.extended select[name="restaurant"] option:not(:first)').remove();
		if ( $(this).val() == 0 )
		{
			restaurantSelect.attr('disabled', 'disabled');
		}else{
			$.ajax({
				type : "GET",
				url : '/lokale/getRestaurants/'+$(this).val(),
				success : function(data){
					var restaurants = $(data).find("restaurant");
					var one = ( restaurants.length == 1 );
					
					restaurants.each(function(){
						restaurantSelect.append('<option value="'+$(this).attr("id")+'" '+( one ? 'selected="selected"' : '' )+'>'+$(this).text()+'</option>')
					});
					restaurantSelect.attr('disabled', '');
					
					if( one )
						restaurantSelect.closest('form').submit();
				}
			});
		}
	});
	
	$('.setrestaurant').bind('click', function(event){
		if( $(event.target).is("a:not(.setrestaurant)") ) return true;
		var id = null;
		
		if( $(this).is("a.setrestaurant") )
			id = $(this).closest('li.setrestaurant').attr('id');
		else if( $(this).is("li.setrestaurant") )
			id = $(this).attr('id');
		if( id )
			ajaxRestaurant(id);
		
		return false;
	})
	
	var dobInput = $('input[name="dob"]');
	if( dobInput.length ) 
	{
		var now = new Date();
		var thisYear = now.getYear();
		
		if (jQuery.browser.msie){
			var startYear = thisYear - 70;
			var endYear = thisYear -3;
		}
		else {
			var startYear = thisYear - 70 + 1900;
			var endYear = thisYear -3 + 1900;
		}
		dobInput.datepicker({
			dateFormat: 'dd-mm-yy',
			firstDay: 1,
			changeMonth: true,
			changeYear: true,
			defaultDate : '-15y',
			yearRange: startYear+':'+endYear,
			showOtherMonths: true
		});
	}
	
	$('#franchising_source').bind('change', function(){
		$('#other_source').css('display', $(this).val() == 5 ? '' : 'none') 
	});
	
	if ($('#agreement').length) {
		var formAgreement = $('#agreement').closest('form');
		var email_reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		formAgreement.bind('submit', function(){
			var err = false;
			if( $('#name').val().length < 3 ){
				$('#name').addClass('red')
				err = true;
			}else $('#name').removeClass('red');
			if( $('#surname').val().length < 3 ){
				$('#surname').addClass('red')
				err = true;
			}else $('#surname').removeClass('red');
			if( $('#email').val().length < 3 || !email_reg.test($('#email').val()) ){
				$('#email').addClass('red')
				err = true;
			}else $('#email').removeClass('red');
			if( $('#phone').val().length < 3 ){
				$('#phone').addClass('red')
				err = true;
			}else $('#phone').removeClass('red');
			if( $('#city :selected').val() == 0 ){
				$('#city').addClass('red')
				err = true;
			}else $('#city').removeClass('red');
			if( $('#registerRestaurant').css('display') != 'none' && $('#restaurant :selected').val() == 0 ){
				$('#restaurant').addClass('red')
				err = true;
			}else $('#restaurant').removeClass('red');
			if( $('#dob_day :selected').val() == 0 ){
				$('#dob_day').addClass('red')
				err = true;
			}else $('#dob_day').removeClass('red');
			if( $('#dob_mth :selected').val() == 0 ){
				$('#dob_mth').addClass('red')
				err = true;
			}else $('#dob_mth').removeClass('red');
			if( $('#dob_year :selected').val() == 0 ){
				$('#dob_year').addClass('red')
				err = true;
			}else $('#dob_year').removeClass('red');
			
			if (err) {
				alert('Uzupełnij poprawnie wszystkie pola formularza.')
				
				return false
			}
			
			var updateStrefa = $('#updateStrefa').length;
			if (!$('#agreement').attr('checked')) {
				alert('Aby kontynuować proszę wyrazić zgodę na przetwarzanie danych.');
			}else if( updateStrefa == 0 ){
				$(this).find('input[type="submit"]').val('Wysyłam...');
				$(this).find('input[type="submit"]').attr('disabled', true);
				
				$.post($(this).attr('action'), formAgreement.serialize(), function(data){
					var code = parseInt(data);
					if( code == 201 ){
						if( confirm("Należysz już do Twojej Strefy, czy chcesz zaktualizować dane?") ){
							formAgreement.append($('<input type="hidden" name="update" value="1" id="updateStrefa" />'));
							formAgreement.submit();
						}else window.location.href = '/strefa/wynik/212.html';
					}else if( !isNaN(code) && code < 4 ) window.location.href = '/strefa/wynik/22.html';
					else  window.location.href = '/strefa/wynik/212.html';
				}, "text");
			}
			
			if( updateStrefa == 0 )
				return false;
		});
	}
	
	if( $('#refer').length )
		$('#refer').bind('click', function(){
			$('table.disabled input').attr('disabled', !$(this).attr('checked'));
		});
		
	var popup = $('#popup');
	if ( popup.length && $.cookie('telepizza_popup') == null ) 
	{
		popup.css('display', 'block');
		
		$('#popup img').bind('load', function(){
			popup.css({
				top: $(window).height() / 2 - popup.height() / 2,
				left: $(window).width() / 2 - popup.width() / 2
			});
		});
		
		$('#popup a.close').click(function(){
			popup.hide();
			$.cookie('telepizza_popup', true);
			
			return false;
		})
	}
	
	var flowplayers = $('.flowplayer');
	if( flowplayers.length ){
		flowplayer("a.flowplayer", "/images/flowplayer.swf", {
			key: '#$d64bb6db7a4208b4a3f',
			clip: {
				autoPlay: false,
				bufferLength: 10,
				autoBuffering: true
			},
			canvas: {
				backgroundColor: "#9d281b"
			},
			play : {
				replayLabel: 'Odtwórz ponownie'
			},
			plugins: {
			   controls: {
			      bufferGradient: 'none',
			      progressColor: '#D00000',
			      timeBgColor: '#262626',
			      bufferColor: '#C78F8E',
			      tooltipColor: '#C9C9C9',
			      sliderColor: '#C9C9C9',
			      buttonOverColor: '#FF0000',
			      volumeSliderGradient: 'none',
			      durationColor: '#ffffff',
			      volumeSliderColor: '#D00000',
			      timeColor: '#B1E0FC',
			      progressGradient: 'none',
			      buttonColor: '#000000',
			      backgroundColor: '#9d281b',
			      tooltipTextColor: '#D00000',
			      borderRadius: '0px',
			      backgroundGradient: 'high',
			      sliderGradient: 'none',
			      height: 24,
			      opacity: 1.0,
				  url: '/images/flowplayer.controls.swf'
			   }
			}
		});
	}
	
	$('#city.register').bind('change', function(){
		var restaurantSelect = $('#registerRestaurant select');
		
		$('#registerRestaurant select option:not(:first)').remove();
		if ( $(this).val() == 0 )
		{
			restaurantSelect.attr('disabled', 'disabled');
		}else{
			$.ajax({
				type : "GET",
				url : '/lokale/getRestaurants/'+$(this).val(),
				success : function(data){
					var restaurants = $(data).find("restaurant");
					var one = ( restaurants.length == 1 );
					
					restaurants.each(function(){
						restaurantSelect.append('<option value="'+$(this).attr("id")+'" '+( one ? 'selected="selected"' : '' )+'>'+$(this).text()+'</option>')
					});
					restaurantSelect.attr('disabled', '');
					
					if( !one )
						$('#registerRestaurant').show();
					else $('#registerRestaurant').hide();
				}
			});
		}
	});
});

function ajaxRestaurant(id)
{
	$.ajax({
		type : "GET",
		url : '/lokale/getRestaurant/'+parseInt(id),
		success : function(data){
			setRestaurant(data);
		}
	});
}

function setRestaurant(data)
{
	$('div#step1 div.restaurant span:first').html($('city', data).text()+', '+$('address', data).text());
	$('div#step1 div.restaurant span.big').html($('phone_numbers phone_number:first', data).text());
	
	$('div#step1 form').css('display', 'none');
	$('div#step1 div.restaurant').css('display', 'block');
	
	$('div#step1 select[name="restaurant"] option:not(:first)').remove();
	$('div#step1 select[name="restaurant"]').attr('disabled', 'disabled');
	$('div#step1 select[name="city"]').val(0);
	$.cookie('city_id', $('city', data).attr('id'));
	$.cookie('restaurant_id', $('restaurant', data).attr('id'));

	if ( document.location.href.indexOf('wybierzLokal') != -1 )
		document.location.href = '/lokale.html';
	else if (document.location.href.indexOf('wybierzMiasto') != -1) 
	{
		var red = $('input[name="redirect"]').val();
		if( red == 'menu' )
			document.location.href = '/menu.html';
		else if( red == 'promocje' )
			document.location.href = '/promocje.html';
	}
	//else if (document.location.href.indexOf('menu') != -1)
	else 
		document.location.href = document.location.href;
}

function getCities(state_id)
{
	$.ajax({
		type : "GET",
		url : '/pobierzMiasta/'+state_id,
		success : function(data){
			var citiesSelect = $('div.body select[name="city"]');
			if( jQuery.browser.msie )
				var width = citiesSelect.width();
			$('div.body select[name="city"] option:not(:first)').remove();
			$(data).find("city").each(function(){
				citiesSelect.append('<option value="'+$(this).attr("id")+'">'+$(this).text()+'</option>')
			});
			if( jQuery.browser.msie )
				citiesSelect.width(width+4);
		}
	});
}
