// DSM & calendar display
// config section 
var i, j, k, l, thisTrigger
// fieldsToWatch are the fields whose value are watched to find if any action needs to be triggered : Direct service message, calendar intialisation
fieldsToWatch = "#depcity, #arrcity";
outwardDateField = "#outwardDate";
returnDateField = "#returnDate";
targetMessage = "#msg";
today = new Date();
thisYear = today.getFullYear();
thisMonth = today.getMonth();
thisDay = today.getDay();
var endDate = new Date();
endDate.setDate(today.getDate() + 120);
var viewallConfig = {
"width":622,
"height":336
}
var displayCurrentLegend;
var messageOutbound
var messageInbound;
var viewall = $('<iframe src="/dynamic/stations.layer" width="'+viewallConfig.width+'" height="'+viewallConfig.height+'" frameborder="0" id="viewall"/>');
var viewallHotel = $('<iframe src="/dynamic/stations.layer.expedia" width="'+viewallConfig.width+'" height="'+viewallConfig.height+'" frameborder="0" id="viewall_hotel"/>');
function displayCurrentLegend(){
    return displayCurrentLegend;
}

function messageInbound(){
    return messageInbound;
}

function messageOutbound(){
    return messageOutbound;
}

calendarDefaultOutwardConfig = {
    "numberOfMonths": 2,
    "mandatory": true,
    "dateFormat": "dd/mm/yy",
    "defaultDate": 0,
    "minDate": today,
    "maxDate": endDate,
    "showOn": "both",
    "buttonImage": "/dimg/icons/calendar_button.png",
    "buttonImageOnly": true,
    "currentText": "",
    "beforeShowDay": directServiceDateOutward,
    "displayLegend": displayCurrentLegend,
    "messageId": messageOutbound
};
calendarDefaultReturnConfig = {
    "numberOfMonths": 2,
    "mandatory": true,
    "dateFormat": "dd/mm/yy",
    "defaultDate": 0,
    "minDate": today,
    "maxDate": endDate,
    "showOn": "both",
    "buttonImage": "/dimg/icons/calendar_button.png",
    "buttonImageOnly": true,
    "currentText": "",
    "beforeShowDay": directServiceDateReturn,
    "displayLegend": displayCurrentLegend,
    "messageId": messageInbound
};

var matchedOD = new Object();
matchedOD.outwardDates = new Array;
matchedOD.returnDates = new Array;
matchedOD.outwardDates = [new Array];
matchedOD.returnDates = [new Array];

//Booking horizon
var bookingHorizon = null;
var bookingHorizonData = null;

function directServiceDateOutward(date){
    for (i = 0; i < matchedOD.outwardDates.length; i++) {
        if ((date.getMonth() == (matchedOD.outwardDates[i][0] - 1)) && (date.getDate() == matchedOD.outwardDates[i][1])) {
            return [true, 'ski_day'];
        }
    }
    return [true, ''];
};

function directServiceDateReturn(date){
    for (i = 0; i < matchedOD.returnDates.length; i++) {
        if ((date.getMonth() == (matchedOD.returnDates[i][0] - 1)) && (date.getDate() == matchedOD.returnDates[i][1])) {
            return [true, 'ski_day'];
        }
    }
    return [true, ''];
};
function watchField()
{
    if ($("#depcity").attr("value")) {
        originFieldVal = $("#depcity").attr("value")
    }
    else {
        originFieldVal = '';
    }
    if ($("#arrcity").attr("value")) {
        destinationFieldVal = $("#arrcity").attr("value")
    }
    else {
        destinationFieldVal = '';
    }
	//[NSI] Ugly workaround to prevent the "Undefined" DSM legend display bug in the datepicker when there's no DSM. 
	//		There MUST be a better place to make this test, but I don't understand the code enough to find it.
	if (dsm.OD.length == 0)
	{
		$(targetMessage).empty();
		$(targetMessage).hide();
		matchedOD.outwardDates = [[]];
		matchedOD.returnDates = [[]];
		displayCurrentLegend = false;
    }

	//Browse JSON variable for default time(@see SvBoControleDirectService)
	try{
		for (i = 0; i < defaultTime.OD.length; i++) {
			//Both OD have a default time
			if ((defaultTime.OD[i].origin.toLowerCase() == originFieldVal.toLowerCase()) && (destinationFieldVal.toLowerCase() == defaultTime.OD[i].destination.toLowerCase()))
	        {    
	        	var defaultOutwardTime = defaultTime.OD[i].defaultOutwardTime;
	        	var defaultInboundTime = defaultTime.OD[i].defaultInboundTime;
				
				//outward list
				if (defaultOutwardTime != "") {
					//check that the time already exist in the list
					insertNewDefaultTime("outwardTime",defaultOutwardTime);
		            
		        }
		        //inbound list
		        //returnlist3 HomePage ID, returnTime BookOnline ID
		        if (defaultInboundTime != "") {
		        	//check that the time already exist in the list - homepage
		        	insertNewDefaultTime("returnlist3",defaultInboundTime);
					
					//check that the time already exist in the list - book online
					insertNewDefaultTime("returnTime",defaultInboundTime);
					
	            }
	            
	        }
	        
		}
	}catch(e)
  	{
  		//Handle errors; defaultTime may not be defined, so the build JSON variable failed, see applicative logs
  	}
    for (i = 0; i < dsm.OD.length; i++) {
    
        if (dsm.OD[i].origin.toLowerCase() == originFieldVal.toLowerCase()) {
        
            if ((dsm.OD[i].origin.toLowerCase() == originFieldVal.toLowerCase()) && (destinationFieldVal.toLowerCase() == dsm.OD[i].destination.toLowerCase()))
             {
                // Direct Service Message
                message = $(targetMessage).html();
                if (message != dsm.OD[i].message) {
                    $(targetMessage).empty();
                    $(targetMessage).hide();
                    if (dsm.OD[i].message != "") {
                        $(targetMessage).append(dsm.OD[i].message);
                        viewall.fadeOut("fast");
                        $(targetMessage).show("fast");                  
                    }
                }
                
                // Outward calendar
                matchedOD.outwardDates = dsm.OD[i].outwardDates;
                
                if (dsm.OD[i].bookingHorizon != null)
                {
	                bookingHorizonData = dsm.OD[i].bookingHorizon.split("/");
    	            bookingHorizon = new Date(bookingHorizonData[0], bookingHorizonData[1], bookingHorizonData[2]);
   	            };
                
                if (dsm.OD[i].directServiceType == 'SKI') {
                    displayCurrentLegend = true;
                    messageOutbound = "directSkiOutboundMessage";
                    messageInbound = "directSkiInboundMessage";
                }
                else 
                    if (dsm.OD[i].directServiceType == 'AVIGNON') {
                        displayCurrentLegend = true;
                        messageOutbound = "directAvignonOutboundMessage";
                        messageInbound = "directAvignonInboundMessage";
                    }
                    else {
                        displayCurrentLegend = false;
                    };
                // Return calendar
                matchedOD.returnDates = dsm.OD[i].returnDates;
                //Changing the horizon
                if (bookingHorizon != null)   
	                changeHorizon(bookingHorizon);
                break;
            }
            else {
                $(targetMessage).empty()
                $(targetMessage).hide();
                matchedOD.outwardDates = [[]];
                matchedOD.returnDates = [[]];
                displayCurrentLegend = false;
                
                //Restoring the default horizon. The test is used to ensure we only do it once, rather than at every tick.
                if (bookingHorizon != null)
                {
                	bookingHorizon = null;
                	bookingHorizonData = null;                	
                    changeHorizon(calendarDefaultReturnConfig["maxDate"]);    	            
   	            };
            };
                    }
        
        else {
            $(targetMessage).empty();
            $(targetMessage).hide();
            matchedOD.outwardDates = [[]];
            matchedOD.returnDates = [[]];
            displayCurrentLegend = false;
			
			//Restoring the default horizon. The test is used to ensure we only do it once, rather than at every tick.
            if (bookingHorizon != null)
            {
	            bookingHorizon = null;
               	bookingHorizonData = null;
               	
               	changeHorizon(calendarDefaultReturnConfig["maxDate"]);
			};
        };
            }
};
/**
* the default time does not exist, it contains minutes. For instance 09:05. This time must be add and sort in the list
**/
function insertNewDefaultTime(listName, defaultTime){
	if(!$("select#"+listName+" option[value='"+defaultTime+"']").val() ){
		
		var find = false;
		$("select#"+listName).each(function(){
			  $("option", this).each(function(i) {
			  	if(defaultTime<$("select#"+listName+" option:eq("+i+")").val() && !find){
			  		find=true;
			  		$("select#"+listName+" option[selected],	select#returnTime option[selected]").removeAttr("selected");
			  		$("select#"+listName+" option:eq("+i+")").before("<option value='"+defaultTime+"'>"+defaultTime+"</option>");
			  		$("select#"+listName+" option[value='"+defaultTime+"'], select#returnTime option[value='"+defaultTime+"']").attr("selected","selected" );
			  	}
			  })	
		});
	 
	}
	//the time already exists
	else{
		$("select#"+listName+" option[selected],	select#returnTime option[selected]").removeAttr("selected");
          	$("select#"+listName+" option[value='"+defaultTime+"'], select#returnTime option[value='"+defaultTime+"']").attr("selected","selected" );
	}
}
function changeHorizon(newHorizon)
{

	//First, we  the fields, to prevent a graphic glitch
	if(!jQuery.browser.msie)
	{
		returnDisabled=$(returnDateField).attr("disabled"); //10.0.1 it3 - NJOY - 13725
		$(outwardDateField).datepicker("disable");
		$(returnDateField).datepicker("disable");
	}
	
	//Changing the horizon
	$(returnDateField).datepicker("change", "maxDate", newHorizon);
	$(outwardDateField).datepicker("change", "maxDate", newHorizon);

    //Restoring the calendar
    if(!jQuery.browser.msie)
	{    
	    $(outwardDateField).datepicker("enable");
	    if (!returnDisabled) $(returnDateField).datepicker("enable"); //10.0.1 it3 - NJOY - 13725	    	
    }
}



function viewAll(viewall, thisTrigger){
    pos = $(thisTrigger).offset();
    triggerHeight = $(thisTrigger).height() + 4;
    viewall.css({
        "top": pos.top + triggerHeight + "px",
        "left": pos.left + "px",
        "position": "absolute"
    });
	 viewallHotel.css({
        "top": pos.top + triggerHeight + "px",
        "left": pos.left + "px",
        "position": "absolute"
    });
    if (viewall.css("display") != "block") {
        $("#datepicker_div").hide();
        // Reset iframe 
		$("#home_col_2, #home_col_3").css({"opacity":0.7})
        if ($("#hotel").attr("checked") || $("#car").attr("checked")) {
			viewallHotel.fadeIn("fast");
        }
        else {
            viewall.fadeIn("fast");
        }
        
    }
    addCloseLink();
    
    $("body").unbind("click focus");
    $("body").bind("click focus", function(e){
        //console.log(e)
        if (e.target != thisTrigger) {
            viewall.fadeOut("fast");
			viewallHotel.fadeOut("fast")
			$("#home_col_2, #home_col_3").css({"opacity":1})
        }
    })
};
function getTrigger(){
    // called by the iframe to get the triggering field
    return thisTrigger;
}

function fadeFrame(){
    // called by the iframe
    watchField();
    viewall.fadeOut("fast");
	viewallHotel.fadeOut("fast")
	$("#home_col_2, #home_col_3").css({"opacity":1})
}

function addCloseLink(){
    frameContent = viewall.contents();
    $("a#close", frameContent).one("click", function(){
        viewall.fadeOut("fast");
		$("#home_col_2, #home_col_3").css({"opacity":1})
        return false;
    })
    frameContentHotel = viewallHotel.contents();
    $("a#close", frameContentHotel).one("click", function(){
        viewallHotel.fadeOut("fast");
		$("#home_col_2, #home_col_3").css({"opacity":1})
        return false;
    })
}

$(document).ready(function() {

    viewall.appendTo("body").hide();
    viewallHotel.appendTo("body").hide();
    $(targetMessage).hide();
    
    $(outwardDateField).datepicker(calendarDefaultOutwardConfig).focus(function(){
        viewall.fadeOut("fast")
    });
    $(returnDateField).datepicker(calendarDefaultReturnConfig).focus(function(){
        viewall.fadeOut("fast")
    });
    
    watchField();
    
    
    // plus-minus buttons, numeric format for passenger number fields.
    $("#adults,#children,#seniors,#youths,#NumAdult0,#NumAdult1,#NumAdult2,#NumChild0,#NumChild1,#NumChild2,#NumSenior0,#NumSenior1,#NumSenior2,#NumYouth0,#NumYouth1,#NumYouth2").plus_minus().numeric();
    
    $("#depcity, #arrcity").bind("focus", function(){
        thisTrigger = this;
        viewAll(viewall, this)
        $("viewAll").focus()
    })
    
    //[NCH] "list all stations" links just move focus to each field. 
    $("#viewallDepartureTowns").bind("click", function(){
       $('#depcity').focus();
	return false;
    })
    $("#viewallArrivalTowns").bind("click", function(){
        $('#arrcity').focus();
	return false;
    })
    
    
    
    $(fieldsToWatch).bind("keyup", function(){
        watchField();
    })
})

$(document).ready(function() {

	$("#NumAdult1,#NumChild1,#NumSenior1,#NumYouth1,#NumAdult2,#NumChild2,#NumSenior2,#NumYouth2").attr({"disabled":"disabled"});

	if($("#room_2").length )
		$("#room_2").is(':checked') ? toggleRoom2("enabled") : toggleRoom2("disabled");
	if($("#room_3").length )
		$("#room_3").is(':checked') ? toggleRoom3("enabled") : toggleRoom3("disabled");

	$("#room_2").click( function() {
		$("#room_2").is(':checked') ? toggleRoom2("enabled") : toggleRoom2("disabled");
	} );
	$("#room_3").click( function() {
		$("#room_3").is(':checked') ? toggleRoom3("enabled") : toggleRoom3("disabled");
	} );
	
	// Affichage des radio-boutons de booking type : Train, Hotel, Car, ... 
	$("#formWithJS").show();
});
function toggleRoom2(status){
	if(status === "disabled") {
		$("#NumAdult1,#NumChild1,#NumSenior1,#NumYouth1").attr({"disabled":"disabled"});
	} else {
		$("#NumAdult1,#NumChild1,#NumSenior1,#NumYouth1").removeAttr("disabled");
	}	
}
function toggleRoom3(status){
	if(status === "disabled") {
		$("#NumAdult2,#NumChild2,#NumSenior2,#NumYouth2").attr({"disabled":"disabled"});
	} else {
		$("#NumAdult2,#NumChild2,#NumSenior2,#NumYouth2").removeAttr("disabled");
	}	
}
$(function(){
	var objects = $("form th.listRooms input");
	function toggleHighLight() {
		objects.each(function() {
			if ($(this).attr("checked")) {
				$(this).parents("tr").removeClass("newRoom");	// on enlève le grisé sur la ligne
			} 
			else {
				$(this).parents("tr").addClass("newRoom");	// on ajoute le grisé sur la ligne
			}
		})
	}
	objects.click(toggleHighLight);
	toggleHighLight();
})
