
$('document').ready(function(){

  /**
  * H2 corners
  */
  $('h2.cal-header, #steps-nights-options ul li, h3.room-type').corner('5px');
  $('.num-rooms').corner('tr tl 5px');

  /**
  * After page load hide the radio options.
  **/
  $('.noshow:input').css('visibility','hidden');


  // Step 1 Select a season
  $('#search-season').change(function(){
    //jump to the page with this new season selected
    var nPrdId = $('#product-id').val();
    var url='/product/'+nPrdId+'/?season='+$(this).val();
    window.location.href = url;
  });


  /**
  * If the Num Nights option changes then
  * Toggle the display of the label
  */
  $('#nights-options li').mouseover(function(){$(this).addClass('over')}).mouseout(function(){ $(this).removeClass('over')});



  /**
  * Night option gets clicked
  * Filter the list of room options
  */

  $('#nights-options li label').click(function(){

    //remove the over class from all the others
    $(this).parent().siblings().removeClass('selected');
    $(this).parent().addClass('selected');

    // what is the slected duration ie. num nights
    var nDur = $(this).attr('for').replace('duration','');

    //show step 3
    $('#step3').removeClass('hidden');
    $('#step3').show();
    $('#step4').hide();
    //show room options
    $('#steps-room-options ul li').hide();
    $('#steps-room-options ul').show();
    $('#steps-room-options').removeClass('noshow');
    $('#step3-instructions').hide();

    //loop through all the room options and find one that has this duration in the classname
    $('li.room-option').each(function(){
      var sClass = $(this).attr('class') ;
      sClass = sClass.replace('room-option alloc-','');
      aDurs = sClass.split('-') ;
      var nFound = 0 ;
      for(j=0;j<aDurs.length;j++){
        nFound= parseInt(nDur)==parseInt(aDurs[j]) ? 1 : nFound;
      }
      if(nFound==1) {
        //set opacity normal and show
        $(this).css('opacity','1').removeClass('hidden').css('filter','alpha(opacity=100)').show();
      }else {
        //set all selectors within it to -select-
        $(this).children('div.room-row').children('.selector').children('select').each(function(){$(this).children('option').eq(0).attr('selected','selected')});
        $(this).children('div.room-row').children('.selector').children('div').children('select').each(function(){$(this).children('option').eq(0).attr('selected','selected')});
        $(this).hide();
      }

      // check this parent for num visible children of type li
      // this hides the bold room type name of there are none of that type available for the selected duration
      if ($(this).parent().children(':visible').length>=1) {
        $(this).parent().parent().removeClass('noshow');
        $(this).parent().parent().show();
      }else {
        //hide room name
        $(this).parent().parent().hide();
      }

    });

  });


  /**
  * When a room type has a num room selected
  * Ensure there is the correct number of room 1, room 2 etc selectors for assigning people to rooms
  **/
  $('.select-rooms').change(function(){
    $('#steps-date-options').css('opacity','1');
    $('#steps-date-options').css('filter','alpha(opacity=100)');

      //how many rooms are selected
      var nRooms = $(this).val();

      //get the room type and season id
      var sTypeSeason = $(this).attr('name');
      sTypeSeason = sTypeSeason.replace('num_','');
      sTypeSeason = sTypeSeason.replace('_rooms','');

      //show the room-row
      var sRoomRowId = '#room-row-'+sTypeSeason ;


      if (nRooms>=1) {
        $(sRoomRowId).show();
      }else {
        $(sRoomRowId).hide();
      }


      // loop through the room-adults and room-children
      // in the num-adults- and num-children divs in the same room-row
      // make sure that at least nRooms selectors are visible
      $(sRoomRowId).children('.selector').each(function(){

        $(this).children('div.hidden').removeClass('hidden');

        //if the rooms was set to 0 make sure adults,children and infants all get set to 0 as well
        if (nRooms==0) {
          $(this).children('.room-adults:visible,.room-children:visible,.room-infants:visible').children('select').val(0);
        }
        $(this).children('.room-adults:visible,.room-children:visible,.room-infants:visible').css('display','none');
        $(this).children('.room-adults:hidden,.room-children:hidden,.room-infants:hidden').filter(function (index) {
                    return index <=nRooms-1 ;
                  }).fadeIn('slow');
      });


    $('#step4').show();

    // remove any specified date
    $("#hidStartDate").val('');

    // hide the calendar
    $('#booking-calendar').hide();

    // reset the calendar chooser to -select-
    $('#month-year').val('');

  });

  $('.select-adults,.select-children').change(function(){
    var sSelName = $(this).attr('name');
    var sRoomSeason = sSelName.replace('num_','');
        sRoomSeason = sRoomSeason.replace('_adults','');
        sRoomSeason = sRoomSeason.replace('_children','');
        aS = sRoomSeason.split('-r');

        sRoomSeason = aS[0];
        nR          = aS[1];

    //check max occupancy
    var nMax = $('#max-'+sRoomSeason).text();
        nMax = parseInt(nMax);

     // get selected occupancy for Adults and Children

     //var nAdults = $('.select-adults[name="num_'+sRoomSeason+'-adults-"]').length>=1 ? $('.select-adults[name="num_'+sRoomSeason+'_adults"]').val() : 0;
     //var nKids = $('.select-children[name="num_'+sRoomSeason+'_children"]').length>=1 ? $('.select-children[name="num_'+sRoomSeason+'_children"]').val() : 0;

     var nAdults = $('#'+sRoomSeason+'-adults-'+nR).length>=1 ? $('#'+sRoomSeason+'-adults-'+nR).val() : 0;
     var nKids = $('#'+sRoomSeason+'-children-'+nR).length>=1 ? $('#'+sRoomSeason+'-children-'+nR).val() : 0;
     var nInfants = $('#'+sRoomSeason+'-infants-'+nR).length>=1 ? $('#'+sRoomSeason+'-infants-'+nR).val() : 0;

     var nTot = parseInt(nAdults) + parseInt(nKids) ;
     var nTotWithInfants = parseInt(nInfants) + nTot ;
     //if nTotWithInfanst >=1 Make sure a num of rooms selector has been set to at least nR for this room type
     if (nTotWithInfants>=1 && parseInt($('#'+sRoomSeason).val()) < parseInt(nR) ) {
       $('#'+sRoomSeason).val(nR) ;
     }


     if (nTot > nMax)  {
      $.prompt('<h2>Warning!</h2>You have chosen too many people<br />This room/ticket is for a maximum of '+nMax+' people' ,
                {prefix:'abp'}
               ).corner('8px');
      // reset the selector to 0
      //var thisID = $(this).attr('id');
      //document.getElementById(thisID).options.selectedIndex=0;
      $(this).val(0);
     }


     //check single adults rule
     if(   sRoomSeason.substr(0,3)=='dbl'
        && $('#accept-single-'+sRoomSeason).text()=='N'
        && nAdults==1
        && nKids<=0
        &&  $('#ticket-only-'+sRoomSeason).text()!='Y'
        ) {
       $.prompt('<h2>Warning!</h2><p class="bold">This break is based on a minimum of 2 people sharing a room.</p><p>Please select at least two adults or 1 Adult and 1 Child.<br /><br />Continuing without doing so may result in you being denied entry to your<br />selected accommodation without refund.<br /><br />If you are a single traveler please contact our Customer Service Team,<br />who will find you an alternative option.</p>' ,
                {prefix:'abp'}
                ).corner('8px').bgiframe();
     } else {
       // Check Min Occupancy
       if (sRoomSeason.substr(0,3)!='dbl' || (sRoomSeason.substr(0,3)=='dbl' && $('#supplement-'+sRoomSeason).length==0 ) ) {
         var nMin = $('#min-'+sRoomSeason).text();
             nMin = parseInt(nMin);
         if (nTot < nMin && nMin>1)  {

           if (sRoomSeason.substr(0,4)=='quad') {
             $.prompt('<h2>Warning!</h2><p class="bold">Warning Quad Rooms are for parties of 4 persons only! If you attempt to book for less than 4, we reserve the right to allocate you a different room type or charge you extra.</p>' ,{prefix:'abp'}).corner('8px');
           } else if (sRoomSeason.substr(0,3)=='tri') {
             $.prompt('<h2>Warning!</h2><p class="bold">Warning Triple Rooms are for parties of 3 persons only! If you attempt to book for less than 3, we reserve the right to allocate you a different room type or charge you extra.</p>' ,{prefix:'abp'}).corner('8px');
           }
            else {
             $.prompt('<h2>Warning!</h2><p class="bold">Price based on minimum occupancy of '+nMin+' people</p><p>If you attempt to book for less than '+nMin+', we reserve the right to allocate you a different room type or charge you extra.</p>' ,{prefix:'abp'}).corner('8px');
           }


         }
       }else {
         //dbl room  so check for allowed single supplements
         var msg = $('#supplement-'+sRoomSeason).text();
       }
     }


  });


  /**
  * When num adults or num children is selected
  * do a wee prompt on blur if adults + children > pax
  **/


  /**
  * A Month/Year  selected
  */
  $('#month-year').change(function(){



    //send all the vars so far as get vars
    //get the HTML for the actual calendar from /calendar/index.php
    var sMonthYear = $(this).val();

    if (sMonthYear!='') {
     $('#booking-calendar').show();
     //jump to page with ALL form vars

     // load the calendar
     // build required vars (NB exclude empty vars)
     var sVars = $("#booking-tab-form :input[value][value!='0']").serialize();

     //$.prompt("form vars are<br />"+ str,{prefix:'abp'});
     if (  $('#duration0').attr('checked')==true || $('#duration0').attr('checked')=='true' || $('#duration0').attr('checked')=='checked' ||  $('#hidduration').val()=='0' ) {
      var sDur = $("input[name='duration']").val()=='0' ? '&duration=0' : '' ;
     }else{
       sDur='';
     }

     window.location.href='/product/'+$('#product-id').val()+'/?'+sVars+sDur ;

     // $('#booking-calendar').load('/product/'+$('#product-id').val()+'/',sVars);

    }else{
     $('#booking-calendar').hide();
    }

  });

  /**
  * Bookable Date Clicked.
  **/
  $('td.this-month-day').mouseover(function(){
    $(this).addClass('over');
  }).mouseout(function(){
    $(this).removeClass('over');
  });

  /**
  * Bookable Date Clicked.
  **/

  $('a.startDate,span.price').click(function(){
    var nPrice = '';
    nPrice = $('span', this).html();

    if(nPrice=='' || nPrice == null || nPrice == 'null'){
      nPrice =  $(this).html();
    }

    //set a Class for the TD by getting the TD id
    var thisID = $(this).attr('id');
    var aId = thisID.split('-');
    var nId = aId[2];
    var sTdId = 'td#day-'+nId ;

    //remove selected class from all other tds
    $('#calendar-table tr td').removeClass('selected');
    //add selected class to our TD
    $(sTdId).addClass('selected');

    // Set the start date in a hidden field
    var sStartDate = $('#hidCalYear').val() + '-' + $('#hidCalMonth').val() + '-' + nId ;
    $('#hidStartDate').val(sStartDate) ;

    // Show a Summary of the Room Choices
    var displayStartDate =  nId + '-' + $('#hidCalMonth').val() + '-' + $('#hidCalYear').val()  ;

    // Rooms Summary.
    var sSummary = '<h2 class="cal-header">Your Holiday Summary :-</h2>' ;
    var nNights = $('input[name=duration]:checked').val();
    if (nNights == 'undefined' || nNights== undefined) { nNights =  $('input[name=duration]').val() ; }
        sSummary+= '<br />Starting on <strong>'+displayStartDate+ '</strong> for <strong>' + nNights + '</strong> nights';
        sSummary+= $('#room-summary').html();
       /* sSummary+= '<strong>Total</strong> price: ' + sCurrencySymbol + nPrice; */
    /*
        //serialize the form and extract the room coices
    var aFormVars = $("#booking-tab-form").serializeArray();

    //create an empty array to hold out room info
    var oRooms = new Object();
    $.each(aFormVars, function(i, field){
      //only grab room inf (start with num_
      if(field.name.substr(0,4)=='num_'){
        //sSummary+='<br />'+field.name+' = '+field.value ;
        //explode by '-'
        var aDetails = field.name.split('-');
        var sRoomType = aDetails[0].replace('num_','');
        if(sRoomType=='dbl') {
          sRoomName = 'Double' ;
        }else if(sRoomType=='tri') {
          sRoomName = 'Triple' ;
        }else if(sRoomType=='quad') {
          sRoomName = 'Quad' ;
        }else if(sRoomType=='other') {
          sRoomName = 'Other' ;
        }

        //split the second part by underscore to get adults/ children/ num rooms
        var aPartTwo = aDetails[1].split('_');
        if(aPartTwo[1]=='rooms' && field.value>=1) {
          var nNumRooms = field.value;
          sSummary+='<br /><br /><strong>'+nNumRooms+' '+sRoomName+ ' room(s)</strong>';
        }

        if(aDetails.length==3) {
          var aPartThree = aDetails[2].split('_');
          if( (aPartThree[1]=='adults' || aPartThree[1]=='children') && field.value>=1) {
            var nNumPeople = field.value;
            var nRoomNumber = aPartThree[0].replace('r','');
            //oRooms[sRoomType][nRoomNumber][aPartTwo[1]] = nNumPeople ;
            if(aPartThree[1]=='adults') {
              sSummary+= '<br />'+'&nbsp;&nbsp;&nbsp;<em>room ' + nRoomNumber + '::</em> ' + nNumPeople + ' x '+ aPartThree[1] ;
            }else {
              sSummary+= ','+'&nbsp; ' + nNumPeople + ' x '+ aPartThree[1] ;
            }
          }
        }

      }

    });*/


    $('#summary').html(sSummary);


    // Present A Book Now Button to post to /shopping-cart/
    $('div#bookbtn').show();
    $('#startover').hide();

    // return false so the link click does nothing.
    return false;
  });



});

