/*

Scripts written by Alex Dickson for Acura Multimedia (http://www.acura.com.au)
jQuery (http://www.jquery.com) by John Resig (http://www.ejohn.org)

*/

// global stuff 

var GOOGLE_ANALYTICS_KEY = 'UA-693909-41';
var DATEPICKER_OPTIONS = {dateFormat: 'dd/mm/yy', yearRange: '2000:2010', constrainInput: true, minDate: new Date()};

// add this class to specify .javascript * in css for quicker css application
$('html').addClass('javascript');

// on DOM ready
$(document).ready(function(){
	$('html').addClass('dom-loaded');


	try { //try get 24bit png working on ie6
		$('img[src$=png]').pngfix();
	} catch(err) {}
	
	
	
	externalLinks.init();
	
    liveFijiTime.init();
    
    if (!$('body').hasClass('static')) {
    
        slidingContent.init();
        images.init();
    }
    
    menu.init();
    
    if ($('body').hasClass('article')) {
    
        reservations.init();
    
    };
    
    if ($('body').hasClass('reservations')) {
    
        reservationsForm.init();
    
    };
    
    contacts.init();
    special.init();
    gallery.init();

	
	if ($('body').hasClass('its-your-island')) {
	       	$('#text').after('<div id="choice-award"><a href="http://www.tripadvisor.com/" rel="external">Traveller\'s 2008 Choice</a></div>');				
	} else if ($('body').hasClass('diving')) {   
       	 	$('#text').after('<div id="padi"><a href="https://www.padi.Com/elearning-scuba-registration/default.aspx?irra=8438"  rel="external" target="_blank">PADI e-Learning </a></div>');			
	}
	
});





// on window loaded
$(window).load(function(){  // window load

	$('html').addClass('window-loaded');


	//google analytics
	try {
		var pageTracker = _gat._getTracker('UA-693909-41');
		pageTracker._trackPageview();
	} catch(err) {}
	
});


var gallery = {

    init: function() {
    
        
    
        $('#body .gallery-link').bind('click', function(event) {
            event.preventDefault();
            loadingModal.show();

            var galleryBlock = $('#gallery-block');
        
            if (!galleryBlock.length) {
                // create it
                
                $('#body').append('<div id="gallery-block"></div>');
                galleryBlock.hide();
            }
            
            var href = $(this).attr('href');
            
            var arg = href.split('/');
            
            arg = arg[arg.length - 2];
            
            
            var jsonLocation = PATH_BASE + '/gallery/' + arg + '.json/';
            
            $.getJSON(jsonLocation,
            function(data){
                loadingModal.hide();

               // alert(data);

                $('#gallery-block')
                .html(data.toString() + '<span class="close">close</span>')
                .fadeIn(1000);
                
                $("#gallery-block a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
		              return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
            	});

                


              
            });
            
            $('#gallery-block .close').live('click', function() {
            
                $('#gallery-block').fadeOut(1000);
            
            });

            
            
            
        
        });
    
    }


}

var menu = {
    activated: null,
    hideDelay: null,
    init: function() {
        var self = this;
        $('#header > ul > li').hoverIntent(function() {
            clearTimeout(self.hideDelay);
            self.show($(this).find('ul'));
        }, function() {
			self.hideDelay = setTimeout(function() {  self.hide(self.activated);  }, 500);                     
        });
        $('#header > ul > li > ul').hoverIntent(function() {  clearTimeout(self.hideDelay); },
        function() {
            self.hide(self.activated);
        });
    },
    show: function(jObj) {
        if (this.activated != jObj) {
            if (this.activated) {
                this.hide(this.activated);
            }
            this.activated = jObj;
            jObj.show().css({opacity: '0.3'}).height(0).stop().animate({height: '88px', opacity: '1.0'}, 800)
        }
    },
    hide: function(jObj) {
         jObj.stop().animate({height: '0', opacity: '0.3'}, 400, function() { $(this).hide();  }); 
    }
}


var special = {
    out: false,
    init: function() {
        
        var self = this;
        $('#special').bind('click', function() {
             if (self.out) {
                self.slideIn();
             } else {
                self.slideOut();
             }
        });
    
    },
    slideOut: function() {
        this.out = true;
        $('#special').animate({right: 0}, 500);

    },
    slideIn: function() {
        this.out = false;
        $('#special').animate({right: '-373px'}, 500);
    }

}


var reservations = {
    form: null,
    init: function() {
        var self = this;
        var resForm = $('#reservations form');
        resForm.append('<span id="check-vacancies">Check Vacancies</span>');
        $('#check-vacancies').bind('click', function() { $(this).parents('form').submit(); });
        $.datepicker.setDefaults(DATEPICKER_OPTIONS);
        resForm.find('#input-arrival-date').datepicker();
        resForm.find('#input-departure-date').datepicker({defaultDate: +7});
        resForm.bind('submit', function() {
            self.form = $(this);
            return self.checkDates();
        });
    },
    checkDates: function() {

        var form = this.form;
        var arrivalInput = form.find('#input-arrival-date');
        var departureInput = form.find('#input-departure-date');
        var arrivalVal = arrivalInput.val();
        var departureVal = departureInput.val();
        var arrivalDate = arrivalInput.datepicker('getDate');
        var departureDate = departureInput.datepicker('getDate');
        var today = new Date();
        if (arrivalVal == 'dd/mm/yyyy' || arrivalVal == null) {
            return this.error('Please enter an arrival date.');
        } else if (departureVal == 'dd/mm/yyyy' || departureVal == null) {
            return this.error('Please enter a departure date.');
        } else if (arrivalDate < today) {
            return this.error('Your arrival date is invalid.');
        } else if (departureDate < today) {
            return this.error('Your departure date is invalid.');
        } else if (departureDate < (arrivalDate.setDate(arrivalDate.getDate() + 1))) {
            return this.error('Please ensure your dates are valid for one night\'s stay.');
        }
        /* musn't of error'd, so let's get that form submitting! */
        return true;
    },
    error: function(error)  {
        
        if ($('#reservations').length) {
        
            if (!$('#reservations-error').length) {
                $('#reservations form').append('<div id="reservations-error"><span></span><p></p></div>');
            }
            
           
            
            $('#reservations-error p').text(error).parent().fadeIn(500);
            setTimeout(function() { $('#reservations-error').fadeOut(500) }, 2500);
            return false; /* don't let that form submit! */
            
        } else { // actual reservation form
        
            return error;
        
        }
    }
}


var liveFijiTime = {
    init: function() {
        var self = this;
        setInterval(function() { self.update(); }, 1000); 
    },
    update: function() {
        var offset = '+12';
        date = new Date();
        utc = date.getTime() + (date.getTimezoneOffset() * 60000);
    	nd = new Date(utc + (3600000 * offset));
        today = nd;
    	var minute = today.getMinutes();
    	var hour24   = today.getHours();
    	var ampm   = null;
    	var hour = null;
    	var day    = today.getDay();
    	if (minute < 10) {
    	   	minute = '0' + minute;
        }
    	if (hour24 < 12) {
    	   	ampm = 'am';
    	} else {
    	   	ampm = 'pm';
        }
        if (hour24 > 12) {
            hour = hour24 - 12;
        } else {
            hour = hour24;
        }
    	$('#fiji-time span').html(hour + ':' + minute + ampm);
    }
}

var slidingContent = {
    init: function() {
      var self = this;
      
      $('#content-body').addClass('non-slid');
      
      $('#body').find('#text > p:not(:first), ul, ol, h3, h4, h5, h6').addClass('temp-hide');
      
      $('#body p:first').after('<div id="show-more">More info &amp; pictures &rarr;</div>');
    
      var resBox = $('#reservations');
      
      
      resBox.insertAfter('#show-more');
    
    
      $('#show-more').bind('click', function() {
      
        self.slideOut();
      
      });
    
    },
    
    slideOut: function() {
    
        var self = this;
        
        $('#choice-award').hide();
        resPlaceholder = $('#online-reservations');
        
        if (resPlaceholder.length) {
        
            $('#reservations').insertBefore(resPlaceholder);
            resPlaceholder.remove();
        } else {
            $('#reservations').insertBefore('#text > p:last');
            
        }


        
       // $('#text > p:last').css('border', '2px solid red'); //before('<strong>hello</strong>');
        

        
        var contentObj = $('#content');
        var contentBodyObj = $('#content-body');
        var bodyObj = $('#body');
        
        var oldWidth = contentBodyObj.width();
        var newWidth = contentObj.width();
        
       contentBodyObj
        .css({left: '-' + (newWidth - oldWidth) + 'px'})
        .width(newWidth)
        .removeClass('non-slid')
        .addClass('slid');
        
        $('#show-more').hide();
        
        
        $('#body .temp-hide').removeClass('temp-hide');
        
        $('#text').jScrollPane({showArrows: true, scrollbarWidth: 15});


        
        contentBodyObj.animate({left: 0}, 1000);
        
        
    
    },
    
    slideIn: function() {
        var self = this;
        var contentWidth = $('#content').width();
        
        $('#content-body').animate({left: '-' + contentWidth + 'px'}, 500, function() {
            
            if (!$('#slide-back').length) {
            
                $('#content').append('<div id="slide-back" title="Take me back">Take me back</div>');
            
            }
            
            $('#slide-back')
            .show()
            .animate({left: '0'}, 800)
            .bind('click', function() {
                $(this).fadeOut(500);
                $('#content-body').animate({left: 0}, 1000);
            
            });
            
            
        
        });
    
    
    }

}

var images = {
    preloaded: {},
    init: function() {
        var self = this;
        if (!$('#content').hasClass('no-image')) {
            $('#content').append('<img src="' + $('#content').css('backgroundImage').replace(/^url|[\(\)]/g, '') + '" id="image-fade" alt="" />')
            $('#images li a').bind('click', function(event) {
                event.preventDefault();
                self.fetch($(this).attr('href'));
            });
        }
    },
    fetch: function(src) {
        loadingModal.show();
        slidingContent.slideIn();
        var self = this;
        if (typeof(this.preloaded[src]) == 'undefined') {
            self.load(src, function(){ self.show(src) });
        } else {
            self.show(src);
        }    
    }, 
    show: function(src) {
        var contentObj = $('#content');
        contentObj.css({backgroundImage: 'url(' + src  +')'});
		contentObj.find('#image-fade').show().fadeOut(1000, function() { $(this).attr({src: src}) });	
        loadingModal.hide();
    },
    load: function(src, callback) {
        var self = this;
        var image = new Image();
		$(image).load(function(){   
			self.preloaded[src] = true; // dont load it again next time
			callback();
		});
        image.src = src;
    }
}


var reservationsForm = {

    init: function() {
    
        
        var form =  $('.reservations #reservations-form');
    
        $.datepicker.setDefaults(DATEPICKER_OPTIONS);
        form.find('#input-arrival-date').datepicker();
        form.find('#input-departure-date').datepicker({defaultDate: +7});

        form
        .find('input[type=submit]')
        .hide()
        .after('<span class="button">Send<span></span></span>');
        
        form.
        find('span.button')
        .bind('click', function() {
            $(this).parents('form').submit();
        });
        
        form.bind('submit', function() { // bit of a hack this, but it was built AFTER the original specs said something quite different
            
            

            
            contacts.form = $(this);
            
            return contacts.validate();
        
        });
    
    
    }




}


var contacts = {
    form: null,
    init: function() {
    
        var self = this;
    
        
    
        $('#contacts .divider').before('<p class="bottom-button"><span class="button">Subscribe<span></span></span></p>');
        $('#enquiry-form .divider').before('<p class="bottom-button"><span class="button">Send<span></span></span></p>');
        $('#media-accred .divider').before('<p class="bottom-button"><span class="button">Login<span></span></span></p>');
        $('#agents .bottom').after('<p class="bottom-button"><span class="button">Login<span></span></span></p>');
   
        $('.column form').bind('submit', function() {
        
            return self.validate();
        
        });
   
        $('.column .button').bind('click', function() {
            
            self.form = $(this).parents('.column').find('form');
            self.form.submit();
        
        });

                
        
   
    },
    
    validate: function() {
        var self = this;
        var fields = {};
        var nameRegex = /^[a-z-'\s]{2,}$/i // ' stupid Coda 
        var emailRegex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
        var enquiryRegex = /^(.|\n){5,}$/;

        
        $(self.form).find('input[type=text], input[type=password], textarea').each(function() {
            name = $(this).attr('name');
            val = $(this).val();
        
            fields[name] = val;
        
        });
        
             
        var errors = [];
        
        // hacky, leverages validation in reservation object
        
        if ($('#reservations-form').length) {
        
            reservations.form = this.form;
            
            var resErrors = reservations.checkDates();
            
            
            if (resErrors != true) {
            
                errors.push(resErrors);
            }
        
        }
        
        
        // test for name
        if (typeof(fields.name) == 'string' && !fields.name.match(nameRegex) ) {
        
            errors.push('You need to enter a valid name.')
        } 
        
        // test for email
        if (typeof(fields.email) == 'string' && !fields.email.match(emailRegex) ) {
        
            errors.push('You need to enter a valid email.')
        } 
        
        // test for enquiry
        if (typeof(fields.enquiry) == 'string' && !fields.enquiry.match(enquiryRegex) ) {
        
            errors.push('You need to enter an enquiry.')
        } 
        
        // test for login
        if (typeof(fields.login) == 'string' && !fields.login.match(nameRegex) ) { // just use the name one again here
        
            errors.push('You need to enter your login.')
        } 
        
        // test for password
        if (typeof(fields.password) == 'string' && !fields.password.match(nameRegex) ) { // just use the name one again here
        
            errors.push('You need to enter your password.')
        }
        
        if (errors.length) { // error present
            
            self.showErrors(errors);
            
            return false;
        
        } else {
    
            // no errors, too easy
            return true;
    
        }
    
    },
    
    showErrors: function(errors) {
    
        if (!$('#contact-errors').length) {
        
            $('body').append('<div id="contact-errors"><strong>Error</strong><p>Sorry, the following errors have occured:</p></div><div id="overlay"></div>');
        
        }
        
        var overlay = $('#overlay');
        var errorBox = $('#contact-errors');
        
        errorBox.hide().find('ul').empty();
        
        var errorsList = '<ul>';
        
        $.each(errors, function(i) {
        
           errorsList += '<li>' + errors[i] + '</li>';
        
        });
        
        errorsList += '</ul>';
        
        
        errorBox.append(errorsList).show();
        
        //errorBox.fadeOut(2000);
        
        
        overlay.hide().fadeIn(1000, function() {
        
            setTimeout(function() {
                errorBox.hide();
                overlay.fadeOut(1000);
            }, 2500);
        
        });
    
    
    }

}

var externalLinks = {
	newWindowTitleText: 'Link opens in a new window',
	init: function() {
		var self = this;
		$('a[rel=external]').each(function() { 
										   
										   if ($(this).attr('title')) {
			   									newTitle = $(this).attr('title') + ' (' + externalLinks.newWindowTitleText + ')';
										   } else {
												newTitle = externalLinks.newWindowTitleText;   
										   }
										   $(this).attr('title', newTitle).bind('click', function() {  
																		  self.openNewWindow($(this).attr('href'));
																		  return false;
																		  }) 
										   });
	},
	
	openNewWindow: function(Uri) {
		var newBlankWindow = window.open(Uri, '_blank');
		newBlankWindow.focus();	
	
	}
	
}





/* loading modal that overlays when ajax'ing */
var loadingModal = {
    show: function() {
        if(!$('#loading-modal').length) {
            $('#content').append('<div id="loading-modal"><strong title="Getting data...">Please wait patiently...</strong></div>');
        }
        $('#content #loading-modal').fadeIn(500);
    },
    hide: function() {
        $('#content #loading-modal').fadeOut(500);
    }
}