//encoding: utf-8

//Create and set today variable
var GdToday = new Date();
if (fncIsDate(GstrDay,GstrMonth,GstrYear)) {
  GdToday = fncNewDate(GstrDay,GstrMonth,GstrYear);
}

//Create string from GdToday to use in routes
var strTempYear = GdToday.getFullYear();
var strTempMonth = GdToday.getMonth()+1;
if (strTempMonth < 10) {
  strTempMonth = "0" + strTempMonth;
}
strTempDay = GdToday.getDate();
if (strTempDay < 10) {
  strTempDay = "0" + strTempDay;
}
var GstrToDay = strTempDay + "/" + strTempMonth + "/" + strTempYear;

function CalendarPopup(){var c;if (arguments.length>0){c = new PopupWindow(arguments[0]);}else{c = new PopupWindow();c.setSize(150,175);}c.offsetX = -102;c.offsetY = 25;c.autoHide();c.monthNames = MONTH_NAMES.slice(0,12);c.monthAbbreviations = MONTH_NAMES.slice(12);c.dayHeaders = DAY_HEADERS;c.returnFunction = "CP_tmpReturnFunction";c.returnMonthFunction = "CP_tmpReturnMonthFunction";c.returnQuarterFunction = "CP_tmpReturnQuarterFunction";c.returnYearFunction = "CP_tmpReturnYearFunction";c.weekStartDay = 0;c.isShowYearNavigation = false;c.displayType = "date";c.disabledWeekDays = {};c.disabledDatesExpression = "";c.yearSelectStartOffset = 2;c.currentDate = null;c.todayText="";c.cssPrefix="";c.isShowNavigationDropdowns=false;c.isShowYearNavigationInput=false;window.CP_calendarObject = null;window.CP_targetInput = null;window.CP_dateFormat = "MM/dd/yyyy";c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow;c.setReturnFunction = CP_setReturnFunction;c.setReturnMonthFunction = CP_setReturnMonthFunction;c.setReturnQuarterFunction = CP_setReturnQuarterFunction;c.setReturnYearFunction = CP_setReturnYearFunction;c.setMonthNames = CP_setMonthNames;c.setMonthAbbreviations = CP_setMonthAbbreviations;c.setDayHeaders = CP_setDayHeaders;c.setWeekStartDay = CP_setWeekStartDay;c.setDisplayType = CP_setDisplayType;c.setDisabledWeekDays = CP_setDisabledWeekDays;c.addDisabledDates = CP_addDisabledDates;c.setYearSelectStartOffset = CP_setYearSelectStartOffset;c.setTodayText = CP_setTodayText;c.showYearNavigation = CP_showYearNavigation;c.showCalendar = CP_showCalendar;c.hideCalendar = CP_hideCalendar;c.getStyles = getCalendarStyles;c.refreshCalendar = CP_refreshCalendar;c.getCalendar = CP_getCalendar;c.select = CP_select;c.setCssPrefix = CP_setCssPrefix;c.showNavigationDropdowns = CP_showNavigationDropdowns;c.showYearNavigationInput = CP_showYearNavigationInput;c.copyMonthNamesToWindow();return c;}


//Create date variables
var GdDate1 = new Date();
var GdDate2 = new Date();


//Initialize form
function init(IobjForm) {
  //Initiate text
  if (/\.is$/.test(document.location.host))
  {
    //document.getElementById('TripTypeHeadline').innerHTML = GaText[14];
    document.getElementById('TripType1').innerHTML = GaText[15];
    document.getElementById('TripType2').innerHTML = GaText[16];
    //document.getElementById('TripType3').innerHTML = GaText[17];
    document.getElementById('NormalFlightsHeadline').innerHTML = GaText[18];
    document.getElementById('OpenFlightHeadline').innerHTML = GaText[20];
    document.getElementById('Outbound').innerHTML = GaText[21];
    document.getElementById('Homebound').innerHTML = GaText[22];
    document.getElementById('PassengerHeadline').innerHTML = GaText[23];
    document.getElementById('ChildrenText').innerHTML = GaText[30];
    document.getElementById('InfantText').innerHTML = GaText[34];
    document.getElementById('CurrencyHeadline').innerHTML = GaText[35];
  }

  //Initiate flight type
  IobjForm.FlightType1.checked = true;
  fncChangeType(IobjForm, IobjForm.FlightType1);

  //Initiate Origin/Destination
  setOrigin(IobjForm.Origin);
  setDestination(IobjForm.Origin, IobjForm.Destination);

  //Initiate PAX
  fncSetAdults (GiAdults,IobjForm.Adults);
  fncSetChildren (GiChildren,IobjForm.Children);
  fncSetInfants (GiChildren,IobjForm.Infants);

  //Initiate Currency
  fncSetCurrency(IobjForm.Currency);
}


//Input checks and submission
function fncCheckSubmit (IobjForm) {

  var bReturn = 
          fncFlightCheck(IobjForm) &&
          fncDateCheck(IobjForm) &&
          fncPaxCheck(IobjForm.Adults, IobjForm.Children, IobjForm.Infants);

  if (bReturn) {
    if ((parseInt(IobjForm.Adults.value, 10)) > 10) {
      IobjForm.action = (confirm(GaText[36])) ? 
          GaGroupBookUrl:
          "https://booking.icelandexpress.com/receiver.asp";
    } else {
      //Submitta á bókunarvél
      IobjForm.action = "https://booking.icelandexpress.com/receiver.asp";
/*
      if (/\.com$/.test(document.location.host)) {
        if ((document.forms['IEXBookingEngine'].elements['Origin'].value == 'STN') || (document.forms['IEXBookingEngine'].elements['Origin'].value == 'CPH')) {
          if ((document.forms['IEXBookingEngine'].elements['Destination'].value == 'KEF') && (document.forms['IEXBookingEngine'].elements['Origin2'].value == '') && (document.forms['IEXBookingEngine'].elements['HomeboundDate'].value < '2007-05-31') && (document.forms['IEXBookingEngine'].elements['HomeboundDate'].value != '') && (document.forms['IEXBookingEngine'].elements['HomeboundDate'].value > '2007-02-01')) {
            if (confirm('Yay! Iceland Express has an Icebreaker Special Offer that applies to your flight dates and route!\n\nClick OK to see the Special Offers or click Cancel to see the regular prices.')) {
              document.forms['IEXBookingEngine'].elements['id'].value = 'ext12431';
              document.forms['IEXBookingEngine'].elements['pin'].value = 'x599b';
            }
            else
            {
              document.forms['IEXBookingEngine'].elements['id'].value = '';
              document.forms['IEXBookingEngine'].elements['pin'].value = '';
            }
          }
        }
      }
*/
    }
    IobjForm.submit();
  }
  return false;
}


function fncSetToDay(IstrDay,IstrMonth,IstrYear) {
  if (fncIsDate(IstrDay,IstrMonth,IstrYear)) {
    GdToDay = fncNewDate(strIdagDag,strIdagManudur,strIdagAr);
  } else {
    alert(GaText[5]);
    bReturn = false;
  }
}


function fncSetDate(IstrDate,IobjItem1,IobjItem2) {
  var bReturn = true,
      dTempDate = new Date(),
      strIdagDag = parseInt(IstrDate.substr(0,2), 10)+'',
      strIdagManudur = parseInt(IstrDate.substr(3,2), 10)+'',
      strIdagAr = parseInt(IstrDate.substr(6,4), 10)+'';
  if (fncIsDate(strIdagDag,strIdagManudur,strIdagAr)) {

    dTempDate = fncNewDate(strIdagDag,strIdagManudur,strIdagAr);
    if (IobjItem1.id == 'date1') {

      if (dTempDate < GdToday) {

        alert(GaText[4]);
        bReturn = false;
      } else {

        GdDate1 = dTempDate;
        fncBuildDateView(IobjItem1,GdDate1);
        //GdDate2 = GdDate1;
        //fncBuildDateView(IobjItem2,GdDate2);
      }
    } else {

      if (dTempDate < GdDate1) {

        alert(GaText[6]);
        bReturn = false;
      } else {

        GdDate2 = dTempDate;
        fncBuildDateView(IobjItem1,GdDate2);
      }
    }
  } else {
    alert(GaText[5]);
    bReturn = false;
  }
  return bReturn;
}


function fncIsRouteBookable (IstrOrigin, IstrDestination, IdDate1, IdDate2) {
  var bReturn = true;
  //Athuga hvort dagsetningin sé innan tímaramma rútunnar.
  return bReturn;
}


/*
// Functional equivalent of: IstrString.substr(0,IiN);
function Left(IstrString, IiN) {
  if (IiN <= 0)
    return "";
  else if (IiN > String(IstrString).length)
    return IstrString;
  else
    return String(IstrString).substring(0,IiN);
}


// Functional equivalent of: IstrString.substr(IstrString.length-IiN);
function Right(IstrString, IiN) {
  var iLen = String(IstrString).length;
  if (IiN <= 0)
    return "";
  else if (IiN > iLen)
    return IstrString;
  else {
    return String(IstrString).substring(iLen, iLen - IiN);
  }
}
*/


function fncHasValue (IobjItem) {
  var bReturn = false;
  if (IobjItem.value.length > 0) {
    bReturn = true;
  } else {
    IobjItem.focus();
  }
  return bReturn;
}


function setOrigin (IobjItem) {
  IobjItem.options.length = 0;
  IobjItem.options[0] = new Option("--- " + GaText[0] + " ---","");
  var iCounter = 1;
  for (var i=0; i<GaAirports.length; i++)
  {
    var airport = GaAirports[i],
        strAirportCode = airport.substr(0,3),
        strAirportName = airport.substr(6);
    IobjItem.options[iCounter] = new Option(strAirportName+" "+strAirportCode, strAirportCode);
    iCounter++;
  }
}


function clearDate() {
  document.getElementById('date1').value="";
  document.getElementById('date2').value="";
}



function setDestination(IobjItem1, IobjItem2, ignoreDefaultCity) {
  try
  {
    document.getElementById('date1').value="";
    document.getElementById('date2').value="";
  }
  catch(e)
  {}

  if (IobjItem1.value == "   ") {
      IobjItem1.selectedIndex = 0;
  }

  if (!ignoreDefaultCity)
  {
    iex_defaultCity = window.iex_defaultCity || '';
    // if a Default City is set (e.g. by one of the "destination pages") then set KEF as the origin airport.
    if (iex_defaultCity && IobjItem1.selectedIndex == 0)
    {
      for (var i=1; i<IobjItem1.options.length; i++)
      {
        var opt = IobjItem1.options[i];
        if (opt.value == 'KEF')
        {
          IobjItem1.selectedIndex = i;
          break;
        }
      }
    }
  }

  IobjItem2.options.length = 0;
  var aTemp = '|';
  for (var i=0; i<GaRoutes.length; i++)
  {
    var route = GaRoutes[i];
    if (route.substr(6,3) == IobjItem1.value) {
      aTemp += route.substr(0,3)+'|';
    }
  }

  // find the airport names/data and weed out duplicates
  var airports = [],
      foundAirports = {},
      i = GaAirports.length;

  while (i--) // loop backwards because we assume non-alphabetized duplicates appear at the front of the GaAirports list
  {
    var airport = GaAirports[i],
        strAirportCode = airport.substr(0,3);
    if (aTemp.indexOf(strAirportCode) > -1  &&  !foundAirports[strAirportCode])
    {
      foundAirports[strAirportCode] = 1;
      var strAirportName = airport.substr(6);
      airports[airports.length] = new Option(strAirportName+" "+strAirportCode, strAirportCode);
    }
  }
  airports.reverse();

  // Popuplate the Select box.
  IobjItem2.options[0] = new Option("--- " + GaText[1] + " ---", "");
  for (var i=0; i<airports.length; i++)
  {
    IobjItem2.options[i] = airports[i];
    // if a Default City is set (and found), then set it as the destination airport.
    if (!ignoreDefaultCity  &&  airports[i].value == iex_defaultCity)
    {
      IobjItem2.selectedIndex = i;
    }
  }

  if (IobjItem2.options.length == 2) {
    IobjItem2.selectedIndex = 1;
  }
}


function setDestination_alt(IobjItem1, IobjItem2) { // used for "open jaw" trips...
  return setDestination(IobjItem1, IobjItem2, true);
}


function fncSetAdults (maxValue, selectElm)
{
  selectElm.options.length = 0;
  for (var i=0; i <= maxValue; i++) {
    var text = i + ((i == maxValue) ? '+' : '');
    selectElm.options[i] = new Option(text, i);
  }
  if (maxValue) { selectElm.selectedIndex = 1; }
}


function fncSetChildren (maxValue, selectElm) {
  selectElm.options.length = 0;
  for (var i=0; i <= maxValue; i++) {
    var text = i + '';
    selectElm.options[i] = new Option(text, i);
  }
  //if (maxValue) { selectElm.selectedIndex = 0; }
}


function fncSetInfants (maxValue, selectElm) {
  selectElm.options.length = 0;
  for (var i=0; i <= maxValue; i++) {
    var text = i + '';
    selectElm.options[i] = new Option(text, i);
  }
  //if (maxValue) { selectElm.selectedIndex = 0; }
}


function fncSetCurrency(IobjItem) {
  var strCode = "";
  var strName = "";
  for (var i=0; i<GaCurencies.length; i++)
  {
    var GaCurency = GaCurencies[i];
    strCode = GaCurency.substr(GaCurency.length-3);
    strName = GaCurency.substr(0, GaCurency.length-6);
    IobjItem.options[i] = new Option(strName,strCode);
  }
}


function fncChangeType(IobjForm, IobjItem) {
  IobjItem.checked = true;

  switch(IobjItem.value) {
    default:
      //Sýni heim dagsetningu
      document.getElementById('date2Area').style.display = 'block';
      //Stilli dagsetningu
      GdDate2 = GdDate2 ||GdDate1;

      //fncBuildDateView(IobjForm.date2,GdDate2);
      //Fel Open Jaw
      IobjForm.Origin2.options.length = 0;
      IobjForm.Destination2.options.length = 0;
      document.getElementById('OpenFlights').style.display = 'none';
      //Set réttan texta í haus
      document.getElementById('NormalFlightsHeadline').innerHTML = GaText[18];

      break;
    case "2":
      //Fel heim dagsetningu
      document.getElementById('date2Area').style.display = 'none';
      //Stilli dagsetningu
      //GdDate2 = null;
      //Fel Open Jaw
      IobjForm.Origin2.options.length = 0;
      IobjForm.Destination2.options.length = 0;
      document.getElementById('OpenFlights').style.display = 'none';
              //Set réttan texta í haus
      document.getElementById('NormalFlightsHeadline').innerHTML = GaText[18];

      break;
    case "3":
      //Sýni heim dagsetningu
      document.getElementById('date2Area').style.display = 'block';
      //Stilli dagsetningu
      GdDate2 = GdDate2 ||GdDate1;

      fncBuildDateView(IobjForm.date2,GdDate2);
      //Sýni Open Jaw
      document.getElementById('OpenFlights').style.display = 'block';
      setOrigin(IobjForm.Origin2);
      setDestination_alt(IobjForm.Origin2, IobjForm.Destination2);
      //Set réttan texta í haus
      document.getElementById('NormalFlightsHeadline').innerHTML = GaText[19];

      break;
  }
}


function fncNewDate(IstrDay,IstrMonth,IstrYear) {
  return new Date(IstrYear, parseInt(IstrMonth,10)-1, IstrDay, 0,0,0,0);;
}


function fncIsDate(IstrDagur,IstrManudur,IstrAr) {
  var boolOk = true;
  IstrDagur = parseInt(IstrDagur, 10);
  IstrAr = parseInt(IstrAr, 10);

  //alert(IstrDagur + "/" + IstrManudur + "/" + IstrAr);
  if ((IstrManudur == "04") || (IstrManudur == "06") || (IstrManudur == "09") || (IstrManudur == "11")) {
    if (IstrDagur > 30) {
      boolOk = false;
    }
  }
  if (IstrManudur == "02") {
    if (IstrAr%4 == 0)
    {
      if (IstrAr%10 != 0)
      {
        if (IstrDagur > 29) {
          boolOk = false;
        }
      } else {
        if (IstrAr%400 != 0)
        {
          if (IstrDagur > 29) {
            boolOk = false;
          }
        } else {
          if (IstrDagur > 28) {
            boolOk = false;
          }
        }
      }
    } else {
      if (IstrDagur > 28) {
        boolOk = false;
      }
    }
  }
  return boolOk;
}


function fncBuildDateView (IobjItem1, IdDate) {
  var point = (GstrLang == "is") ? '.' : '';
  IobjItem1.value = GaWeekdays[IdDate.getDay()] + ", " + IdDate.getDate() + point+" " + GaMonths[IdDate.getMonth()] + " " + IdDate.getFullYear();
}


function fncGetRadioValue(IobjForm) {
  var iRadioValue = "";
  for (var i=0; i<IobjForm.FlightType.length; i++) {
    if (IobjForm.FlightType[i].checked) {
      iRadioValue = IobjForm.FlightType[i].value;
    }
  }
  iRadioValue = parseInt(iRadioValue, 10);
  return iRadioValue;
}


function fncFlightCheck (IobjForm) {
  var bReturn = true;
  if ((!fncHasValue(IobjForm.Origin)) && bReturn) {
    alert(GaText[2]);
    bReturn = false;
    IobjForm.Origin.focus();
  }
  if ((!fncHasValue(IobjForm.Destination)) && bReturn) {
    alert(GaText[3]);
    bReturn = false;
    IobjForm.Destination.focus();
  }
/*
  if (bReturn) {
    fncIsRouteBookable(IobjForm.Destination.value, IobjForm.Origin.value,dDate1,dDate2)
  }
*/
  if ((fncGetRadioValue(IobjForm) == 3) && bReturn) {
    if ((!fncHasValue(IobjForm.Origin2)) && bReturn) {
      alert(GaText[41]);
      bReturn = false;
      IobjForm.Origin2.focus();
    }
    if ((!fncHasValue(IobjForm.Destination2)) && bReturn) {
      alert(GaText[42]);
      bReturn = false;
      IobjForm.Destination2.focus();
    }
/*
    if (bReturn) {
      fncIsRouteBookable(IobjForm.Destination2.value, IobjForm.Origin2.value,dDate1,dDate2)
    }
*/
  }
  return bReturn;
}


function fncDateCheck (IobjForm) {
  var bReturn = true;
  if (IobjForm.FlightType2.checked == true) {
    if ((IobjForm.date1.value == "") && bReturn) {
      alert(GaText[39]);
      bReturn = false;
    }

    if ((GdDate1.getFullYear() == GdToday.getFullYear()) && (GdDate1.getDate() == GdToday.getDate()) && (GdDate1.getMonth() == GdToday.getMonth()) && bReturn) {
      if (!confirm(GaText[8])) {
        bReturn = false;
      }
    }

  } else {

    if ((IobjForm.date1.value == "") && bReturn) {
      alert(GaText[39]);
      bReturn = false;
    }
    if ((IobjForm.date2.value == "") && bReturn) {
      alert(GaText[38]);
      bReturn = false;
    }

    if ((GdDate1.getFullYear() == GdToday.getFullYear()) && (GdDate1.getDate() == GdToday.getDate()) && (GdDate1.getMonth() == GdToday.getMonth()) && bReturn) {
      if (!confirm(GaText[8])) {
        bReturn = false;
      }
    }
    if ((GdDate1.getFullYear() == GdDate2.getFullYear()) && (GdDate1.getDate() == GdDate2.getDate()) && (GdDate1.getMonth() == GdDate2.getMonth()) && bReturn) {
      if (!confirm(GaText[7])) {
        bReturn = false;
      }
    }

  }

  if (bReturn) {
    var strTempYear1 = GdDate1.getFullYear();
    var strTempMonth1 = GdDate1.getMonth()+1;
    if (strTempMonth1 < 10) {
        strTempMonth1 = "0" + strTempMonth1;
    }
    strTempDay1 = GdDate1.getDate();
    if (strTempDay1 < 10) {
        strTempDay1 = "0" + strTempDay1;
    }
    var strTempDate1 = strTempYear1 + "-" + strTempMonth1 + "-" + strTempDay1;
    IobjForm.OutboundDate.value = strTempDate1;

    var strTempYear2 = GdDate2.getFullYear();
    var strTempMonth2 = GdDate2.getMonth()+1;
    if (strTempMonth2 < 10) {
        strTempMonth2 = "0" + strTempMonth2;
    }
    strTempDay2 = GdDate2.getDate();
    if (strTempDay2 < 10) {
        strTempDay2 = "0" + strTempDay2;
    }
    var strTempDate2 = strTempYear2 + "-" + strTempMonth2 + "-" + strTempDay2;
    IobjForm.HomeboundDate.value = strTempDate2;

    if (IobjForm.FlightType2.checked == true) {
        IobjForm.HomeboundDate.value = "";
    }
  }
  return bReturn;
}


function fncPaxCheck (IobjItem1,IobjItem2,IobjItem3) {
  var bReturn = true;
  var iAdults = parseInt(IobjItem1.value, 10);
  var iChildren = parseInt(IobjItem2.value, 10);
  var iInfants = parseInt(IobjItem3.value, 10);
  if (((iAdults + iChildren + iInfants) < 1) && bReturn) {
    alert(GaText[11]);
    bReturn = false;
    IobjItem1.focus();
  }
  if (iAdults == 0  &&  iChildren > 0  &&  bReturn) {
    if (!confirm(GaText[12])) {
      bReturn = false;
      IobjItem2.focus();
    }
  }
  if ((iInfants > iAdults) && bReturn) {
    if (iAdults > 0) {
      alert(GaText[9]);
      bReturn = false;
    } else {
      alert(GaText[10]);
      bReturn = false;
    }
    IobjItem3.focus();
  }
  if (false && bReturn) {
    //Hópabókun
  }
  return bReturn;
}


function fncShowLayer (objName) {
  document.getElementById(objName).style.display='block';
}


function fncHideLayer (objName) {
  document.getElementById(objName).style.display='none';
}
