// JavaScript Document
var timeout = 1000, timer, currentDD, balloontime, docheight;
$(document).ready(function() {
   // do stuff when DOM is ready
   
	defaultText();
	
	//apply to each menubar link
	$('#menubar > li a').each(function(){
		$(this).hover(openDD, setClose);		
	});
	
	//apply to each dropdownlist
	$('.dropdown').each(function(){
		$(this).hover(
			cancelClose,
			setClose
		);
	});
	
	//add to contact form
	$('#form_contact').submit(validateContact);
	
	//add to Trip Planning form
	$('#planning').submit(validatePlanning);
	
	//add listener to newsletter signups
	$('.signupForm').each(function(){
		$(this).submit(validateNewsletter); 
	});
	//lightbox for trip galleries
	$('#trip-gallery a').click(function(){
		var name = $(this).attr('title');
		var descript = $(this).find('img').attr('alt');
		var idnum = parseInt($(this).attr('id').replace('gallerypic',''),10);
		
		var fullsize = 
        '<div id="full-size">'
            +'<div id="picture-box">'
                +'<div id="picture-top">'
                    +'<div id="picture-close">Close</div>'
                    +'<div id="picture-name">'+name+'</div>'
                +'</div>'
                +'<img id="picture-full" alt="'+name+'" src="'+$(this).attr('href')+'" />'
                +'<div id="picture-bottom">'
                    +'<div id="picture-prev" title="'+(idnum-1)+'">Previous</div>'
                    +'<div id="picture-next" title="'+(idnum+1)+'">Next</div>'
                    +'<div id="picture-description">'+descript+'</div>'
                +'</div>'
            +'</div>'
        +'</div>';		
		$('#wrapper').append(fullsize);
		docheight = $(document).height();
		
		$('#full-size').css('height',docheight+'px');
		//set close button
		$('#picture-close').click(function(){
			$('#full-size').remove();
		});
		//set prev and next buttons
		$('#picture-prev, #picture-next').click(function(){
			var idnum = parseInt($(this).attr('title'),10);			
			if (idnum >= 0 && idnum < $('#trip-gallery a').length){				
				var newpic = '#gallerypic'+idnum;				
				var newname = $(newpic).attr('title');
				var newdescript = $(newpic).find('img').attr('alt');
				$('#picture-name').html(newname);
				$('#picture-description').html(newdescript);
				$('#picture-full').attr({
					'src':$(newpic).attr('href'),
					'alt':name
				});
				$('#picture-prev').attr('title',idnum-1);
				$('#picture-next').attr('title',idnum+1);
				$('#picture-full').load(adjustPosition);
			}
		});		
		
		$('#picture-full').load(adjustPosition);
		return false;
	});	
	
	$('#custombooking').submit(validateCustomBooking);
});
function adjustPosition(){
	//position picture
	var	offset = $(window).scrollTop();		
	var	winheight = $(window).height();
	var picheight = $(this).height();
	var desheight = $('#picture-bottom').outerHeight();
	var topheight = $('#picture-top').outerHeight();
	var pos;
	//alert('offset: '+offset+' winheight: '+winheight+' picheight: '+picheight+' desheight: '+desheight);
	var picbottom = offset + picheight + desheight + topheight;		
	if (picbottom <= docheight){
		pos = winheight/2 - picheight/2 + offset;
	}else{
		pos = docheight-picheight-des.outerHeight();			
	}		
	$('#picture-box').css({'margin-top':pos+'px'});
	$(this).slideDown(500);			
}
function defaultText(){
	//switch out default text on focus
	$('.news-textbox').each(function(){
		$(this).focus(function(){
			if ($(this).val() == $(this)[0].title){
				$(this).val('');
				$(this).addClass('active-text');
			}
		});
	});

	//check if text empty otherwise implement default text on focus
	$('.news-textbox').each(function(){
		$(this).blur(function(){
			if ($(this).val() == ''){
				$(this).val($(this)[0].title);
				$(this).removeClass('active-text');
			}
		});
	});
	
	//blur the textbox
	$('.news-textbox').each(function(){
		$(this).blur();
	});
	
}
//gets the id of a dropdown corresponding to a link
function getDropId(id){
	var linkid = '#' + id.attr('id');

	return linkid.replace('mlink','drop');
}
//set the countdown to closer
function setClose(){
	timer = setTimeout(closeDD, timeout);
}
//cancels the closedown
function cancelClose(){
	clearTimeout(timer);
}
//closes a dropdown
function closeDD(){
	$(currentDD).hide();
	currentDD = null;
}
//open or retain a dropdown
function openDD(){
	var newDD = getDropId($(this));
	cancelClose();
	if ((currentDD != null)&&(currentDD != newDD)){
		closeDD();
	}
	currentDD = newDD;	
	if ($(currentDD + ' > a').length > 0){ 
		var position = $(this).position();
		$(currentDD).css('left', position.left + 'px');
		$(currentDD).show();
	}
}
//when page completely loaded including images
$(window).load(function() {
	//check for existence of smallbox 1,2 etc
	var smallboxes = $('.smallyellow, .smallgreen');
	if (smallboxes.length > 0){
		for (var n=1; n<smallboxes.length; n+=2){
			//equalize the heights of two smallboxes, either to 230 or to the largest of the 2 if one's larger
			/*min-height:230px;*/
			var minheight = 200;
			var leftheight = $('#smallbox'+n).height();
			var rightheight = $('#smallbox'+(n+1)).height();
			if ((leftheight < minheight)&&(rightheight < 230)){
				//both are less than 230
				$('#smallbox'+n).css({'height':minheight+'px'});
				$('#smallbox'+(n+1)).css({'height':minheight+'px'});
			}else if (leftheight > rightheight){
				//left box is bigger
				$('#smallbox'+(n+1)).css({'height':leftheight+'px'});
			}else if (leftheight < rightheight){
				//right box is bigger
				$('#smallbox'+n).css({'height':rightheight+'px'});
			}
		}
	}
	//check for existance of trip pictures and adjust if width > 300
	$('.trippic, .right-trippic').each(function(){
		if ($(this).width() > 300) $(this).css({'width':'300px'});
	});
	
	//add mouseover and mouseon events for BC fishing map
	$('#fishing-map .fishing-spot').each(function(){
		$(this).hover(showballoon, hideballoon);
	});
	//add mouseover and mouseon events for BC fishing map
	$('#fishing-locations > ol li a').each(function(){
		$(this).hover(markspot, unmarkspot);
	});
});

//show a balloon when over fishing spot
function showballoon(){
//	clearTimeout (balloontime);
	var spotid = $(this).attr('id');
	
	spotid = spotid.replace('fishspot','');	
	
	var num = parseInt(spotid,10)-1; //get id number	
	var data, xcoord, ycoord;
	$.ajax({
		type: 'GET',
		url: $('#map_file').val(),
		dataType: 'xml',
		success: function(xml){
			data = $(xml).find('location:nth('+(num)+')');
			xcoord = parseInt(data.find('x').text(),10);
			ycoord = parseInt(data.find('y').text(),10);
			$('#balloon-M').text(data.attr('name'));
			$('#balloon').each(function(){		
				var height = $(this).height();
				var x, y;
				x = xcoord-20;
				y = ycoord-height-5;
				$(this).css({'left':x+'px', 'top':y+'px'});
				
				$(this).show();				
			});
		}
	});
}
//hide a balloon when out of fishing spot
function hideballoon(){	
	$('#balloon').hide();
}
//mark spot on map whenever text
function markspot(){
	var spotid = '#' + $(this).attr('id') + ' a';

	spotid = spotid.replace('locationlink','fishspot');	
	$(spotid).addClass('on');
}
//unmark spot on map whenever text
function unmarkspot(){
	var spotid = '#' + $(this).attr('id') + ' a';

	spotid = spotid.replace('locationlink','fishspot');
	$(spotid).removeClass('on');
}
//validate the contact form
function validateContact(){
	var email = $('#contact_email');
	var message = '';
	if ($('#contact_name').val()==''){
		message += 'Please Provide a Name\n';
		$('#name_req').show();
	}else{
		$('#name_req').hide();
	}
	if (email.val()==''){
		message += 'Please Provide an Email\n';
		$('#email_req').show();
	}else{
		$('#email_req').hide();
	}
	if ($('#contact_comment').val()==''){
		message += 'Please Provide a Comment\n';
		$('#comment_req').show();
	}else{
		$('#comment_req').hide();
	}
	if (!validateEmail(email.val())){
		message += 'Your Email is not a Valid Email\n';
		$('#email_req').show();
	}else{
		$('#email_req').hide();
	}
	if (message == '') return true;
	alert (message);
	return false;	
}
/*Validates Trip Planning */
function validatePlanning(){
	var email = $(this).find('.news-textbox').val();
	if ($('#contact_name').val()==''){
		message += 'Please Provide a Name\n';
		$('#name_req').show();
	}else{
		$('#name_req').hide();
	}
	
	if (email==''){
		message += 'Please Provide an Email\n';
		$('#email_req').show();		
	}else{
		$('#email_req').hide();
	}
		
	if (!validateEmail(email)){
		message += 'Your Email is not a Valid Email\n';
		$('#email_req').show();
	}else{
		$('#email_req').hide();
	}
	if (message == '') return true;
	alert (message);
	return false;
}
/*Validates Trip Planning*/
function validateNewsletter(){
	var email = $(this).find('.news-textbox').val();
	if (email==''){
		alert ('Please provide an email');		
	}else if (!validateEmail(email)){
		alert ('Your Email is not a Valid Email');
	}else{
		return true;
	}
	return false;
}
/*Validates Booking Contact Form*/
function validateCustomBooking(){
	var email = $(this).find('#email').val();
	if (email==''){
		alert ('Please provide an email');		
	}else if (!validateEmail(email)){
		alert ('Your Email is not a Valid Email');
	}else if ($('#name').val() == ''){
		alert ('Please Provide Your Name!');
	}else{
		return true;
	}
	return false;
}
//validates an email using unicode characters
function validateEmail(email){
	var emailreg = /^((([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/ 
	if (!emailreg.exec(email))
		return false;
	else
		return true;
}
function changepreview(){
	$('#homepagepic').attr('src','../images/hotdeals/'+$('#homepic').val());
}

/*
Author: James Thomson
Company: Red Label Communications
Copyright 2010. All Rights Reserved.
*/
$(function(){  
	if($('#leftbanner').length > 0){
		var pos = null;
		var speed = 1000;
		var timer = 5000;
		var autoPlay = true;
		var $active;
		var $next;
		var $toggler = $('a.playToggle');
		
		var bWidth = $('div.banner img').outerWidth(); // get the banner width
		var numImg = $('div.banner img').length; // get the number of images contained in banner
		
		$('div.banner').css('width', bWidth*numImg); // set the banner width based on the number of images
		
		$('div.banner a').each(function(x) {
			$(this).attr('id', x); // apply an ID to each image
			$('div.control').append('<a rel="'+x+'" href="#">'+x+'</a> '); // add a button/number for each image
		});
		
		$('div.banner a:first').addClass('active');
		$('div.control a:first').addClass('selected');
		
		$('a.playToggle').live('click', function() {playToggle();}); // on mouse click run function playToggle
		
		function getNext(){
			$active = $('div.banner a.active');
			$next = $active.next();
			$active.addClass('last-active'); 
			/* if($active.attr('id') == (numImg-1)){ // check to see if is last slide
				$next = $('div.banner a:first');
				pos = $next.position();
				$('div.banner a:first').addClass('active');	
			}
			else { */
				pos = $next.position();
				$next.addClass('active');
			// }
			$('div.banner').animate({'left' : -pos.left}, 1000, function(){
				$('div.banner a:last').after($('div.banner a:first')); // move the first image after the last image to create infinate loop
				$('div.banner').css({'left' : '0px'}); // set left back to 0 for infinate loop
				$active.removeClass('active last-active');
				$('div.control a').removeClass('selected');
				$('div.control a[rel='+$next.attr('id')+']').addClass('selected');
				if(autoPlay == true){
					playBanner();
				}
			});
		}
		
		function playBanner() {
			playCycle = setTimeout(getNext, timer);
		}
		
		function playToggle() {
			if(autoPlay == true) {
				clearInterval(playCycle);
				autoPlay = false;
				$toggler.text('Play');
			}
			else {
				autoPlay = true;
				playBanner();
				$toggler.text('Pause');
			}
		}
		
		$('div.control a', this).live('click', function() {
			clearInterval(playCycle);
			$active = $('div.banner img.active');
			
			var i = $(this).attr('rel');
			var $current = $('div.banner img#'+i+'');	
			
			pos = $current.position();
			$('div.banner').animate({'left' : -pos.left}, 1000, function(){
				$active.removeClass('active');
				$current.addClass('active');
				$toggler.text('Play');
				autoPlay = false;
			});
			$('div.control a').removeClass('selected');
			$(this).addClass('selected');
			return false;
		});
		
		if(autoPlay == true) { // if autoPlay is on (true) playBanner, otherwise do nothing, but set playToggle text to 'Play'
			playBanner();
		}
		else {
			$toggler.text('Play');
			return;
		}
	}
});
