/**
 * DOM Utilies Object for handling basic DOM actions
 * @author					Dave Shepard
 * @version					1.0
 * @required libraries:		JQuery 1.3.2 or later
 * 
 * Usage:
 *     $(document).ready(function(){
 *     		DOMUtilities.init();
 *     });
 *     
 * Can be initialized via the init(); method to apply to entire <body> or
 * a scope can be passed to limit the initialization to the child elements
 * of a particular element. Individual methods can als be called and passed
 * a scope.
 */
var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$(locality+' a[rel*="external"]').attr("target","_blank");
	},
	inputAutoClear: function(locality){
		$(locality+' input.clearField').focus(function(){
			if(this.defaultValue == this.value) this.value='';
		}).blur(function(){
			if(this.value == '') this.value = this.defaultValue;
		});
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver')
			.mouseover(function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).mouseout(function(){
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if(this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.","_i.");
				}
			}).filter("input").mousedown(function(){
				this.src = this.src.replace("_o.","_a.");
			}).mouseup(function(){
				this.src = this.src.replace("_a.","_i.");
			});
	},
	init: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}

var gallery = {
    startwidth: [],
    startheight: [],
    intervalSpeed: 10000,
    animateHandler: 0,
    animating: false,
    els: {},
    
    change: function(currentImage, nextImage){
        var self = this;

        currentImage.removeClass('active');
        nextImage.addClass('active');
       
        //Check to see if browser is IE, if so Show instead of Fade
        if (this.isMSIE == true){
            nextImage.show();
            currentImage.hide();
            self.animating = false;
        } else {
            nextImage.stop().fadeIn('normal', function(){
                currentImage.hide();
                self.animating = false;
            });            
        }
    },
    
    goTo: function(imageIndex){
        var currentImage = this.els.images.filter('.active');
        var nextImage = this.els.images.eq(imageIndex);

        //Stop animating
        clearInterval(this.animateHandler);
        
        //Run change animation
        this.change(currentImage, nextImage);
    },
    
    nextslide: function(){
        var currentImage = this.els.images.filter('.active');
        var nextImage = currentImage.next();
        
        //Check to see if last image, if so set first image as next
        if(nextImage.length == 0){
            nextImage = this.els.images.first();
        }
        //Get index of gallery image and set thumbnail as active
        var gallIndex = this.els.images.index(nextImage);        
        this.els.thumbs.removeClass('active');
        this.els.thumbs.eq(gallIndex).addClass('active');
        
        //Run change animation
        this.change(currentImage, nextImage);
    },
    
    resizenow: function(){
        var realWidth = this.els.window.width();
        var rightColWidth = this.els.rightCol.width();
        var browserwidth = Math.max(realWidth - rightColWidth, 457);
        var browserheight = this.els.wrapper.height() - 100 - this.els.header.outerHeight();
        
        for(var i = 0; i < this.els.imageObjects.length; i++){
            var img = this.els.imageObjects[i];
            
            //Define image ratio
            var ratio = this.startheight[i]/this.startwidth[i];
            
            //Gather browser and current image size
            var imagewidth = img.width();
            var imageheight = img.height();
            
            //Resize image to proper ratio
            if((browserheight/browserwidth) > ratio){
                this.els.gallery.height(browserheight);
                img.height(browserheight).css({
                    left: '50%',
                    marginLeft: 0 - imagewidth/2 - rightColWidth/2,
                    top: '50%',
                    marginTop: 0 - imageheight/2,
                    width: 'auto'
                });
            } else {
                this.els.gallery.height(browserheight);
                img.width(browserwidth + 40).css({
                    left: '50%',
                    marginLeft: 0 - (browserwidth + 40)/2 - rightColWidth/2,
                    top: '50%',
                    marginTop: 0 - imageheight/2,
                    height: 'auto'
                });
            }
        }
    },
    
    init: function(){
        var self = this;
        
        this.isMSIE = (navigator.userAgent.indexOf ( "MSIE" ) != -1);

        this.els.window = $(window);
        this.els.wrapper = $('#wrapper');
        this.els.gallery = $('#gallery');
        this.els.galleryMenu = $('#gallery_menu');
        this.els.thumbs = this.els.galleryMenu.find('a.galleryThumb');
        this.els.images = this.els.gallery.children('img');
        this.els.viewGalleryContainer = this.els.galleryMenu.find('#view_gallery_container')
        this.els.galleryPicker = this.els.galleryMenu.find('#gallery_picker');
        
        this.els.imageObjects = [];
        for(var i = 0; i< this.els.images.length; i++){
            var img = $(this.els.images[i]);
            this.els.imageObjects.push(img);
            this.startheight.push(parseInt(img.attr('height')));
            this.startwidth.push(parseInt(img.attr('width')));
        }
        
        if(document.getElementById('hotel_info')){
            this.els.rightCol = this.els.wrapper.find('#hotel_info');
        } else {
            this.els.rightCol = this.els.wrapper.find('#right_col');
        }
        
        this.els.header = $('#header');
        
        //Bind resize to window
        this.els.window.resize(function(){
    		self.resizenow();
            setTimeout(function(){
                gallery.resizenow();
            },10);
    	});
        
        //Check to see if there are multiple images
        if(this.els.images.length > 1){
            this.els.images.first().addClass('active');
            this.els.images.not(':first').hide();
            self.animateHandler = setInterval( 'gallery.nextslide()', self.intervalSpeed );
        }
        
        //Bind Click to thumbnails if they exist
        if(this.els.thumbs.length){
            this.els.thumbs.bind('click', function(e){
                e.preventDefault();
                $this = $(this);
                
                if(!self.animating){
                    self.animating = true;
                    var imageIndex = self.els.thumbs.index($this);
                    self.els.thumbs.removeClass('active');
                    $this.addClass('active');
                    self.goTo(imageIndex);
                }
            });
        }
        
        //Gallery Flyout show/hide 
        if(this.els.galleryMenu.length){
            this.els.galleryMenu.find('#view_gallery').bind('click', function(e){
                e.preventDefault();
                if(self.isMSIE){
                    self.els.viewGalleryContainer.css({left: 0}).hide();
                    self.els.galleryPicker.css({left: 0}).show();
                } else {
                    self.els.viewGalleryContainer.animate({
                        left: '-117px'
                    }, function(){
                        self.els.galleryPicker.animate({
                            left: '0px'
                        });
                    });
                }
            });            
            this.els.galleryMenu.find('#close_gallery').bind('click', function(e){
                e.preventDefault();
                if (self.isMSIE) {
                    self.els.viewGalleryContainer.css({left: 0}).show();
                    self.els.galleryPicker.css({left: 0}).hide();
                } else {
                    self.els.galleryPicker.animate({
                        left: '-297px'
                    }, function(){
                        self.els.viewGalleryContainer.animate({
                            left: '0px'
                        });
                    });
                }
            });
        }
        
        this.resizenow();
        setTimeout(function(){
            gallery.resizenow();
        },10);
        this.els.window.load(function(){
            self.resizenow();
            $('#gallery-logo').fadeOut();
        });
    }    
}

$(document).ready(function(){
	DOMUtilities.init();
    gallery.init();
    
    var UA = navigator.userAgent.toLowerCase();
    var isIE6 = (UA.match(/msie 6/) && !UA.match(/msie 7|8/) && !UA.match(/chrome/)) ? true : false;
    
    if(isIE6){
        if(document.getElementById('jdv_nav')){
            $('#jdv_nav').bind('mouseenter mouseleave', function(event){
                if(event.type == "mouseenter"){
                    $(this).find('.dropdown').show();
                } else {
                    $(this).find('.dropdown').hide();
                }
            });
        }
    }
    
    if(document.getElementById('testimonial_list')){
        $('#testimonial_list').cycle({
            pager: '#testimonial_list_nav',
            pause: true,
            height: 100,
            contentResize: 0,
            delay: 2500,
			timeout: 10000
        });
    }
    
    if(document.getElementById('hotel_detail_booknow') && document.getElementById('book_now_modal')){
        $('#hotel_detail_booknow').click(function(e){
            e.preventDefault();
            $('#book_now_modal').fadeIn('normal');
            return false;
        });
        $('#book_now_modal a.close').click(function(e){
            e.preventDefault();
            $('#book_now_modal').fadeOut('normal');
            return false;
        });
    }
    if(document.getElementById('bookingform_date_picker')){
        var $bookingform_date_picker = $('#bookingform_date_picker').datepicker({
            onSelect: function(){
                var date = this.value;
                var datePieces = date.split("/");
                
                document.getElementById('data_stay_month').value = datePieces[2] + "_" + datePieces[0];
                document.getElementById('data_stay_day').value = datePieces[1];
            }
        });
        
        $('#book_now_form').find('.btn.btnCalendar').bind('click', function(event){
            event.preventDefault();
            $bookingform_date_picker.datepicker('show');
        });
    }
    
    if(typeof(jQuery.fn.fancybox) == 'function'){
        $('a.vTour').fancybox({
            padding: 10,
            width: 572,
            height: 667,
            autoScale: false,
            titleShow: true,
            title: "Virtual Tour",
            type: 'iframe'
        });
    }
});
