/* Author: Mathtieu Aussaguel
 July 6th, 2011
 */


$(function() {
  if (window.FLINT_SCRIPT_DONE === true) {
      return;
  }

  // Homepage
  if ($('#homepage').length) Homepage.init();
  if ($('#campaign-holder').length) Campaign.init();
  if ($('.main-holder-bg-resize').length) MainHolderBgResize.init();

  // LookBook page
  if ($('#look-book').length) LookBook.init();
  if ($('#nav .drop-down-nav').length) DropDownNav.init();
  
  //Competition Form
  if ($('#competition-form').length) Competition.init();
  if ($('form #country').length && $('form .country-other').length) utils.countrySelector.init();
  if ($('a.popup-iframe-page').length) {utils.decjubaOverlay.init();}

  if($('span.header-cart-count').length) {Cart.init();}

  window.FLINT_SCRIPT_DONE = true;
});

// Homepage Functions
var Homepage = {
  init: function() {
    // Background image element dom element
    var $bgImage = $('img.bg-body:first');

    // Image Resizer
    if ($bgImage.length) bgImageResize = new ElementResize($bgImage, $('.page'), true);

    // Show Image
    $bgImage.css('opacity', 0)
        .show()
        .animate({'opacity':1}, {
	    duration: 1000,
	    easing: 'easeInOutQuad',
	    complete: function() {
		if($('#home-image-blocks').length) {
		   $('#home-image-blocks article').css({opacity: 0});
		   $('#home-image-blocks').css({display: 'block'});
		   $('#home-image-blocks article').each(function(i)  {
		       setTimeout(function() {
			   $('#home-image-blocks article:eq('+i+')').animate({opacity:1}, 1000, 'easeInOutQuad');
		       }, i*250);
		   });
		}
	    }
	});
  }
};

var Cart = {
    init: function() {
        this.$headerCartCount = $('span.header-cart-count');
        this.$headerCartValue = $('span.header-cart-value');
        if (this.$headerCartCount.length > 0) {
            var cartCount = parseInt(utils.readCookie('totalCartProducts'));
            if (cartCount > 0) {
                this.$headerCartCount.html(cartCount);
                miniCart.init();
            } else {
                
            }
        }
        if (this.$headerCartValue.length > 0) {
            var cartValue = utils.readCookie('totalCartValue');
            if (Number(cartValue) > 0) {
                this.$headerCartValue.html('AUD $'+cartValue);
            }
        }
    }
}

var miniCart = {
    init: function() {
        //Store references to all the relevant elements
        this.$link = $('#minicart');
        this.$wrapper = $('#minicart-tooltip');
        this.$title = $('#minicart-tooltip-title');
        this.$spinner = $('#minicart-tooltip-loading');
        this.$content = $('#minicart-tooltip-content');

        //Declare template
        $.tmpload('minicart', 'templates/minicart.tmpl.html');

        this._handleEvents();
    },
    _handleEvents: function() {
        var self = this;

        this.$link.click(function(event) {
            //Stop the cart link from activating
            event.preventDefault();
            self.showTooltip();
        });
    },
    showTooltip: function() {
        var self = this;

        //Prevent multiple calls
        if (this.isLoading === true) {
            return;
        } else {
            this.isLoading = true;
        }

        //Bind with a .minicart namespace so we can unbind later
        $(document).bind('click.minicart', function(event){
            var $target = $(event.target);

            //If they click on anything but the minicart link and the tooltip, or their children, hide the tooltip
            if ($target.is('#minicart') === false
                && $target.is('#minicart-tooltip') === false
                && $target.parents('#minicart').length === 0
                && $target.parents('#minicart-tooltip').length === 0) {
                    self.hideTooltip();
            }
        });

        //Emtpy content and set header text
        this.$content.empty();
        this.$title.html('<p>' + self.$link.text() + '</p>');
        this.$spinner.html('<div class="spinner"></div>');
        
        this.$wrapper.fadeIn();

        //Load the template and the cart JSON simultaneously
        $.when(
            $.tmpload('minicart'), //Load and cache template
            $.getJSON('rest/cart')
        ).then(function(tmpl, data){
            //Both AJAX calls have completed

            //Remove any existing content
            self.$content.empty();

            //Apply the template, add the data to an array inside an object so we can {{each}} inside the template
            $.tmpl( tmpl, {data: [ data[0] ]} )
                .appendTo(self.$content);

            //Remove loading indicator and fade in freshly loaded content
            self.$spinner.empty();
            self.$content.fadeIn();

            //Keep track of state
            self.isLoading = false;
            self.isOpen = true;
        });
    },
    hideTooltip: function() {
        this.$wrapper.fadeOut();

        //Keep track of state
        this.isOpen = false;
        this.isLoading = false;

        //Remove the 'hideTooltip' click handler
        $(document).unbind('click.minicart');
    }
};

// image Resize class
// $e : jQuery DOM element to resize
// $w : jQuery DOM element to resize wrapper
// resize : boolean true if element needs to be resized on window resize
function ElementResize($e, $w, resize) {

  // if image is not defined, we can't process
  if (typeof $e === 'undefined') return false;
  var eData = $e.data();

  // Calculate image size and resize it
  this.resize = function() {
    // Update the element dimensions css properties
    $e.css(ImageUtils.getFullScreenImageSize(eData, {width: $w.width(), height: $w.height()}, true));
  };

  // initial resize
  this.resize();

  // resize image on window resize
  if (resize) $(window).resize(this.resize);
}


// LookBook Functions
var LookBook = {
  state : 'closed',

  // INIT
  init: function() {
    // private variables
    var that = this;

    // public variable
    this.$window = $(window); // Window
    this.$listing = $('#look-book-listing:first'); // Get the listing
    this.$listingLis = this.$listing.find('li');


    // instance sections dimensions
    this.instanceD = {
      left  : {width: 150},
      right : {width: 226},
      media : {width: 414, height: 597}
    };

    // Get instance object
    this.$instanceListWrapper = $('.look-book-detail-listing-wrapper');
    this.$instanceList = this.$instanceListWrapper.find('.look-book-detail-listing');
    this.$instances = this.$instanceList.find('li.look-book-detail-item');
    this.$instance = this.$instances.first();

    // Mega zoom objects
    this.$zoomContainer = $('div.zoom-container');
    this.$zoomImg = this.$zoomContainer.children('img:first');

    this.$window.resize(function(){
        that.$zoomContainer.css({
             'top': $(window).scrollTop()
        });
        that.$zoomImg.css({
            'margin-top': 0
        });
    });

    this.$tempLi = $('<li />', {'class': 'look-book-detail-listing-li'}).append(this.$instanceListWrapper);

    // Init Instances
    this.initInstances();

    // Check if the list is not empty
    if (!this.$listing.length) return false;

     function arrangeFloats($activeItem) {
         var $lastRowItem = $activeItem;

         if ($lastRowItem.length == 0 || typeof($lastRowItem) === 'undefined') return;

         that.$tempLi.detach();

         window.log($lastRowItem);

         that.$listingLis.removeClass('after-active');

         while ($lastRowItem.offset().top === ($lastRowItem.next().length ? $lastRowItem.next().offset().top : 0)) {
            $lastRowItem = $lastRowItem.next();
        }

        if ($lastRowItem.next().length) {
            $lastRowItem.next().addClass("after-active");
        }

         that.$listingLis.eq($lastRowItem.index()).after(that.$tempLi);
     }

      $(window).resize(function(){
            arrangeFloats(that.$listingLis.filter('.active:first'));
      });

    // click on listing li
    this.$listingLis.live('click', function() {
      var $this = $(this),
          $lastRowItem = $this;

      if (!$this.hasClass('active') && !$this.hasClass('look-book-detail-listing-li') && !$this.hasClass('look-book-detail-item')) {


        // update the active class
        that.$listingLis.removeClass('active');

        $this.addClass('active');

//        $(this).offsetRight();

//        last li index on the row

        arrangeFloats($lastRowItem);

        // Show instance
        that.initInstance($this.index());


      } else {
        $(window).stop()
            .scrollTo(that.$instance, 100)
            .addClass('active');
      }
    });

    // Handle the back link
    this.$instances.find('.back').live('click', function() {
      var _height = that.$instanceListWrapper.height();

      that.$media.fadeOut(300, 'easeOutQuad', function(){
          //Scroll the window back up
          $('html,body').animate({
              scrollTop: $(window).scrollTop() - that.$listingLis.eq(0).height()
          }, 600, 'easeInOutExpo');

           // hide the instances
          that.$instanceListWrapper.animate({height:0}, 600, 'easeInOutExpo', function() {
            that.$instanceListWrapper.hide().height(_height);
              that.$tempLi.detach();
          });
          // remove and listing item with active class
          that.$listingLis.removeClass('active');
      });

      return false;
    });

      // Auto-navigate based on /item-x in the URL
      if (typeof(lookbookItemId) !== 'undefined') {
          that.$listingLis.filter('[data-item-id=' + lookbookItemId + ']').click();
      }

      //Handle keyboard navigation
      $(document).keydown(function(event){
         var key = event.which;
         if (that.$instanceListWrapper.is(":visible") && !that.$instanceListWrapper.is(":animated")) {
             if (key === 27 || key === 38) { //Esc or Up
                that.$instance.find('a.back').click();
             } else if (key === 37) { //Left
                that.$instance.find('a.link-prev').click();
             } else if (key === 39) { //Right
                that.$instance.find('a.link-next').click();
             }
         }
      });
  },


  // INIT INSTANCES
  initInstances: function() {
    var that = this,
        oldScrollTop,
        oldOverflowY,
        $html = $('html'),
        $body = $('body'),
        nLi = this.$instances.length,
        $prev = this.$instances.find('.link-prev'),      // prev icons
        $next = this.$instances.find('.link-next'),      // next icons
        $zoom = this.$instances.find('.zoom');      // zoom icons


    // show the media
    this.resizeInstances();

    // when click on zoom icon
    $zoom.live('click', function() {
        var scrollTop = $(window).scrollTop(),
            $img = that.$instance.find('img');

        oldScrollTop = scrollTop;

        that.$zoomImg.attr('src',$img.attr('data-zoom-src'));
        that.$zoomContainer.css('top',$(window).scrollTop()).fadeIn(function(){
            oldOverflowY = $html.css('overflow-y')
            $html.css('overflow-y', 'hidden').scrollTop(scrollTop);
        });

      return false;
    });

      function calculateZoom(winHeight, scrollTop, imgHeight, pageY) {
          var percentFromTop = ((pageY - scrollTop) * 100) / winHeight;
          return ((imgHeight * (percentFromTop / 100)) - (winHeight * (percentFromTop / 100))) * -1;
      }

    this.$zoomContainer.mousemove(function(event){
         that.$zoomImg.css('margin-top', calculateZoom($(window).height(), $(window).scrollTop(), that.$zoomImg.height(), event.pageY));
    });
    this.$zoomContainer.find('.zoom-out').click(function(){
        that.$zoomContainer.fadeOut();
        $html.css('overflow-y',oldOverflowY).scrollTop(oldScrollTop);
    })

    // when click on the previous arrow
    $prev.live('click', function() {

      // update current value
      current = that.$instance.index();

      // get the next index
      var nextIndex = (current === 0) ? (nLi - 1) : (current - 1);

      // swap lis
      that.showInstance(nextIndex, true);

      return false;
    });

    $next.live('click', function() {
      // update current value
      current = that.$instance.index();

      // get the next index
      var prevIndex = ((current + 1) === nLi) ? 0 : (current + 1);

      // swap lis
      that.showInstance(prevIndex, true);
      return false;
    });
  },

  // RESIZE INSTANCES
  resizeInstances: function() {
    var that = this;
    var resize = function() {
      var _width = $('.main-holder').width();
      that.$instanceListWrapper.width(_width);
      that.$instanceListWrapper.height(that.$window.height());

//      that.$tempLi.width(_width);
//      that.$tempLi.height(that.$window.height());
      that.$instances.height((that.$window.height()));


      that.$instanceList.width((_width * that.$instances.length));


      that.$instances.width((_width));

      that.$instances.each(function(i) {
        $(this).css('left', i * _width);
      });


      that.$instanceList.css('left', '-' + that.$instance.css('left'));

      $(window).stop().scrollTo(that.$instanceList, 0);
    };

    // resize the media
    resize();
    $(window).bind('resize', resize);

  },

  // INIT INSTANCE
  initInstance: function(index) {
    var that = this,
        $thumbnail = this.$listingLis.eq(index),
        $media = this.$instanceListWrapper.find('.media'),
        instanceListWrapperHeight = this.$instanceListWrapper.height();

    // show the associate instance
    this.$instance = that.$instanceList.eq(index);

    this.showInstance(index, false);
    this.$instanceListWrapper.hide().height(0).show().stop(true, true)

      $media.css('opacity','0');
      //Ensure the body is tall enough to handle the expanded image - otherwise the expand animation butts up against the bottom of the page in the bottom row
      $('body').css('min-height', $('body').outerHeight() + $(window).height() + 500);

      $('#footer').fadeOut();

    $('html,body').stop().animate({scrollTop: $thumbnail.offset().top + $thumbnail.height() + 11}, 1200, 'easeOutExpo');
    this.$instanceListWrapper.animate({height: instanceListWrapperHeight}, 1200, 'easeInOutExpo', function() {
        $('body').css('min-height', '');
        $('#footer').fadeIn();
        that.resizeMedia();
        });
      setTimeout(function(){
          $media.animate({
              'opacity': 1
          }, 1000, 'easeOutQuad')
      }, 1000)
  },

  // SHOW INSTANCE
  // Swap 2 gallery lis
  showInstance: function(index, animating) {
    var that = this,
        _left;
    // Hide current Media
    if (typeof this.$media !== 'undefined') this.hideMedia();

    // Update the $instance variable
    this.$instance = this.$instances.eq(index);

    // get the left position of the instance to show
    _left = '-' + that.$instance.css('left');

    // Go to the next slide
    if (animating) {
      this.$instanceList.stop(true, true).animate({'left': _left}, 900, 'easeInOutExpo', function() {
        //$(window).stop().scrollTo(that.$instances, 0);
      });
    } else {
      this.$instanceList.stop(true, true).css('left', _left);
      //$(window).stop().scrollTo(that.$instances, 0);
    }

    // show and resizeMedia
    this.resizeMedia();
  },

  resizeMedia: function() {
    this.$media = this.$instance.find('.media');
    this.$mediaImage = this.$media.find('img:first');

    var that = this;

    // update the src attr
    this.$mediaImage.attr('src', this.$mediaImage.attr('data-src'))


    // update media dimensions
    var resize = function() {
      var maxWidth = $('.main-holder').width() - that.instanceD.left.width - that.instanceD.right.width - 60,
          maxHeight = that.$window.height(),
          imageSize = ImageUtils.getFullScreenImageSize(that.instanceD.media, {width:maxWidth, height: maxHeight});

      // center the image
      imageSize['margin-left'] = Math.floor((maxWidth - imageSize.width + 40) / 2);
      that.$mediaImage.css(imageSize);

      // reposition the previous and next element
      var topPosition = Math.floor((imageSize.height / 2) - 9);
      that.$media.find('.link-prev').css({top: topPosition, left: imageSize['margin-left']}).end()
          .find('.link-next').css({top: topPosition, left: imageSize['margin-left'] + imageSize.width - 37});

      // reposition the zoom icon
      that.$media.find('.zoom').css('left', imageSize['margin-left'] + imageSize.width - 37);
    };


    // resize the media
    resize();
    $(window).bind('resize', resize);

    this.showMedia();
  },

  // HIDE MEDIA
  hideMedia: function() {
    //this.$media.animate({'opacity' : 0}, 200, 'easeInQuad');
  },

  // SHOW MEDIA
  showMedia: function() {

    // show the media
    this.$media.show();

      var $socialList = this.$instance.find('div.socia-list');
      if ($socialList.find('.fb-like').length == 0) {
          var $likeContainer = $('<div />');
          $likeContainer.html('<fb:like class="fb-like" href="' + $socialList.attr('data-fb-like-href') + '" send="true" layout="button_count" width="150"  show_faces="false" font=""></fb:like>');
          $socialList.append($likeContainer);
          FB.XFBML.parse($likeContainer[0]);
      }
    //this.$media.css('opacity', 0).show().animate({'opacity':1}, 1000, 'easeOutExpo');

  }



};


// 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;
  }

};

var DropDownNav = {
    fadeInDuration : 250,
    init: function() {
        $primaryNavList = $('ul#nav');
	$primaryNavList.addClass('drop-down-active');
        totalItems = $('.main-level', $primaryNavList).length;

        $('.drop-down-nav', $primaryNavList).css({
            display: 'none',
            opacity: 0
        });
	if($('.drop-down-nav-shop-selected', $primaryNavList).length) {
	    $('.drop-down-nav-shop-selected', $primaryNavList).css({
		display: 'block',
		opacity: 1
	    });
	}
        this.enableHover();
        this._setMinimumWidths();
    },
    _setMinimumWidths: function() {
        $('#nav').children('li').each(function(){
           var $this = $(this),
                menuItemWidth = $this.width(),
                $subNav = $this.children('ul:first');
            if ($subNav.length && menuItemWidth > $subNav.width()) {
                $subNav.css('width', menuItemWidth - parseInt($subNav.css('padding-left')) - parseInt($subNav.css('padding-right')));
            }
        });
    },
    enableHover: function() {
	$('.main-level', $primaryNavList).mouseenter(function() {
	    DropDownNav.showNavItem($('li.main-level', $primaryNavList).index($(this)));
        });
        $primaryNavList.mouseleave(function() {
            $('li.main-level .drop-down-nav', $primaryNavList).css({
                opacity: 0,
                display: 'none'
            });
            $('li.main-level a.main-level-link', $primaryNavList).removeClass('main-level-link-active');
        });
    },
    showNavItem: function(index) {
	$('li.main-level .drop-down-nav').stop(true, true).css({
            opacity:0,
            display: 'none'
        });
        $('li.main-level a.main-level-link').removeClass('main-level-link-active');
        $('li.main-level:eq(' + index + ') a.main-level-link').addClass('main-level-link-active');
        $('li.main-level:eq(' + index + ') .drop-down-nav', $primaryNavList).css({
            display: 'block'
        }).animate({opacity: 1}, {
	    duration: DropDownNav.fadeInDuration,
	    queue: true
	});
    }
}

Campaign = {
    containerWidth: 0,
    containerHeight: 0,
    containerMargin: 0,
    minHeight: 677,
    currentIndex: 0,
    totalImages: 0,
    applicationStarted: false,
    init : function () {
	// Background image element dom element
	this.$container = $('#campaign-holder');
	this.totalImages = $('#campaign-holder img').length;
	this.containerWidth = this.$container.width();
	this.containerMargin = (($(window).height() - $('#footer').offset().top) + this.$container.offset().top) + 13;
	this.$selectedImageHolder = $('.campaign-image:eq(0)', this.$container);
	this.$nextLink = $('.campaign-control-next', this.$container);
	this.$prevLink = $('.campaign-control-prev', this.$container);
	
	this.$selectedImageHolder.addClass('active');
	this.$prevLink.css({opacity: 0, display: 'block'});
	this.$nextLink.css({opacity: 0, display: 'block'});
	
	this.enableResize();
    },
    enableControls : function () {
	that = this;
	if(that.applicationStarted === false) {
	    that.$prevLink.animate({opacity: 1}, {duration: 1000, easing: 'swing', queue: true});
	    setTimeout(function() {
		that.$nextLink.animate({opacity: 1}, {duration: 1000, easing: 'swing', queue: true});
	    }, 250);
	    that.applicationStarted = true;
	}
	that.$nextLink.click(function(e) {
	    e.preventDefault();
	    that.disableControls();
	    that.showImage(that.currentIndex+1, 1);
	});
	that.$prevLink.click(function(e) {
	    e.preventDefault();
	    that.disableControls();
	    that.showImage(that.currentIndex-1, -1);
	});
	$(document).keydown(function(e) {
	    e.preventDefault();
	    that.disableControls();
	    if(Number(e.keyCode) === 39) {
		that.showImage(that.currentIndex+1, 1);
	    }if (Number(e.keyCode) === 37) {
		that.showImage(that.currentIndex-1, -1);
	    }
	})
    },
    disableControls : function () {
	that.$prevLink.unbind('click');
	that.$nextLink.unbind('click');
	$(document).unbind('keydown');
    },
    enableResize : function () {
	that = this;
	$(window).resize(function(e) {
	    that.resizeImage($(this).height() - that.containerMargin + 12);
	});
	$('.campaign-image', that.$container).removeClass('loading').css({left : $(window).width()});
	$('.campaign-image:eq(0)', that.$container).css({left : 0});
	if(that.applicationStarted === false) {
	    that.resizeImage($(window).height() - that.containerMargin +12);
	    that.enableControls();
	}
    },
    resizeImage : function (imageHeight) {
	that = this;
	imageWidth = $('img', that.$selectedImageHolder).attr('data-width');
	if(imageHeight > that.minHeight && ($(window).width() - 14) > $('img', that.$selectedImageHolder).height()) {
	    $('img', that.$container).css({height: imageHeight});
	    $('.campaign-image', that.$container).css({width: $(window).width() - 24});
	    that.$container.height(imageHeight);
	}
    },
    showImage : function (index, animationDirection) {
        that = this;

        if(index === -1) {
            that.currentIndex = that.totalImages-1;
            index = that.totalImages-1;
        } else if(index === that.totalImages) {
            that.currentIndex = 0;
            index = 0;
        } else {
            that.currentIndex = index;
        }

        $newImage = $('.campaign-image:eq('+index+')', that.$container);
        $newImage.addClass('active').css({left: animationDirection*$(window).width()});

        setTimeout(function() {
            that.$selectedImageHolder.animate({left: (animationDirection*-1)*$(window).width()}, {
            duration: 1000,
            easing: 'easeInOutExpo',
            queue: false,
            complete: function() {
                $(this).removeClass('active');
            }
            });
        }, 50);

        $newImage.animate({left: 0}, {
            duration: 1000,
            easing: 'easeInOutExpo',
            queue: false,
            complete:function() {
            that.$selectedImageHolder = $newImage;
            that.enableControls();
            }
        });
    }
}

MainHolderBgResize = {
    minResizableHeight: 563,
    init : function () {
        this.$bgHolder = $('.main-holder-bg-resize');
        this.$contentHolder = $('#content');
        this.containerMargin = (($(window).height() - $('#footer').offset().top) + this.$bgHolder.offset().top) + 8;
        this.enableResize();
        this.enlargeBox($(window).height(), 750);
    },
    enableResize : function() {
        that = this;
        $(window).resize(function() {
            that.checkResize();
        });
    },
    checkResize : function () {
        that = this;
        if(typeof resizeTimeout !== 'undefined') clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            that.enlargeBox($(window).height(), 250);
        }, 150);
        /*if(Number($(window).height() - that.containerMargin) > that.$contentHolder.height()) {
            that.$bgHolder.height($(window).height() - that.containerMargin);
        } */
    },
    enlargeBox : function (windowHeight, animationDuration) {
        that = this;
        that.$bgHolder.stop(true, true);

        var newHeight;
        if(Number(windowHeight - that.containerMargin) > that.$contentHolder.height()) {
            newHeight = windowHeight - that.containerMargin;
            if(Number(newHeight) <= that.minResizableHeight) {
                newHeight = that.minResizableHeight;
            }
        } else {
            newHeight: that.$contentHolder.height();
        }
        that.$bgHolder.animate({
        height: newHeight
        }, {
        duration: animationDuration,
        easing: 'easeInOutExpo',
        complete: function(){
            $(this).css({
                'height': 'auto',
                'min-height': newHeight
                });
            }
        });
    }
}

var Competition = {
    init: function () {
	this.$friendContainer = $('#competition-form .competition-refer');
	$('.competition-friend', this.$friendContainer).hide();
	$('.competition-friend:eq(0)', this.$friendContainer).show();
	$('.competition-friend-control', this.$friendContainer).hide();
	$('.country-au, .country-other').hide();
	this.enableFields();
	this.checkFields();
    },
    checkFields : function () {
	that = this;
	$('.competition-friend', that.$friendContainer).each(function(i) {
	    if($('input', $(this)).val() !== '') {
		$(this).show();
	    }
	    if($('input.friendName', $(this)).val() !== '' && $('input.friendEmail', $(this)).val() !== '') {
		$('.competition-friend-control', $(this)).show();
	    }
	});
    },
    enableFields : function () {
	that = this;
	$('input', that.$friendContainer).change(function() {
	    this.$parent = $(this).parents('.competition-friend');
	    if($('input.friendName', this.$parent).val() !== '' && $('input.friendEmail', this.$parent).val() !== '') {
		$('.competition-friend-control', this.$parent).show();
	    }
	});
	$('.competition-friend-control', that.$friendContainer).click(function(e) {
	    e.preventDefault();
	    $('.competition-friend:eq('+(Number($('a.competition-friend-control', that.$friendContainer).index($(this)))+1)+')', that.$friendContainer).show();
	});
    }
}













