var $j = jQuery.noConflict();
var $current_loader = null;

var packageLookup = {
    "nodes":[]
};

var _returnPackageSet = {
   "nodes":[]
};

var base_booking_engine_qs = 'parent_path_to_top=' + SiteVars.path_to_top;

$j(document).ready(function() {

  $j('#StartingCity').change(function() { TripSearch.calculateDates(); });
  $j('#StartingDate').change(function() { 
    TripSearch.calculateDates(); 
    $j('#packageYear').remove(); 
    $j('form.trip-search-form').append('<input type="hidden" name="PackageYear" id="packageYear" value="' + $j('#StartingDate').val().substring(2) + '"/>');
  });
  $j('#EndCity').change(function() { TripSearch.calculateDates(); });
  $j('#Duration').change(function() { TripSearch.calculateDates(); });   

  //Selectbox
  $j('select#cardType').selectmenu({transferClasses: true, width: 250});
  $j('select').selectmenu({transferClasses: true, width: 200});
  /* From api.jquery.com/load:
     "... if the current document does not contain an element with an ID of ..., the .load() method is not executed." */
  //if (SiteVars.currentLocale == 'en_CA' || SiteVars.currentLocale == 'en_CA_BC') {     
    $j('#session-info').load(SiteVars.path_to_top + '/ajax/welcome', base_booking_engine_qs);
  //} else {
  //  $j('#session-info').hide();
  //}
  loadJqueryUI();
  
  //validateSubscribeForm();
  if (SiteVars.this_url.indexOf('/contact_us/request_brochure') > -1) {
      validateRequestBrochureForm();
  }
  
  if (SiteVars.this_url.indexOf('/guests/photo_gallery/submit_photos') > -1) {
    validatePhotoUploadForm(); 
  }
  
  if (SiteVars.this_url.indexOf('/contact_us/book_your_trip') > -1) {
   validateRequestQuoteForm();
  }
  
  if (SiteVars.this_url.indexOf('/guests/testimonials/submit_testimonial') > -1) {
   validateTestimonial(); 
  }
  
  $j(".image-rounded, .image-rounded2").load(function() { 
    var img = $j(this);    
    img.wrap(function() {
      return '<span class="' + img.attr('class') + '" style="background:url(\'' + img.attr('src') + '\') no-repeat center center; width: ' + img.attr("width") + 'px; height: ' + img.attr("height") + 'px;"></span>';
    }).css("opacity", "0");
    
     if (SiteVars.this_url.indexOf('/booking/choose-service') > -1) {
       $j('.disabled-servicelevel .image-rounded').css({opacity:0.5});
     }
     if (SiteVars.this_url.indexOf('/booking/hotel-options') > -1) {
       $j('.disabled .image-rounded').css({opacity:0.5});
     }
  });
  
  $j(".inner-image-rounded img").load(function() { 
    var img = $j(this);    
    img.wrap(function() {
      return '<span class="image-rounded" style="background:url(\'' + img.attr('src') + '\') no-repeat center center; width: ' + img.attr("width") + 'px; height: ' + img.attr("height") + 'px;"></span>';
    }).css("opacity", "0");
  });
  
  
  $j("a .image-rounded, a .image-rounded2").load(function() {
    $j(this).wrap(function(){
      return "<span class='mask'></span>";
    });
  });
 
  $j("#divButton, #linkButton, #search-controls div a, .group-button a, #main-column form .submit").button();
  /*
  $j("a .image-rounded img, a .image-rounded2 img").load(function() {
    $j(this).wrap(function(){
      return '<span class=\'mask\'></span>';
    });
  });
  */	
  /* general tiles across site */
  equalHeightByRow('.general-tile-item .tile-content');
  
  
  $j(document).ready(function() {
      initEqualHeights();
  });  
  
  if (SiteVars.this_url == '/') {
    $j('.c-panel-bottom').mouseover(function() {
        $j(this).find('a').addClass('c-hover');
        $j(this).addClass('c-panel-over');
    });
    
    $j('.c-panel-bottom').mouseout(function() {
        $j(this).find('a').removeClass('c-hover');
        $j(this).removeClass('c-panel-over');
    });
    
    
  }

  
  if($j("#main-column form").length && SiteVars.this_url.indexOf('/routes_and_packages/') < 0 && SiteVars.this_url.indexOf('/booking/') < -1) {
    //Request Form Validation
    $j("#main-column form #email").validate({
        expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+\\-?[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
        message: "Should be a valid Email id"
    });
    
    $j("#main-column form #first, #main-column form #last, #main-column form #upload_file,  #main-column form #j_captcha_response, #main-column form #selectorstartDate, #main-column form #numAdults, #main-column form #numChildren, #main-column form #numInfants,#main-column form #phone, #main-column form #fax,#main-column form #address_1,#main-column form #city,#main-column form #state,#main-column form #zip").validate({
         expression: "if (VAL) return true; else return false;",
         message: "Please enter the Required field"
    });
  
    $j("#main-column form #country").validate({
        expression: "if (VAL) return true; else return false;",
        message: "Please make a selection"
    });
    
    $j('#j_captcha_response').validate({
        expression: "if (VAL) return true; else return false;",
        message: "Please enter the Required field"
    });
    
    
    if (SiteVars.this_url.indexOf('/submit_testimonial') > -1) {
      $j('#confirm_email').validate({
        expression: "if ((VAL == jQuery('#email').val()) && VAL) return true; else return false;",
        message: "Please enter the Required field"
      });
      
    }       
  
    var $upload_file = $j("#upload_file");
    if ($upload_file.length > 0) {
      $j('#upload_file').fileinput();
    }
  }
  
  
  /* site search */
  $j('#site-search-term').focus(function() {
    
      if ($j('#site-search-term').val() == SiteVars.modules.phrasePack.defaultSearchText) {
        $j('#site-search-term').val('');
      }
  });
  $j('#site-search-term').blur(function() {
       if ($j('#site-search-term').val() == '') {
         $j('#site-search-term').val(SiteVars.modules.phrasePack.defaultSearchText);
       }
  });
  
  $j('#site-search-button').click(function() {
      if (($j('#site-search-term').val() == SiteVars.modules.phrasePack.defaultSearchText) ||
        $j('#site-search-term').val() == '') {
           alert('Please enter a keyword'); 
        } else {
          $j('#search-form').submit();
        }
  });
  
  
  $j(".tabs").tabs({
    cache: true,
    spinner: '',
    select: function(event, ui) {
      var panel = $j(ui.panel);
      if (panel.is(":empty")) {
        var src = SiteVars.path_to_top + '/template_images/rmv/layout/loader24.gif';
        panel.append("<div class='loader'><img src='" + src + "' /></div>");
      }
      
    },
    load: function(event, ui) {
      $j(ui.panel).find(".loader").remove();
      
      if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
       // $j('.pkg .tabs #overview .group').equalHeight();
       // $j('.pkg .tabs #dining ul.menus li').equalHeight();
        $j('.pkg .tabs #itinerary table').equalizeTables({children: ['.desc']});
        $j('.pkg .tabs #dates table.days').equalizeTables();
        $j('.pkg .tabs #dates table.times').equalizeTables();
      }

      // update tab 
      
      var a = $j(ui.panel).find('#overview a');
      
      
      
      for (var i = 0; i < a.length; i++) {
        if (a[i].href.indexOf('#') > 0) {
          
           a[i].href = a[i].href.substring(a[i].href.indexOf('#'));
           
           $j(a[i]).click(function() {
               $j('.tabs').tabs('select',  $j(this).attr('hash')  ); 
           });
           
        }
      }      
      
      // apply buttons
      $j(".button").button({
          icons: {
          secondary: 'ui-icon-carat-1-e' 
      }}); // end of buttons
      
      
    }
  });
  
});

// this runs all of the equal height stuff
// moved here so that we could re-init it when font size is selected
function clearHeights() {
  
  $j('.general-tile-item .tile-content').height('auto');
  
  if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
    
    $j('.badges-float .desc-block').height('auto');
    $j('div.route-summary-float .desc-block').height('auto');
    
  }
  
  if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
      $j('.pkg.overview .levels ul.cols .prices').equalHeight();
      $j('.pkg.overview .levels ul.cols .short-desc-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .train-exp-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .dining-exp-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .hotels-block').equalHeight();
  }  
  
  $j('.large-panel-container .item p').height('auto');
  $j('.large-panel-container .item .title').height('auto'); 
  
  
  
  if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
    equalHeightByRow('.badges-float .desc-block');
    equalHeightByRow('div.route-summary-float .desc-block');
  }
  
  // Equal Heights
  if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
      $j('.pkg.overview .levels ul.cols .prices').equalHeight();
      $j('.pkg.overview .levels ul.cols .short-desc-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .train-exp-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .dining-exp-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .hotels-block').equalHeight();
  }
  
        

  $j(document).ready(function() {
    $j('.main-panel-header .item p').equalHeight();
    $j('.main-panel-header .item .title').equalHeight();  
    
    if (SiteVars.this_url.indexOf('/destinations') > -1) {
      /* not needed 
       $j('.dest-cr-panels .destination-item .description-block').equalHeight();
       $j('.dest-van-panels .destination-item .description-block').equalHeight();
       $j('.dest-over-panels .destination-item .description-block').equalHeight();
       $j('.dest-vi-panels .destination-item .description-block').equalHeight();
       $j('.dest-east-panels .destination-item .description-block').equalHeight();
       */
    }
    
    if (SiteVars.this_url.indexOf('/service_level') > -1) {
      
         $j('.service-item .tagline-block').equalHeight();
         $j('.service-item .service-desc-block').equalHeight();
         //$j('.service-item .train-image-block').equalHeight();
         
         $j('.whistler-service-summary .service-item .tagline-block').equalHeight();
         $j('.whistler-service-summary .service-item .service-desc-block').equalHeight();
         
         //equalHeightByRow('div.service-summary');
    }    
    
    if (SiteVars.this_url == '/media_kit') {
     
    }
    
  });
  
  

  
  
  /* site search */
  $j('#site-search-term').focus(function() {
    
      if ($j('#site-search-term').val() == SiteVars.modules.phrasePack.defaultSearchText) {
        $j('#site-search-term').val('');
      }
  });
  $j('#site-search-term').blur(function() {
       if ($j('#site-search-term').val() == '') {
         $j('#site-search-term').val(SiteVars.modules.phrasePack.defaultSearchText);
       }
  });
  
  $j('#site-search-button').click(function() {
      if (($j('#site-search-term').val() == SiteVars.modules.phrasePack.defaultSearchText) ||
        $j('#site-search-term').val() == '') {
           alert('Please enter a keyword'); 
        } else {
          $j('#search-form').submit();
        }
  });
  
  // Tab content is initially hidden so that it does not show until jquery.tabs is done working.
  // This also ensures that scripts which depend on the width/height of elements can do their work before
  // jquery.tabs hides part of the content.
  $j(".tabs").css("visibility", "hidden");
  $j(window).load(function() {
    $j(".tabs").tabs().css("visibility", "visible");
  });
  
}


function initEqualHeights() {

  equalHeightByRow('.general-tile-item .tile-content');
  
  if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
    
    equalHeightByRow('.badges-float .desc-block');
    equalHeightByRow('div.route-summary-float .desc-block');
    
  }
  
  
  // Equal Heights
  if (SiteVars.this_url.indexOf('/routes_and_packages') > -1) {
      $j('.pkg.overview .levels ul.cols .prices').equalHeight();
      $j('.pkg.overview .levels ul.cols .short-desc-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .train-exp-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .dining-exp-block').equalHeight();
      $j('.pkg.overview .levels ul.cols .hotels-block').equalHeight();
      
  }
  
  
      
    $j('.large-panel-container .item p').equalHeight();
    $j('.large-panel-container .item .title').equalHeight();  
    

    if (SiteVars.this_url.indexOf('/service_level') > -1) {
      
         $j('.service-item .tagline-block').equalHeight();
         $j('.service-item .service-desc-block').equalHeight();
         //$j('.service-item .train-image-block').equalHeight();
         
         $j('.whistler-service-summary .service-item .tagline-block').equalHeight();
         $j('.whistler-service-summary .service-item .service-desc-block').equalHeight();
         
         //equalHeightByRow('div.service-summary');
    }    
    

    
    
}


//{{{ equalize tables
(function($) {

    // ensure all tables have an equal number of rows, and set each corresponding row to equal height
    // REQUIRED: the equalHeight plugin
    // TODO: refactor into separate private methods
    $.fn.equalizeTables = function(options) {
      
      var opts = $.extend({}, $.fn.equalizeTables.defaults, options);
      
      if (this.length < 2) {
        return this;
      }
      
      var $tables = this.filter('table');
      
      var sizes = _.map($tables, function(e) {
        return $(e).find('tbody tr').length;
      });
      
      var max = _.max(sizes);
      
      // only add empty rows if needed
      if (_.any(sizes, function(x){ return x != max; })) {
        var $largest = $tables.eq(sizes.indexOf(max));
        
        var $dummy = $largest.find('tbody tr').first().clone();
        $dummy.find('td').html('');
        
        // isolate smaller tables
        var $subset = $tables.filter(function(i) {
          return $(this).find('tbody tr').length != max; 
        });
        
        // add empty rows
        $subset.each(function() {
          var $this = $(this);
          var $tbody = $this.find('tbody');
          var diff = max - $tbody.find('tr').length;
  
          for (var i=0 ; i < diff ; i++)
            $dummy.clone().appendTo($tbody);
        });
      }

      // now that all tables have an equal number of rows, let them all have equal height
      for (var i=0 ; i < max ; i++) {
        var $cells = $tables.find('tbody tr:nth-child(' + (i + 1) + ')');
        
        // optionally set specified cell children to equal height
        for (var c=0 ; c < opts.children.length ; c++)
          $cells.find(opts.children[c]).equalHeight();
        
        $cells.equalHeight();
      }
      
      return this;
    };
    
    $.fn.equalizeTables.defaults = {
      children: []
    };
    
})(jQuery); //}}}

//{{{ selective print
(function($) {
    
    // print only the selected elements
    $.fn.print = function(options) {
      
      var opts = $.extend({}, $.fn.print.defaults, options);
      
      var id = "itinerary-printer";
      var $frame = $('<iframe name="' + id + '">');
      
      $frame.css("position", "relative")
            .css("left", "-9999px")
            .css("width", "1px")
            .css("height", "1px");
      
      $frame.appendTo($("body"));
      
      var page = $frame[0].contentWindow;
      var dom = page.document;
      
      var $bag = $("<div>");
      
      this.each(function() {
        $(this).clone().appendTo($bag);
      });
      
      // remove all adjustments used on the screen
      $bag.find('*').height('auto');
      
      dom.open();
      dom.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
      dom.write("<html>");
      dom.write("<head>");
      dom.write("<link rel='stylesheet' media='all' type='text/css' href='" + opts.styles + "'>");
      
      dom.write("</head>");
      dom.write("<body" + (opts.bodyClass ? ' class="' + opts.bodyClass + '"' : '') + ">");
      dom.write("<div id='logo'><img src='" + opts.logo + "'></div>");
      
      // insert our content
      dom.write($bag.html());
      
      dom.write("</body>");
      dom.write("</html>");
      dom.close();
      
      page.focus();
      
      try {
        page.document.execCommand('print', false, null);
      } catch (e) {
        page.print();
      }
        
      
      // wait a little bit before removing the iframe; it sometimes gets removed before the browser
      // has time to respond
      
      setTimeout(
        function() { $frame.remove(); },
        30 * 1000
      );
      
    };
    
    $.fn.print.defaults = {
      bodyClass: null,
      logo: '',
      styles: $('link[rel="stylesheet"][media="print"]').first().attr('href')
    };

})(jQuery); //}}}

//{{{ photo gallery
(function($) {

    // create a lightboxed slideshow from a list of images
    // DEPS: lightbox_me and jquery.cycle
    $.fn.photo_gallery = function(options) {
      
      var opts = $.extend({}, $.fn.photo_gallery.defaults, options);
      
      var numPhotos = this.find('img').length;
      
      // 0: construct slideshow container
      var $box = $('<div><h3></h3></div>').addClass('lightbox photos');
      
      // 1: add close, prev, next elements
      $box.append($('<a class="close" href="#">x</a>'));
      $box.append($('<div class="nav"><a class="prev" href="#">&#171;</a><a class="next" href="#">&#187;</a></div>'));
      
      // 2: clone slides into it
      var $slides = $('<div></div>').addClass('slides');
      this.find("a").each(function() {
        var $this = $(this);
        var w = $this.attr('data-width') ? ' width="' + $this.attr('data-width') + '" ' : '';
        var h = $this.attr('data-height') ? ' height="' + $this.attr('data-height') + '" ' : '';
        $slides.append('<img src="' + $this.attr('href') + '" title="' + $this.attr('title') + '"' + w + h + ' />');
      });
      
      $box.append($slides);
      
      // 3: added the status indicator
      var $status = $('<span class="status"></span>');
      $box.append($status);
      
      // 4: connect anchors
      this.find('a').click(function() {

        var $this = $(this);
        var i = $this.parent().index();

        $box.lightbox_me({
          centered: true,
          destroyOnClose: true
        });

        // 5: start the slideshow
        $slides.cycle({
          fx: 'scrollHorz',
          timeout: 0,
          speed: 500,
          startingSlide: i,
          next: '.next',
          prev: '.prev',
          after: function (current, next, opts, forward) {
            var pos = $(this).index() + 1; // for us humans
            $('.lightbox.photos h3').html($slides.find('img').eq(pos).attr('title'));
            $('.lightbox.photos .status').html(pos + '/' + numPhotos);
          }
        });

        return false;
      });
      
      $(document).bind('keyup', function(e) {
        if (e.keyCode == 37)
          $slides.cycle('prev');
        else if (e.keyCode == 39)
          $slides.cycle('next');
        return false;
      });
      
      return this;
    };
    
    $.fn.photo_gallery.defaults = {};
    
})(jQuery); //}}}

(function($){
	$.fn.equalHeight = function() {
		tallest = 0;
		this.each(function(){
			thisHeight = $(this).height();
			if( thisHeight > tallest)
				tallest = thisHeight;

		});
		this.each(function(){
			$(this).height(tallest);
		});
	}
})(jQuery);


// april 26 to oct 6
function noOutsideDates(date) {
  
  var m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  
  // date must be between april 26 to october 6
  var dt = date.getFullYear() + '' + m + '' + d;
  var ct = date.getFullYear() + '0426';
  var ed = date.getFullYear() + '1006';
  
  if ((parseInt(dt,10) >= parseInt(ct,10)) && (parseInt(dt,10) <= parseInt(ed,10)) ) {
    return([true]);
  }

  return([false]);
  
}
var SubscribeForm = {
  init:function() {
    
    $j('#subscribe-form').submit(function(e) {
        var regex = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
        $j('#newsletter-err-resp').hide();
        $j('#newsletter-suc-resp').hide();
        if ( $j('#subscribe-email').val() == '' || $j('#subscribe-email').val() == 'name@email.com' ) {
            $j('#newsletter-err-resp').show();
            return false;
        }
        
        if ( regex.test($j('#subscribe-email').val())  ) {
          
          
          $j.ajax({
            url:'/ajax/subscribe',
            type:'POST',
            data: $j('#subscribe-form').serialize(),
            contentType:'application/x-www-form-urlencoded',
            complete: function(){
              $j('#newsletter-suc-resp').show();
            }
          });          
          
        } else {
                $j('#newsletter-err-resp').show();
        }

        return false;
        
        
    });

    
    
    
  }
};

var TripSearch = {
  
  
  // if any of the trip search fields are filled out then we need to 
  // run this code again to show the correct dropdown options.
  init:function() {
    var from = $j('#StartingCity option:selected').val();
    var to = $j('#EndCity option:selected').val();
    var dep  = $j('#StartingDate option:selected').val().replace(' ', '');
    var dur  = $j('#Duration option:selected').val();
    
    if (from != '' || to != '' || dep != '' || dur != '') {
      TripSearch.calculateDates();
    }
  },
  
  
  calculateDates:function() {
    
       $j("#trip-search select").selectmenu("disable"); 
    
       var from = $j('#StartingCity option:selected').val();
       var to = $j('#EndCity option:selected').val();
       var dep  = $j('#StartingDate option:selected').val().replace(' ', '');
       var dur  = $j('#Duration option:selected').val();
       var arrQueryStr = new Array();
       

       if (from == '' && to == '' && dep == '' && dur == '') {
         TripSearch.resetFields();
         $j("#trip-search select").selectmenu("enable"); 
         return; 
       }
       
       
       if (from != '') {  arrQueryStr.push('TripsearchFrom:"| ' + from + ' |"'); }
       if (to != '') {  arrQueryStr.push('TripsearchTo:"| ' + to + ' |"'); }
       if (dep != '') {  arrQueryStr.push('TripsearchDept:"| ' + dep + ' |"'); }
       if (dur != '') {  arrQueryStr.push('Duration:"' + dur + '"'); }
       
       // refresh package set
       $j.getJSON(SiteVars.path_to_top + '/json/tripsearch', 
         {"query":arrQueryStr.join(" AND ")},
          function(data) {
            
           packageLookup.nodes = data.nodes;
             
             _returnPackageSet.nodes.length = 0;
             
             
             var skip = false;
             
             
             //console.time('native');
             for(var idx = 0; idx < packageLookup.nodes.length; idx++) {
                var value = packageLookup.nodes[idx]; 
                skip = false; // reset
                
                if (from != '' && value.frm != from) { skip = true; }
                if (to != '' && value.to != to) { skip = true; }
                if (dep != '' && value.dept.indexOf('|' + dep + '|') < 0) { skip = true; }
                
                if (skip == false) {
                  _returnPackageSet.nodes.push(packageLookup.nodes[idx]);
                }
             }
           
             
             // now repopulate all of the search dropdowns BUT ONLY IF NOT 0
             if (_returnPackageSet.nodes.length > 0) {
               $j('#StartingCity >option:not([value=""])').remove();
               $j('#EndCity >option:not([value=""])').remove();
               $j('#StartingDate >option:not([value=""])').remove();
               $j('#Duration >option:not([value=""])').remove();
               
               
               for(var idx = 0; idx < packageLookup.nodes.length; idx++) {
                  var value = packageLookup.nodes[idx]; 
               
                   // remove
                   //console.log('wanting to add... ' + value.to);
                   // now do our checks
                   
                   if(0 == $j('#StartingCity option[value='+value.frm+']').length) {
                     //console.log('adding...');
                     $j('#StartingCity').append($j("<option></option>").val(value.frm).text(_tripsearch_from[value.frm]));
                   }             
                   
                   
                   
                   // need to also make sure we are not selecting the same
                   
                   
                   if((0 == $j('#EndCity option[value='+value.to+']').length)) {
                     //console.log('adding...');
                     $j('#EndCity').append($j("<option></option>").val(value.to).text(_tripsearch_to[value.to]));
                   }
                   
                  var deptArr = value.dept.split('|');
                  for (var x = 0; x <  deptArr.length; x++) {
                    var dept = deptArr[x];
                   
                      if(0 == $j('#StartingDate option[value="'+dept+'"]').length && dept != '') {
                        var month = dept.substring(0, 2);
                        var year = dept.substring(2);
                        
                        $j('#StartingDate').append($j("<option></option>").val(dept).text(SiteVars.modules.phrasePack.months_full[parseInt(month, 10) - 1] + ' ' + year));
                      }
                   
                  }
                  
                  
                   if(0 == $j('#Duration option[value="'+value.dur+'"]').length) {
                     //console.log('adding duration...');
                     
                     $j('#Duration').append($j("<option></option>").val(value.dur).text(_tripsearch_dur[value.dur]));
                   }             
                    
               }
               
               
             }
             //console.timeEnd('native');  
             
             // now sort
             
             var durOpts = $j('#Duration option');
             
             durOpts.sort(function(a,b) {
                if (b.value == '') return 1;
                if (a.value == '') return -1;
                if (a.text > b.text) return 1;
                else if (a.text < b.text) return -1;
                else return 0
             });
             
             
             $j("#Duration").empty().append( durOpts );                       
             
             
             // now reselect
             
             $j('#StartingCity option[value="' + from + '"]').attr('selected','selected');
             $j('#EndCity option[value="' + to + '"]').attr('selected','selected');
             $j('#StartingDate option[value="' + dep + '"]').attr('selected','selected');
             $j('#Duration option[value="' + dur + '"]').attr('selected','selected');
       
             
             
             /* if one or the other is selected then we need to make sure that the empty dropdown doesn't have dupes */
             var check_start = $j('#StartingCity option:selected').val();
             var check_end   = $j('#EndCity option:selected').val();
             
             
             
             if(check_start != '') { // then make sure it doesnt have same values as check_end
               // remove any items that are in check_end
               $j('#EndCity option[value="' + check_start + '"]').remove();
               // remove any other check_start items
               $j('#StartingCity option').each(function() {
                   if( $j(this).val() != '' && $j(this).val() != check_start) {
                       $j(this).remove();
                   }
               });
               
             } else if(check_end != '') { // then make sure it doesnt have same values as check_start
               // remove other option from check_start
               $j('#StartingCity option[value="' + check_end + '"]').remove();
               
               $j('#EndCity option').each(function() {
                   if( $j(this).val() != '' && $j(this).val() != check_end) {
                       $j(this).remove();
                   }
               });               
               
             }
             
             
             TripSearch.sortFields();
             
             $j('#trip-search select').selectmenu({transferClasses: true, width: 200});
             $j("#trip-search select").selectmenu("enable"); 
             
             /*
             console.log(to);
             console.log(from);
             console.log(dep);
             console.log(dur);
             console.log('======');
             //console.log('query: ' + query);
             console.log('old length: ' + packageLookup.nodes.length);
             console.log('new length: ' + _returnPackageSet.nodes.length);
             */
         });    
  },
  
  sortFields:function() {
    //$j('#StartingCity >option:not([value=""])')
    //$j('#EndCity >option:not([value=""])')
    
    //$j('#trip-search select').selectmenu({transferClasses: true, width: 200});
     
    var tempStartArray = new Array();
    var tempEndArray = new Array();
    var from = $j('#StartingCity option:selected').val();
    var to = $j('#EndCity option:selected').val();
    
    // need to reset
    
      for(var key in _tripsearch_from) {
         if (_tripsearch_from.hasOwnProperty(key) ){
           // $j('#StartingCity').append($j("<option></option>").val(key).text(_tripsearch_from[key]));
           var check = $j('#StartingCity option[value="' + key + '"]');
           
           if (check.length > 0) {
              tempStartArray.push(  $j("<option></option>").val(key).text(_tripsearch_from[key])  ); 
           }
         }
      }    
      $j('#StartingCity >option:not([value=""])').remove();
      for(var i = 0; i < tempStartArray.length; i++) {
        $j('#StartingCity').append(tempStartArray[i]);
      }
      tempStartArray = 0; // clean up mem
      
      // TODO SELECT THE SELECTED CITY
      
      
      for(var key in _tripsearch_to) {
         if (_tripsearch_to.hasOwnProperty(key) ){
           // $j('#StartingCity').append($j("<option></option>").val(key).text(_tripsearch_from[key]));
           var check = $j('#EndCity option[value="' + key + '"]');
           
           if (check.length > 0) {
              tempEndArray.push(  $j("<option></option>").val(key).text(_tripsearch_to[key])  ); 
           }
         }
      }     
      $j('#EndCity >option:not([value=""])').remove();
      for(var i = 0; i < tempEndArray.length; i++) {
        $j('#EndCity').append(tempEndArray[i]);
      }    
      tempEndArray = 0;
    
      
     $j('#StartingCity option[value="' + from + '"]').attr('selected','selected');
     $j('#EndCity option[value="' + to + '"]').attr('selected','selected');
    
    
  },
  resetFields:function() {
     $j('#StartingCity >option:not([value=""])').remove();
     $j('#EndCity >option:not([value=""])').remove();
     $j('#StartingDate >option:not([value=""])').remove();
     $j('#Duration >option:not([value=""])').remove();  
     
 
     // from
     for(var key in _tripsearch_from) {
       if (_tripsearch_from.hasOwnProperty(key) ){
          $j('#StartingCity').append($j("<option></option>").val(key).text(_tripsearch_from[key]));
       }
     }

     for(var key in _tripsearch_to) {
       
       if (_tripsearch_to.hasOwnProperty(key)){
          $j('#EndCity').append($j("<option></option>").val(key).text(_tripsearch_to[key]));
       }
     }     
     
     // duration
     for(var key in _tripsearch_dur) {
       if (_tripsearch_dur.hasOwnProperty(key)){
          $j('#Duration').append($j("<option></option>").val(key).text(_tripsearch_dur[key]));
       }
     }
 
     
     // dates
     // 2011
     for(var i = 3; i < 10; i++) {
       var month = (i + 1) < 10 ? '0' + (i + 1) : (i + 1);
       var year =  SiteVars.CMS_DATE_YEAR;
       $j('#StartingDate').append($j("<option></option>").val(month + ' ' + year).text(SiteVars.modules.phrasePack.months_full[i] + ' ' + year));
     }
     
     // 2012
     
     for(var i = 3; i < 10; i++) {
       var month = (i + 1) < 10 ? '0' + (i + 1) : (i + 1);
       var year =  parseInt(SiteVars.CMS_DATE_YEAR, 10) + 1;
       $j('#StartingDate').append($j("<option></option>").val(month + ' ' + year).text(SiteVars.modules.phrasePack.months_full[i] + ' ' + year));
     }     
     
     // duration
     
     
     $j('#trip-search select').selectmenu({transferClasses: true, width: 200});    
  }
};

$j(document).ready(function() {
    $j('#subscribe-email').focus(function() {
      if ($j('#subscribe-email').val() == 'name@email.com') {
        $j('#subscribe-email').val('');
      }      
    });
    
    $j('#subscribe-email').blur(function() {
      if ($j('#subscribe-email').val() == '') {
        $j('#subscribe-email').val('name@email.com');
      }         
    });
    

    Facebook.createWidget();
    SubscribeForm.init();
    if (SiteVars.this_url.indexOf('/booking/') < 0) {
      TripSearch.init();
    }
});

//{{{ (basic) caching ajax wrapper around jquery's ajax functions
var cajax = (function() {
  var methods = {},
      cache = {};
  
  //{{{ Get 
  methods.get = get;
  function get (url, data, success) {
    
    var key = url + data; // fixme: robust enough?
    
    
    
    if (cache[key] != undefined) {
      //debug('cache hit:', url, '[', data, ']');
      if (typeof success === 'function')
        success(cache[key]);
    } else {
      //debug('cache miss:', url, '[', data, ']');
      return jQuery.get(url, data, function(data) {
        cache[key] = data;
        if (typeof success === 'function')
          success(data);
      });
    }
  } //}}}
  
  function debug () {
    var args = Array.prototype.slice.call(arguments);
    console.log(args.join(' '));
  }
  
  return methods;
})();
//}}}



function equalHeightByRow(selector) {
    var currentTallest = 0;
    var currentRowStart = 0;
    var rowDivs = new Array();
    
    $j(selector).each(function(index) {
    
        if(currentRowStart != $j(this).position().top) {
    
            // we just came to a new row.  Set all the heights on the completed row
            for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
    
            // set the variables for the new row
            rowDivs.length = 0; // empty the array
            currentRowStart = $j(this).position().top;
            currentTallest = $j(this).height();
            rowDivs.push($j(this));
    
        } else {
    
            // another div on the current row.  Add it to the list and check if it's taller
            rowDivs.push($j(this));
            currentTallest = (currentTallest < $j(this).height()) ? ($j(this).height()) : (currentTallest);
    
        }
        // do the last row
        for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
    
    });
}

/* called from facebook app */
function equalFooterHeights() {
 // $j('.FooterContent .panel').equalHeight();
 // $j('#guest-photos .panel').height($j('#guest-photos .panel').height() + 24);
 // $j('#helpful-links .panel').height($j('#helpful-links .panel').height() + 24);
}

// use for booking engine
function loadBookingUI() {
  $j(".lightbox button, .lightbox .button").button();

  //Selectbox
  $j('.lightbox select').selectmenu({transferClasses: true, width: 200});
}
// use for regular site
function loadJqueryUI() { 
    // Datepicker
  $j('#datepicker').datepicker({
        showOn: "button",
        buttonImage: "template_images/rmv/layout/icon_calendar1.png"
  });

  // Button
  $j("#divButton, #linkButton, #search-controls li a, .button, #main-column form .submit").button();
  
  $j(".learn-more").button();

  $j("#tripSearchButton").button();

  $j(".trip-map a div span, .button.add").button({
    icons: {
        primary: 'ui-icon-circle-plus' 
  }});
  
    $j(".trip-map a div span, .button.remove").button({
    icons: {
        primary: 'ui-icon-circle-minus' 
  }});

  // Selectbox
  // See https://github.com/fnagel/jquery-ui/wiki/Selectmenu
  
  
  if ($j("#upload_file").length) {
    $j('#upload_file').fileinput();
  }

}


function showLoading() {
  $j(".loading").show();
}

function hideLoading() {
  $j(".loading").hide();
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

