/* Flight Module Start */

function flightIncludePegasus(is_return)	{
	
	if (is_return == 1) var _selector_1 = '#sl-trips-cont';
	else var _selector_1 = '#fl-trips-cont';
	
	$.ajax({
		type: "GET",
		url: ROOT+"ucak-bileti/get-pegasus-flights?ajax=1&nossl=1&is_return="+is_return,
		dataType: "json",
		beforeSend: function(){
			$(_selector_1).append(
				'<div id="pegasus_results_loading" style="font-size:13px;font-weight:bold;line-height:30px;padding:5px 0;text-align:center;">' +
				'Pegasus Havayolları\'na ait uçuşlar hazırlanıyor...</div>'
			);
		},
		error: function(){$('#pegasus_results_loading').remove();},
		success: function(data){
			$('#pegasus_results_loading').remove();

			if (data.error)	{
				
			}
			else	{
				pegasus_data = data.price_array;
				pegasus_sort_pocket = Array();
				
				$(_selector_1+' .trip-row').each(function(_index){
					
					var price_elm = $(this).find('.trip-price');
					var total_price = parseInt(price_elm.attr('total_fare'));

					for (i=0; i<pegasus_data.length; i++)	{
						//there is a bug in here inArray
						if (parseInt(pegasus_data[i])<=total_price && $.inArray(pegasus_data[i], pegasus_sort_pocket)==-1)	{
							if (_index>1)	{
								$(this).before(data.html[i]);
							}
							pegasus_sort_pocket.push(pegasus_data[i]);
						}
					}
				});

				if (pegasus_data.length!=pegasus_sort_pocket.length)	{
					for (i=0; i<pegasus_data.length; i++)	{
						if ($.inArray(pegasus_data[i], pegasus_sort_pocket)==-1)	{
							$(_selector_1).append(data.html[i]);
							pegasus_sort_pocket.push(pegasus_data[i]);
						}
					}
				}
			}
		}
	});
}

function flightCustomRange(input) {
	if (input.name == "ReturnDate")  {
		return {
			minDate: $("input[name=FlightDate]").datepicker("getDate"),
			maxDate: null
		};
	}
	else   {
		return {
			minDate: 0,
			maxDate: null
		};
	}
}

function flightGetComparisonResults(selected_trip)	
{
	$.ajax({
		type: "GET",
		url: ROOT+"ucak-bileti/get-comparison-results?nossl=1&selected="+selected_trip,
		beforeSend: function(){
			Busy = true;
			
			if (selected_trip != null)	{
				$("#select-a-trip-sl").html("DÖNÜŞ").removeClass("first-leg-green").fadeIn();
				
				$("#sl-trips-cont").html(
					"<div id=\"loadiding-trips-wide\">" +
                    "<div class=\"loading-img\"><img src=\""+ROOT+"img/v2/loading.gif\"/></div>" +
                    "<div class=\"loading-text\" style=\"font-size: 13px;\">Dönüş için uçuş bilgileriniz hazırlanıyor, lütfen bekleyin...</div>" +
                    "</div>"
				).parent().show();
				
				if (_blockui_include_maximum_card == true)  {
					$("#maximum_banner").show();
				}
				
			}
		},
		error: function(){
			Busy = false;
		},
		success: function(data){
			if (selected_trip == null)	{
				$("#flight_list").html(data);

				if ($("#fl-trips-cont .trip-row").length > 0 && $('#fl-trips-cont .trip-row:visible').length == 0)	{
					$('#fl-trips-cont .no-filtered-trip').show();
					$("#filter-airline").html(flightSetAirlineFilters());
				}
				else	{
					if ($("#fl-trips-cont .trip-row").length > 0)	{
						$("#select-a-trip-fl").fadeIn();
						$("#filter-airline").html(flightSetAirlineFilters());
						
						//include pagesus flights if available
						if (IsInternational == false && IncludePegasus > 0)	{
							flightIncludePegasus(0);
						}
					}
				}
			}
			else	{
				$("#sl-trips-cont").html(data);
				
				if ($("#sl-trips-cont .trip-row").length > 0 && $('#sl-trips-cont .trip-row:visible').length == 0)	{
					$('#sl-trips-cont .no-filtered-trip').show();
					$("#filter-airline").html(flightSetAirlineFilters());
				}
				else	{
					if ($("#sl-trips-cont .trip-row").length > 0)	{
						
						$("#select-a-trip-sl").html("Lütfen dönüş yönü için bir uçuş seçin").addClass("first-leg-green").fadeIn();
						$("#filter-airline").html(flightSetAirlineFilters());
						
						//include pagesus flights if available
						if (IsInternational == false && IncludePegasus > 0)	{
							flightIncludePegasus(1);
						}
					}
				}
			}
			
			Busy = false;
		}
	});
}

function flightSetAirlineFilters()
{
	filter_html = "<li class=\"item\">";
	
	if (FilterAirline == "")	{
		filter_html += "<span class=\"filter-item-2\">Tümü</span>";
	}
	else	{
		filter_html += "<a airline=\"\" href=\"#\" class=\"filter-item-1\">Tümü</a>"; 
	}

	filter_html += "</li>";
	
	if (IsInternational == false)	{
		
		if (filter_airlines != null)	{
			for (i=0; i<filter_airlines.length; i++)	{
				filter_html += "<li class=\"item\">";
				
				if (FilterAirline == filter_airlines[i])	{
					filter_html += "<span class=\"filter-item-2\">";
				}
				else	{
					filter_html += "<a airline=\""+filter_airlines[i]+"\" href=\"#\" class=\"filter-item-1\">";
				}
				
				if (filter_airlines[i] == 'THY') filter_html += "Türk Hava Yolları";
				else if (filter_airlines[i] == 'SUN') filter_html += "Sun Express";
				else if (filter_airlines[i] == 'ANJ') filter_html += "Anadolujet";
				else if (filter_airlines[i] == 'ATJ') filter_html += "Atlasjet";
				else if (filter_airlines[i] == 'ZY' || filter_airlines[i] == 'SKY') filter_html += "Sky";
				else if (filter_airlines[i] == 'BJT') filter_html += "Borajet";
				
				if (FilterAirline == filter_airlines[i]) filter_html += "</span>";
				else filter_html += "</a>";
				
				filter_html += "</li>";
			}
		}
	}
	else	{
		$.each(filter_airlines, function(k, v)	{

			filter_html += "<li class=\"item\">";
			
			if (FilterAirline == k)	{
				filter_html += "<span class=\"filter-item-2\">"+v+"</span>";
			}
			else	{
				filter_html += "<a airline=\""+k+"\" href=\"#\" class=\"filter-item-1\">"+v+"</a>";
			}
			
			filter_html += "</li>";
		});
	}
		
	return filter_html;
}

function flightClearFilters()
{
	$("input[name=FilterAirline], input[name=FilterDayPart]").val("");
	$('#FlightForm').submit();
}

function flightGetAutoCompleteSelectedFirstLeg()
{
    fl = $("input[name=Origin]").val();
    if (fl.length > 0) return fl;
}

function flightShowOverlay(cont_elm_id, msg)	{
	if (cont_elm_id != null)	{
		$('#'+cont_elm_id).block({ 
			overlayCSS: { 
				backgroundColor: '#419107',
				opacity: .2 
			},
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', 
			forceIframe: true,
			quirksmodeOffsetHack: 4,
			message: (msg == null ? "<h1 style='padding:0;color:#3366CC;font-family:arial,Verdana;font-size:18px;font-weight:bold;'>"
				+"<div style='padding-bottom:5px;'><img src='"+ROOT+"img/v2/loading.gif'/></div><div>İşleminiz gerçekleştiriliyor, lütfen bekleyin...</div>"
				+"</h1>" : msg),
			css: {
				padding: "15px 0"
			} 
		}); 	
	}
	else	{
		if (_blockui_include_maximum_card)	{
			$.blockUI({ 
				overlayCSS: { 
					backgroundColor: '#419107',
					opacity: .2 
				},
				iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', 
				forceIframe: true,
				quirksmodeOffsetHack: 4,
				message: (msg == null ? "<h1 style='padding:0;color:#3366CC;font-family:arial,Verdana;font-size:18px;font-weight:bold;'>"
					+"<div style='padding-bottom:5px;'><img src='"+ROOT+"img/v2/loading.gif'/></div><div>İşleminiz gerçekleştiriliyor, lütfen bekleyin...</div>"
					+"</h1>"
					+"<div style='margin-top: 15px;background-color: #e11d6f;'>"
			        +"<img src='"+ROOT+"img/v2/flight/maximum_loading.gif'/>"
			        +"</div>" : msg),
			    css: {
					padding: "15px 0 0"
				}
			});
		}
		else	{
			$.blockUI({ 
				overlayCSS: { 
					backgroundColor: '#419107',
					opacity: .2 
				},
				iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', 
				forceIframe: true,
				quirksmodeOffsetHack: 4,
				message: (msg == null ? "<h1 style='padding:0;color:#3366CC;font-family:arial,Verdana;font-size:18px;font-weight:bold;'>"
					+"<div style='padding-bottom:5px;'><img src='"+ROOT+"include/loading.gif'/></div><div>İşleminiz gerçekleştiriliyor, lütfen bekleyin...</div>"
					+"</h1>" : msg),
				css: {
					padding: "15px 0"
				}
			});
		}
	}
}

function flightHideOverlay(cont_elm_id)	{
	if (cont_elm_id)
		$('#'+cont_elm_id).unblock();
	else
		$.unblockUI();
}

function flightValidate(_form)	{
	var all_inputs = _form.find('input,select,textarea').filter(":input")
	.not(":submit, :reset, :image, [disabled]");

	//reset errors
	all_inputs.removeClass('error');
	$("div.error-cont").hide();
	var error = false;
	
	all_inputs.each(function(){
		//required check
		if ($(this).hasClass('required'))	{
			//select
			if (this.nodeName.toLowerCase()=='select')	{
				var val = $(this).val();
				if (!val || val.length == 0)	{
					$(this).addClass('error');
					error = true;
				}
			}
			//text
			else if (this.nodeName.toLowerCase()=='input' || this.nodeName.toLowerCase()=='textarea')	{
				if ($.trim(this.value).length == 0)	{
					$(this).addClass('error');
					error = true;
				}
			}
		}
		
		if ($(this).hasClass('masked_phone'))	{
			if (!/^0[0-9]{3} [0-9]{3} [0-9]{4}$/.test(this.value))	{
				$(this).addClass('error');
				error = true;
			}
		}

		if ($(this).hasClass('masked_mobile'))	{
			if (!/^05[0-9]{2} [0-9]{3} [0-9]{4}$/.test(this.value))	{
				$(this).addClass('error');
				error = true;
			}
		}

		if ($(this).hasClass('publicid'))	{
			if (!/^[0-9]{11}$/.test(this.value))	{
				$(this).addClass('error');
				error = true;
			}
		}

		if ($(this).hasClass('email') || $(this).hasClass('email2'))	{
			if (!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(this.value))	{
				$(this).addClass('error');
				error = true;
			}
			if($('.email').val() != $('.email2').val() ) {
				$(this).addClass('error');
				error = true;
			}
		}
		
		if ($(this).hasClass('creditcard'))	{
			if (!/^[0-9]{16}$/.test(this.value))	{
				$(this).addClass('error');
				error = true;
			}
		}
		
		if ($(this).hasClass('cvv'))	{
			if (!/^[0-9]{3}$/.test(this.value))	{
				$(this).addClass('error');
				error = true;
			}
		}
	});

	if (error)	{
		$("div.error-cont").html("Lütfen kırmızı renkli alanları eksiksiz doldurun.").fadeIn();
		window.parent.$('html, body').animate({
			scrollTop: $("div.error-cont:first").offset().top
		}, 1000);
	}
	
	return !error;
}

function flightValidatePassengers()	{
	var AdultCount = parseInt($('select[name=AdultCount]').val());
	var ChildCount = parseInt($('select[name=ChildCount]').val());
	var InfantCount = parseInt($('select[name=InfantCount]').val());
	var SeniorCount = parseInt($('select[name=SeniorCount]').val());
	var StudentCount = parseInt($('select[name=StudentCount]').val());
	
	if ((SeniorCount+AdultCount+StudentCount+ChildCount) > 4)	{
		alert('Bir seferde bebek hariç en fazla 4 yolcu için işlem yapılabilir.');
		return false;
	}
	
	if (InfantCount > AdultCount+SeniorCount)	{
		alert('Bebek yolcu sayısı, yetişkin ve yaşlı yolcu sayılarının toplamından fazla olamaz.');
		return false;
	}
	
	if (ChildCount > AdultCount+SeniorCount)	{
		alert('Çocuk yolcu sayısı, yetişkin ve yaşlı yolcu sayılarının toplamından fazla olamaz.');
		return false;
	}
	
	if (SeniorCount == 0 && AdultCount == 0)	{
		
		if (StudentCount == 0)	{
			alert('Yolculuklarınızda en az 1 adet yetişkin, öğrenci ya da 65 yaş üstü yolcu bulunmalıdır.');
			return false;
		}
		
		if (ChildCount > 0 || InfantCount > 0)	{
			alert('Çocuk ve bebek yolculara tek başlarına bilet kesilemez.');
			return false;
		}
	}

	return true;
}

function flightChargingFormHandler(is_iframe)	{
	
	$('#ChargingForm form').ajaxForm({
		dataType: 'json',
		beforeSubmit: function(){

			if (is_iframe)	{
				window.parent.$('.error-cont').hide().html('');
			}
			else	{
				$('.error-cont').hide().html('');
			}

			var CardName = $.trim($('input[name=CardName]').val());
			if (CardName.length<5)	{
				alert('Lütfen kartın üzerinde yazan ismi girin');
				$('input[name=CardName]').focus();
				Busy = false;
				return false;
			}
			if ($('input[name=CardNumber]').val().length!=16)	{
				alert('Lütfen 16 haneli kredi kartı numaranızı girin');
				$('input[name=CardNumber]').focus();
				Busy = false;
				return false;
			}
			if ($('input[name=CVV]').val().length!=3)	{
				alert('Lütfen kartınızın arkasında yazan 3 haneli CVV numarasını girin');
				$('input[name=CVV]').focus();
				Busy = false;
				return false;
			}
			
			if ($('select[name=CardDistributer]').val()==0)	{
				alert('Lütfen kartınızın türünü seçin');
				$('select[name=CardDistributer]').focus();
				Busy = false;
				return false;
			}
			
			/*if ($('select[name=CardType]').val()==0)	{
				alert('Lütfen kartınızın türünü seçin');
				$('select[name=CardType]').focus();
				Busy = false;
				return false;
			}*/

			Busy = true;
			flightShowOverlay(null, null);
		},
		success: function(data){
			if (data.status=='ok')	{
				//redirect for 3D
				if (data.gate)	{
					window.location.href = data.gate;
				}
			}
			else if (data.status=='NormalCharging')	{
				//open modal
				flightHideOverlay();
				Busy = false;
				$('#NormalChargingWidget input[name=mobile]').val(data.mobile);
				$("#NormalChargingWidget").dialog('open');
			}
			else if (data.status=='ContinueWith3D')	{
				//resubmit with 3D
				$('#ChargingForm form input[name=charging_method]').val(1);
				$('#ChargingForm form').submit();
			}
			else	{
				if (is_iframe)	{
					window.parent.$('.error-cont').html('Bir hata meydana geldi, lütfen bir süre bekleyip tekrar deneyin. Sorun devam ediyorsa destek almak için 0212-496-1697 numaralı telefonu arayabilirsiniz.').show();
					window.parent.$('html, body').animate({
						scrollTop: $(".bossayfa").offset().top
					}, 1000);
				}
				else	{
					$('.error-cont').html('Bir hata meydana geldi, lütfen bir süre bekleyip tekrar deneyin. Sorun devam ediyorsa destek almak için 0212-496-1697 numaralı telefonu arayabilirsiniz.').show();
					$('html, body').animate({
						scrollTop: $(".bossayfa").offset().top
					}, 1000);
				}
				flightHideOverlay();
				Busy = false;
			}
		},
		error: function(){
			alert('Bir hata meydana geldi. Lütfen tekrar deneyin...');
			flightHideOverlay();
			Busy = false;
		}
	});
	
	$('input[name=CardNumber]').keyup(function(){
		if (this.value.substring(0, 1)==5)	{
			$('select[name=CardType]').val('Master');
		}
		else if (this.value.substring(0, 1)==4)	{
			$('select[name=CardType]').val('Visa');
		}
		else	{
			$('select[name=CardType]').val('0');
		}
	});
	
	$('input[name=CardNumber]').blur(function(){
		if ($('input[name=CardNumber]').val().substring(0, 1)==5)	{
			$('select[name=CardType]').val('Master');
		}
		else {
			$('select[name=CardType]').val('Visa');
		}
	});	
	
	
	$("#NormalChargingWidget").dialog({
		autoOpen: false,
		modal: true,
		position: 'center',
		width: 550,
		height: 'auto',
		resizable: false,
		open: function(){}
	});

	$('#NormalChargingWidget').parent().css('border-color', '#55b4e8');

	$('#SmsCodeSubmit').click(function(e){
		e.preventDefault();

		if (!/^[0-9A-Za-z]{3,10}$/.test($('#NormalChargingWidget input[name=code]').val()))	{
			alert('Lüften geçerli bir doğrulama kodu girin.');
			$('#NormalChargingWidget input[name=code]').focus();
			return false;
		}

		$.ajax({
			type: "POST",
			url: ROOT+"ucak-bileti/validate-sms-code?ajax=1",
			data: {
				'mobile': $('#NormalChargingWidget input[name=mobile]').val(),
				'code': $('#NormalChargingWidget input[name=code]').val()
			},
			dataType: "json",
			beforeSend: function(){
				//$('#FavoriteForm').hide();
				//$('#FavFormLoading').show();
			},
			error: function(){
				alert('İşleminizi şu an gerçekleştiremiyoruz, lütfen daha sonra tekrar deneyin.');
				//$("#fav_search_dialog").dialog("close");
			},
			success: function(data){
				if (data.status=='ChargingFailed')	{
					$('#NormalChargingWidget').dialog('close');
					$('.error-cont').html('Ödeme sırasında bir hata meydana geldi, lütfen kart bilgilerinizi kontrol edip tekrar deneyin.').show();
					$('html, body').animate({
						scrollTop: $(".bossayfa").offset().top
					}, 1000);
				}
				else if (data.status=='ValidationCodeError')	{
					alert('Geçersiz bir sms doğrulama kodu girdiniz. Lütfen girdiğiniz kodu kontrol edip tekrar deneyin.');
				}
				else if (data.status=='ok')	{
					window.location.href = ROOT+'ucak-bileti/odeme-onay';
				}
				else	{
					alert('İşleminizi şu an gerçekleştiremiyoruz, lütfen daha sonra tekrar deneyin.');
				}
			}
		});
	});
}

function flightInitComparisonPage()	
{
	$("input[name=FlightDate]").datepicker({
		dateFormat: 'dd.mm.yy',
		defaultDate: $(this).attr('value'),
		beforeShow: flightCustomRange,
		onSelect: function(dateText, inst) {
			if (!$("input[name=ReturnDate]").attr('disabled') &&
					Date.parse($("input[name=FlightDate]").val()).compareTo(Date.parse($("input[name=ReturnDate]").val()))>=0)	{
				
				$("input[name=ReturnDate]")
				.val(
					Date.parse($("input[name=FlightDate]").val())
					.add(2).day().toString('dd.MM.yyyy')
				);
			}
		},
		duration: '',
		numberOfMonths: 1,
		changeMonth: true,
		changeYear: true
	});
	
	$("input[name=ReturnDate]").datepicker({
		dateFormat: 'dd.mm.yy',
		defaultDate: $(this).attr('value'),
		beforeShow: flightCustomRange,
		duration: '',
		numberOfMonths: 1,
		changeMonth: true,
		changeYear: true
	});
	
	$("input[name=IsOneWay]").click(function(){
		if (!this.checked) {
			$("input[name=ReturnDate]").enable().val(
				Date.parse($("input[name=FlightDate]").val())
				.add(1).week().toString('dd.MM.yyyy')
			);
		}
		else $("input[name=ReturnDate]").val('Tek Yön').enable(0);
	});

	$("input[name=OriginSelector]").autocomplete(ROOT+'ucak-bileti/ajax-autocomplete-airports?nossl=1', {
		minChars: 3,
		max: 10,
		delay: 100,
		autoFill: true,
		selectFirst: true,
		scrollHeight: 220,
		matchCase: true
	});

	$("input[name=OriginSelector]").result(function(event, data, formatted) {
		if (data) $("input[name=Origin]").val(data[1]);
		else $("input[name=Origin]").val('');
	});

	$("input[name=DestinationSelector]").autocomplete(ROOT+'ucak-bileti/ajax-autocomplete-airports?nossl=1', {
		minChars: 3,
		max: 10,
		delay: 100,
		autoFill: true,
		selectFirst: true,
		scrollHeight: 220,
		matchCase: true
	});

	$("input[name=DestinationSelector]").result(function(event, data, formatted) {
		if (data) $("input[name=Destination]").val(data[1]);
		else $("input[name=Destination]").val('');
	});
	
	$('#FlightForm').ajaxForm({
        beforeSubmit: function(arr, form, options){
		
			$('#FlightForm input').removeClass('f-error-1');
			$('#ErrorDiv').hide().find('p').hide();
	
			if ($.trim(form[0].OriginSelector.value).length == 0)	{
				$('#OriginError').show();
				$('input[name=OriginSelector]').addClass('f-error-1');
				$('#ErrorDiv').show();
				return false;
			}
	
			if ($.trim(form[0].DestinationSelector.value).length==0)	{
				$('#DestinationError').show();
				$('input[name=DestinationSelector]').addClass('f-error-1');
				$('#ErrorDiv').show();
				return false;
			}
	
			if (!$('input[name=ReturnDate]').attr('disabled') && 
				$('input[name=FlightDate]').datepicker('getDate') > $('input[name=ReturnDate]').datepicker('getDate')
			)	{
				$('#DateError').show();
				$('#ErrorDiv').show();
				return false;
			}
	
			if (!flightValidatePassengers())	{
				return false;
			}
	
			if (ChangeReturnDateClicked != true)	{
				flightShowOverlay(null, null);
			}
			
            Busy = true;
        },
        success: function(data){
            if (data == 'Ok')  {
            	if (ChangeReturnDateClicked != true)	{
            		window.location.href = ROOT + "ucak-bileti/karsilastir";
            	}
            	else	{
            		flightGetComparisonResults($("#fl-trips-cont .trip-row.selected").attr("index"));
            		ChangeReturnDateClicked = false;
            		Busy = false;
            	}
            }
            else if (data == "InvalidSession")    {
                alert("Oturumunuz sona erdi! Lütfen sayfayı yeniden yükleyerek tekrar deneyin.");
                if (ChangeReturnDateClicked != true) flightHideOverlay();
                Busy = false;
            }
            else if (data == "InvalidSearchParameters")    {
                alert("Geçersiz bir işlem yaptınız! Lütfen arama kriterlerinizi kontrol ederek tekrar deneyin.");
                if (ChangeReturnDateClicked != true) flightHideOverlay();
                Busy = false;
            }
            else {
            	alert("Bir hata meydana geldi! Lütfen bir süre bekleyip tekrar deneyin.");
            	if (ChangeReturnDateClicked != true) flightHideOverlay();
            	Busy = false;
            }
        },
        error: function(){
        	alert("Bir hata meydana geldi! Lütfen bir süre bekleyip tekrar deneyin.");
        	if (ChangeReturnDateClicked != true) flightHideOverlay();
            Busy = false;
        }
    });
	
	$("#BookingForm").ajaxForm({
        beforeSubmit: function(arr, form, options){
			flightShowOverlay(null, null);
	        Busy = true;
	    },
	    success: function(data){
	        if (data == 'Ok')  {
        		window.location.href = ROOT + "ucak-bileti/rezervasyon";
	        }
	        else if (data == "InvalidSession")    {
	            alert("Oturumunuz sona erdi! Lütfen sayfayı yeniden yükleyerek tekrar deneyin.");
	            flightHideOverlay();
	            Busy = false;
	        }
	        else if (data == "InvalidSearchParameters" || data == "InvalidTrips")    {
	            alert("Geçersiz bir işlem yaptınız! Lütfen arama kriterlerinizi kontrol ederek tekrar deneyin.");
	            flightHideOverlay();
	            Busy = false;
	        }
	    },
	    error: function(){
	    	alert("Bir hata meydana geldi! Lütfen bir süre bekleyip tekrar deneyin.");
	    	flightHideOverlay();
	        Busy = false;
	    }
	});
	
	$('.airline-filter a').live('click', function(e){
		e.preventDefault();
		$('input[name=FilterAirline]').val($(this).attr('airline'));
		$('#FlightForm').submit();
	});

	$('.daypart-filter a').live('click', function(e){
		e.preventDefault();
		$('input[name=FilterDayPart]').val($(this).attr('daypart'));
		$('#FlightForm').submit();
	});
	
	$('.daypart-filter a, .airline-filter a').live("mouseover", function(){
		$(this).addClass('filter-item-2').removeClass('filter-item-1')
	});
	
	$('.daypart-filter a, .airline-filter a').live("mouseout", function(){
		$(this).addClass('filter-item-1').removeClass('filter-item-2')
	});

	$('div.UnsupAirline').live('click', function(e){
		alert('Bu havayolunun biletleri henüz Enuygun.com üzerinden alınmamaktadır.');
		return false;
	});
	
	
	$('#fl-trips-cont .trip-row').live("click", function(){
		if (!Busy)   {
			var $this = $(this);
			
			if ($this.hasClass('NotForSale'))	{
				alert('Bu uçuş rezervasyon ve satın almalara kapalı durumda.');
			}
			else	{
				Busy = true;
				selected_elm = this;
                
				$('#fl-trips-cont .trip-row').removeClass('selected');
				$this.addClass('selected').find('input[type=radio]').attr('checked', true);
				$('#BookingForm input[name=firstLeg]').val($this.attr('index'));
				
				if (IsInternational == true)	{
					$('#BookingForm').submit();
				}
				else	{
					if (IsTwoWay)   {
						$this.parent().parent().parent().removeClass('u660').addClass('u325');
						$('#single-trips .first-leg').removeClass('first-leg-green').html('GİDİŞ');
						
						window.parent.$('html, body').animate({
							scrollTop: $(".right-content").offset().top
						}, 1000);
						
						flightGetComparisonResults($(selected_elm).attr('index'));
					}
					else    {
						$('#select-a-trip-fl').removeClass('first-leg-green').html('GİDİŞ');
						$('#BookingForm').submit();
					}
				}
				
				return false;
			}
		}
	});
	
	$('#sl-trips-cont .trip-row').live("click", function(){
		var $this = $(this);
		
		if (!$this.hasClass('NotForSale'))	{
			
			$this.parent().find('div.trip-row').removeClass('selected');
			$this.addClass('selected').find('input[type=radio]').attr('checked', true);
			$('#BookingForm input[name=secondLeg]').val($this.attr('index'));

			$('#BookingForm').submit();
		}
		else	{
			alert('Bu uçuş rezervasyon ve satın almalara kapalı durumda.');
		}
	});
}

function flightInitReservationPageVar2()
{
	$.blockUI.defaults.applyPlatformOpacityRules = false;
	$.blockUI.defaults.css = {};
	
	$("#BookingForm").ajaxForm({
		dataType: 'json',
		beforeSubmit: function(){
			Busy = true;
			flightShowOverlay();
		},
		success: function(data){

			if (data.status=='Ok')	{
				window.location.href = data.gate;
				return false;
			}
			else if (data.status=='ValidationError') {
				alert('İşleminiz gerçekleştirilirken bir hata meydana geldi! Ana sayfaya yönlendiriliyorsunuz.');
				window.location.href = ROOT+"ucak-bileti?e=1";
                return false;
			}
			else if (data.status=='InvalidSession')	{
				alert('Oturumunuz sona erdi, ana sayfafımıza yönlendirildikten sonra tekrar deneyebilirsiniz.');
				window.location.href = ROOT+"ucak-bileti?e=1";
				return false;
			}
			else if (data.status=='RemoteServiceError')	{
				alert('Havayolu firmasının sistemlerindeki anlık bir sorundan dolayı işleminizi gerçekleştiremedik. Lütfen bir süre bekledikten sonra tekrar deneyin ya da ana sayfamıza dönerek işleminizi baştan başlatın.');
			}
			else	{
				alert('Sistemlerimizdeki anlık bir sorundan dolayı işleminizi gerçekleştiremedik. Lütfen bir süre bekledikten sonra tekrar deneyin ya da ana sayfamıza dönerek işleminizi baştan başlatın.');
			}
			
			flightHideOverlay();
			Busy = false;
		},
		error: function(){
			alert('Sistemlerimizdeki anlık bir sorundan dolayı işleminizi gerçekleştiremedik. Lütfen bir süre bekledikten sonra tekrar deneyin ya da ana sayfamıza dönerek işleminizi baştan başlatın.');
			flightHideOverlay();
			Busy = false;
		}
	});

	$('#TicketingSubmit').click(function(e){
        e.preventDefault();
        
        if (!Busy && flightValidate($("#BookingForm")))   {

            if (!$('#Agreement').attr('checked'))   {
                alert('Kullanım kurallarını okuyup onaylamanız gerekmektedir.');
                return false;
            }

            $("#BookingForm").submit();
        }
        else return false;
    });

	$('input[name=CardNumber]').keyup(function(){
        if (this.value.substring(0, 1)==5)  {
            $('select[name=CardType]').val('Master');
        }
        else if (this.value.substring(0, 1)==4) {
            $('select[name=CardType]').val('Visa');
        }
        else    {
            $('select[name=CardType]').val('0');
        }
    });
    
    $('input[name=CardNumber]').blur(function(){
        if ($('input[name=CardNumber]').val().substring(0, 1)==5)   {
            $('select[name=CardType]').val('Master');
        }
        else {
            $('select[name=CardType]').val('Visa');
        }
    });
    
	$.mask.options = {
		attr: 'alt', // an attr to look for the mask name or the mask itself
		mask: null, // the mask to be used on the input
		type: 'fixed', // the mask of this mask
		maxLength: -1, // the maxLength of the mask
		defaultValue: '', // the default value for this input
		textAlign: true, // to use or not to use textAlign on the input
		selectCharsOnFocus: false, //selects characters on focus of the input
		setSize: false, // sets the input size based on the length of the mask (work with fixed and reverse masks only)
		autoTab: false, // auto focus the next form element
		fixedChars : '[(),.:/ -]', // fixed chars to be used on the masks.
		onInvalid : function(){},
		onValid : function(){},
		onOverflow : function(){}
	};
	
	$.mask.masks.passenger_phone = {mask: '0999 999 9999'};
	
	$('input[name^=PassengerPhone],#ContactMobile').setMask();
	
	$('#ContactMobile').blur(function(){
		if (this.value.substring(0,2)=='05')	{
			$('#PassengerPhone1').val(this.value);
		}
	});

	$('#PassengerFirstName1, #PassengerLastName1').blur(function(){
        if ($('#PassengerFirstName1').val() != '' && $('#PassengerLastName1').val() != '' && $('input[name=CardName]').val() == '')  {
            $('input[name=CardName]').val($('#PassengerFirstName1').val() + " " + $('#PassengerLastName1').val());
        }
    });

	$('#AgreementLink').click(function(e){
		e.preventDefault();
		window.parent.$('html, body').animate({
			scrollTop: $('#rules').offset().top
		}, 1000);
		$('#rules').toggle();
	});

	$('.number').numeric();
	
	if (preAuthError == 1)	{
		window.parent.$('html, body').animate({
			scrollTop: $("#charging-error-cont").offset().top
		}, 1000);
	}
}

function showOverlay(cont_elm_id)	{
	if (cont_elm_id == null)	{
		$.blockUI({
			overlayCSS: {
				backgroundColor: '#419107',
				opacity: .2
			},
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
			forceIframe: true,
			quirksmodeOffsetHack: 4,
			message: "<h1 style='padding:0;color:#3366CC;font-family:arial,Verdana;font-size:18px;font-weight:bold;'>"
				+"<div style='padding-bottom:5px;'><img src='"+ROOT+"include/loading.gif'/></div><div>İşleminiz gerçekleştiriliyor, lütfen bekleyin...</div>"
				+"</h1>",
		    css: {
				padding: "15px 0 0"
			}
		});
	}
	else	{
		$('#'+cont_elm_id).block({
			overlayCSS: {
			backgroundColor: '#419107',
			opacity: .2
		},
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
				forceIframe: true,
				quirksmodeOffsetHack: 4
		});
	}
}

function hideOverlay(cont_elm_id)	{
	if (cont_elm_id != null)
		$('#'+cont_elm_id).unblock();
	else
		$.unblockUI();
}
$().ready(function() {
	$(".flight_search input[name=OriginSelector]").autocomplete(ROOT+'ucak-bileti/ajax-autocomplete-flights?nossl=1', {
	    minChars: 3,
	    max: 10,
	    delay: 100,
	    autoFill: false,
	    selectFirst: true,
	    scrollHeight: 220,
	    matchCase: true
	});
	
	$(".flight_search input[name=OriginSelector]").result(function(event, data, formatted) {
	    if (data) $(".flight_search input[name=Origin]").val(data[1]);
	    else $(".flight_search input[name=Origin]").val('');
	});
	
	$(".flight_search input[name=DestinationSelector]").autocomplete(ROOT+'ucak-bileti/ajax-autocomplete-flights?nossl=1', {
		minChars: 3,
		max: 10,
		delay: 100,
		autoFill: false,
		selectFirst: true,
		scrollHeight: 220,
		matchCase: true
	});
	$(".flight_search input[name=DestinationSelector]").result(function(event, data, formatted) {
		if (data) $(".flight_search input[name=Destination]").val(data[1]);
		else $(".flight_search input[name=Destination]").val('');
	});
	
	$(".flight_search input[name=FlightDate]").datepicker({
        dateFormat: 'dd.mm.yy',
        defaultDate: $(this).attr('value'),
        beforeShow: flightCustomRange,
        onSelect: function(dateText, inst) {
            if (!$(".flight_search input[name=ReturnDate]").attr('disabled') &&
                Date.parse($(".flight_search input[name=FlightDate]").val()).compareTo(Date.parse($(".flight_search input[name=ReturnDate]").val()))>=0)  {
                
                $(".flight_search input[name=ReturnDate]")
                .val(
                    Date.parse($(".flight_search input[name=FlightDate]").val())
                    .add(7).day().toString('dd.MM.yyyy')
                );
            }
        },
        duration: '',
        numberOfMonths: 1,
        changeMonth: true,
        changeYear: true
    });
    $(".flight_search input[name=ReturnDate]").datepicker({
        dateFormat: 'dd.mm.yy',
        defaultDate: $(this).attr('value'),
        beforeShow: flightCustomRange,
        duration: '',
        numberOfMonths: 1,
        changeMonth: true,
        changeYear: true
    });

	$(".start_date_icon").click(function(e){
        e.preventDefault();
        $(this).prev().trigger('focus');
    });
    $(".end_date_icon").click(function(e){
        e.preventDefault();
        if($(this).prev().attr('disabled') == false) { $(this).prev().trigger('focus'); }
    });
});
/* Flight Module Finish */

