/* Author:

*/
var win, el, pg, li, G = {counter:0, max:0, w: 0, pg: null}, cat = {h:0, el: null, state: 'openned'}, M = {curr: null}, C = {el: null}, autoPlay = true, autoPlayInterval = null, emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

$(function() {
  win = $(window);

  // fancybox
	$("a[rel=photo-gallery]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
		}
	});
	
	$("#searchform > input#s").bind('focus blur', onSearchHandler);
	
	// sets up the slideshow (home, programs, etc)
	setUpSlideShow(autoPlay);
	
	// renders the categories button clickable
	setUpCategoriesButton();
	
	// sets up the hover effects on the main menu
	setUpHoverEffects();
	
	// sets up the contact us related stuff
	setUpContactUs();
});

setUpHoverEffects = function() {
  $("div#main-wrapper ul#menu-a-knock-at-midnight > li").bind('mouseenter mouseleave', onHoverHandler);
};

onHoverHandler = function(e) {
  var el = $(e.currentTarget);
  switch(e.type) {
    case "mouseenter":
      if(M.curr) {
        M.curr.removeClass("hovered");
      }
      M.curr = el.find("> a");
      M.curr.addClass("hovered");
      el.find('> ul').stop(true).animate({opacity: 1}, 550);
      break;
    case "mouseleave":
      if(M.curr) {
        M.curr.removeClass("hovered");
        el.find('> ul').stop(true).animate({opacity: 0}, 550);
      }
      M.curr = null;
      break;
  }
};

onSearchHandler = function(e) {
  var el = $(e.currentTarget);

  switch(e.type) {
    case "focus":
      if(el.val() == "Search") {
        el.val("");
      }
      break;
    case "blur":
      if(el.val().length === 0) {
        el.val("Search");
      }
      break;
  }
};

setUpCategoriesButton = function() {
  cat.el = $("div#right-column div#categories");
  cat.el.find("h1").bind('click', categoriesHandler);
  cat.el.find("h1 > a").bind('click', function(e){ e.preventDefault(); });
};

categoriesHandler = function(e) {
  if(cat.el.filter(":animated").length > 0) {
    return;
  }
  switch(cat.state) {
    case "openned":
      cat.h = cat.el.height();
      cat.el.animate({height: '0px'}, 550, function() {
        $(this).css('border', 'none');
      });
      cat.el.find('> h1').css({'background-position-y': 'bottom'});
      cat.state = "closed";
      break;
    case "closed":
      cat.el.animate({height: cat.h+'px'}, 550).css('border-bottom', '1px solid #000');
      cat.el.find('> h1').css({'background-position-y': 'top'});
      cat.state = "openned";
      break;
  }
}

setUpSlideShow = function(_autoplay) {
  el = $("div#content div.slideshow");
	
	li = el.find("ul.slideshow-container li");
	G.w = 913;
	
	if(li.length > 1) {
	  el.find("nav").css({display: 'block'})
	}

  if((el.attr('id') !== "main-gallery")) {
    G.w = 715;
  }
	
	pg = $("ul#main-paginator-cont");
	G.pg = pg.find('> li').first();
	
	el.find("ul.slideshow-container > li").each(function(id, dom){
	  var t = $(this);

    t.find('> img').css({display: 'block'});

	  if(id+1 === G.counter) {

    } else {
      t.css({left:(G.w*id)+"px"});
    }
    
    G.max = id+1;
	});
	
	el.find("nav a").bind('click', onGalleryHandler);
	pg.find("> li").each(function(id, dom){
	  $(this).bind('click', {id: id}, onPaginatorHandler);
	});

	setAutoPlay();
};

setAutoPlay = function() {
  clearInterval(autoPlayInterval);
  autoPlayInterval = setInterval(function() {
	  onAutoPlayHandler();
	}, 5000);
};

onAutoPlayHandler = function() {
  el.find("nav a#gallery-right").trigger('click', [true]);
};

onGalleryHandler = function(e, triggered) {
  if(li.filter(":animated").length > 0) {
    return;
  }
  
  // resets the timer if user is clicking the button
  if(!triggered) {
    setAutoPlay();
  }

  switch(e.currentTarget.id) {
    case "gallery-right":
      G.counter = (G.counter+1>=G.max) ? 0: G.counter+1;
      break;
    case "gallery-left":
      G.counter = (G.counter<=0) ? G.max-1: G.counter-1;
      break;
  }

  G.pg.removeClass("selected-paginator");
  G.pg = pg.find("> li").eq(G.counter);
  G.pg.addClass("selected-paginator");
  G.pg.trigger('click');

  animateGallery();
};

animateGallery = function() {
  var t = el.find("ul.slideshow-container li");

  t.each(function(id, dom) {
    $(this).animate({left: G.w*(id-G.counter)}, 550);
  });
};

onPaginatorHandler = function(e) {
  if(li.filter(":animated").length > 0 || (G.pg[0] === e.currentTarget)) {
    return;
  }
  
  G.counter = e.data.id;
  
  G.pg.removeClass("selected-paginator");
  G.pg = pg.find("> li").eq(G.counter);
  G.pg.addClass("selected-paginator");
  
  animateGallery();
};

onWindowScrollHandler = function(e) {
  if(win.scrollTop() > 149) {
    if(C.el.filter(':animated').length === 0) {
      C.to = null;
      C.el.animate({top: win.scrollTop()}, 550, checkScrollStatus);
    } else {
      C.to = win.scrollTop();
    }
  } else {
    C.to = null;
    C.el.stop(true).animate({top: '0px'}, 550, checkScrollStatus);
  }
};

checkScrollStatus = function() {
  C.el.stop(true);

  if(C.to) {
    onWindowScrollHandler(null);
  }
};

setUpContactUs = function() {
  win.bind('scroll', onWindowScrollHandler);
  C.el = $("ul#menu-a-knock-at-midnight li").last().find('> a');

  $("div#close-contact-button").bind('click', function(e) { e.preventDefault(); onCloseHandler(e); } );
  C.el.bind('click', onContactUsHandler);
};

onContactUsHandler = function(e) {
  win.unbind('resize');

  var scope = this;

  $("div#submit-button a").unbind('click').bind('click', function(e) { e.preventDefault(); window.onCheckContactForm(e); });

  showContactForm();
};
  
showContactForm = function() {
  var scope = this, back = $("#pop-background"), cont = $('div#contact-us-content');
  
  win.scrollTop(0);
  
  if(back.filter(':animated').length > 0) {
    return;
  }
  
  //clears the form's values
  cont.find('input').val("");
  cont.find('textarea').first().val("");
  cont.find('input').removeClass('erroneous');
  cont.find('textarea').first().removeClass("erroneous");
  
  win.bind('resize', onResizeHandler);

  back.css({display: 'block'});

  back.animate({height: win.height(), top: win.height()}, 0, function() {
    var el = $("div#contact-us-container"), h = el.height();

    el.css({height: '0px', display: 'block'})
      .delay(500)
      .animate({height: h+'px'}, 500, 'easeInExpo');
  }
  ).animate({top: '0px'}, 500, 'easeOutExpo', function() {
    onResizeHandler(null);
  });
};
  
onCheckContactForm = function(e) {
  var el, offset, data = 'post=form', error = 0;

  emailPattern.lastIndex = 0;
  
  $('div#contact-us-content').find('input').each(function(id, dom) {
    el = $(this);
    offset = el.offsetParent();
    el.removeClass('erroneous');
    if(offset.hasClass('required') && !el.val()) {
      error++;
      el.addClass('erroneous');
    } else if(offset.hasClass('email-address') && !emailPattern.exec(el.val())) {
        error++;
        el.addClass('erroneous');
    }

    data += "&"+el.attr('id')+"="+escape(el.val());
  });

  el = $('div#contact-us-content').find('textarea').first()
                                  .removeClass('erroneous');

  if(el.val().length < 1) {
    el.removeClass('erroneous')
      .addClass('erroneous');

      error++;
  }

  data += "&msg="+escape(el.val());

  if(error===0) {
    sendContactForm(data);
  }
}

sendContactForm = function(dataString) {
    $("div#form-status").removeClass('sending')
                        .removeClass('sent')
                        .addClass('sending')
                        .css({display: 'block'});

   $.ajax({
     type: "POST",
     url: "/email.php",
     data: dataString,
     error: function(jqXHR, textStatus, errorThrown) {
       // console.log(jqXHR, textStatus, errorThrown);
     },
     success: function() {
         $("div#form-status").removeClass('sending')
                             .addClass('sent');
     }
   });
}

onResizeHandler = function(e) {
  $("div#contact-us-container").css({top: '200px'});
  $("#pop-background").css({height: Math.max($(document).height(),$(window).height(),document.documentElement.clientHeight), width: win.width()});
};
  
onCloseHandler = function() {
  var h, scope = this, section = $("div#contact-us-container");
  h = section.height();
  
  win.unbind('resize');
  
  section.animate({height: 0}, 500, 'easeInExpo', function() {
    section.css({display: 'none', height: h});
  });

  $("#pop-background").delay(600)
                      .animate({top: win.height()+'px'}, 375, 'easeInQuint', function() {
                        $("#pop-background").css({height: '0px', display: 'none'});
                      });
};
