$(document).ready(function() {

 	updateEvents();
});

function changeCalendar(el, year, month, routeID, shablon){
	var parent;
	if(shablon){
		parent = $(el).parents("td.c2");
	} else{
		parent = $(el).parent().parent();
	}
	$.ajax({
		url: "/routes/calendar.html",
  		dataType: 'json',
  		beforeSend: function(){
    			$(parent).css('cursor', 'progress');
		},

   		success: function(data){
    			$(parent).css('cursor', 'default');
    			$(parent).html( data.html );
    			if(shablon) {
    				updateEvents();
    				$(".forma-date-date", parent).click();
    			}
    			
   		},

   		error: function(data){
    			$(parent).css('cursor', 'default');
   		},
   		data: { month: month, year: year, json: 1, routeid: routeID, calshablon: shablon }
	});	
}

function checkCard(){
	var cardnumber = $('#forma-routes-bottom-input').val();
	
	var msg = $("#forma-routes-bottom-message");
	msg.html('');
	if(!cardnumber){
		msg.html('Введите номер карты').css('color','red');
		return false
	}
	
	var cardfields = new Array("name", "email", "tel"); 
	$.ajax({
		url: "/routes/checkcard.html",
  		dataType: 'json',
  		type: 'post',
  		beforeSend: function(){
    			$.each(cardfields, function(index, value) {
    				$(this).val('');
    			});
		},

   		success: function(data){
   			if(data.error){
   				msg.html( data.error ).css('color','red');
   			} else {
				$('#name').val( data.name );
				$('#email').val( data.email );
				$('#tel').val( data.tel );
				updatePrice();
   			}
   		},

   		error: function(data){
   		},
   		data: { cardnumber: cardnumber }
	});		
}

function toInt(x){
    return (parseInt(x) + 0);
}

var sendparams = new Array();

function routeObject(ID, date, humans, time, price, sum, sumcard ){
	this.id = ID;
	this.date = date;
	this.humans = humans;
	this.time = time;
	this.price = price;
	this.sum = sum;
	this.sumcard = sumcard;
}

function updatePrice(){
	sendparams =  new Array();
	var totalprice = 0;
	var cardeconomy = 0;
	var i = 1;
	$("span.addroute").each(function(){
		var jselecteddate = $("td.c2 span.day", this);
		var selmonth = toInt( jselecteddate.attr('month'));
		var selyear = toInt( jselecteddate.attr('year') );
		var selday = toInt( jselecteddate.html() );
		if(!selday || !selyear || !selmonth) return false;
		
		
		var today = new Date();
		var selecteddate = new Date(selyear,selmonth,selday + 1)
		var days = selecteddate >= today ? Math.ceil((selecteddate - today) / (1000 * 60 * 60 * 24)) : null;
		if(days){
			var sumwithoutcard;
			var pricewithoutcard;
			var humans = toInt( $("td.c4 span.selected", this).html() );
			var pricewithoutcardfieild;
			var pricefield = 'price';
			if(days >= 7 && days <= 14  ) pricefield = 'price7';
			if(days > 14 ) pricefield = 'price14';
			if($('#forma-routes-bottom-input').val() && $('#email').val()){
				pricewithoutcardfieild = pricefield;
				pricefield = 'pricecard';
				pricewithoutcard = toInt( $(this).attr( pricewithoutcardfieild ) );
				sumwithoutcard = pricewithoutcard * humans;
			}
			
			var price = toInt( $("span.routetime", this).attr( pricefield ) );
			var routesum = price * humans;
			if(!sumwithoutcard) sumwithoutcard = routesum;
			
			if(sumwithoutcard){
				cardeconomy += sumwithoutcard - routesum;
			}
			var routesum = price * humans;
			totalprice += routesum;
			$("td.c5", this).html( sumwithoutcard );
			
			var routeID = toInt( $(this).attr( 'ID' ) );
			var time = $("span.routetime", this).html();
			//selmonth = selmonth + 1;
			sendparams[sendparams.length] = new routeObject(routeID, selday+'.'+selmonth+'.'+selyear, humans, time, pricewithoutcard, sumwithoutcard, routesum);
		} else{
			$("td.c5", this).html( '?' );
		}
	});
	$('#totalprice').html(totalprice);
	if(cardeconomy) $("#forma-routes-bottom-message").css('color','').html( "Экономия по карте = <span style='color: #fc0;'>" + cardeconomy + "</span> $" );
}


function updateEvents(){
    
    $(".p-spoiler").css({position: "absolute", opacity: 0});

    $(".h-spoiler").click(
        function () {
            var ref = $(this).attr('ref');
            if ($("#"+ref).css("position") == 'absolute') {
                $("#"+ref).css("position", "relative");
                $("#"+ref).animate({opacity: 1}, 'fast');
            } else {
                $("#"+ref).css({position: "absolute", opacity: 0});
            }
        }
    );

    $("body").click(
        function() {
            $(".forma-routes-routelist").css("visibility", "hidden");
            $("#forma-routes .calendar").css("display", "none");
            $(".forma-date-date").closest("div").removeClass("forma-date-click");
            $(".forma-date-prev").css("display", "none");
	    	$(".forma-date-next").css("display", "none");
        }                                                                     
    );
    
	$("#forma-routes table td.c6 span").click(function() {
		if($(this).parents("span.back-ticket").size() > 0){
    		var parrent = $(this).parents("span.back-ticket");
    		$(parrent).prev().show();
        	$(parrent).remove();
        		
		} else{
    		var parrent = $(this).parents("span.routecontainer");
        	$(parrent).remove();
		}
	});	

	$(".forma-date td.xdate").click( function(){
    	var calparent = $(this).parents("div.forma-date");
    	
		$("span.day", calparent).html( $(this).html() );
		updatePrice();
		
		// Update time
		var span_parent = $(this).parents("span:first");
		$("td.c3 div.forma-routes-routelist", span_parent).html('');
		$("td.c3 span.routetime", span_parent).html('--:--');
		
		var times = jQuery.parseJSON( $(this).attr('params'));
		var times_html = '';
		for (var i=0; i < times.length; i++) {
			var times_item = times[i];
			var rtime = times_item['rtime']
			var item_pricecard = times_item['pricecard'];
			var item_price = times_item['price'];
			var item_price7 = times_item['price7'];
			var item_price14 = times_item['price14'];
			times_html += '<a pricecard="'+item_pricecard+'" price14="'+item_price14+'" price7="'+item_price7+'" price="'+item_price+'" class="time" href="javascript:void(0);">'+rtime+'</a>\n';
		}
		
		$("td.c3 div.forma-routes-routelist", span_parent).html(times_html);

		$(".forma-routes-routelist a").click(
        function() {
        	var parent2 = $(this).parent().parent();
        	if( $("span.routetime", parent2).size() > 0){
        		var spantime = $("span.routetime", parent2);
        		spantime.html( $(this).html() );
        		
        		spantime.attr('price', $(this).attr('price') );
        		spantime.attr('price7', $(this).attr('price7') );
        		spantime.attr('price14', $(this).attr('price14') );
        		spantime.attr('pricecard', $(this).attr('pricecard') );
        	}
        	
            var parrent = $(this).parent();
            $(parrent).css("visibility", "hidden");
            updatePrice();
        }
	    );
	    calparent.removeClass("forma-date-click");
	    $(".forma-date-prev").css("display", "none");
	    $(".forma-date-next").css("display", "none");
		$(".calendar", calparent).css("display", "none");
		return false;
	});
    				
	$("#forma-routes table td.c4 span").click(
        function() {
            var parrent = $(this).parent();
            $("span", parrent).removeClass("selected");
            $(this).addClass("selected");
            updatePrice();
        }
    );

    $(".forma-routes-route span, .forma-routes-route ins").click(
        function() {
            var parrent = $(this).parent();
            $(".forma-routes-route").css("z-index", 0);
            $(parrent).css("z-index", "1000");
            $(".forma-routes-routelist").css("visibility", "hidden");
            $(".forma-routes-routelist", parrent).css("visibility", "visible");
            return false;
        }
    );

    $(".forma-routes-routelist a").click(
        function() {
        	var parent2 = $(this).parent().parent();
        	if( $("span.routetime", parent2).size() > 0){
        		var spantime = $("span.routetime", parent2);
        		spantime.html( $(this).html() );
        		
        		spantime.attr('price', $(this).attr('price') );
        		spantime.attr('price7', $(this).attr('price7') );
        		spantime.attr('price14', $(this).attr('price14') );
        		spantime.attr('pricecard', $(this).attr('pricecard') );
        	}
        	
            var parrent = $(this).parent();
            $(parrent).css("visibility", "hidden");
            updatePrice();
        }
    );

    $(".forma-date").click(
        function() {
            var parrent = $(this);
            $(".forma-date").css("z-index", 0);
            $(parrent).css("z-index", 1000);
            $(".calendar").css("display", "none");
            $(".forma-date-date").removeClass("forma-date-click");
            $(this).addClass("forma-date-click");
            $(".calendar", parrent).css("display", "block");
            
           	$(".forma-date-prev", this).css("display", "block");
	    	$(".forma-date-next", this).css("display", "block");
            return false;
        }
    );

//    $(".forma-date .calendar td.xdate").click(
//        function() {
//            var parrent = $(this).parents(".forma-date");
//            $(".calendar", parrent).css("display", "none");
//            $(".forma-date-date", parrent).removeClass("forma-date-click");
//        }
//    );
}

function addroute(routeid, backflag, el){
	if(!routeid) return false;
	var backcontainer;
	if(backflag) {
		$(el).parent().hide();
		backcontainer = document.createElement('span');
		$(backcontainer).addClass("back-ticket")
	}
	
	var addcontainer;
	if( $(el).parents("span.routecontainer").size()>0 ){
		var addcontainer = $(el).parents("span.routecontainer");
	} else {
		addcontainer = $('#add-routes');
	}
	
	$.ajax({
		url: "/routes/addroute.html",
  		dataType: 'json',
  		type: 'post',
  		beforeSend: function(){
//    			$.each(cardfields, function(index, value) {
//    				$(this).val('');
//    			});
		},

   		success: function(data){
   			if(data.error){
   				//addcontainer.append( data.error ).css('color','red');
   			} else {
   				if(backflag){
   					$(backcontainer).html( data.html );
   					addcontainer.append( backcontainer );
   				} else {
   					addcontainer.append( data.html );
   				}
   				updateEvents();
   			}
   		},

   		error: function(data){
   		},
   		data: { routeid: routeid, backflag: backflag}
	});		
}

function zakaz( btnsubmit ) {
	if ($('#blackbox').css("display") == 'block') {
		$('#blackbox').fadeOut("slow");
        $('#zakaz').fadeOut("slow");
        window.location='/';
	} else {
		if($(btnsubmit).is('.disabled')){
			alert('Запрос выполняется, пожалуйста, подождите..');
			return false;
		}
		updatePrice();
		
		if(sendparams.length==0){
			alert('Выберите рейсы');
			return false;
		}
		var senddata = new Array();
		senddata.push(sendparams); 

		if(!$('#forma-routes-bottom-input').val() && !$('#email').val() && !$('#tel').val()){
			alert('Введите номер карты или контактные данные');
			return false;
		}
		senddata.push( $('#forma-routes-bottom-input').val() ); 
		senddata.push( escape( $('#name').val() ) );
		senddata.push( $('#email').val() );
		senddata.push( $('#tel').val() );
		
		$.ajax({
			url: "/routes/zakazroute.html",
	  		dataType: 'json',
	  		contentType: "application/json; charset=utf-8",
	  		type: 'post',
	  		beforeSend: function(){
				$('#blackbox').fadeIn("slow");
				$('#zakaz').fadeIn("slow");
				$(btnsubmit).addClass('disabled');
				$( btnsubmit ).prev(".loading").show();
			},
	
	   		success: function(data){
	   			$( btnsubmit ).prev(".loading").hide();
	   			$(btnsubmit).removeClass('disabled');
	   			if(data.error){
	   				$("#zakaz-container").html(data.error);
	   			} else {
	   				$("#zakaz-container").html(data.html);
	   			}
	   		},
	
	   		error: function(data){
	   			$("#zakaz-container").html('Системная ошибка, повторите попытку позже..');
	   			$(btnsubmit).removeClass('disabled');
	   			$( btnsubmit ).prev(".loading").hide();
	   		},
	   		data: JSON.stringify(senddata)
		});			
	}
}



