// common functions for bookingWidget

// fix ie6 select box issue
$(function() {
  $('#p7PMnav').children("li").children("ul").bgiframe();
  $('#p7PMnav').children("li").children("ul").children("li").children("ul").bgiframe();
});

// fix back button pre-populate issue
$(function() {
  var f = document.RequestAirForm;
  var originDisplay = getAirportDisplayByAirportCode(f.departCity.value);
  if (originDisplay != null) f.origin1.value = originDisplay;
  var destinationDisplay = getAirportDisplayByAirportCode(f.returnCity.value);
  if (destinationDisplay != null) f.destination1.value = destinationDisplay;
  if (isRoundTrip(f)) {
    $('#returnDates').css("visibility","visible");
  } else {
    $('#returnDates').css("visibility","hidden");
  }
  updateCouponCodeFields(f);
});

// retrieve seasonality info on load
var seasonalityData;
var seasonalityMsg_startEnd;
var seasonalityMsg_endResume;
var seasonalityMsg_starts;
var seasonalityMsg_ends;
// TODO: make it configurable
var srvCommingAirports = [];

function airportsJsGetAirport(city_code) {
    var tmp_airport=null;
    for( var i=0; i < seasonalityData.airports.length; i++ ) {
        tmp_airport = seasonalityData.airports[i];
        if(tmp_airport.code == city_code) {
            // check for omitted data
            if(tmp_airport.seasons == null) {
                tmp_airport.seasons = [];
            }
            if(tmp_airport.cities == null) {
                tmp_airport.cities = [];
            }
            tmp_airport.name = airport_code_to_full_name[city_code];
            return tmp_airport;
        }
    }
}

function getAjaxAirportMessage(element, city_code) {
    var locale = getPathParam(1);

    jQuery.get("/data/jsp/messaging.jsp?type=airport&message="+city_code+"&locale="+locale,
        function(data) {
        	element.innerHTML = "<div name='Desc" + airport.code 
				+ "' class='highlightCityInfo' style='padding-bottom: 10px'>" 
				+ data.replace(/^\s+|\s+$/g,"") + "</div>";
        });
}

// this function takes a variable length argument list ARG and replaces any 
// strings in ARG[0] of the form "$1" with ARG[1], "$2" with ARG[2], etc. up
// to "$9".  
function gsubSeasonalityMessage() {
    var msg="";
    var args=gsubSeasonalityMessage.arguments;
        
    // gets around checking for argument lists higher than 10 on the 
    // string substitute
    if(args.length>0 && args.length <= 10) {
        msg = args[0];
        for(var i=1; i < args.length; i++) {
            msg = msg.replace("$"+i, args[i]);
        }
        
        return msg;
    }
}

function checkSeasonality( city1, city2, cityPairDate, is_origin )
{
    var tmp_airport = airportsJsGetAirport( city1 );
    var is_regular_service = false;
    var check_season = null;
    var msg = "";
    var valid = true;

    var service_message = "Seasonal service from";
    if (city1 == 'YKA')
    {
        service_message = "Service from";
    }
    
    //if (city1 == 'MZT')
    //{
      //  msg = "We are currently finalizing our winter 2008/09 schedule for Mazatlan. Please check back shortly for our new schedule.";
        //alert( msg );
        //return false;
    //}
    //else if (city1 == 'SJD')
    //{
      //  msg = "We are currently finalizing our winter 2008/09 schedule for Cabo San Lucas. Please check back shortly for our new schedule.";
//        alert( msg );
    //    return false;
    //}

    
    if( tmp_airport && tmp_airport.seasons.length > 0 )
    {
        var city2_airport = airportsJsGetAirport( city2 );
        for( var i=0; i < tmp_airport.seasons.length; i++ )
        {
            var tmp_season = tmp_airport.seasons[i];
            if(tmp_season.cities == null) {
                tmp_season.cities = [];
            }

            if( is_origin == tmp_season.origin && tmp_season.cities.length == 0 && check_season == null )
            {
                check_season = tmp_season;
            }
            else if( is_origin == tmp_season.origin )
            {                
                for( var j=0; j < tmp_season.cities.length; j++ )
                {
                    if( city2 == tmp_season.cities[j] )
                    {
                        check_season = tmp_season;
                    }
                }
            }
        }
        
        // If there's a default season or the city matches another season,
        // then we'll check the dates for the season found.
        if( check_season != null )
        {    
            // Flip the city pair if the city checked was the destination city.
            if( !is_origin )
            {
                var tmp = tmp_airport;
                tmp_airport = city2_airport;
                city2_airport = tmp;
            }
            
            // handle dpecial data scenario where startdate is defined but not enddate
            if(typeof check_season.end == "undefined") {
                check_season.end = '';
            }
            if(typeof check_season.start == "undefined") {
                check_season.start = '';
            }

            // Format start/end dates
            if( check_season.end != '') {
                d = Date.parseExact(check_season.end, "yyyyMMdd");
                check_season.end_text = d.toString("MMM d, yyyy");
            }
            
            if( check_season.start != '' ) {
                d = Date.parseExact(check_season.start, "yyyyMMdd");
                check_season.start_text = d.toString("MMM d, yyyy");
            }
            
            if( check_season.end != '' && check_season.start != '' )
            {
                if( ( check_season.end < check_season.start ) && ( cityPairDate > check_season.end ) && ( cityPairDate < check_season.start ) )
                {
                    if (is_origin && tmp_airport.code == 'YXE')
                    {
                        msg = "Due to runway construction taking place at the Saskatoon airport, we are unable to operate flights out of Saskatoon on July 23 and 24, 2008. We apologize for the inconvenience and hope you are able to find an alternative flight that will work for you.";
                    }
                    else if (!is_origin && city2_airport.code == 'YXE')
                    {
                        msg = "Due to runway construction taking place at the Saskatoon airport, we are unable to operate flights into Saskatoon on July 22 and 23, 2008. We apologize for the inconvenience and hope you are able to find an alternative flight that will work for you.";
                    }
                    else
                    {
                        msg = gsubSeasonalityMessage(seasonalityMsg_endResume,
                            tmp_airport.name, 
                            city2_airport.name,
                            check_season.end_text, 
                            check_season.start_text+".");
                    }
                    alert( msg );
                    valid = false;
                }
                else if( ( check_season.end > check_season.start ) && ( ( cityPairDate > check_season.end ) || ( cityPairDate < check_season.start ) ) )
                {
                        msg = gsubSeasonalityMessage(seasonalityMsg_startEnd,
                            tmp_airport.name, 
                            city2_airport.name, 
                            check_season.start_text,
                            check_season.end_text+".");
                    alert( msg );
                    valid = false;
                }
            }
            else if( ( check_season.end != '' ) && ( cityPairDate > check_season.end ) )
            {
                msg = gsubSeasonalityMessage(seasonalityMsg_ends,
                    tmp_airport.name, 
                    city2_airport.name, 
                    check_season.end_text+".");
                alert( msg );
                valid = false;
            }
            else if( ( check_season.start != '' ) && ( cityPairDate < check_season.start ) )
            {
                msg = gsubSeasonalityMessage(seasonalityMsg_starts,
                    tmp_airport.name, 
                    city2_airport.name, 
                    check_season.start_text+".");
                alert( msg );
                valid = false;
            }
        }
    }
    return valid;
}

function updateTripType(f) {
  var lang = getPathParam(1);
  if (isRoundTrip(f)) {
    $('#returnDates').css("visibility","visible");
  } else {
    $('#returningDateInt').val("");
    $('#retMonthInt').val("mm");
    if(lang == 'fr') {
	$('#retDay').val("jj");
    }
    else {
	$('#retDay').val("dd");
    }
    $('#returnDates').css("visibility","hidden");
  }  
}

function getCouponFieldCount(f) {
  var maxFields = 6;
  var adultCount = parseInt(f.adults.value);
  var childCount = parseInt(f.children.value);
  var fieldCount = adultCount + childCount;
  if (fieldCount > maxFields) {
    fieldCount = maxFields;
  }
  return fieldCount;
}

function updateCouponCodeFields(f) {
  var couponList = retrieveCouponCodeFields(f);
  populateCouponCodeFields(f,couponList);
}

function retrieveCouponCodeFields(f) {
  var couponList=new Array();
  var fieldCount = getCouponFieldCount(f);
  for (i=1;i<=fieldCount;i++) {
    fieldName = "couponNumber" + i;
    if (f.elements[fieldName] != null) {
	  couponList[i] = f.elements[fieldName].value;
    } else {
	  couponList[i] = "";
	}
  }
  return couponList;
}

function populateCouponCodeFields(f,couponList) {
  var fieldCount = getCouponFieldCount(f);
  var label = "Guest";
  if (f.language.value == "fr") {
    label = "Invité";
  }
  $('#couponCodeFields').html('');
  for (i=1;i<=fieldCount;i++) {
    $('#couponCodeFields').append('<p class="couponCode">'+label+' '+i+'<br /><input id="coupon'+i+'" maxlength="7" name="couponNumber'+i+'" value="'+couponList[i]+'" size="8" type="text" /></p>');
  }
}

function applyCouponToAll(f) {
  var fieldCount = getCouponFieldCount(f);
  var couponNumber = f.couponNumber1.value;
  if (!f.applyToAll.checked) {
    couponNumber = "";
  }
  for (i=2;i<=fieldCount;i++) {
    fieldName = "couponNumber" + i;
    if (f.elements[fieldName] != null) {
      f.elements[fieldName].value = couponNumber;
    }
  }
}

function submitPromoCode(message) {
  var f = document.RequestAirForm;
  if (isValidPromoCode(f) && isValidCouponCodes(f)) {
    if (f.promoCode.value != '') {
      $('#ODmessages').html(message);
    }
  }
  MM_showHideLayers('enterPromo','','hide');
}

function isValidPromoCode(f) {
  var bValid = true;
  var fieldCount = getCouponFieldCount(f);
  f.promoCode.value = jQuery.trim(f.promoCode.value);
  if (f.promoCode.value == '') {
    for(i=1;i<=fieldCount;i++) {
      e = document.getElementById('coupon'+i);
      if (e != null) {
        e.value = jQuery.trim(e.value);
        if (e.value != '') {
          e.value = e.value.toUpperCase();
          bValid = false;
        }
      }
    }
  }
  return bValid;
}

function isValidCouponCodes(f) {
  var bValid = true;
  var fieldCount = getCouponFieldCount(f);
  f.promoCode.value = jQuery.trim(f.promoCode.value);
  if (f.promoCode.value != '') {
    f.promoCode.value = f.promoCode.value.toUpperCase();
    for(i=1;i<=fieldCount;i++) {
      e = document.getElementById('coupon'+i);
      e.value = jQuery.trim(e.value);
      if (e.value != '') {
        e.value = e.value.toUpperCase();
      } else {
        bValid = false;
      }
    }
  }
  return bValid;
}

function clearPromoCodeFields() {
  var f = document.RequestAirForm;
  f.promoCode.value = '';
  var fieldCount = getCouponFieldCount(f);
  for (i=1;i<=fieldCount;i++) {
    fieldName = "couponNumber" + i;
    if (f.elements[fieldName] != null) {
      f.elements[fieldName].value = '';
    }
  }
}

function cancelPromoCode() {
  MM_showHideLayers('enterPromo','','hide');
  clearPromoCodeFields();
}

function getSrvCommingMsgKey(f) {
  var msgKeyBase = 'service.comming.soon.';
  var origAC = f.departCity.value;
  var destAC = f.returnCity.value;
  
  for( var i=0; i < srvCommingAirports.length; i++ ) {
        var scsac = srvCommingAirports[i];
        if(scsac == origAC) {
            return msgKeyBase + origAC;
        }
        else if(scsac == destAC) {
            return msgKeyBase + destAC;
        }
  }
  return '';
}

function submitStepOne(f) {
  var bValid = true;
  var message = '';
  var bValidOrigin = true;
  var bValidDestination = true;
  var bValidDepartDate = true;
  var bValidReturnDate = true;
  var strCarriageReturn = '\n';
  var strBullet = ' - ';

  f.depMonth.value = getMonthString(f.depMonthInt.value);
  if (isRoundTrip(f)) {
    f.retMonth.value = getMonthString(f.retMonthInt.value);
  }
  f.depYear.value = getYear(f.depMonthInt.value, f.depDay.value);
  if (isRoundTrip(f)) {
    f.retYear.value = getYear(f.retMonthInt.value, f.retDay.value);
  }
	
  if (!isValidOriginAirport(f)) {
    bValid = false;
    bValidOrigin = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.originCity') + strCarriageReturn;
  }
  if (!isValidDestinationAirport(f)) {
    bValid = false;
    bValidDestination = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.destinationCity') + strCarriageReturn;
  }
  if (isRoundTrip(f) && bValidOrigin && bValidDestination && !isValidOriginDestinationPair(f)) {
    bValid = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.originDestination.pair') + strCarriageReturn;
  }
  if (!isValidDepartDate(f)) {
    bValid = false;
    bValidDepartDate = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.departDate') + strCarriageReturn;
  }
  if (bValidDepartDate && !isValidDepartDateRange(f)) {
    bValid = false;
    bValidDepartDate = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.departDate.range') + strCarriageReturn;
  }
  if (isRoundTrip(f) && !isValidReturnDate(f)) {
    bValid = false;
    bValidReturnDate = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.returnDate') + strCarriageReturn;
  }
  if (isRoundTrip(f) && bValidReturnDate && !isValidReturnDateRange(f)) {
    bValid = false;
    bValidReturnDate = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.returnDate.range') + strCarriageReturn;
  }
  if (isRoundTrip(f) && bValidDepartDate && bValidReturnDate && !isValidRoundTripDates(f)) {
    bValid = false;
    message += strBullet + getAjaxValidationMessage('booking.returnDate.before.departDate') + strCarriageReturn;
  }
  if (!isValidGuests(f)) {
    bValid = false;
    message += strBullet + getAjaxValidationMessage('booking.tooMany.guests') + strCarriageReturn;
  }
  if (!isValidInfants(f)) {
    bValid = false;
    message += strBullet + getAjaxValidationMessage('booking.tooMany.infants') + strCarriageReturn;
  }
  if (!isValidPromoCode(f)) {
    bValid = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.promoCode') + strCarriageReturn;
  }
  if (!isValidCouponCodes(f)) {
    bValid = false;
    message += strBullet + getAjaxValidationMessage('booking.invalid.couponCodes') + strCarriageReturn;
  }
  var srvSoonMsgKey = getSrvCommingMsgKey(f);
  if (srvSoonMsgKey != '') {
    bValid = false;
    message += strBullet + getAjaxValidationMessage(srvSoonMsgKey) + strCarriageReturn;
  }
  
  if (bValid) {
    if (isValidSeasonalDates(f)) {
      f.submit();
    }
  } else {
    message = getAjaxValidationMessage('booking.header') + strCarriageReturn + message
    alert(message);
  }
}

function getAjaxValidationMessage(validation_code) {
    var locale = getPathParam(1);
    var result = "####";
    
    $.ajax({
        type: 'GET',
        url: "/data/jsp/messaging.jsp?type=validation&message="+validation_code+"&locale="+locale,
        dataType: 'text',
        success: function(d){
        result = d.replace(/^\s+|\s+$/g,""); 
        },
        
        data: {},
        async: false
    });
    
    return result;
}

function isValidOriginAirport(f) {
  var bValid = false;
  if(f.origin1.value.indexOf(f.departCity.value) == -1) {
    f.departCity.value = "";
  }
  
  if (f.departCity.value != '') {
    if (isValidAirport(f.departCity.value)) {
      bValid = true;
    }
  }
  return bValid;
}

function isValidDestinationAirport(f) {
  var bValid = false;
  if(f.destination1.value.indexOf(f.returnCity.value) == -1) {
    f.returnCity.value = "";
  }
  
  if (f.returnCity.value != '') {
    if (isValidAirport(f.returnCity.value)) {
      bValid = true;
    }
  }
  return bValid;
}


function isValidOriginDestinationPair(f) {
  var bValid = false;
/*
  var validDestinationList = getDestinationsByAirportCode(origin);
  for (var i = 0; i < validDestinationList.length; i++) {
    if (destination == validDestinationList[i]) {
      bValid = true;
      break;
    }
  }
*/
  bValid = true;
  return bValid;
}

function isValidDepartDate(f) {
  var bValid = false;
  if (isValidYearMonthDate(f.depYear.value, f.depMonthInt.value, f.depDay.value)) {
    bValid = true;
  }
  return bValid;
}

function isValidReturnDate(f) {
  var bValid = false;
  if (isValidYearMonthDate(f.retYear.value, f.retMonthInt.value, f.retDay.value)) {
    bValid = true;
  }
  return bValid;
}

function isValidDepartDateRange(f) {
  var bValid = false;
  var futureDate = new Date();
  futureDate.setDate(futureDate.getDate() + 330);
  departDate = parseYearMonthDate(f.depYear.value, f.depMonthInt.value, f.depDay.value, new Date());
  if (!isNaN(departDate) && !isNaN(futureDate)) {
    if (departDate < futureDate) {
      bValid = true;
    }
  }
  return bValid;
}

function isValidReturnDateRange(f) {
  var bValid = false;
  var futureDate = new Date();
  futureDate.setDate(futureDate.getDate() + 330);
  returnDate = parseYearMonthDate(f.retYear.value, f.retMonthInt.value, f.retDay.value, new Date());
  if (!isNaN(returnDate) && !isNaN(futureDate)) {
    if (returnDate < futureDate) {
      bValid = true;
    }
  }
  return bValid;
}

function isValidRoundTripDates(f) {
  var bValid = false;
  departDate = parseYearMonthDate(f.depYear.value, f.depMonthInt.value, f.depDay.value, new Date());
  returnDate = parseYearMonthDate(f.retYear.value, f.retMonthInt.value, f.retDay.value, new Date());
  if (!isNaN(returnDate) && !isNaN(departDate)) {
    if (returnDate >= departDate) {
      bValid = true;
    }
  }
  return bValid;
}

// return the date in a "YYYYMMDD" format, zero filling MM and DD if necessary
function seasonalityDateFormat(yField, mField, dField) {
    return yField.value + 
        (mField.value.length == 1 ? "0"+mField.value : mField.value) + 
        (dField.value.length == 1 ? "0"+dField.value : dField.value);
}

function isValidSeasonalDates(f) {
  var bValid = false;

    // Check seasonal Dates
    var depDate = seasonalityDateFormat(f.depYear, f.depMonthInt, f.depDay);
    var retDate = seasonalityDateFormat(f.retYear, f.retMonthInt, f.retDay);
    
    if (!checkSeasonality(f.departCity.value,f.returnCity.value,depDate,true))
        bValid = false;
    else if (!checkSeasonality(f.returnCity.value,f.departCity.value,depDate,false))
        bValid = false;
    else if (isRoundTrip(f) && !checkSeasonality(f.departCity.value,f.returnCity.value,retDate,false))
        bValid = false;
    else if (isRoundTrip(f) && !checkSeasonality(f.returnCity.value,f.departCity.value,retDate,true))
        bValid = false;
  else
    bValid = true;

  return bValid;
}

function isValidGuests(f) {
  var bValid = false;
  var maxCount = 6;
  var adultCount = parseInt(f.ADT.value);
  var childCount = parseInt(f.CHD.value);
  if (maxCount >= (adultCount + childCount)) {
    bValid = true;
  }
  return bValid;
}

function isValidInfants(f) {
  var bValid = false;
  var adultCount = parseInt(f.ADT.value);
  var infantCount = parseInt(f.INF.value);
  if (adultCount >= infantCount) {
    bValid = true;
  }
  return bValid;
}

function isValidAirport(airport) {
  var bValid = false;
/*
  var validAirportList = getCompleteAirportList();
  for (var i = 0; i < validAirportList.length; i++) {
    if (airport == validAirportList[i]) {
      bValid = true;
      break;
    }
  }
*/
  bValid = true;
  return bValid;
}

function isRoundTrip(f) {
  var bValid = false;
  if (f.direction[0].checked) {
    bValid = true;
  }
  return bValid;
}

function isOneWay(f) {
  var bValid = false;
  if (!isRoundTrip(f)) {
    bValid = true;
  }
  return bValid;
}

// month is one based
function isValidYearMonthDate(year, month, date) {
  return !isNaN(parseYearMonthDate(year, month, date));
}

// month is one based
function parseYearMonthDate(year, month, date) {
  d = 0/0;
  if (isInt(year) && isInt(month) && isInt(date)) {
    d = new Date(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(date, 10));
    if (d.getFullYear() != parseInt(year, 10) || d.getMonth() != parseInt(month, 10) - 1 || d.getDate() != parseInt(date, 10)) {
      d = 0/0;
    }
  }
  return d;
}

// integer test
function isInt(s) {
  var chars = "0123456789";
  if (s == null) {
    return false;
  } else if (!isNaN(s) && s.length != 0) {
    return true;
  } else {
    isInteger = false;
    for (i = 0; i < s.length; i++) {
      if (chars.indexOf(s.charAt(i)) == -1) {
        isInteger = false;
        break;
      } else {
        isInteger = true;
      }
    }
    return isInteger;
  }
}

// return Sabre month as a string
function getMonthString(s) {
  s = s.replace(/^[0]+/g,"");
  var months = ['','JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
  return months[s];
}

// determine year based on curent month/day and entered month/day
function getYear(month, day) {
  var today = new Date();
  var year = today.getFullYear();
  if (month < (today.getMonth() + 1)) {
    year++;
  } else if (month == (today.getMonth() + 1)) {
    if (day < (today.getDate())) {
      year++;
    }
  }
  return year;
}

function formatACItem(item) {
    return(item.name);
}

var originAD = [];

$(document).ready(function() {  
    // store trimmed responses
    var locale = getPathParam(1);

    jQuery.get("/data/jsp/messaging.jsp?type=validation&message=seasonality.starts.and.ends&locale="+locale, 
        function(cd) {
            seasonalityMsg_startEnd=cd.replace(/^\s+|\s+$/g,""); 
        });
    jQuery.get("/data/jsp/messaging.jsp?type=validation&message=seasonality.ends.and.resumes&locale="+locale, 
        function(cd) {
            seasonalityMsg_endResume=cd.replace(/^\s+|\s+$/g,""); 
        });
    jQuery.get("/data/jsp/messaging.jsp?type=validation&message=seasonality.starts&locale="+locale,
        function(cd) {
            seasonalityMsg_starts=cd.replace(/^\s+|\s+$/g,""); 
        });
    jQuery.get("/data/jsp/messaging.jsp?type=validation&message=seasonality.ends&locale="+locale,
        function(cd) {
            seasonalityMsg_ends=cd.replace(/^\s+|\s+$/g,""); 
        });

});

