/* Author: Matthieu Aussaguel
 Date: 20/06/2011
 Flint Interactive
 */

var HoverNav = {
  animateOpts: {duration: 250, easing: 'easeOutExpo', queue: true},
  init: function() {
    this.$navWrapper = $('.mainNavInner');
    this.$secondaryNav = $('#secondaryNav');
    this.$primaryNav = $('#primaryNav');
    if (!$('ul.active li', this.$secondaryNav).length) {
      this.$secondaryNav.css({top: -27});
    }
    this.enableControls();
  },
  enableControls : function() {
    var that = this;
    $('a', that.$primaryNav).mouseenter(function() {
      that.showSubNav($('.primaryNav a', that.$primaryNav).index($(this)));
    });
    if (!$('ul.active li', this.$secondaryNav).length) {
      that.$primaryNav.mouseenter(function() {
        that.openNav();
      });
      that.$navWrapper.mouseleave(function() {
        that.closeNav();
        $('ul', that.$secondaryNav).hide();
      });
    } else {
      that.$navWrapper.mouseleave(function() {
        if (that.$secondaryNav.hasClass('closed')) that.openNav();
        $('ul', that.$secondaryNav).hide();
        $('ul.active', that.$secondaryNav).show();
      });
    }
  },
  showSubNav: function(index) {
    var that = this;
    $('ul', that.$secondaryNav).hide();
    if ($('ul:eq(' + index + ') li', that.$secondaryNav).length == 0) {
      that.closeNav();
    } else {
      that.openNav();
      $('ul:eq(' + index + ')', that.$secondaryNav).show();
    }
  },
  closeNav : function() {
    var that = this;
    that.$secondaryNav.stop(true, true).animate({top: -27}, that.animateOpts).addClass('closed');
  },
  openNav : function() {
    var that = this;
    that.$secondaryNav.stop(true, true).animate({top: 0}, that.animateOpts).removeClass('closed');
  }

};

$(function() {
	if($('.cat-expand').length) {
		$('.cat-expand').click(function(e) {
			e.preventDefault();
			var $parent = $(this).parent();
			$('.expand', $parent).click();
		});
	}

  if ($('.accordianContent').length) {

    var $bottom = $('.accordianContent .bottom'),
        $topLink = $('.accordianContent .top a');

    $bottom.accordion({autoHeight: false, collapsible: true});

    // toggle the accordion content
    $topLink.click(function() {

      var $this = $(this),
          state = ($this.hasClass('open')) ? 'CLOSE TO VIEW IMAGES' : 'OPEN TO VIEW CONTENT';

      $this.toggleClass('close')
          .toggleClass('open')
          .text(state);

      $bottom.slideToggle('fast');

      return false;
    });

    //  init the background slider
    backgroundImage.initImageSet();
  }

  if ($('#basic-template').length) backgroundImage.initImageSet();

  if ($('#secondaryNav.hover-nav ul').length) HoverNav.init();

  if ($('.event-side-ads').length) EventAds.init();

  if ($('#event-type').length) EnquiryTypeSelect.init();

  if ($('#event-feature-images').length) EventLandingHero.init();

  if ($('.simple-gallery').length) {
    var $simpleGallery = $('.simple-gallery');
    $simpleGalleryImages = $simpleGallery.find('.slides_container img'),
        $simpleGalleryWrapper = $simpleGallery.parent(),
        dataSymbols = ['date', 'title', 'introduction', 'link'],
        data = null;

    $simpleGallery.slides({
      play: 5000,
      fadeEasing: "easeOutQuad",
      generateNextPrev: true,
      next: 'eventNext',
      prev: 'eventPrev',
      animationComplete: function(current) {
        data = $simpleGalleryImages.eq(current - 1).data();
        for (var i = 0, l = dataSymbols.length; i < l; i++) {
          if (dataSymbols[i] == 'link') {
            $simpleGalleryWrapper.find('.' + dataSymbols[i]).attr('href', data[dataSymbols[i]]);
          } else {
            $simpleGalleryWrapper.find('.' + dataSymbols[i]).html(data[dataSymbols[i]]);
          }
        }
      }
    });
  }


  // handle the page blog template
  if ($('body.blog').length) Blog.init();

  // Show the fancybox on click
  $("a.moreInfo, a.popup-register-link").fancybox();


  $("a.galleryFancy").fancybox();
  // automatically open fancy box
  if($('a.initial-load-info-link').length) {
      $('a.initial-load-info-link').click();
  }

// Handle the forms including validation
  if ($('form').length) {

    // Enquiry form
    if ($('#enquiryForm').length) {
      var $form = $('#enquiryForm'),
          $hearAboutSelect   = $form.find('#hear-about'),
          $hearAboutOther   = $form.find('#hear-about-other'),
          $hearAboutReferral   = $form.find('#hear-about-referral');

          $hearAboutSelect.change(function() {
            var value = $(this).val().trim().toLowerCase();
            console.log(value)
            if (value === 'referral' ) {
                if ($hearAboutOther.length && $hearAboutOther.is(':visible')) $hearAboutOther.hide();
                if ($hearAboutReferral.length) $hearAboutReferral.show();
            } else {
              if (value === 'other') {
                if ($hearAboutReferral.length && $hearAboutReferral.is(':visible')) $hearAboutReferral.hide();
                if ($hearAboutOther.length) $hearAboutOther.show();
              } else {
                if ($hearAboutOther.length && $hearAboutOther.is(':visible')) $hearAboutOther.hide();
                if ($hearAboutReferral.length && $hearAboutReferral.is(':visible')) $hearAboutReferral.hide();
              }
            }
          });
    }

    
    if ($('#entry-page').length) {

      // Show fancybx
      $("a#leaveComment, a#leaveCommentText").fancybox({'titleShow' : false});

      // For comment form to appear on load after checkking the hash tag in the url
      if (window.location.hash === '#comment') {
        $("a#leaveComment").click();
        window.location.hash = '';
      }

      // Comment form submit
      $('#commentForm').live('submit', function() {
        var $form = $(this),
            $wrapper = $form.parent();

        var hideCommentBox = function() {
          $.fancybox.close();

          setTimeout(function() {
            $wrapper.find('h2').remove();

            $form.css({'visibility':'visible'})
                .find(':input')
                .not(':button, :submit, :reset, :hidden')
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');
          }, 2000);
        };

        $.ajax({
          url: "index.php?do=restCommentCreate&" + $form.serialize(),
          success: function(data, status) {
            $form.css({'visibility':'hidden'});
            if (status === 'success') {
              var message = 'Your comment has been submitted for approval, this may take up to 48 hours.';
              $('<h2 />', {'id': 'successful-message'}).css('opacity', 0)
                  .text(message)
                  .insertBefore($form)
                  .animate({'opacity': 1}, 400, function() {
                    // Hide the comment modal window after 2 seconds
                    setTimeout(hideCommentBox, 2000);
                  });
            } else {
              var message = 'An error has occurred, please try again';
              $('<h2 />', {'id': 'error-message'}).css('opacity', 0)
                  .text(message)
                  .insertBefore($form)
                  .animate({'opacity': 1}, 400, function() {
                    // Hide the comment modal window after 2 seconds
                    setTimeout(hideCommentBox, 2000);
                  });
            }
          }
        });
        return false;
      });
    }


    // Only used on blog and gallery sections
    if ($('form.autosubmit').length) {
      var $form = $('form.autosubmit');
      if ($form.find('.subcategoryItem').length) {
        var $categoryInputs = $form.find('ul.categoryItem > li > .expander > input'),
            $subcategoryInputs = $form.find('ul.subcategoryItem input'),
            $expandLinks = $form.find('.expand');


        var showSubcategoryUl = function($u, animate) {
          // Show the sub categories
          if ($u.is('visible')) return;
          if (typeof animate !== 'undefined' && animate === true) {
            $u.stop(true, true)
                .slideDown();
          } else {
            $u.show();
          }
          // Replace the link text + by a -
          $u.siblings('.expand')
              .removeClass('close')
              .addClass('open')
              .text('-')
              .attr('title', 'Less');
        };

        var hideSubcategoryUl = function($u, animate) {
          if ($u.is(':hidden')) return;

          // Show the sub categories
          if (typeof animate !== 'undefined' && animate === true) {
            $u.stop(true, true)
                .slideUp();
          } else {
            $u.hide();
          }
          // Replace the link text + by a -
          $u.siblings('.expand')
              .removeClass('open')
              .addClass('close')
              .text('+')
              .attr('title', 'More');
        };

        // Handle click category and on load
        if ($expandLinks.length) {
          // show subcategories on load if input checked
          $expandLinks.each(function() {
            var $categoryUl = $(this).siblings('div.expander');
            if ($categoryUl.find('input:checked').length)  showSubcategoryUl($categoryUl);
          });

          // toggle subcategories on click on expand link
          $expandLinks.live('click', function() {
            var $expandLink = $(this),
                $subcategoryUl = $expandLink.siblings('div.expander');

            if ($expandLink.hasClass('close')) {
              showSubcategoryUl($subcategoryUl, true);
            }
            else {
              hideSubcategoryUl($subcategoryUl, true);
            }
            return false;
          });
        }


        $categoryInputs.change(function() {
          $categoryInputs.filter('.checked')
              .not(':checked')
              .removeClass('checked')
              .parent()
              .find('.subcategoryItem input')
              .removeAttr('checked');

          // update the subcategory check boxes
          $categoryInputs.filter(':checked')
              .not('.checked')
              .addClass('checked')
              .parent()
              .find('.subcategoryItem input')
              .attr('checked', 'checked');
        });
        $subcategoryInputs.change(function() {
          // update the category check boxes
          $subcategoryInputs.not(':checked')
              .parents('.subcategoryItem')
              .siblings('input.checked')
              .removeAttr('checked')
              .removeClass('checked');

        });
      }
      $('form.autosubmit').change(function() {
        // Submit the form
        $form.submit();
      });
    }


    $('form').each(function() {
      if (!$('form').hasClass('noValidation')) {
        var form = this,
            $form = $(form),
            $errorContainer = $('.errorContainer', form);

        $form.validate({
          confirm_email: {
            equalTo: "#email"
          },
          invalidHandler:function() {
            $form.find('label.errorLabel')
                .removeClass('errorLabel');
          },
          errorContainer: $errorContainer,
          errorPlacement: function(error, element) {
            element.parent()
                .find('label')
                .addClass('errorLabel');
          }
        });
      }
    });


    // Validate the forms
    $('form').live('submit', function() {
      var submittedForm = this,
          $submittedForm = $(submittedForm);

      if ($submittedForm.hasClass('registerForm')) {
        var formDataString = $submittedForm.serialize(),
            formActionUrl = $submittedForm.attr('action'),
            errors = '';


        // Posting the registration form via AJAX
        $.ajax({
          type: "POST",
          url: formActionUrl,
          data: formDataString,
          success: function(data) {

            if ($('response', data).attr('status') == 'ok') {
              // show success message and hide fancybox on success
              $submittedForm.parent().animate({opacity: 0}, 200, function() {
                $('<h3 />', {'id': 'successful-message'}).css('opacity', 0)
                    .text('Thank you for registering, a representative from our team will be in contact with you shortly.')
                    .insertBefore($(this))
                    .animate({'opacity': 1}, 400);
              });
              setTimeout($.fancybox.close, 3500);
            } else {
              // show error messages
              $('response', data).find('error').each(function() {
                errors += '<li>' + $(this).attr('message') + '</li>';
              });
              $submittedForm.find('.errors').html(errors);
            }
          }
        });
        return false;
      }
    });
  }
})
    ;

var backgroundImage = {
  timeOut: null,
  initImageSet: function() {
    var set = this.getImageTabData(0);

    this.showImageSet(set);

    $(window).resize(this.updateImageSizes);

    if ($('#basic-template').length) {
      // Basic Template
      set = this.getImageData();
      this.showImageSet(set);
    } else {
      // Initialise the new image set on click
      // Basic Accordion Region
      $('h2 a').click(function() {
        var $h2 = $(this).parent();

        if (!$h2.hasClass('ui-state-active')) {
          set = backgroundImage.getImageTabData($h2.index() / 2);
          backgroundImage.showImageSet(set);
        }
      });
    }

  },

  getImageData: function() {
    var data = [],
        $images = $('#background-images').children('details');


    if (typeof $images !== 'undefined') {
      // Looping through each image
      $images.each(function() {
        data.push($(this).data());
      });
    }
    return data;
  },

  getImageTabData: function(index) {
    var data = [],
        $accordionBlocks = $('div.accordianContentBlock'),
        $images = $accordionBlocks.eq(index)
            .find('span.tab-background-images')
            .children('details');


    if (typeof $images !== 'undefined') {
      // Looping through each image
      $images.each(function() {
        data.push($(this).data());
      });
    }
    return data;
  },

  showImageSet: function(set) {
    var $ul = $('ul#bgImages'),
        footerHeight = 62;

    // Remove the current list if it exists
    if ($ul.length) $ul.remove();

    // Create the new list if background images are set
    if (set.length) {

      // Create the list
      var ul = $('<ul/>', {id: 'bgImages'});

      // Create the list items
      $.each(set, function(i, image) {
        $('<li />').append($('<img/>', {src     :   image.imageSource,
          width   :   Math.ceil(image.imageWidth),
          height  :   Math.ceil(image.imageHeight - footerHeight)}))
            .appendTo(ul)
      });

      // Show the images
      ul.prependTo($('#contentWrapper'));
      backgroundImage.updateImageSizes();

      if (set.length > 0) backgroundImage.initAnimation();
    }
  },

  //update the images sizes on window resize
  updateImageSizes: function() {

    var contentWidth = $(window).width(), // get content width
        contentHeight = $('.page').outerHeight() - 174 - 62 - 38, //  get the content height
        contentRatio = contentWidth / contentHeight,
        ratio;


    // Loop through every list item
    $('ul#bgImages li').each(function() {

      // get the image ration
      var $image = $(this).children('img:first'),
          height = $image.height(),
          width = $image.width(),
          imageRatio = width / height;

      // calculate the ratio
      if (contentRatio > imageRatio) {
        ratio = contentWidth / width;
        $image.width(contentWidth).height(height * ratio);
      } else {
        ratio = contentHeight / height;
        $image.width(width * ratio).height(contentHeight);
      }
    });
  },

  initAnimation: function() {
    var $ul = $('ul#bgImages')
    nlis = $ul.find('li').length;

    if (nlis === 1) {
      $ul.find('li')
          .stop(true, true)
          .first()
          .css('opacity', 0)
          .show()
          .animate({'opacity':1}, 1500, 'easeInOutQuad');
    } else {

      if (typeof this.timeOut !== 'undefined') clearTimeout(this.timeOut);

      if ($ul.length) {
        (function() {
          var $current = $ul.find('li:visible');
          index = 0;

          if ($current.length) {
            // handle the animation
            $current.stop(true, true).animate({'opacity': 0}, 1500, 'easeInOutQuad', function() {
              $(this).hide()
            });
            index = $current.index() + 1;

          }

          // if the current one is the last one
          if (nlis === index) index = 0;


          $ul.find('li')
              .eq(index)
              .css('opacity', 0)
              .show()
              .animate({'opacity':1}, 1500, 'easeInOutQuad');


          backgroundImage.timeOut = setTimeout(arguments.callee, 6000)
        }())
      }
    }
  }
};

var Blog = {
  init: function() {
    if ($('.galleryImages').length) this.entry.galleryInit();

    // Show the print window on load after checkink the hash in the url
    if (window.location.hash === '#printDocument') {
      window.print();
      window.location.hash = '';
    }

    $('a#print, a#printText').live('click', function() {
      window.print();
      return false;
    });

  },
  entry: {
    galleryInit: function() {
      var $galleryImages = $('.galleryImages'),
          play = $('body#entries-page').length ? 0 : 5000;


      // Initialise the slider
      $galleryImages.each(function() {
        var $gallery = $(this);

        $gallery.slides({
          generateNextPrev: true,
          effect: 'slide',
          play: play,
          animationComplete: function(current) {
            // Update the counter with the current position
            if (parseInt(current, 10) < 10) current = '0' + current;
            $gallery.find('.galleryImagesCounter')
                .children('span')
                .text(current);
          }
        });
      })
    }
  }
};

//var Event = {
//  init: function() {
//    $('#showAll').live('click', function() {
//      $(this).hide();
//      $('#events-set-show-all').fadeIn();
//      return false;
//    });
//  }
//};

var EventAds = {
  init: function() {
    this.showTime = 6000;
    this.firstTime = true;
    $('.event-side-ads a').css({zIndex: 1, opacity: 0});
    $('.event-side-ads').css({visibility: 'visible'}).each(function(i) {
      EventAds.initAdDisplay($(this));
    });
  },
  initAdDisplay : function(obj) {
    that = this;
    $('a:eq(0)', obj).addClass('selected').css({zIndex:2}).animate({opacity: 1}, {
      duration: 750,
      easing: 'easeInOutQuad',
      queue: false,
      complete: function() {
	if(that.firstTime === true) {
	    that.firstTime = false;
	    setTimeout(function() {
	      that.rotate(obj);
	    }, that.showTime+2000)
	} else {
	    setTimeout(function() {
	      that.rotate(obj);
	    }, that.showTime)
	}
	
      }
    });

  },
  rotate : function(obj) {
    $('a.selected', obj).stop(true, true);
    totalAds = $('a', obj).length;
    this.$selectedAd = $('a.selected', obj);
    if ($('a', obj).index(this.$selectedAd) === totalAds - 1) {
      this.$newAd = $('a:eq(0)', obj);
    } else {
      newIndex = $('a', obj).index(this.$selectedAd) + 1;
      this.$newAd = $('a:eq(' + newIndex + ')', obj);
    }
    this.$selectedAd.css({zIndex : 2}).removeClass('selected');
    this.$newAd.css({zIndex : 10}).addClass('selected');
    ;
    this.$newAd.animate({opacity: 1}, {
      duration: 750,
      easing: 'easeInOutQuad',
      queue: false,
      complete: function() {
        $('a', obj).css({zIndex : 1, opacity: 0});
        $(this).css({zIndex : 2, opacity: 1});
        setTimeout(function() {
          that.rotate(obj);
        }, that.showTime);
      }
    });
  }
}


String.prototype.capitalizeFirstLetter = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

var EnquiryTypeSelect = {
  init : function () {
    this.$eventTypeSelect = $('#event-type');
    this.$eventStyleSelect = $('#event-style');
    this.defaultOpts = new Array();
    this.extraOpts = new Array();
    /*this.extraOpts = {
     'Celebration' : ['Birthday','Christening','Christmas Party','Debutant Ball','Graduation','University Ball','Other'],
     'Corporate' : ['Breakfast', 'Cooking Class','Cocktail Party','Conference','Dinner','Exhibition','Lunch','Other'],
     'Weddings' : ['Cocktail','Dinner - 3 course','Dinner - 4 course','Indian Catering','Kitchen Tea','Kosher Catering','Lunch','Off-site Catering','Wedding Ceremony']
     } */
    this.celebrationOpts = ['Birthday','Christening','Christmas Party','Debutant Ball','Graduation','University Ball','Other'];
    this.corporateOpts = ['Breakfast', 'Cooking Class','Cocktail Party','Conference','Dinner','Exhibition','Lunch','Other'];
    this.weddingOpts = ['Cocktail','Dinner - 3 course','Dinner - 4 course','Indian Catering','Kitchen Tea','Kosher Catering','Lunch','Off-site Catering','Wedding Ceremony'];
    $('option', this.$eventStyleSelect).each(function(i) {
      EnquiryTypeSelect.defaultOpts.push($(this).attr('value'));
    });
    this.createOpts();
    this.$eventTypeSelect.change(function(e) {
      EnquiryTypeSelect.updateOptions(document.getElementById($(this).attr('id')).selectedIndex);
    });
    if(Number(document.getElementById(this.$eventTypeSelect.attr('id')).selectedIndex) != 0) {
	EnquiryTypeSelect.updateOptions(Number(document.getElementById(this.$eventTypeSelect.attr('id')).selectedIndex));
    }
  },
  createOpts : function() {
    var that = this;
    $('option', this.$eventTypeSelect).each(function(i) {
      switch ($(this).text()) {
        case 'Celebrations + Parties' :
          that.extraOpts[i] = that.celebrationOpts;
          break;
        case 'Corporate' :
          that.extraOpts[i] = that.corporateOpts;
          break;
        case 'Weddings' :
          that.extraOpts[i] = that.weddingOpts;
          break;
        default :
          break;
      }
    });
  },
  updateOptions : function (index) {
    var that = this;
    that.$eventStyleSelect.html('');
    if (typeof that.extraOpts[index] !== 'undefined') {
      $('<option/>', {
        value : '',
        html : 'Please select'
      }).appendTo(that.$eventStyleSelect);
      $(that.extraOpts[index]).each(function(i) {
        $('<option/>', {
          value : that.extraOpts[index][i],
          html : that.extraOpts[index][i]
        }).appendTo(that.$eventStyleSelect);
      });
    } else {
      $(that.defaultOpts).each(function(i) {
        if (that.defaultOpts[i] === '') {
          $('<option/>', {
            value : '',
            html : 'Please select'
          }).appendTo(that.$eventStyleSelect);
        } else {
          $('<option/>', {
            value : that.defaultOpts[i],
            html : that.defaultOpts[i]
          }).appendTo(that.$eventStyleSelect);
        }
      });

    }
  }
}

EventLandingHero = {
    rotateWait : 6000,
    init : function() {
	this.$container = $('#event-feature-images');
	$('span', this.$container).css({zIndex : 1, opacity: 0, visibility: 'visible'});
	setTimeout(function() {
	    EventLandingHero.showImage();
	}, 500);
    },
    showImage : function(index) {
	that = this;
	if(typeof index === 'undefined') {
	    $('span:eq(0)', that.$container).css({zIndex : 10}).animate({opacity: 1} , {
		duration : 350,
		queue : false,
		complete : function () {
		    $(this).css({zIndex: 2}).addClass('selected');
		    $('a', that.$container).attr('href', $(this).attr('data-link'));
		    if($('span', that.$container).length > 1) {
			setTimeout(function() {
			    that.showImage(1);
			}, that.rotateWait);
		    }
		}
	    });
	} else {
	    $selectedImage = $('span.selected', that.$container);
	    $selectedImage.removeClass('selected').stop(true, true);
	    $newImage = $('span:eq(' + index + ')', that.$container);
	    if(index >= ($('span', that.$container).length-1)) {
		newIndex = 0;
	    } else {
		newIndex = index+1;
	    }
	    $newImage.css({zIndex : 10, opacity: 0}).animate({opacity: 1} , {
		duration : 350,
		queue : false,
		complete : function () {
		    $('span', that.$container).css({zIndex : 1});
		    $('a', that.$container).attr('href', $(this).attr('data-link'));
		    $(this).css({zIndex: 2}).addClass('selected');
		    setTimeout(function() {
			that.showImage(newIndex);
		    }, that.rotateWait);
		}
	    });
	}
    }
};


// Image Utils
var ImageUtils = {
// Result optimal size of an image
  getFullScreenImageSize: function(imageSize, containerSize, crop) {
    var d = {}; // final dimensions
    if (typeof crop === 'undefined' || crop === false) {
      var wRatio = containerSize.width / imageSize.width,
          hRatio = containerSize.height / imageSize.height;

      // Default dimensions
      d['width'] = Math.floor(wRatio * imageSize.width);
      d['height'] = Math.floor(wRatio * imageSize.height);

      // if too big
      if ((d['width'] > containerSize.width) || (d['height'] > containerSize.height)) {
        d['width'] = Math.floor(hRatio * imageSize.width);
        d['height'] = Math.floor(hRatio * imageSize.height);
      }

    } else {
      var contentRatio = containerSize.width / containerSize.height,
          mRatio = imageSize.width / imageSize.height;

      // calculate the ratio
      if (contentRatio > mRatio) {
        d['width'] = containerSize.width;
        d['height'] = Math.floor(imageSize.height * (containerSize.width / imageSize.width));
      } else {
        d['width'] = Math.floor(imageSize.width * (containerSize.height / imageSize.height));
        d['height'] = containerSize.height;
      }

    }
    return d;
  }

};
