// Plugin allows placeholder to display in non-html5 compatible browsers
$('input[placeholder], textarea[placeholder]').placeholder();

// creates bg controls for thumbnails
function hideOverflow(){
   	if($.browser.msie && $.browser.version<="8.0"){
   		$('.pageable, .content-pager').removeClass('hidecontent'); 
   	}
   	else {
   		$('.hidecontent').css('opacity', 1 ); 
   	}	
}

var slideCnt = $('.slide-pages a');

// creates bg controls for thumbnails
$(slideCnt).click(function(){ 
	// returns thumbnail position
	var indexS = $(this).parent().children().index(this); 
	$.vegas('jump', indexS)('pause');
	$(slideCnt).removeClass('active');
	$(this).addClass('active');
});

// adds .last to final paragraph in content - added via javascript due to dynamic implementation of content
function addContentClasses(){
	if($('body').hasClass('blog') == 0) {
		$('.content p:last, .paginate .page p:last').addClass('last');
		$('.content p:first').addClass('intro');
	}
}
addContentClasses();

// Ties background switch to menu link click
function vegasControls(){
	$('.cntrl').click(function(){
		var indexli = $(this).parent('li').index() + 1;
		$.vegas('jump', indexli)('pause');
	});
}

// for corporate page toggle hovers for room names
$('.thumb-wrap').hover(function(){
  		$(this).child('div').show();
	}, function() {
		$(this).child('div').hide();
});

// translate pagination controls to french
function paginateLang() {
    if($('.fr .nextLink')) {
        $('.nextLink').eq(0).val('Précédent');
        $('.nextLink').next().val('Suivant');
    }
}
paginateLang();

// removes "last" and "first" for english pagination
function paginateTranslate() {
	if($('body.press').hasClass('fr')) {
		$('.pagination a:contains("First")').text('Début');
		$('.pagination a:contains("Last")').text('Fin');
		$('.pagination').show();
	}
}
paginateTranslate();

// -------------- JQUERY TOOLS ------------------ //

$('.tabbed').tabs('.menu-rt .cell', { tabs:'.cntrl', effect: 'fade'}); // initiates menu tabIndex
$('.tabs').tabs("> .pane", {effect: 'fade'}); // initiates nexted tabs (menus, etc.)
$('.tabs-terms').tabs(".pane", {effect: 'fade'}); // initiates nexted tabs (menus, etc.)
$('.tabs-sub, .tabs-sub-fn').tabs('> .pane', {effect: 'fade'}); // initiates tertiary nested tabs

var api = $('.tabbed').data('tabs'); // initial api for menu items
var apiTop = $('.tabs').data('tabs'); // initiate api for 2nd tier tabs
var apiSub = $('.tabs-sub').data('tabs'); // initiate tier for 3rd tier tabs
		
$('.tabs li').click(function(){ // reset nested tab index
	apiSub.click(0);
});

// checks URL hash and opens appropriate menu tag
function openTab(){
	var theHash = location.hash.split('#');
	var index = parseInt(theHash[1]) - 1;
	if($('.menu-li a').hasClass('cntrl')) {
		api.click(index);
	}
}
$(function(){ openTab(); });

//setups up popups
$('.artefact-right[rel], .artefact-left[rel], #arte-award, .certpop[rel], .newsletter[rel], .corporate .thumb-wrap[rel], .rooms .thumbs img').overlay({
	mask: {
	  color: '#000',
	  loadSpeed: 400,
	  opacity: 0.8
	},
	top: 'center'
}); 

var apiArtefacts = $('.artefact-right[rel], .artefact-left[rel]').data('overlay');
var apiAward = $('#arte-award').data('overlay');

// initialize scrollable
$(".scrollable").scrollable({circular:true, items: '.gallery', next: '.nextSlide', prev: '.prevSlide'});

// associate thumbs to large images
$('.rooms .thumbs img, .dining .thumbs img').click(function(){
	var thisNum = $(this).index();
	var thisParent = $('.thumbs').index($(this).parent('.thumbs'));
	$('.scrollable').eq(thisParent).data('scrollable').seekTo(thisNum,0);
});

$('.corporate div.thumb-wrap').click(function(){
	var thisIndex = $(this).index();
	$('.scrollable').eq(thisIndex).data('scrollable').seekTo(0,0);
});

$('.corporate a.thumb-wrap').click(function(){
	var thisIndex = $(this).parent().index();
	$('.scrollable').eq(thisIndex).data('scrollable').begin(0);
});

// -------------- MANAGES DISPLAY FOR RIGHT MENU AND LEFT COL HEIGHT ------------------ //

var $menuRt = $('.dining .menu-rt, .services .menu-rt, .packages .menu-rt, .corporate .menu-rt, .rooms .menu-rt, .cafe-artefact .menu-rt'); // specific instances of right menu

$(function() { leftColHeight(); }); // on page ready measure and shift right menu top-margin
$('.tabbed, .tabs, .tabs-terms, .tabs-sub').click(function() { leftColHeight(); });  // trigger menu shift and page resize on tab click
$(window).resize(function() { leftColHeight(); }); // trigger menu shift and page resize on body resize


// checks height of window and right column and resets left column
function leftColHeight() {
    
    var $colLeft = $('#left-col');
    var colLeftHeight = $('#left-col').outerHeight();
    var colRightHeight = $('#right-col').outerHeight();
    var windowHeight = $(window).height();    

    if (colRightHeight > colLeftHeight){
        $colLeft.removeClass('base');
        $colLeft.css('height', colRightHeight);
    }
    else if (colRightHeight < colLeftHeight || colLeftHeight < windowHeight) {
        $colLeft.attr('style',"");
        $colLeft.addClass('base');
    }

    setMenuMargin();
}

function setMenuMargin(){ // finds menu height and shifts
  var menuHeight = $menuRt.height();
  shiftMenu(menuHeight);
}

function shiftMenu(menuHeight) { // shift menu top margin dynamically
	var newTop = ($(window).height() - menuHeight) / 3;
	if (newTop > 50) {
  		$menuRt.animate({ marginTop : newTop }, 1000, 'swing');  
	} else { $menuRt.animate({ marginTop : '36px' }, 1000, 'swing'); }
}

// -------------- GOOGLE MAP / CONTACT PAGE ------------------ //

// initializes Google Map
function initialize() {
  var map = new GMap2(document.getElementById("map"));
  map.setCenter(new GLatLng(46.81510,-71.22668), 13);
  map.setMapType(G_NORMAL_MAP);
  var point = new GLatLng(46.81457,-71.20224);
  map.addOverlay(new GMarker(point));
}

// forces map height to 100%
function resizeMap(){
	$(window).resize(function(){
		var winHeight = $(window).height();
		if(winHeight >= 758){
			$('#map').css('height', winHeight);
		}
	}).trigger('resize');
}

// -------------- TREASURE HUNT ------------------ //

function treasureHunt() {

// if not present create default array and store in cookie
if($.cookie('treasure_hunt') == null) {

    var treasure = new Array(
        "arteContact",0,
        "arteCorp",0,
        "arteServices",0,
        "arteRooms",0,
        "arteDining",0,
        "artePack",0,
        "arteHotel",0,
        "arteHome", 0,
        "completed", "not completed"
    );
       $.cookie('treasure_hunt', treasure, { expires: 31, path: '/' });
}

// capture cookie info
var treasureFound = $.cookie('treasure_hunt');

// create check array and parse values
var treasureCheck = new Array();
var treasureCheck = treasureFound.split(',');

// check number artefacts and write to page
var treasureTotal = (treasureCheck.length - 2) / 2;
$('.thTotal').text(treasureTotal);

// checks array for found items and, if all are found, pops congrats message
function checkFound() { 
    var foundItems = 0;
    var lastValue = treasureCheck.length - 1;

    for(var i=0; i<treasureCheck.length; i++) {
        var value = treasureCheck[i];
        if(value == 1) {
            ++foundItems;
        }
    }
    
    if(foundItems == treasureTotal && treasureCheck[lastValue] == "not completed") {
    	
    	if($('body').hasClass('fr')){
    		$('<div class="congratulations"><span class="b">F&eacute;licitations!</span> - Tous les objets trouv&eacute;s! <a href="#" class="b">Recueillir le prix</a></div>').prependTo('#arte-tip');
    	} else {
    		$('<div class="congratulations"><span class="b">Congratulations</span> - All artefacts have been found! <a href="#" class="b">Collect Prize</a></div>').prependTo('#arte-tip');
    	}
    	
    	$('.congratulations a').bind('click', function(){
    		apiArtefacts.close();
    		setTimeout("apiAward.load()",500);
    	});
    	
        treasureCheck[lastValue] = "completed";
    }

	// write results to page
    $('.thProgress').text(foundItems);

}

// onclick checks element ID against array and determines if artefact has been found
$('.artefact-right, .artefact-left').click(function(){
    var artefactID = $(this).attr('id');

    for(var e=0; e<treasureCheck.length; e++) {
        var matchID = treasureCheck[e];
        var k = e + 1;

        if(matchID == artefactID) {
            treasureCheck[k] = 1;
            checkFound();
            
            // reset clear cookie and update with new found items array
            $.cookie('treasure_hunt', null);
            $.cookie('treasure_hunt', treasureCheck, { expires: 31, path: '/' });
        }

    }

});

} treasureHunt();

// -------------- VALIDATION (general) ------------------ //

// newsletter validation rules
$("#newsletter-form").validate({ 
  rules: {
		Email: {
			required:true,
			email: true
			}
  	},
  submitHandler: function(form) {
          $.ajax({
              type: "GET",
              url: $(form).attr('action'),
              data: $(form).serialize(),
              crossDomain: true,
              timeout: 3000
            });
          $('#newsletter form').fadeOut(700).remove();
          if($('body').hasClass('fr')){
            $('<div>Merci! Vous êtes maintenant inscrit à l\'infolettre.</div>').fadeIn(700).appendTo('#newsletter-ft');
          } else {
		  	$('<div>You have successfully subscribed!</div>').fadeIn(700).appendTo('#newsletter-ft');
		  }
     }
		
});
