var monthNames = new Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var noteEditMode = false;

function openHotelBookingPage() {
    var hotelBookingUrl = new Array();
    hotelBookingUrl['exp'] = "'http://service.bfast.com/bfast/click?bfmid=26917872&siteid=41635796&bfpage=deeplink&GOTO=HOTSEARCH&CityName=' +sTripDestination + '&InDate=' +bestTripStartDate + '&OutDate=' +bestTripEndDate + '&NumAdult=1'";
    hotelBookingUrl['hot'] = "'http://click.linksynergy.com/fs-bin/statform?id=8KQyBpa6sz8&offerid=113245&offerid=93322&bnid=509&subid=0&type=4&inputId=hotel-index&destCity=' +sTripDestination + '&startDay=' +departureDate.getDate() + '&startMonth=' + (departureDate.getMonth() + 1) + '&endDay=' +returnDate.getDate() + '&endMonth=' + (returnDate.getMonth() + 1) + '&endDate=' +returnD + '&startDate=' +depDate";
    hotelBookingUrl['kayak'] = "'http://www.kayak.com/s/search/hotel?id=8KQyBpa6sz8&offerid=100094&type=4&subid=0&ai=8KQyBpa6sz8&pa=1&df=us1&d1=' +fullStartDate + '&d2=' +fullEndDate + '&crc=' +sTripDestination + ',' +state + ',' +sCountryCode";
    hotelBookingUrl['price'] = "'http://www.jdoqocy.com/interactive?aid=10408266&pid=2124264&ProductID=5&name=pclnbanner_hot&ROOMS=1&url=http://www.priceline.com/qp.asp&city=' +sTripDestination + '&CheckInDate=' +bestTripStartDate + '&CheckOutDate=' +bestTripEndDate";
    hotelBookingUrl['orb'] = "'http://www.orbitz.com/App/ValidateHotelSearch?id=8KQyBpa6sz8&offerid=66478&type=4&subid=&keywordPIB=' +sTripDestination + '&monthInPIB=' + monthNames[departureDate.getUTCMonth()] + '+' +departureDate.getFullYear() + '&dayInPIB=' + departureDate.getDate() + '&monthOutPIB=' + monthNames[returnDate.getUTCMonth()] + '+' + returnDate.getFullYear() + '&dayOutPIB=' +returnDate.getDate() + '&numberOfGuestsPIB=1&numberOfRoomsPIB=1'";
    
    xajaxSetCookie("hotelLinkout", tripId+":"+selectedDate+":"+selectedDestination);

    var selectBox = document.getElementById(("hotels"));
    var whichHotel = selectBox.options[selectBox.selectedIndex].value;
    var hotelLink = '';
    var depDate = bookingStartDate;
    var departureDate = new Date(depDate);

    if (depDate.length != 10) {
        var subSt = depDate.substring(6, 8);
        var finalDepDate = depDate.substring(0, 6) + 20 + subSt;
        departureDate = new Date(finalDepDate);
    }
    var returnD = bookingEndDate;
    var returnDate = new Date(returnD);
    if (returnD.length != 10) {
        var subESt = returnD.substring(6, 8);
        var finalEDepDate = returnD.substring(0, 6) + 20 + subESt;
        returnDate = new Date(finalEDepDate);
    }
    var fullStartDate = (departureDate.getMonth() + 1) + '/' +departureDate.getDate() + '/' +departureDate.getFullYear();
    var fullEndDate = (returnDate.getMonth() + 1) + '/' +returnDate.getDate() + '/' +returnDate.getFullYear();
    var country = sCountryCode;
    var state = sState;

    hotelLink = eval(hotelBookingUrl[whichHotel]);
    
    javascript : urchinTracker(hotelLink);
    fullStartDate=null;
    fullEndDate=null;
    country=null;
    state=null;
    departureDate=null;
    depDate=null;
    returnDate=null;
    returnD=null;
    hotelBookingUrl=null;
    selectBox=null;
    whichHotel=null;
    showPopup(hotelLink);
  
    return false;
}

function openCarsBookingPage() {
    var carBookingUrl = new Array();
    //carBookingUrl['exp'] = "'http://service.bfast.com/bfast/click?bfmid=26917872&siteid=41635796&bfpage=deeplink&GOTO=CARWIZD&PickUpLoc='+sTripDestination+'&PickUpDate='+bookingStartDate+'&PickUpTime=Morning&DropOffDate='+bookingEndDate+'&DropOffTime=Evening'";
    carBookingUrl['exp'] = "'http://service.bfast.com/bfast/click?bfmid=26917872&siteid=41635796&bfpage=deeplink&GOTO=CARSEARCH&PickUpLoc=' +airportCode + '&FromDate=' +bookingStartDate + '&ToDate=' +bookingEndDate";
    //carBookingUrl['hot'] = "'http://click.linksynergy.com/fs-bin/statform?id=8KQyBpa6sz8&offerid=93322&bnid=979&subid=0&startLocation='+sTripDestination+'&selectStartAirportCode='+airportCode+'&startDay='+departureDate.getDate()+'&startMonth='+departureDate.getMonth()+'&endDay='+returnDate.getDate()+'&endMonth='+returnDate.getMonth()+'&startTime=9000&endTime=2000&isUnderageDriver=false&startSearchType=N&inputId=index&selectedCarTypes=ECAR&isDebitCardSelected=false'";
    carBookingUrl['hot'] = "'http://click.linksynergy.com/fs-bin/statform?id=8KQyBpa6sz8&offerid=93322&bnid=979&subid=0&startLocation=' +airportCode + '&startDay=' +departureDate.getDate() + '&startMonth=' + (departureDate.getMonth() + 1) + '&endDay=' +returnDate.getDate() + '&endMonth=' + (returnDate.getMonth() + 1) + '&endTime=2000&isUnderageDriver=false&startSearchType=N&inputId=index&selectedCarTypes=ECAR&isDebitCardSelected=false'";
    carBookingUrl['kayak'] = "'http://www.kayak.com/s/search/car?id=8KQyBpa6sz8&offerid=100094&type=4&subid=0&ai=8KQyBpa6sz8&d1=' +fullStartDate + '&d2=' +fullEndDate + '&ap=' +airportCode + '&crc=' +sTripDestination + ',' +state + ',' +sCountryCode";
    //carBookingUrl['price'] = "'http://www.kqzyfj.com/interactive?aid=10408266&pid=2124264&PickUpLoc='+airportCode+'&DropOffLoc='+airportCode+'&VECHCLASS=SCAR&PICKUPTIME=09:00&DROPOFFTIME=09:00&url=http://www.priceline.com/qp.asp'";
    carBookingUrl['price'] = "'http://www.tkqlhce.com/interactive?ProductID=8&aid=10408266&pid=2124264&PickUpLoc=' +airportCode + '&DropOffLoc=' +airportCode + '&DropOffDate=' +bookingEndDate + '&PickUpDate=' +bookingStartDate + '&VECHCLASS=SCAR&PICKUPTIME=09:00&DROPOFFTIME=09:00&url=http://www.priceline.com/qp.asp'";
    carBookingUrl['orb'] = "'http://www.orbitz.com/App/PerformOrbotCarSearch?id=8KQyBpa6sz8&offerid=66478&type=4&subid=&pickupLocation=' +airportCode + '&pickupDay=' +departureDate.getDate() + '&pickupMonth=' + monthNames[departureDate.getUTCMonth()] + '+' +departureDate.getFullYear() + '&pickupTime=8+am&dropoffLocation=Same+as+pick-up&dropoffMonth=' + monthNames[returnDate.getUTCMonth()] + '+' +returnDate.getFullYear() + '&dropoffDay=' +returnDate.getDate() + '&dropoffTime=8+pm'";

    var selectBox = document.getElementById(("cars"));
    var whichCar = selectBox.options[selectBox.selectedIndex].value;
    var carLink = '';
    var depDate = bookingStartDate;
    var departureDate = new Date(depDate);
    if (depDate.length != 10) {
        var subSt = depDate.substring(6, 8);
        var finalDepDate = depDate.substring(0, 6) + 20 + subSt;
        departureDate = new Date(finalDepDate);
    }
    var returnD = bookingEndDate;
    var returnDate = new Date(returnD);
    if (returnD.length != 10) {
        var subESt = returnD.substring(6, 8);
        var finalEDepDate = returnD.substring(0, 6) + 20 + subESt;
        returnDate = new Date(finalEDepDate);
    }
    var fullStartDate = (departureDate.getMonth() + 1) + '/' +departureDate.getDate() + '/' +departureDate.getFullYear();
    var fullEndDate = (returnDate.getMonth() + 1) + '/' +returnDate.getDate() + '/' +returnDate.getFullYear();
    var country = sCountryCode;
    var state = sState;
    var airportCode = destinationAirportCode;
    
    carLink = eval(carBookingUrl[whichCar]);
    
    fullStartDate=null;
    fullEndDate=null;
    country=null;
    state=null;
    departureDate=null;
    depDate=null;
    returnDate=null;
    returnD=null;
    carBookingUrl=null;
    selectBox=null;
    whichCar=null;
    javascript : urchinTracker(carLink);
    showPopup(carLink);
    
    return false;

}
function openBookingPage(userId) {
    xajaxSetCookie("flightLinkout", tripId+":"+selectedDate+":"+selectedDestination);
    
    var currentTrip = tripData[currentDetailsKey];
    var _currentTripUserOrigin = currentTrip['tripUserOrigin'][userId];
    var fare = currentTrip['javascriptFares'][_currentTripUserOrigin];
    var parts = fare[0].split(";");
    
    var originAirportCode = parts[1].split(':')[0];
    var destinationAirportCode = parts[1].split(':')[1];
    var departureDateFormatted = currentTrip['departureDateFormatted'];
    var returnDateFormatted = currentTrip['returnDateFormatted'];
    var priceLineDepartureDate= currentTrip['priceLineDepartureDate'];
    var priceLineReturnDate = currentTrip['priceLineReturnDate'];
    var orbDeparture = currentTrip['orbDeparture'];
    var orbDepartureDate = currentTrip['orbDepartureDate'];
    var orbArrival = currentTrip['orbArrival'];
    var orbArrivalDate = currentTrip['orbArrivalDate'];
    var selectBox = document.getElementById(("selectProvider" + userId).replace('-', '_'));
    bookingSite = selectBox.options[selectBox.selectedIndex].value;
    return openFlightBookingPage(bookingSite, originAirportCode, destinationAirportCode, departureDateFormatted, returnDateFormatted, priceLineDepartureDate, priceLineReturnDate, orbDeparture, orbDepartureDate, orbArrival, orbArrivalDate);
}

function openFlightBookingPage(bookingSite, originAirportCode, destinationAirportCode, departureDateFormatted, returnDateFormatted, priceLineDepartureDate, priceLineReturnDate, orbDeparture, orbDepartureDate, orbArrival, orbArrivalDate) {    
    var flightBookingUrl = new Array();
    flightBookingUrl['exp'] = "'http://service.bfast.com/bfast/click?bfmid=26917872&siteid=41635796&bfpage=deeplink&GOTO=EXPFLTWIZ&FrAirport=' +originAirportCode + '&ToAirport=' +destinationAirportCode + '&FromDate=' + departureDateFormatted + '&ToDate=' + returnDateFormatted + '&NumAdult=1&NumChild=0&FromTime=Morning&ToTime=Morning'";
    flightBookingUrl['hot'] = "'http://click.linksynergy.com/fs-bin/statform?id=8KQyBpa6sz8&offerid=93322&bnid=978&subid=0&origCity=' +originAirportCode + '&destinationCity=' +destinationAirportCode + '&startDate=' + departureDateFormatted + '&endDate=' + returnDateFormatted + '&noOfTickets=2&inputId=index'";
    flightBookingUrl['trav'] = "'http://travel.travelocity.com/flights/InitialSearch.do?Service=CJUS&dateLeavingTime=Anytime&dateReturningTime=Anytime&flightType=roundtrip&leavingFrom=' +originAirportCode + '&goingTo=' +destinationAirportCode + '&leavingDate=' + departureDateFormatted + '&returningDate=' + returnDateFormatted + '&aid=10398279&pid=2124264&url=http://travel.travelocity.com/flights/InitialSearch.do'";
    flightBookingUrl['pline'] = "'http://www.kqzyfj.com/interactive?name=pclnbanner_air&id=pclnbanner_air&ProductID=1&DepCity=' +originAirportCode + '&ArrCity=' +destinationAirportCode + '&DepartureDate=' + priceLineDepartureDate + '&ReturnDate=' + priceLineReturnDate + '&NumTickets=1&aid=10408266&pid=2124264&url=http://www.priceline.com/qp.asp'";
    flightBookingUrl['orb'] = "'http://www.orbitz.com/App/ValidateFlightSearch?id=8KQyBpa6sz8&offerid=66478&type=4&subid=&slice1:departCity=' +originAirportCode + '&slice1:arriveCity=' +destinationAirportCode + '&Slice1:month=' + orbDeparture + '&Slice1:day=' + orbDepartureDate + '&Slice2:month=' + orbArrival + '&Slice2:day=' + orbArrivalDate + '&adult=1'";
    flightBookingUrl['kayak'] = "'http://www.kayak.com/s/search/air?id=8KQyBpa6sz8&offerid=100094&type=4&subid=0&ai=8KQyBpa6sz8&l1=' +originAirportCode + '&l2=' +destinationAirportCode + '&d1=' + departureDateFormatted + '&d2=' + returnDateFormatted + '&ft=rt&pa=1&cb=Economy'";

    urlLink = eval(flightBookingUrl[bookingSite]);
    javascript : urchinTracker(urlLink);
    showPopup(urlLink);
    return false;
}


function showPopup(urls) {
    openResizableWindow(urls, 800, 600)
    return;
}

function removeDestination() {
  var destinationId = $('editDestId').value;
  var destinationGroupCount = $('editDestGroupCount').value;
  var msg = "Delete this destination. Are you sure?";
  if (destinationGroupCount == 1) {
    msg = "Deleting destination choice will remove all associated note/hotel/car entries. Are you sure?"
  } 
  if (confirm(msg)) {
   xajax_removeDestination(destinationId, selectedDate, selectedDestination); 
   disable("destinationRow"+destinationId); 
  }
  return false;
}

function editDestination(destId, destGroupCount, cityId, cityName, firstDestinationId) {
    changeSelectedDestination(firstDestinationId);
    $('editDestId').value = destId;
    $('editDestGroupCount').value = destGroupCount;
    $('editLocation_id').value = cityId;
    $('editLocation').value = cityName;
    $('editLocation').setAttribute('oldValue',cityName);
    $('destRadio'+firstDestinationId).checked = true;
    var editDiv = $("editDestFrm");
    editDiv.parentNode.removeChild(editDiv);
    $("destinationRow"+destId).appendChild(editDiv);
    editDiv.style.display="block";
    return false;
}

function changeDestination() {
  if (validCityElement('editLocation', false, 'Destination')) {
      var destId = $('editDestId').value;
      var cityId = $('editLocation_id').value;
      xajax_changeDestination(destId, cityId, selectedDate);
  }
}

function removeDate() {
  var dateId = $('editDateId').value;
  if (confirm("Deleting date choice will remove all associated note/hotel/transportation entries.\nAre you sure?")) {
      xajax_removeDate(dateId, selectedDate, selectedDestination);
      disable("dateRow"+dateId);
  }
  return false;
}

function editDate(dateId, departDate, returnDate) {
    changeSelectedDate(dateId);
    $('dateRadio'+dateId).checked = true;
    var editDiv = $("editDateForm");
    $('editDeparture').value = departDate;
    $('editReturn').value = returnDate;
    $('editDateId').value = dateId;
    editDiv.parentNode.removeChild(editDiv);
    $("dateRow"+dateId).appendChild(editDiv);
    editDiv.style.display="block";
    return false;
}

function changeDate() {
  var dateId = $('editDateId').value;
  xajax_changeDate(dateId, $('editDeparture').value, $('editReturn').value, selectedDestination);
}

function removeMember(userId, type) {
  if (confirm("Delete this member. Are you sure?")) {
      xajax_removeMember(userId, selectedDate, selectedDestination);
      disable("memberRow"+userId);
  }
  return false;
}

function removeHotel(hotelId) {
  if (confirm("Delete this hotel choice. Are you sure?")) {
      xajax_removeActivity(hotelId, selectedDate, selectedDestination);
      disable("hotelRow"+hotelId);
  }
  return false;
}

function removeCar(carId) {
  if (confirm("Delete this transportaion choice. Are you sure?")) {
      xajax_removeActivity(carId, selectedDate, selectedDestination);
      disable("carRow"+carId);
  }
  return false;
}

function editNote(noteId) {
  displayEditNote(noteId);
  xajax_editActivity(noteId, selectedDate, selectedDestination);
  return false;
}

function removeNote(noteId) {
  if (confirm("Delete this note. Are you sure?")) {
      xajax_removeActivity(noteId, selectedDate, selectedDestination);
  }
  return false;
}

function addDestination() {
  if (validCityElement('newLocation', false, "destination")){
    xajax_addDestination($('newLocation_id').value, selectedDate, selectedDestination, $('partOfSameChoice').checked);
  }
  return false;
}

function clearDealsTab() {
  $('priceTabInnerContents').setAttribute("loaded", false);
  $('priceTabInnerContents').innerHTML='<div style="height:200px;"><br/><br/>Loading...</div>';
  if ($('priceTabContents').style.display == "block") {
    showTab('priceTab','tab');
  } 
}

function addDate() {
  xajax_addDate($('newDeparture').value, $('newReturn').value, selectedDate, selectedDestination);
  return false;
}

function addMember() {
  xajax_addMember(null, $('newEmail').value, $('newHometown_id').value, selectedDate, selectedDestination);
  return false;
}

function addHotelCar() {
  clearInfoFields("hotelCarForm");
  if (validHotelCarForm("hotelCarForm"))
      xajax_saveActivity(xajax.getFormValues("hotelCarForm"));
  return false;
}

function validHotelCarForm(frmName) {
    var frm = $(frmName);
    var name = frm.activity_name.value;
    if (name == '') {
        alert('Please enter name');
        return;
    }
    var startDay = frm.start_day.selectedIndex;
    var endDay = frm.end_day.selectedIndex;
    if (startDay != 0 && endDay == 0) {
        alert('Please select end day.');
        frm.end_day.focus();
        return;
    }
    
    if (startDay == 0 && endDay != 0) {
        alert('Please select start day.');
        frm.start_day.focus();
        return;
    }
    var startTime = '';
    var endTime = '';
    if (startDay != 0) {
        if (startDay > endDay) {
            alert('End day must be after start day.');
            frm.end_day.focus();
            return;
        }
        startTime = frm.start.value;        
        endTime = frm.end.value;
        if (startDay == endDay) {
            if (Date.parse('jan 1 2000 '+startTime) > Date.parse('jan 1 2000 '+endTime)) {
                alert('End time must be after start time.');
                return;
            }
        }
    }
    return true;
}


function saveNote() {
  clearInfoFields("activityForm");
  if (validActivityForm("activityForm"))  {
      if ($("activityForm").image.value.trim() != "") {
        $("activityForm").submit();
      } else {
        xajax_saveActivity(xajax.getFormValues("activityForm"));
      }
  }
  return false;
}

function validActivityForm(frmName) {
    var frm = $(frmName);
    var name = frm.activity_name.value;
    if (name == '') {
        alert('Please enter name');
        return;
    }
    var startDay = parseInt(frm.start_day.value);
    var endDay = frm.end_day.selectedIndex;
    var startTime = '';
    var endTime = '';
    if (startDay > endDay) {
        alert('End day must be after start day ('+startDay+').');
        return false;
    }
    startTime = frm.start.value;        
    endTime = frm.end.value;
    if (startDay == endDay) {
        if (Date.parse('jan 1 2000 '+startTime) > Date.parse('jan 1 2000 '+endTime)) {
            alert('End time must be after start time.');
            return false;
        }
    }
    var cityOptional = true;
    if (frm.address1.value.trim() != "" || frm.address2.value.trim() != "" || frm.zipcode.value.trim() != "")
        cityOptional = false;
    return validCityElement('addressCity', cityOptional, "city")
}

function pagingResponse(tableType, linkType, pageNo, totalResults, perPage) {
  var previousPageNo = linkType == 'N' ? pageNo-1 : pageNo+1;
  var lableId = document.getElementById(tableType + '_Label');
  var previousLinkTdId = document.getElementById(tableType + '_P');
  var nextLinkTdId = document.getElementById(tableType + '_N');
  var previousLinkId = document.getElementById(tableType + '_LinkP');
  var nextLinkId = document.getElementById(tableType + '_LinkN');
  var previousTableId =  document.getElementById(tableType + '_' +previousPageNo);
  var currentTableId =  document.getElementById(tableType + '_' + pageNo);

  currentTableId.style.display = '';
  previousTableId.style.display = 'none';

  previousLinkId.href="javascript:pagingResponse('" + tableType + "', 'P', " + (pageNo-1) + ", " + totalResults + ", " + perPage + ")";

  nextLinkId.href="javascript:pagingResponse('" + tableType + "', 'N', " + (pageNo+1) + ", " + totalResults +  ", " + perPage + ")";

  previousLinkTdId.style.display = pageNo-1 >= 0 ? '' : 'none';
  nextLinkTdId.style.display = totalResults > (pageNo+1)*perPage ? '' : 'none';
  
  lableId.innerHTML = pageNo+1;
  
  eval("window.pageFor"+tableType+"="+pageNo);
  
  adjustGroupHeights();
}

function restorePage(tableType, totalResults, perPage) {
    var curPage = eval("window.pageFor"+tableType);
    if (typeof(curPage) != 'undefined') {
        for (var i=0;i<curPage && i < totalResults/perPage;i++)
            pagingResponse(tableType, 'N', 1+i, totalResults, perPage);
    }
}

function  changeSelectedDestination(element) {
    var newValue = element;
    if (typeof(element) == 'object')
        newValue = element.value;
    if (selectedDestination != newValue) {
        selectedDestination = newValue;
        dateDestinationChanged();
        xajax_refreshDestinations(selectedDestination);
    }
}

function dateDestinationChanged() {
    $("hotelCar").innerHTML = "<br/>Loading...";
    $("dailyViewContent").innerHTML = "<br/>Loading...";
    xajax_refreshActivites(selectedDate, selectedDestination);
}        

function refreshNotes() {
    xajax_refreshNotes(selectedDate, selectedDestination);
}

function changeSelectedDate(element) {
    var newValue = element;
    if (typeof(element) == 'object')
        newValue = element.value;
    if (selectedDate != newValue) {
        selectedDate = newValue;
        dateDestinationChanged();
        xajax_refreshDates(selectedDate);
    }
}

function slideDown(elementId) {
    new Effect.SlideDown(elementId, {afterFinish:adjustGroupHeights});
}

function slideUp(elementId) {
    new Effect.SlideUp(elementId, {afterFinish:adjustGroupHeights});
}

function displayAddNote(day) {
    var activityDiv = $("addActivityFrm");
    activityDiv.style.display = "none";
    var frm = $("activityForm");
    var activityId = frm.activityId.value;
    activityDiv.parentNode.removeChild(activityDiv);
    if ($("day_"+day).hasChildNodes()) {
         $("day_"+day).insertBefore(activityDiv, $("day_"+day).childNodes[0]);
    } else
        $("day_"+day).appendChild(activityDiv);
    if (activityId != "") {
        $("activityContent"+activityId).style.display = "block";
        xajax_editActivity(-1, selectedDate, selectedDestination);
    } else  {
        frm.start_day.value = day;
        frm.end_day.selectedIndex = day;        
        slideDown("addActivityFrm");
    }
}

function displayEditNote(noteId) {
    var frm = $("activityForm");
    var activityId = frm.activityId.value;
    if (activityId != "") {
        $("activityContent"+activityId).style.display = "block";
    }
    $("activityContent"+noteId).style.display = "none";
    var activityDiv = $("addActivityFrm");
    activityDiv.parentNode.removeChild(activityDiv);
    $("activityRow"+noteId).appendChild(activityDiv);
    activityDiv.style.display = "none";
}

function displayAddHotel() {
    var frm = $("hotelCarForm")
    frm.activityType.value = "H";
    frm.start_day.selectedIndex = 1;
    frm.end_day.selectedIndex = 1;
    frm.parentNode.removeChild(frm);
    $("hotelForm").appendChild(frm);
    slideDown("addHotelCarFrm");
}

function displayAddCar() {
    var frm = $("hotelCarForm")
    frm.activityType.value = "T";
    frm.start_day.selectedIndex = 1;
    frm.end_day.selectedIndex = 1;
    frm.parentNode.removeChild(frm);
    $("carForm").appendChild(frm);
    slideDown("addHotelCarFrm");
}

function updateVote(type, id, value) {
    xajax_updateVote(type, id, value);
}

function openEditSettings() {
    $("tripInfo").innerHTML = "<br/>Loading..."
    xajax_getEditSettings(); 
}

function finalizeTrip() {
    if (selectedDate == -1 || selectedDestination == -1)
    {
        alert("You must have at least one destination and one date in trip to finalize trip.");
        return;
    }
    if ($("finalize").checked == true)
        xajax_lockTrip(selectedDate, selectedDestination);
    else
        xajax_unlockTrip(selectedDate, selectedDestination);
}

function updateOriginCity() {
    if (validCityElement("origin_city_for_trip", false, "Origin City")) {
        xajax_updateOriginCity($("origin_city_for_trip_id").value);
    }
}

function showPrintView() {
    wnd = window.open("/trip/print/"+tripId+"?selectedDate="+selectedDate+"&selectedDestination="+selectedDestination, "printView");
    wnd.focus();
}

function inviteFriend(userId) {
  disable("friendRow"+userId);
  xajax_addMember(userId, null, null, selectedDate, selectedDestination);
}

function addFriendByEmail(email) {
  xajax_addFriendByEmail(email, selectedDate, selectedDestination);
  return false;
}

function  changeImage(trip_id){
    window.SetUrl=function(value){
        document.getElementById('image').value=value;
    }
    var filemanager='/FCKeditor/editor/filemanager/browser/default/browser.html';
    var connector='connectors/php/connector.php?TripId='+trip_id;
    window.open(filemanager+'?Connector='+connector+'&Type=Image','fileupload','modal,width=600,height=400');
}

function editDestinationDay(destinationId) {
    toggleDisplay('editDestinationDayLink'+destinationId, 'editDestinationDayInput'+destinationId);
    return false;
}

function saveDateDestination() {
   if (validCityElement("guideFor", false, "City") && validNumber("numDays","trip duration")) {
     xajax_saveDateDestination($("guideFor_id").value, $("numDays").value);
   }
}

function moveActivity(activityId, day, evt) {
    if (activityId == "") return;
    var ctrlKey = (evt && evt.ctrlKey)
    xajax_copyMoveActivity(activityId, day, selectedDate, selectedDestination, selectedDate, selectedDestination, tripId, ctrlKey, true);
}

function showCopyNote(activityId) {
    window.copyNoteDialog = Dialog.confirm(
          {url: "/trip/copynote/"+tripId+"/"+activityId+"?dateid="+selectedDate, options: {method: 'get'}},  
          {windowParameters: {width:500}, 
           okLabel: "Copy",
           ok:function(win) {copyNote(activityId);return true;}
          }); 
    return false;
}

function copyNote(activityId) {
    if ($('nocopy')) return;
    if ($('copyToAnotherDay') && $('copyToAnotherDay').checked) {
        xajax_copyMoveActivity(activityId, getSelectedValue('destDay'), selectedDate, selectedDestination, selectedDate, selectedDestination, tripId, true, true);
    }
    else if ($('copyToAnotherChoice') && $('copyToAnotherChoice').checked) {
        var destChoice = getSelectedValue('destChoice')
        var toDate = destChoice.split(":")[0];
        var toDest = destChoice.split(":")[1];
        xajax_copyMoveActivity(activityId, 1, selectedDate, selectedDestination, toDate, toDest, tripId, true, false);
    } else if ($('copyToTrip') && $('copyToTrip').checked) {
        xajax_copyMoveActivity(activityId, 1, selectedDate, selectedDestination, null, null, getSelectedValue('destTrip'), true, false);
    }
}

function showCopyTrip(tripType) {    
      if (selectedDate == -1 || selectedDestination == -1) {
        alert("You must have at least one date choice and one destination choice to copy.");
      } else {
        Dialog.confirm(
              {url: "/i/copy_"+tripType+".html", options: {method: 'get'}},  
              {windowParameters: {width:400}, 
               okLabel: "Copy",
               ok:function(win) {copyTrip();return true;}
              }); 
      }
    return false;
}

function copyTrip() {
    var type="Trip"; 
    if ($('copyToBlog') && $('copyToBlog').checked) 
        type="Blog"; 
    if ($('copyToGuide') && $('copyToGuide').checked) 
        type="Guide"; 
    xajax_copyTrip(type, selectedDate, selectedDestination);
}

function clearClipboard() {
    xajax_clearClipboard();
}

function setDestinationDay(destinationId) {
    var dayDropDown = $("day_"+destinationId);
    if (dayDropDown) {
        xajax_setDestinationDay(destinationId, dayDropDown.options[dayDropDown.selectedIndex].value, selectedDate, selectedDestination);
    }
    return false;
}

function resendInvite() {
    if ($("resendMessage").value.trim() == "") {
        alert("Please enter a message to send.");
        return;
    }
    xajax_resendInvite($("resendMessage").value.trim());
    toggleDisplayX('resendInviteForm');
}

function editArrivalDeparture(userId, bookingId) {
    var frm = $("arrivalDepartForm");
    if (frm) {
        var oldBookingId = frm.booking_id.value;
        if (oldBookingId != "" && oldBookingId >= 0) {
            $("timing_content_"+userId+"_"+oldBookingId).style.display = "block";
        }
    }
    if (bookingId != -1)
        $("timing_content_"+userId+"_"+bookingId).style.display = "none";
    var inoutDiv = $("addArrivalDepartureFrm");
    inoutDiv.parentNode.removeChild(inoutDiv);
    if (bookingId != -1)
        $("timing_"+userId+"_"+bookingId).appendChild(inoutDiv);
    else 
        $("timing_"+userId).appendChild(inoutDiv);
    inoutDiv.style.display = "none";
    xajax_editArrivalDeparture(userId, bookingId, selectedDate, selectedDestination);
}

function removeArrivalDeparture(userId, bookingId) {
    if (!confirm("Are you sure, you want to remove this arrival/departure record?"))
        return;

    xajax_removeArrivalDeparture(userId, bookingId, selectedDate, selectedDestination);
}

function cancelEditArrivalDeparture(userId) {
    var frm = $("arrivalDepartForm");
    if (frm) {
        var oldBookingId = frm.booking_id.value;
        if (oldBookingId != "" && oldBookingId >= 0) {
            $("timing_content_"+userId+"_"+oldBookingId).style.display = "block";
        }
    }
    var inoutDiv = $("addArrivalDepartureFrm");
    inoutDiv.style.display = "none";
}

function saveArrivalDeparture() {
    clearInfoFields("arrivalDepartForm"); 
    var frm = $("arrivalDepartForm");
    frm.forDestination.value = selectedDestination;
    frm.forDate.value = selectedDate;
    xajax_saveArrivalDeparture(xajax.getFormValues("arrivalDepartForm"));
}

function mailOptionChanged() {
    var mailOption = $("mail").options[$("mail").selectedIndex].value;
    var remindOption = $("remindInterval").options[$("remindInterval").selectedIndex].value;
    xajax_saveMailOptions(mailOption, remindOption);
}

function disableVoting() {
    xajax_disableVoting(selectedDate, selectedDestination);
}

function addMembersToTrip() {
    var element = $("shareEmails");
    if (element.value != "" && element.value != element.getAttribute("info"))
        window.location.href = $("inviteMemberForm").action + "?submit=true&emails="+escape(element.value);
}

function changeOrganizer() {
    var users = $("changeOrganizer");
    xajax_changeOrganizer(users.options[users.selectedIndex].value);
}

function updateURL() {
    $('shortNameUrl').innerHTML="";
    var text = document.createElement("span");
    text.innerHTML = $('short_name').value;
    $('shortNameUrl').appendChild(text);
}

function updateAttending(new_attending) {
	$('current_attending').innerHTML = "Saving...";
	xajax_updateTripUserAttending(new_attending, selectedDate, selectedDestination);
}

function init_trip_name_and_message() {
	$('organizer_message').onmouseover=highlite_organizer_message;
	$('organizer_message').onmouseout=unhighlite_organizer_message;
	$('organizer_message').onclick=make_editable_trip_name_and_message;
	$('organizer_message').title = "Click here to update the message";
	if ($('organizer_message').innerHTML == "") {
		$('organizer_message').innerHTML = default_organizer_message;
	}

	$('trip_name').onmouseover=highlite_trip_name;
	$('trip_name').onmouseout=unhighlite_trip_name;
	$('trip_name').onclick=make_editable_trip_name_and_message;
	$('trip_name').title = "Click here to change the title";
}

function make_editable_trip_name_and_message() {
	$('organizer_message').style.display = "none";
	$('organizer_message_edit').style.display = "";
	$('trip_name').style.display="none";
	$('trip_name_edit_textarea').style.display = "";
}

function cancel_edit_trip_name_and_message() {
	$('organizer_message').style.display = "";
	$('organizer_message_edit').style.display = "none";

	$('trip_name').style.display = "";
	$('trip_name_edit_textarea').style.display = "none";
	
	xajax_cancelEditTripNameAndMessage();
}

function save_edit_trip_name_and_message() {
	$('organizer_message_edit_textarea').disabled="true";
	$('trip_name_and_message_edit_status').innerHTML = "Saving...";
	$('trip_name_and_message_buttons').style.display = "none";

	$('trip_name_edit_textarea').disabled="true";
	xajax_updateTripNameAndMessage($('trip_name_edit_textarea').value, $('organizer_message_edit_textarea').value);
}

function handle_update_trip_name_and_message(status) {
	$('trip_name_and_message_edit_status').innerHTML = status;
	setTimeout("finish_handle_update_trip_name_and_message()", 2000);
}

function finish_handle_update_trip_name_and_message() {
	$('organizer_message').style.display = "";
	$('organizer_message_edit').style.display = "none";
	$('trip_name_and_message_edit_status').innerHTML = "";
	$('organizer_message_edit_textarea').disabled="";
	$('trip_name_edit_textarea').disabled="";
	$('trip_name_edit_textarea').style.display = "none";
	$('trip_name').style.display = "";
	$('trip_name_and_message_buttons').style.display = "";
}

function highlite_organizer_message() {
	$('organizer_message').style.backgroundColor="#FFFF99";
}

function unhighlite_organizer_message() {
	$('organizer_message').style.backgroundColor="";
}

function highlite_trip_name() {
	$('trip_name').style.backgroundColor="#FFFF99";
}

function unhighlite_trip_name() {
	$('trip_name').style.backgroundColor="";
}

var default_comment = "Click here to enter a reply";
var current_comment;

function init_set_comment() {
    if ($('comment')) {
    	$('comment').onmouseover=highlite_comment;
    	$('comment').onmouseout=unhighlite_comment;
    	$('comment').title = "Click here to update your reply";
    	$('comment').onclick=make_editable_comment;
    	if ($('comment').value == "") {
        	$('comment').value = default_comment;
    	} 
    	current_comment = $('comment').value;
    }
}

function highlite_comment() {
	$('comment').style.backgroundColor = "#FFFF99";
}

function unhighlite_comment() {
	$('comment').style.backgroundColor = "white";
}

function cancel_edit_comment() {
	$('comment').value = current_comment;
	$('comment').onmouseover = highlite_comment;
	$('comment_buttons').style.display = "none";
}

function save_edit_comment() {
	$('comment').disabled="true";
	$('comment_status').innerHTML = "Saving...";
	$('comment_save').disabled="true";
	$('comment_cancel').disabled="true";
	$('comment_buttons').style.display = "none";
	xajax_updateTripReplyComment($('comment').value, selectedDate, selectedDestination);
}

function handle_update_comment() {
	$('comment').disabled="";
	$('comment').onmouseover = highlite_comment;
	$('comment_status').innerHTML = "Reply saved!";
	$('comment_save').disabled="";
	$('comment_cancel').disabled="";
	current_comment = $('comment').value;
	setTimeout("$('comment_status').innerHTML='';", 8000);
}

function make_editable_comment() {
	unhighlite_comment();
	$('comment').onmouseover=null;
	$('comment_buttons').style.display="";
	//current_comment = $('comment').value;
	if (current_comment == default_comment) {
		$('comment').value = "";
	}
}

