// 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 displayCurrentLegend;
var messageOutbound
var messageInbound;
var viewallConfig = {
"width":722,
"height":322
}
var viewall = $('<iframe src="/dynamic/stations.layer.timetables" 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": new Date(thisYear, thisMonth + 4, thisDay),
    "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": new Date(thisYear, thisMonth + 4, thisDay),
    "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];

var bookingHorizonData = null;
var bookingHorizon = 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 = '';
    }
    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"]);    	            
   	        };
        };
            }
};

function changeHorizon(newHorizon)
{
	//First, we disable 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 
        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")
        }
    })
};
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")
}

function addCloseLink(){
    frameContent = viewall.contents();
    $("a#close", frameContent).one("click", function(){
        viewall.fadeOut("fast");
        return false;
    })
    frameContentHotel = viewallHotel.contents();
    $("a#close", frameContentHotel).one("click", function(){
        viewallHotel.fadeOut("fast");
        return false;
    })
}

$(document).ready(function() {

    viewall.appendTo("body").hide();
    viewallHotel.appendTo("body").hide();
    $(targetMessage).hide();
    watchField();
    $(outwardDateField).datepicker(calendarDefaultOutwardConfig).focus(function(){
        viewall.fadeOut("fast")
    });
    $(returnDateField).datepicker(calendarDefaultReturnConfig).focus(function(){
        viewall.fadeOut("fast")
    });
    // plus-minus buttons, numeric format for passenger number fields.
    $("#adults,#children,#seniors,#youths").plus_minus().numeric();
    $("#depcity, #arrcity").bind("focus", function(){
        thisTrigger = this;
        viewAll(viewall, this)
        $("viewAll").focus()
    })
    
     //[NSI] I was forced to use this workaround to get the field to work. To fix.
    $("#viewallDepartureTowns").bind("click", function(){
        $('#depcity').focus();
		return false;      

    })
    $("#viewallArrivalTowns").bind("click", function(){
        $('#arrcity').focus();
		return false;      
    })
    
    
    $(fieldsToWatch).bind("keyup", function(){
        watchField();
    })
})

