// ten80r core.js


var ten80r = function(){

  return {
    animationSettings: {
		  duration: 1.5,
			easing: 'easeIn',
			callback: function(){
			  ten80r.sliderRunning = false;
			}
		},
		sliderRunning: false,
		initialSlidePause: 8000,
		slidePause: 8000,
		calendarLock: false,
		noAction: true,
		pagelockTimeout: null, 
    
		init: function(){
			this.setContentHeight();
			this.setCarouselPosition();
			if(this.isProperty === true) {
				this.setBookingHandlers();
		    this.setPricingHandlers();
				this.setLocationMapHandler();
				this.initController();
			}
			
			this.setLanguageHandler();
			this.initMask();
			this.initNav();
			this.showNav.defer(300, this);
			this.showContent.defer(500, this);
			if(this.pageType == 'contact'){
				this.initContact();
			}
			if(this.hasCarousel === true){
				Ext.get('new-prev').on('click', doPrev);
			  Ext.get('new-next').on('click', doNext);
				//Ext.fly('new-next').on('click', doNext);
			}
			if(this.pageType == 'home'){
				this.initSlideshow();
			}
			if(Ext.isMac && !Ext.isSafari){
			  Ext.fly('container').addClass('ff-mac');
			}
			this.initSearch();			

		},
		
		initController: function(){
			
		},
		
		initSearch: function(){
		  Ext.get('nav-search').on('click', this.launchSearch, this);
			this.dateFormat = '%d-%m-%Y';
			this.fromDate = Ext.get('from-date');
			this.fromDate.dom.value = '';
			this.fromDate.on('focus', this.launchFromCalendar, this);
			this.toDate = Ext.get('to-date');
			this.toDate.dom.value = '';
			this.toDate.on('focus', this.launchToCalendar, this);		
			Ext.get('search-submit').on('click', this.submitSearch, this);
		},
		
		launchSearch: function(){
		  this.showMask();
			Ext.fly('search-form-wrapper').fadeIn({ duration: 1 });
		},
		
		launchFromCalendar: function(){
		  this.cal1 = this.fromDate.dom;
			this.cal1pos = RichCalendar.get_obj_pos(this.cal1);
			this.richCal1 = new RichCalendar();
			this.richCal1.auto_close = true;
	    this.richCal1.user_onchange_handler = this.searchFromDateChangeHandler;
	    this.richCal1.show(this.cal1pos[0]-32, this.cal1pos[1]+30);
		},
		
		searchFromDateChangeHandler: function(cal){
		  ten80r.searchFromDateChange(cal);
		},
		
		searchFromDateChange: function(cal){
			this.searchFromDate = cal.get_formatted_date(this.dateFormat);
		  this.fromDate.dom.value = this.searchFromDate;
			//cal.hide();
			cal = null;
			this.richCal1 = null;
		},
		
		launchToCalendar: function(){
		  this.cal2 = this.toDate.dom;
			this.cal1pos = RichCalendar.get_obj_pos(this.cal2);
			this.richCal1 = new RichCalendar();
			this.richCal1.auto_close = true;
	    this.richCal1.user_onchange_handler = this.searchToDateChangeHandler;
	    this.richCal1.show(this.cal1pos[0]-32, this.cal1pos[1]+30);
		},
		
		searchToDateChangeHandler: function(cal){
		  ten80r.searchToDateChange(cal);
		},
		
		searchToDateChange: function(cal){
			this.searchToDate = cal.get_formatted_date(this.dateFormat);
		  this.toDate.dom.value = this.searchToDate;
			//cal.hide();
			cal = null;
			this.richCal1 = null;
		},
		
		submitSearch: function(){
			Ext.get('search-results').update('searching availability...');
			window.location = "/"+LANG+"/search-new/?from="+this.searchFromDate+"&to="+this.searchToDate;
			return;
			Ext.Ajax.request({
				url: '/php/search.php',
				method: 'post',
			  params: {
				  from: this.searchFromDate,
					to: this.searchToDate
				},
				success: ten80r.searchResponse
			});
			//window.location = '/search/?from='+this.searchFromDate+'&to='+this.searchToDate;
		},
		
		searchResponse: function(response){
		  var availableProperties = eval(response.responseText);
			var html = '';
			for(var i=0; i<availableProperties.length; i++){
			  var el = Ext.get('portfolio-'+availableProperties[i]);
				if(el){
					html +=el.dom.innerHTML;
				}
			}
			if(html == ''){
				Ext.get('search-results').update('We have no availability for the dates specified.');
			} else {
			  Ext.get('search-results').update(html);
			}
		},
		
		initSlideshow: function(){
			this.slidePos = 1;
			this.slideCount = Ext.fly('frame').select('.slide').getCount();
		  this.nextSlide.defer(this.initialSlidePause, this);
		},
		
		nextSlide: function(){
			var currentSlide = Ext.fly('slide-'+this.slidePos);
			currentSlide.fadeOut({duration: 1});
			this.slidePos++;
      if(this.slidePos >= this.slideCount) this.slidePos = 1;
			var nextSlide = Ext.fly('slide-'+this.slidePos);
			nextSlide.fadeIn({duration: 2});
		  this.nextSlide.defer(this.slidePause, this);
		},
		
		setContentHeight: function(){
		  var h = 0;
			Ext.get('contents').select('.content').each(function(el){
        var newH = el.getHeight();
				if(newH > h){
				  h = newH;
				}
			});
			Ext.get('contents').setHeight(h + 30);
		},
		
		setLocationMapHandler: function(){
		  var el = Ext.fly('show-location');
			if(el != null){
			  el.un('click', this.showLocationMap, this);
				el.on('click', this.showLocationMap, this);
			}
		},
		
		showLocationMap: function(){
		  this.showMask();
			Ext.fly('location-full').fadeIn({ duration: 1 });
		},
		
		toggleScroll: function(){
			var el = Ext.get('scroll-marker');
			if(el.hasClass('scrolled')){
				window.scrollTo(0,0);	
			} else {
			  //Ext.fly(document).scrollTo('top', 2000); // not working for some reason
				window.scrollTo(0,2000);	
			}
			el.toggleClass('scrolled');
		  
		},
		
		onAjaxRequest: function(){
		  this.showMask();
		},
		
		onAjaxFailure: function(){
		  alert('transport failure, please try again');
			this.hideMask();
		},
		
		initContact: function(){
		  Ext.fly('basic-contact-submit').on('click', this.basicContactSubmit, this);
			Ext.fly('callback-submit').on('click', this.callbackSubmit, this);
			Ext.Ajax.on('beforerequest', this.onAjaxRequest, this);
      Ext.Ajax.on('requestcomplete', this.handleAjaxResponse, this);
      Ext.Ajax.on('requestexception', this.onAjaxFailure, this);
		},
		
		basicContactVerify: function(){
		  return true;
		},
		
		basicContactSubmit: function(){
		  if(!this.basicContactVerify()) return;
			Ext.Ajax.request({
				url: '/php/basic-contact.php',
			  form: 'basic-contact',
				success: ten80r.basicContactResponse,
				params: null
			});
		},
		
		basicContactResponse: function(con, response, opts){
		  var el = Ext.fly('basic-contact-form-wrapper').hide();
			el.dom.innerHTML = '<div class="ajax-response">We have received your enquiry, thank you.</div>';
			el.fadeIn({duration: 1}).highlight();
			//if(Ext.isIE) setTimeout("window.location.reload();", 3000);
		},
		
		bookingVerify: function(){
		  return true;
		},
		
		bookingSubmit: function(){
		  if(!this.bookingVerify()) return;
			Ext.Ajax.request({
				url: '/php/booking-contact.php',
			  form: 'booking-form',
				success: ten80r.bookingResponse,
				params: null
			});
			Ext.fly('booking-form-wrapper').fadeOut();
		},
		
		bookingResponse: function(con, response, opts){
		  var el = Ext.fly('booking-reponse');
			el.dom.innerHTML = 'We have received your enquiry, thank you.';
			el.fadeIn({duration: 1});
		  ten80r.hideMask.defer(3000, ten80r);
		},
		
		callbackVerify: function(){
		  return true;
		},
		
		callbackSubmit: function(){
		  if(!this.basicContactVerify()) return;
			Ext.Ajax.request({
				url: '/php/callback-contact.php',
			  form: 'callback-form',
				success: ten80r.callbackResponse,
				params: null
			});
		},
		
		callbackResponse: function(con, response, opts){
		  var el = Ext.fly('callback-form-wrapper').hide();
			el.dom.innerHTML = '<div class="ajax-response">We have received your request, thank you. We look forward to speaking to you shortly.</div>';
			el.fadeIn({duration: 1}).highlight({});
			
		},
		
		handleAjaxResponse: function(con, response, opts){
			this.hideMask();
		},
		
		setCarouselPosition: function(){
			var spot = window.location.href.split('#');
			var num = 0;
			if(spot[1]){
				var urlNum = parseInt(spot[1]);
				var numberOfSlides = Ext.select('.content').getCount();
				var slideShift = urlNum % numberOfSlides;
				//var num = (Math.floor(setupNum / numberOfSlides)) + (urlNum % numberOfSlides);
				//alert(slideShift);
				var num = slideShift;
				if(num > 0){
					for(var i=0; i < num; i++){
						doNext(true);
					}
				} else {
					for(var i=0; i > num; i--){
						doPrev(true);
					}
				}
			}
			this.carouselPos = num;
		},
		
		setBookingHandlers: function(){
			Ext.fly('contents').select('.button-enquire').each(function(el){
        el.on('click', this.showBookingOptions, this);
			}, this);
			Ext.fly('booking-submit').on('click', this.bookingSubmit, this);
		},
		
		setLanguageHandler: function(){
		  var el = Ext.get('language');
			el.on('click', ten80r.showLanguageOptions, ten80r);
			Ext.fly('language-select').select('.language-option').each(function(element){
        element.on('click', this.hideMask, this);
			}, this);
			
			
		},
		
		showLanguageOptions: function(){
		  this.showMask();
			Ext.get('language-select').fadeIn({duration: .3});
		},
		
		showBookingOptions: function(e, el){
			ten80r.noAction = false;
		  this.showMask();
			var name = e.getTarget('.new-header', null, true).child('.enquire-name', null, true).dom.innerHTML;
			//var details = el.abbr.split(';');
			//Ext.fly('bf-year').dom.value = details[0];
			//Ext.fly('bf-week').dom.value = details[1];
			//Ext.fly('bf-price').dom.value = details[2];
			//Ext.fly('booking-week').dom.innerHTML = details[1];
			//Ext.fly('booking-year').dom.innerHTML = details[0];
			//Ext.fly('booking-details').dom.innerHTML = el.abbr;
			Ext.fly('booking-property-name').update(name);
			Ext.fly('booking-reponse').hide();
			Ext.fly('booking-form-wrapper').fadeIn({ duration: .4});
			Ext.get('booking-select').fadeIn({ duration: .4});

			
			
		},
		
		initMask: function(){
			this.mask = Ext.get('mask');
			//this.mask.on('click', this.hideMask, this);
			this.mask.select('.mask-close').each(function(el){
        el.on('click', this.hideMask, this);
			}, this);
		},
		
		initNav: function(){
			this.nav = Ext.get('nav');
			//this.quickPortfolio = Ext.get('portfolio-quickview');
			//this.quickPortfolio.hover(function(){}, this.hideQuickPortfolioNav, this);
			//this.navToggle = Ext.get('navToggle');
			//this.navToggle.on('click', this.toggleNav, this);
			//Ext.get('nav-portfolio').hover(this.showQuickPortfolioNav, function(){}/*this.hideQuickPortfolioNav*/, this);
			//this.quickPortfolio.on('click', this.showQuickPortfolio, this);
		},
		
		showMask: function(dur, opacity){
			//dur = dur || .2;
			//opacity = opacity || .98
			Ext.fly('contents').hide();
		  this.mask.fadeIn({duration: .2, endOpacity: .98});
		},
		
		hideMask: function(dur){
			//dur = dur || .1;
			Ext.fly('contents').show();
			this.mask.select('.mask-content').each(function(el){ el.dom.style.display = 'none'; });
			Ext.getBody().select('.rc_calendar').each(function(el){ el.dom.style.display = 'none'; });
		  this.mask.fadeOut({duration: .1, endOpacity: 0, remove: false, useDisplay: true });
			
		},
		
		toggleNav: function(){
			if(this.navToggle.hasClass('hideNav')){
		    this.nav.setHeight(0, {duration: .2});
			} else {
			  this.nav.setHeight(95, {duration: .2});
			}
			this.navToggle.toggleClass('hideNav');
		},
		
		showNav: function(){
		  Ext.fly('nav').fadeIn({duration: .6, endOpacity: 1});
		},
		
		showFrame: function(){
		  Ext.fly('frame').fadeIn({duration: .6, endOpacity: 1});
			if(this.hasCarousel === true){
		    this.showClickPrevNext.defer(1000);
			}
		},
		
		showHeaders: function(){
		  Ext.fly('headers').fadeIn({duration: .6, endOpacity: 1});
		},
		
		showContent: function(){
		  Ext.fly('contents').fadeIn({duration: .6, endOpacity: 1});
		},
		
		showClickPrevNext: function(){
		  //Ext.fly('click-prev').fadeIn({duration: 1}); //.highlight();
			//Ext.fly('click-next').fadeIn({duration: 1}); //.highlight();
		},
		
		setPricingHandlers: function(){	
			return;
			Ext.fly('calendar-prev').on('click', this.calendarPrev, this);
			Ext.fly('calendar-next').on('click', this.calendarNext, this);
		},
		
		unsetPricingHandlers: function(){	
			return;
			Ext.fly('calendar-prev').un('click', this.calendarPrev);
			Ext.fly('calendar-next').un('click', this.calendarNext);
		},
		
		calendarPrev: function(){
        if(this.calendarLock === true){
					return;
				}
				this.calendarLock = true;
				var anim = {duration: 2};
				var el = Ext.fly('cal-showing');
				this.calendarUnlock.defer(500, this);
				if(el.hasClass('first')) return;
				var prevEl = el.prev();
				el.setY(el.getTop() + 200, anim).dom.id = '';
				prevEl.setY(prevEl.getTop() + 200, anim).dom.id = 'cal-showing';

		},
		
		calendarNext: function(){
        if(this.calendarLock === true){
					return;
				}
				this.calendarLock = true;
				var anim = {duration: 2};
				var el = Ext.fly('cal-showing');
				this.calendarUnlock.defer(500, this);
				if(el.hasClass('last')) return;
				var nextEl = el.next();
				el.setY(el.getTop() - 200, anim).dom.id = '';
				nextEl.setY(nextEl.getTop() - 200, anim).dom.id = 'cal-showing';
				
		},
		
		calendarUnlock: function(){
		  this.calendarLock = false;
		},
		
		checkPrevNext: function(){
		  /*if(Ext.fly('pic-showing').next().hasClass('skip-me')){
				Ext.get('click-next').hide();
			} else {
				Ext.get('click-next').show();
			}
			if(Ext.fly('pic-showing').prev().hasClass('skip-me')){
				Ext.get('click-prev').hide();
			} else {
				Ext.get('click-prev').show();
			}*/
		}
		
	}

}();


Ext.onReady(function() {
	ten80r.init();
	
	if(ten80r.hasCarousel === true){
		
		// and the content
		var foundFirst = false;
		var i = 0;
		Ext.fly('contents').select('.content').each(function(el){
			i++;
			if(el.dom.id == 'content-showing'){
				foundFirst = true;
			} else if(foundFirst == false){
				el.setLeft(-996, false);
			} else {
				el.setLeft(996, false);
			}
		});
	}
	
});



function setPricingHandlers(){	
  Ext.fly('calendar-prev').on('click', function(){
    var anim = {duration: 1, callback: function(){}};
		var el = Ext.fly('cal-showing');
		if(el.hasClass('first')) return;
		var prevEl = el.prev();
		el.setY(el.getTop() + 190, anim).dom.id = '';
		prevEl.setY(prevEl.getTop() + 190, anim).dom.id = 'cal-showing';
	});
	Ext.fly('calendar-next').on('click', function(){
    var anim = {duration: 1.5};
		var el = Ext.fly('cal-showing');
		if(el.hasClass('last')) return;
		var nextEl = el.next();
		el.setY(el.getTop() - 190, anim).dom.id = '';
		nextEl.setY(nextEl.getTop() - 190, anim).dom.id = 'cal-showing';
	});
}

function setPricingDisplay(id){
  //Ext.get('month-display').dom.innerHTML = html;
	Ext.get('prices-wrapper').select('.pricing-table').hide();
	var el = Ext.fly(id);
	if(el!=null){
		el.fadeIn({duration: .3});


	}
}

function showPricing(){
  Ext.get('calendar').fadeIn({duration: .2});
	Ext.fly('calendar-next').highlight();
}
function hidePricing(){
  Ext.get('calendar').dom.style.display = 'none';
}


function doNext(noAdd, force){
	  if(ten80r.sliderRunning == true && force != true) return;
		ten80r.sliderRunning = true;
		var basicLeft = Ext.get('contents').getLeft();
		var currentEl = Ext.fly('content-showing');
		var nextEl = currentEl.next();
		var swapEl = Ext.get('contents').first();
		
		
    // move the current one out of the way
		currentEl.setX(basicLeft - 700, ten80r.animationSettings)
		currentEl.dom.id = '';
		nextEl.setX(basicLeft, ten80r.animationSettings)
		nextEl.dom.id = 'content-showing';
		
		
		
		/*
		var nextIdEl = nextEl.select('.property-id').item(0);
		if(nextIdEl != null){
		  
		} else {
			hud.revert();
		}
    */
		Ext.DomHelper.append('contents', {
      tag: 'div',
      cls: swapEl.dom.className,
      html: swapEl.dom.innerHTML
		});
	  
	  // move the back one round
		swapEl.remove();
		ten80r.checkPrevNext.defer(200);
		/*		
		if(Ext.fly('pic-showing').hasClass('skip-me')){
			doPrev.defer(300);
		}
		*/
		
		
		
		ten80r.setLocationMapHandler();
		
		hud.notify();
		
		if(nextEl.hasClass('skip-me')) doNext(null, true);
		
		
};

function doPrev(noSubtract, force){
	  if(ten80r.sliderRunning == true && force != true) return;
    ten80r.sliderRunning = true;
		var basicLeft = Ext.get('contents').getLeft();
		var currentEl = Ext.fly('content-showing');
		var nextEl = currentEl.prev();
		var swapEl = Ext.get('contents').last();
		
    
		currentEl.setX(basicLeft + 700, ten80r.animationSettings);
		currentEl.dom.id = '';
		

		nextEl.setX(basicLeft, ten80r.animationSettings);
		nextEl.dom.id = 'content-showing';
    // move the current one out of the way
		
		
    
		Ext.DomHelper.insertFirst('contents', {
      tag: 'div',
      cls: swapEl.dom.className,
			style: 'left:-996px',
      html: swapEl.dom.innerHTML
		});
	  
	  // move the back one round
		swapEl.remove();
		
		ten80r.checkPrevNext.defer(200);
		
		ten80r.setLocationMapHandler();
		
		hud.notify();
		
		if(nextEl.hasClass('skip-me')) doPrev(null, true);
		
		
		
	};

