jQuery.ajaxSetup({
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
  }
});

jQuery.fn.caption = function(text) {
  return $(this).each(function() {
    var img = $(this);
    var alt = text || img.attr('alt');
    
    if (alt && alt != '') {
      img.load(function() {
        img.wrap('<div></div>');
        var wrapper = img.parent();
        
        wrapper.width(img.width());
        wrapper.height(img.height());
        wrapper.css('position', 'relative');
        
        wrapper.addClass(img.attr('class'));
        img.removeAttr('class');
        
        var shading = $('<div />');
        shading.css({
          'position': 'absolute',
          'left': '0',
          'bottom': '0',
          'width': '100%',
          'background-color': '#000',
          'color': '#fff',
          'opacity': '0.7'
        });
        wrapper.append(shading);
        
        var caption = $('<p>' + alt + '</p>');
        caption.css({
          'padding': '10px',
          'font-size': '90%',
          'margin': '0'
        });
        shading.append(caption);
      });
    }
  });
};

jQuery.expr[':'].loaded = function(node) {
  if (!node.complete) return false;
  if (typeof node.naturalWidth != 'undefined' && node.naturalWidth == 0) return false;
  return true;
};

var Slideshow = function(list, options) {
	Slideshow.parent = list.parent('div');
	
  var self = this;
  
  this.options = options;
  this.list = list;
  
	var switcher = Slideshow.parent.find('.switch-slideshow');
	if (switcher.get(0)) { $('a', switcher).click(Slideshow.switchToVideo); }

  list.wrap('<div></div>');
  var wrapper = list.parent();
  
  wrapper.css('position', 'relative');
  wrapper.width(options.width);
  wrapper.height(options.height);
  
  var id = list.attr('id');
  var klass = list.attr('class')
  list.removeAttr('id');
  list.removeAttr('class');
  wrapper.attr('id', id);
  wrapper.attr('class', klass);
  
  list.find('li').css('position', 'absolute');
  
  var shading = $('<div class="shading" />');
  shading.css({
    'position': 'absolute',
    'left': '0',
    'bottom': '0',
    'width': '100%',
    'background-color': '#fff',
    'color': '#4c4c4c'
  });
  
  wrapper.append(shading);
  shading.append(this.createControls());
  
  this.captions = this.moveCaptions();
  shading.append(this.captions);
  this.captions.find('li:not(:first)').hide();
  
  this.interval = setInterval(function() { self.nextImage(); }, 5000);
};
Slideshow.text = {
  pause: 'Pause',
  play: 'Play'
};
Slideshow.prototype = {
  createControls: function() {
    var self = this;
    
    var controls = $('<div class="controls" />');
    controls.css({
      'float': 'right',
      'padding': '10px',
      'font-size': '70%',
      'text-align': 'right'
    });
    
    this.pauseButton = $('<a href="#" class="pause">' + Slideshow.text.pause + '</a>').appendTo(controls).css({
      'color': '#4c4c4c',
      'text-decoration': 'none',
      'margin-right': '0.8em'
    }).click(function() { self.pause(); return false; });
    
    this.playButton = $('<a href="#" class="play">' + Slideshow.text.play + '</a>').appendTo(controls).css({
      'color': '#4c4c4c',
      'text-decoration': 'none',
      'display': 'none',
      'margin-right': '0.8em'
    }).click(function() { self.play(); return false; });
    
    this.index = $('<ul class="index" />').css('display', 'inline').appendTo(controls);
    this.list.find('li').each(function(i) {
      $('<li><a href="#">' + (i+1) + '</a></li>').appendTo(self.index).css({
        'display': 'inline'
      }).find('a').css({
        'color': '#4c4c4c',
        'text-decoration': 'none',
        'margin': '0 0.3em'
      }).click(function() {
        self.pause();
        self.loadImage(self.list.find('li:nth-child(' + (i+1) + ')'));
        return false;
      });
    });
    this.index.find('li:first').addClass('current');
    
    return controls;
  },
  
  moveCaptions: function() {
    var captions = $('<ul class="captions" />');
    this.list.find('p').each(function(i) {
      var li = $('<li></li>').append($(this));
      captions.append(li);
    });
    return captions;
  },
  
  play: function() {
    var self = this;
    this.interval = setInterval(function() { self.nextImage(); }, 5000);
    this.playButton.hide();
    this.pauseButton.show();
  },
  
  pause: function() {
    clearInterval(this.interval);
    this.pauseButton.hide();
    this.playButton.show();
  },
  
  imageLoaded: function(item) {
    return item.find('img').is(':loaded');
  },
  
  loadImage: function(item) {
    var current = this.list.find('> li:visible');
    if (current != item) {
      var i = this.list.find('> li').index(item);
      
      this.index.find('li').removeClass('current');
      this.index.find('li:nth-child(' + (i+1) + ')').addClass('current');
      
      this.captions.find('li:visible').fadeOut('slow');
      this.captions.find('li:nth-child(' + (i+1) + ')').fadeIn('slow');
      
      current.fadeOut('slow');
      item.fadeIn('slow');
    }
  },
  
  nextImage: function() {
    var current = this.list.find('> li:visible');
    
    if (this.imageLoaded(current)) {
      var next = current.next();
      if (next.length == 0) next = this.list.find('li:first');
      
      if (this.imageLoaded(next)) {
        this.loadImage(next);
      }
    }
  }
};
Slideshow.switchToVideo = function() {
	Slideshow.parent.find('.slideshow > ul').hide();
	Slideshow.parent.find('.slideshow .controls').hide();
	Slideshow.parent.find('ul.switch-slideshow').hide();
	
	Slideshow.parent.find('#tour-video').show();
	swfobject.embedSWF("/assets/theme/player/gallery.swf", "tour-video",
                     "800", "350", "8.0.0", "/assets/theme/player/expressInstall.swf",
                     { videoURL: Slideshow.videoUrl, autoplay: true, locale: Slideshow.locale });
	
	return false;
};
Slideshow.switchToPhotos = function() {
	Slideshow.parent.find('.slideshow > ul').show();
	Slideshow.parent.find('.slideshow .controls').show();
	Slideshow.parent.find('ul.switch-slideshow').show();
	
	Slideshow.parent.find('#tour-video').empty().hide();
};

jQuery.fn.slideshow = function(options) {
  return $(this).each(function() {
    var list = $(this);
    var caption = list.find('img:first').attr('alt');
    
    new Slideshow(list, $.extend(options, { caption: caption }));
  });
};



var Player = function(div, options) {
  var self = this;
  
  this.images = div.find('#viewer-pane li');
  this.captions = div.find('#text-pane ul.text li')
  this.page = div.find('#pagination span');
  
  this.setupButtons(div);
  
  this.interval = setInterval(function() { self.nextImage(); }, 5000);
};
Player.prototype = {
  setupButtons: function(div) {
    var self = this;
    
    this.pauseButton = div.find('a.pause');
    this.playButton = div.find('a.play');
    this.nextButton = div.find('a.next');
    this.previousButton = div.find('a.previous');
    
    this.pauseButton.click(function() {
      self.pause();
      return false;
    });
    
    this.playButton.click(function() {
      self.play();
      return false;
    });
    
    this.nextButton.click(function() {
      self.pause();
      self.nextImage();
      return false;
    });
    
    this.previousButton.click(function() {
      self.pause();
      self.previousImage();
      return false;
    });
  },
  
  play: function() {
    var self = this;
    this.interval = setInterval(function() { self.nextImage(); }, 5000);
    this.playButton.hide();
    this.pauseButton.show();
  },
  
  pause: function() {
    clearInterval(this.interval);
    this.pauseButton.hide();
    this.playButton.show();
  },
  
  imageLoaded: function(item) {
    return item.find('img').is(':loaded');
  },
  
  loadImage: function(item) {
    var self = this;
    var current = this.images.filter(':visible');
    
    if (!this.fading && current != item) {
      var i = this.images.index(item);
      this.fading = true;
      
      this.page.text(i+1);
      
      this.captions.filter(':visible').fadeOut('slow');
      this.captions.filter('li:nth-child(' + (i+1) + ')').fadeIn('slow');
      
      current.fadeOut('slow');
      item.fadeIn('slow', function() { self.fading = false; });
    }
  },
  
  previousImage: function() {
    var current = this.images.filter(':visible');
    
    if (this.imageLoaded(current)) {
      var next = current.prev();
      if (next.length == 0) next = this.images.filter(':last');
      
      if (this.imageLoaded(next)) {
        this.loadImage(next);
      }
    }
  },
  
  nextImage: function() {
    var current = this.images.filter(':visible');
    
    if (this.imageLoaded(current)) {
      var next = current.next();
      if (next.length == 0) next = this.images.filter(':first');
      
      if (this.imageLoaded(next)) {
        this.loadImage(next);
      }
    }
  }
};

jQuery.fn.player = function(options) {
  return $(this).each(function() {
    new Player($(this), options);
  });
};


jQuery.fn.fadehover = function() {
  $(this).css({ 'opacity': '0.4' });
  
  return $(this).each(function() {
    $(this).hover(
      function() { $(this).css({ 'opacity': '1' }); },
      function() { $(this).css({ 'opacity': '0.4' }); }
    );
  });
};

jQuery.fn.selfLabel = function() {
  var text = $(this).attr('alt');
  
  function setDefault() {
    if ($(this).val() == '') {
      $(this).addClass('default');
      $(this).val(text);
    }
  }
  
  function removeDefault() {
    if ($(this).val() == text) {
      $(this).removeClass('default');
      $(this).val('');
    }
  }
  
  $(this).focus(removeDefault).blur(setDefault);
  
  $(this).addClass('default');
  $(this).val(text);
};


var WeddingCalendar = {
  init: function() {
    var base = WeddingCalendar.base = $('#wedding-calendar');
    WeddingCalendar.legend = $('.legend', base);
    var months = $('.month', base);
    
    $(months[0]).find('a.next').hide();
    $(months[1]).find('a.previous').hide();
    
    $('a.next', base).click(WeddingCalendar.nextMonth);
    $('a.previous', base).click(WeddingCalendar.previousMonth);
  },
  
  nextMonth: function() {
    $('.month:first', WeddingCalendar.base).remove();
    $('a.next', WeddingCalendar.base).hide();
    $('a.previous', WeddingCalendar.base).show();
    
    var month = $('<div class="month loading" />').insertBefore(WeddingCalendar.legend);
    
    $.get($(this).attr('href'), {}, function(data) {
      if (month.parent().length > 0) {
        month.replaceWith(data);
        month = $('.month:last', WeddingCalendar.base);
      
        $('a.previous', month).hide();
        $('a.previous', month).click(WeddingCalendar.previousMonth);
        $('a.next', month).click(WeddingCalendar.nextMonth);
      }
    }, 'html');
    
    return false;
  },
  
  previousMonth: function() {
    $('.month:last', WeddingCalendar.base).remove();
    $('a.previous', WeddingCalendar.base).hide();
    $('a.next', WeddingCalendar.base).show();
    
    var month = $('<div class="month loading" />').prependTo(WeddingCalendar.base);
    
    $.get($(this).attr('href'), {}, function(data) {
      if (month.parent().length > 0) {
        month.replaceWith(data);
        month = $('.month:first', WeddingCalendar.base);
      
        $('a.next', month).hide();
        $('a.next', month).click(WeddingCalendar.nextMonth);
        $('a.previous', month).click(WeddingCalendar.previousMonth);
      }
    }, 'html');
    
    return false;
  }
};


var WeddingPlanner = {
  fields: {},
  
  init: function() {
    WeddingPlanner.prepareCheckboxFields();
    WeddingPlanner.prepareQuantityFields();
    
    WeddingPlanner.field = $('<input type="text" />').appendTo('#wedding-planner .total').after('USD');
    WeddingPlanner.updateTotal();
    
    $('#wedding-planner input').change(WeddingPlanner.updateTotal);
  },
  
  getPrice: function(field) {
    return parseInt(field.text().replace(/,/, '').match(/\$(\d+)/)[1]);
  },
  
  preselect: function(code) {
    if (code == '') return;
    
    var field = $('#wedding-planner .' + code);
    field.addClass('preselected');
    $('label input', field).click();
  },
  
  prepareCheckboxFields: function() {
    $("#wedding-planner .checkbox:contains($)").each(function() {
      var price = WeddingPlanner.getPrice($(this));
      var field = $(this).find('input')[0];
      
      WeddingPlanner.fields[field.id] = function() {
        return $(field).is(':checked') ? price : 0;
      };
    });
  },
  
  prepareQuantityFields: function() {
    $("#wedding-planner .quantity").each(function() {
      var price = WeddingPlanner.getPrice($(this));
      var checkbox = $(this).find('label input')[0];
      var field = $(this).find('> input')[0];
      
      var func, m, toggle;
      
      if (m = this.className.match(/add-(\d+)/)) {
        func = function() {
          if (checkbox && !$(checkbox).is(':checked')) return 0;
          
          var val = parseInt($(field).val());
          var count = parseInt(m[1]);
          
          return isNaN(val) ? price : (price + count * val);
        };
      } else {
        func = function() {
          if (checkbox && !$(checkbox).is(':checked')) return 0;
          
          var val = parseInt($(field).val());
          return isNaN(val) ? 0 : (price * val);
        };
      }
      
      WeddingPlanner.fields[field.id] = func;
    });
  },
  
  updateTotal: function() {
    WeddingPlanner.field.val('$' + WeddingPlanner.calculateTotal());
  },
  
  calculateTotal: function() {
    var func;
    var result = 0;
    
    $('#wedding-planner input').each(function() {
      if (func = WeddingPlanner.fields[this.id]) {
        result += func();
      }
    });
    
    return result;
  },
  
  createTooltips: function(tooltips) {
    function createTooltip(field, content) {
      var link = $('<a href="#" class="info"><img src="/assets/theme/images/icons/information.png" alt="Information" /></a>');
      $('#' + field).parent().append(link);
      
      var tooltip = $('<div class="tooltip">' + content + '</div>').appendTo('body');
      tooltip.css('position', 'absolute');
      tooltip.hide();
      
      link.click(function() { return false; });
      link.mousemove(function(e) {
        tooltip.show();
        tooltip.css({ left: e.pageX + 10, top: e.pageY + 10 });
      });
      link.mouseout(function() {
        tooltip.hide();
      });
    }
    
    for (var field in tooltips) { createTooltip(field, tooltips[field]); }
  }
};

var Vallarta = {
  enterName: 'Please enter your name.',
  enterEmail: 'Please enter your email.',
  enterComment: 'Please enter a comment.',
  commentSubmitted: 'Your comment has been submitted and is awaiting moderation.'
};


$(function() {
  $('#quick-links .search input.query').selfLabel();
  
  $('#navigation > li').hover(function() {
    $(this).find('> a').andSelf().addClass('hover');
  }, function() {
    $(this).find('> a').andSelf().removeClass('hover');
  });
  
  $('img.caption').caption();
  
  $('ul.slideshow').slideshow({ width: 800, height: 383 });
  $('ul#home-slideshow').slideshow({ width: 948, height: 448 });
  $('#home-slideshow img').click(function() {
    var url = $('#home-slideshow ul.captions li:visible a:first').attr('href');
    document.location = url;
  });
  
  $('img.fade-hover').fadehover();
  
  $('#photo-gallery #player').player();
  
  $('#corporate-responsibility .right li, #corporate-responsibility .post-content').each(function() {
    $('p > img', this).prependTo(this);
    $('p:empty').remove();
  });
  
  function validateField(id, error) {
    function trim(str) {
      return str.replace(/^\s+|\s+$/g, '');
    }

    function blank(str) {
      return trim(str) == '';
    }
    
    var f = $(id);
    f.next('p').remove();
    
    if (blank(f.val())) {
      f.after('<p class="error">' + error + '</p>');
      return false;
    } else {
      return true;
    }
  }
  
  $('#testimonials #add form').submit(function() {
    var valid = validateField('#comment_name', Vallarta.enterName);
    valid = validateField('#comment_email', Vallarta.enterEmail) && valid;
    valid = validateField('#comment_comment', Vallarta.enterComment) && valid;
    
    if (valid) {
      var target = $(this).attr('action');
      var data = $(this).serialize();
      
      var container = $(this).parent();
      container.empty();
      container.addClass('submitting');
      
      $.post(target, data, function() {
        container.removeClass('submitting').addClass('submitted');
        container.html('<p>' + Vallarta.commentSubmitted + '</p>')
      });
    }
    
    return false;
  });
  
  $('#blog form').submit(function() {
    var valid = validateField('#comment_name', Vallarta.enterName);
    valid = validateField('#comment_email', Vallarta.enterEmail) && valid;
    valid = validateField('#comment_comment', Vallarta.enterComment) && valid;
    
    if (valid) {
      var target = $(this).attr('action');
      var data = $(this).serialize();
      
      var container = $(this);
      container.empty();
      container.addClass('submitting');
      
      $.post(target, data, function() {
        container.removeClass('submitting').addClass('submitted');
        container.html('<p>' + Vallarta.commentSubmitted + '</p>')
      });
    }
    
    return false;
  });
  
  $('.expandable h3 a').click(function() {
    $(this).parents('.expandable').addClass('expanded').find('ul').show();
    
    return false;
  });
  
  if (jQuery.fn.fancyZoom) {
    $('a#share-link').fancyZoom({
      width: 420,
      onShow: function() {
        $('#zoom_content form').submit(function() {
          var valid = validateField('#zoom_content #share_sender_name', 'Please enter your name.');
          valid = validateField('#zoom_content #share_sender_email', 'Please enter your email.') && valid;
          valid = validateField('#zoom_content #share_recipient_email', "Please enter a recipient's email.") && valid;
        
          if (valid) {
            var target = $(this).attr('action');
            var data = $(this).serialize();
          
            var container = $(this);
            container.empty();
            container.addClass('submitting');

            $.ajax({
              type: 'POST',
              url: target,
              data: data,
              complete: function() {
                container.removeClass('submitting').addClass('submitted');
              },
              success: function() {
                container.html('<p>Email has been sent.</p>');
              },
              error: function() {
                container.html('<p>Email sending failed. Please check the email address and try again.</p>')
              }
            });
          }
        
          return false;
        });
      }
    });
  }
  
  $('.date-of-birth input.date').datepicker({
    showOn: 'both',
    buttonImage: '/assets/theme/images/icons/calendar.png',
    buttonImageOnly: true,
    duration: '',
    yearRange: '-100:0',
    maxDate: 0,
    hideIfNoPrevNext: true
  });
  
  $('input.date').datepicker({
    showOn: 'both',
    buttonImage: '/assets/theme/images/icons/calendar.png',
    buttonImageOnly: true,
    duration: '',
    minDate: '-2m',
    maxDate: '+5y',
    hideIfNoPrevNext: true
  });


$('a#video1').fancyZoom({width: 420});
$('a#video2').fancyZoom({width: 420});
$('a#video3').fancyZoom({width: 420});
$('a#video4').fancyZoom({width: 420});
$('a#video5').fancyZoom({width: 420});
$('a#share-this').fancyZoom({width: 420});
$('a#phonenumber').fancyZoom({width: 420});
$('a#videoflash').fancyZoom({width: 420});
$('a#video').fancyZoom({width: 420});



$("#res").validate();

});

