// JavaScript
var Order;
var mpCssPath = 'http://schedule.kinomax.ru/data/mp.html.css';

$(function(){
	
	if ($('#mp-cinemas-schedule-list').length > 0) {
		loadCss(mpCssPath);
		getFilmSchedule($('#film-external-id').val());
		//$('#city-selector').css('opacity', 0);
		
		$('#city-selector select[name="city_id"]').change(function(){
			getFilmSchedule($('#film-external-id').val(), $(this).val());
		});
	}
	
	if ($('#mp-films-schedule-list').length > 0) {
		loadCss(mpCssPath);
		getCinemaSchedule($('#cinema-external-ident').val());		
	}
	
	if ($('#mp-cinema-hall-plan').length > 0) {
		loadCss(mpCssPath);
		getHallPlan();
	}
	
	if ($('#mp-cinema-ordering-processing').length > 0) {
		loadCss(mpCssPath);
		orderProcess();
	}
	
	if ($('#mp-cinema-payment').length > 0) {
		orderPaymentType();
	}
	
	if ($('#mp-cinema-payment-presale').length > 0) {
		orderPaymentPresale();
	}
	
	if ($('#mp-cinema-payment-confirm').length > 0) {
		orderPaymentConfirm();
	}
	
	if ($('#mp-cinema-order-cancel').length > 0) {
		orderCancel();
	}
	
	if ($('#mp-lk-sessions').length > 0) {
		lkSessions( '','' );
	}

	if ($('#mp-lk-dnk').length > 0) {
		lkDNK();
	}
	
	$('#form-city-id').change(function(){
		lkSessions($('#form-city-id').val(), $('#form-day').val());
	});
	
	$('#form-day').change(function(){
		lkSessions($('#form-city-id').val(), $('#form-day').val());
	});
	
	if ($('#mp-lk-reservations').length > 0) {
		var reserved = $('.lk-reserve');
		if ( reserved.length > 0 )
		{
			reserved.each( function(i, val) {
				var id = $(this).attr('id').split('-');
				lkCheckReservation( id[3] );
			});
		}		
	}
});

function getFilmSchedule( filmID, cityID )
{
	$('#mp-cinemas-schedule-list')
	 .css('height', 130)
	 .addClass('mp-content-loading-small')
	 .html('<div style="text-align:center; position:relative; top: 10%; color: #444; font-size:12px;" class="mp-loading-text">Подождите, идет загрузка сеансов</div>');
	
	$.ajax({
		url: '/schedule/schedule.php',
		type: 'get',
		data: {'filmID' : filmID, 'cityID' : cityID},
		success: function(response) {
			$('#mp-cinemas-schedule-list').removeClass('mp-content-loading-small').css('height', 'auto');
			$('#mp-cinemas-schedule-list').html(response);
		}, 
		error: function() {
			
		}
	});
}

function lkSessions( cityID, scheduleDate )
{
	$('#mp-lk-sessions')
	 .css('height', 130)
	 .addClass('mp-content-loading-small')
	 .html('<div style="text-align:center; position:relative; top: 10%; color: #444; font-size:12px;" class="mp-loading-text">Подождите, идет загрузка списка сеансов</div>');
	
	$.ajax({
		url: '/schedule/schedule.php',
		type: 'get',
		data: {'cityID':cityID,'scheduleDate':scheduleDate,'sortByHalls':'true'},
		success: function(response) {
			$('#mp-lk-sessions').removeClass('mp-content-loading-small').css('height', 'auto');
			$('#mp-lk-sessions').html(response);
		}, 
		error: function() {
			
		}
	});
}

function lkCheckReservation( reservationID )
{
	$('#mp-reservation-status-'+reservationID)
	 .html('<img src="http://schedule.kinomax.ru/data/loader-small-black.gif" style="vertical-align: text-bottom;" /> Подождите, проводится проверка брони...');
	
	$.ajax({
		url: '/schedule/reservchecker.php',
		type: 'get',
		data: {'reservationID':reservationID},
		success: function(response) {			
			$('#mp-reservation-status-'+reservationID).html(response);
		}, 
		error: function() {
			
		}
	});
}

function getCinemaSchedule( cinemaID )
{
	$('#mp-films-schedule-list')
	 .css('height', 130)
	 .addClass('mp-content-loading-small')
	 .html('<div style="text-align:center; position:relative; top: 10%; color: #444; font-size:12px;" class="mp-loading-text">Подождите, идет загрузка списка фильмов</div>');
	
	$.ajax({
		url: '/schedule/schedule.php',
		type: 'get',
		data: {'cinemaID' : cinemaID},
		success: function(response) {
			$('#mp-films-schedule-list').removeClass('mp-content-loading-small').css('height', 'auto');
			$('#mp-films-schedule-list').html(response);
		}, 
		error: function() {
			
		}
	});
}

function orderProcess()
{
	$('#mp-cinema-ordering-processing')
	 .css('height', 200)
	 .addClass('mp-content-loading')
	 .html('<div class="mp-loading-text">Ваш запрос обрабатывается. Пожалуйста, подождите.</div>');
	 
	var sessionID = $('#mp-session-id').val();
	var act = $('#mp-session-act').val();
	var placesList = $('#mp-places-list').val();
	var customerName = $('#mp-customer').val();
	var anonymous = $('#mp-anonymous').val();
	var levelID = $('#mp-level-id').val();
	
	$.ajax({
		url: '/schedule/booking.php',
		cache: false,
		type: 'get',
		data: {'sessionID':sessionID,'act':act,'placesList':placesList,'customerName':customerName,'anonymous':anonymous,'levelID':levelID},
		success: function(response) {
			$('#mp-cinema-ordering-processing').removeClass('mp-content-loading-small').css('height', 'auto');
			//alert(response);
			$('#mp-cinema-ordering-processing').html(response);
		}, 
		error: function() {
			
		}
	});
}

function lkDNK()
{
	$('#mp-lk-dnk')
	 .css('height', 50)
	 .html('Общаемся с сервером. Пожалуйста, подождите.');

	$.ajax({
		url: '/schedule/lk.php',
		cache: false,
		type: 'get',
		success: function(response) {
			$('#mp-lk-dnk').css('height', 'auto');
			$('#mp-lk-dnk').html(response);
		},
		error: function() {}
	});
}

function lkDNKTransactionsList()
{
	var fromDay = $('#FromDay option:selected').val();
	var fromMonth = $('#FromMonth option:selected').val();
	var fromYear = $('#FromYear option:selected').val();
	var toDay = $('#ToDay option:selected').val();
	var toMonth = $('#ToMonth option:selected').val();
	var toYear = $('#ToYear option:selected').val();

	$('#mp-lk-dnk')
	 .css('height', 50)
	 .html('Общаемся с сервером. Пожалуйста, подождите.');

	$.ajax({
		url: '/schedule/lk.php',
		cache: false,
		type: 'get',
		data: {'fromDay':fromDay,'fromMonth':fromMonth,'fromYear':fromYear,'toDay':toDay,'toMonth':toMonth,'toYear':toYear},
		success: function(response) {
			$('#mp-lk-dnk').css('height', 'auto');
			$('#mp-lk-dnk').html(response);
		},
		error: function() {}
	});
}

function orderCancel()
{
	$('#mp-cinema-order-cancel')
	 .css('height', 200)
	 .addClass('mp-content-loading')
	 .html('<div class="mp-loading-text">Ваш запрос обрабатывается. Пожалуйста, подождите.</div>');
	 
	var reservationID = $('#mp-reservation-id').val();
	var cancelCode = $('#mp-cancel-code').val();
	
	$.ajax({
		url: '/schedule/cancel.php',
		type: 'get',
		data: {'act':'cancel','reservationID':reservationID,'cancelCode':cancelCode},
		success: function(response) {
			$('#mp-cinema-order-cancel').removeClass('mp-content-loading-small').css('height', 'auto');
			$('#mp-cinema-order-cancel').html(response);
		}, 
		error: function() {
			
		}
	});
}

function orderPaymentType()
{
	$('#mp-cinema-payment')
	 .css('height', 200)
	 .addClass('mp-content-loading')
	 .html('<div class="mp-loading-text">Ваш запрос обрабатывается. Пожалуйста, подождите.</div>');
	 
	var reservationID = $('#mp-reservation-id').val();
	var paymentType = $('#mp-payment-type').val();
	
	$.ajax({
		url: '/schedule/booking.php',
		type: 'get',
		data: {'sessionID':sessionID,'act':act,'placesList':placesList,'customerName':customerName,'anonymous':anonymous,'levelID':levelID},
		success: function(response) {
			$('#mp-cinema-ordering-processing').removeClass('mp-content-loading-small').css('height', 'auto');
			$('#mp-cinema-ordering-processing').html(response);
		}, 
		error: function() {
			
		}
	});
}

function orderPaymentPresale()
{
	$('#mp-cinema-payment-presale')
	 .css('height', 200)
	 .addClass('mp-content-loading')
	 .html('<div class="mp-loading-text">Проверяется статус брони. Пожалуйста, подождите.</div>');
	 
	var reservationID = $('#mp-reservation-id').val();
	var paymentType = $('#mp-payment-type').val();
	var step = $('#mp-step').val();
	var name = $('#mp-name').val();
	var lastName = $('#mp-last-name').val();
	var secondName = $('#mp-second-name').val();
	var email = $('#mp-email').val();
	var result = $('#mp-result').val();
	
	$.ajax({
		url: '/schedule/payment.php',
		type: 'get',
		data: {'reservationID':reservationID,'paymentType':paymentType,'step':step,'name':name,'lastName':lastName,'secondName':secondName,'email':email,'result':result},
		success: function(response) {
			$('#mp-cinema-payment-presale').removeClass('mp-content-loading-small').css('height', 'auto');
			$('#mp-cinema-payment-presale').html(response);
		}, 
		error: function() {
			
		}
	});
}

function getHallPlan() 
{
	$('#mp-cinema-hall-plan')
	 .css('height', 500)
	 .addClass('mp-content-loading')
	 .html('<div class="mp-loading-text">Подождите, идет подключение к кинотеатру</div>');
	
	var sessionID = $('#mp-session-id').val();
	var type = getParam('type');
	
	$.ajax({
		url: '/schedule/hallplan.php',
		type: 'get',
		data: {'sessionID':sessionID,'type':type},
		success: function(response) {
			$('#mp-cinema-hall-plan').removeClass('mp-content-loading').css('height', 'auto');
			$('#mp-cinema-hall-plan').html(response);
			
			Order = new Ordering;
			Order.activateOrdering();
		}, 
		error: function() {
		}
	});			
}
		
function getParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function loadCss( href ) 
{
	if(document.createStyleSheet) {
		document.createStyleSheet( href );
	}
	else {
		var styles = "@import url('"+href+"');";
		var newSS=document.createElement('link');
		
		newSS.rel='stylesheet';
		newSS.href='data:text/css,'+escape(styles);
		document.getElementsByTagName("head")[0].appendChild(newSS);
	}
}

var Ordering = function() {
	var userPrice = 0;
	var a = {};
	var placesLimit = $('#mp-places-limit').val();
	
	this.activateOrdering = function() {
		$(".hall-place:not(.reserved-2):not(.reserved-3)").click(function(){
			
			if ($(this).hasClass('your-reserved')) {
				$(this).removeClass('your-reserved');
				var id=$(this).attr('id').split('-');
					$('#order-'+id[1]+'-'+id[2]).remove();
					
					var placeType = $(this).attr('rel');
					var rawPrice = $('.place-desc .'+placeType).next().children('.price-sum').attr('id');
						userPrice = userPrice - parseInt(rawPrice);
						
					if (userPrice == 0) {
						$('#your-order').hide();
						$('#credentials').hide();
					}
			} else {
				
				if ($('.your-film-order').length >= placesLimit) {
					alert( 'Больше нельзя!' );
					return false;
				}
				
				$(this).addClass('your-reserved');
				var example=$('#your-order > .example').clone();
				var id=$(this).attr('id').split('-');
				var placeType = $(this).attr('rel');
				var price = $('.place-desc .'+placeType).next().children('.price-sum').text();
				var rawPrice = $('.place-desc .'+placeType).next().children('.price-sum').attr('id');
					userPrice = userPrice + parseInt(rawPrice);
					a = {'1-1': {}};
				$('span:eq(0)', example).text(id[1]);
				$('span:eq(1)', example).text(id[2]);
				$('span:eq(2)', example).text(price);
				example.removeClass('example').addClass('your-film-order').attr('id','order-'+id[1]+'-'+id[2]).show();
				$('#your-order').show();
				$('#credentials').show();
				example.insertAfter('#your-order > span');
			}
			
			$('#user-price span:eq(0)').text(userPrice / 100);
		});
	}
	
	this.createOrder = function(type) {
		var placesList = '';
		var customerNameObj = $('#user-name');
		if ( customerNameObj.length == 0 )
			customerName = '';
		else
			customerName = customerNameObj.val();
			
		var sessionID = $('#mp-session-id').val();
		var orderType = $('#mp-places-ordertype').val();
		var anonymousLogin = $('#mp-places-anonymous').val();
		var levelID = $('#mp-level-id').val();
		
		if ( customerName.length == 0 && anonymousLogin == 'true' )
		{
			alert( 'Пожалуйста, укажите фамилию' );
			$('#user-name').focus();
			
			return false;
		}
		
		$('.your-film-order').each( function(i, val) {
			placesList = placesList + $(this).find('span:eq(0)').text() + ':';
			placesList = placesList + $(this).find('span:eq(1)').text() + ';';
		});
		placesList.substring( 0, placesList.length-1 );
		
		location.href = '/ordering/sessions/' + sessionID + '.htm?act=' + type + '&places=' + placesList + '&customer=' + encodeURIComponent( customerName ) + '&levelID=' + levelID + '&anonymous=' + anonymousLogin;
		return false;
	}
	
}

