/* 
	Author: Pablo Martínez Novelo
	Website: http://greenlabs.com.mx
*/

//defines a new method for the array class to search occurrencies in it
Array.prototype.hasInArray = function(value) {
	var i;
	for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
		if (this == value) {
			return true;
		}
	}
	return false;
};
var appProgressBar = function(){
	//progressBar
	var setProgressBar = function(step){
		var progress = $('div#progress');
		progress.animate({width: step}, 'slow');
	}
	
	return{
		init: function(step){
			setProgressBar(step);
		}
	}
}
/*============================================== Home =====================================================*/
var homeScript = function(){

	var initialize = function(div, lat, longi) {
		var latlng = new google.maps.LatLng(lat, longi);
		var centerPos = new google.maps.LatLng(20.923823, -86.961946);
	    var myOptions = {
	      	zoom: 10,
	      	center: centerPos,
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
			},
			panControl: false,
			zoomControl: true,
			scaleControl: true,
	      	mapTypeId: google.maps.MapTypeId.HYBRID
	    };
	    var map = new google.maps.Map(document.getElementById(div), myOptions);
		map.setTilt(45);
		var marker = new google.maps.Marker({
		      position: latlng, 
		      map: map, 
		      title:"Jolie Jungle Ecolodge"
		  });
	}
	
	var bindEvents = function(){
		$('button.callToReserve').live('click', function(event) {
			var lang = $.trim($('div#lang').text());
			window.location = 'http://www.joliejungle.com/reservaciones/date_select/'+lang;
		});
	}
	
	var onloadExec = function(){
		initialize("locationMap", 20.924362, -87.128453);
		bindEvents();
	}
	
	return {
		init:onloadExec
	}
}
/*==============================================Gallery sliders in Rooms and Services====================================*/
var gallerySliders = function(){
	
	var bindEvents = function(){
		$("div#gallery").slides({
			play: 5000,
			paginationClass: 'pagUl',
			effect: 'fade'
		});
	}
	
	var onloadExec = function(){
		bindEvents();
	}
	
	return {
		init:onloadExec
	}
}
/*==============================================Dialogs in gallery====================================*/
var galleryDialogs = function(){
	
	var bindEvents = function(){
		$("a.galImg").fancybox();
	}
	
	var onloadExec = function(){
		bindEvents();
	}
	
	return {
		init:onloadExec
	}
}
/*============================================== Contact NAMESPACE =====================================================*/
var contactScript = function(){
	
	var host = 'http://www.joliejungle.com/';
	
	var bindEvents = function(){
		$('input#contactSubmitBot').live('click', function(event) {
			event.preventDefault();
			var contactObject = '';
			$('form#contactForm :input').each(function(index) {
				if($(this).is(':text, textarea')){
					contactObject += $(this).attr('name')+"="+$(this).val()+"&";
				}
			});
			contactObject = contactObject.substring(0, contactObject.length-1);
			contactSubmit(contactObject);
		});
	}
	
	var contactSubmit = function(contactObject){
		var preloaderWhite = $('img#preloaderWhite');
		$('input#contactSubmitBot').fadeOut('fast', function(){
			preloaderWhite.clone().appendTo('p#submit').addClass('temp');
		});
		$.ajax({
			url: host+'contact/sendContact/',
			type: 'POST',
			dataType: 'text',
			data: contactObject,
			success: function(data, textStatus, xhr) {
				$('.temp').remove();
				$('input#contactSubmitBot').fadeIn('fast');
				var msg = "Your message was sent successfully! / Su mensaje fué enviado exitosamente!";
				alert(msg);
				$('form:input').each(function(index) {
					$(this).val('');
				});
			},
			error: function(xhr, textStatus, errorThrown) {
				$('.temp').remove();
				log(errorThrown);
			}
		});
	}
	
	var onloadExec = function(){
		bindEvents();
	}
	
	return {
		init:onloadExec
	}
}
/*==============================================Dates selection NAMESPACE =====================================================*/
var selectDates = function(){
	
	//animates de progress bar
	var setProgress = function(progressPctg){
		var progress = $('div#progress');
		if (progress.width() < progressPctg) {
			progress.animate({width: progressPctg}, 'slow');
		}
	}
	
	var setMessage = function(step){
		var message = $('p#progressMsg');
		switch(step){
			case 1:
				message.text($('li#book_step_1').text());
				break;
			case 2:
				message.text($('li#book_step_2').text());
				break;
			case 3:
				message.text($('li#book_step_3').text());
				break;
			case 4:
				message.text($('li#book_step_4').text());
				break;
			default:
				message.text($('li#book_step_1').text());
		}
	}

	//binds all events in page
	var bindEvents = function(){
		$('input.datepicker').datepicker({
			numberOfMonths: 2
		});
		$('img.calpicker').live('click', function(event) {
			$(this).siblings('input').focus();
		});
		$( "div#adultSlider" ).slider({
			value:1,
			min: 1,
			max: 5,
			step: 1,
			slide: function( event, ui ) {
				$( "input#adults" ).val(ui.value);
				setProgress(300);
				setMessage(4);
			}
		});
		$( "div#childSlider" ).slider({
			value:0,
			min: 0,
			max: 3,
			step: 1,
			slide: function( event, ui ) {
				$( "input#children" ).val(ui.value);
				setProgress(300);
			}
		});
		$( "div#roomSlider" ).slider({
			value:1,
			min: 1,
			max: 3,
			step: 1,
			slide: function( event, ui ) {
				$( "input#rooms" ).val(ui.value);
				setProgress(300);
			}
		});
		$('input#checkIn').change(function() {
			var progress = $('div#progress');
			if (progress.width() < 100) {
				progress.animate({width: 100}, 'slow');
				setMessage(2);
			}
		});
		$('input#checkOut').change(function() {
			var progress = $('div#progress');
			if (progress.width() < 200) {
				progress.animate({width: 200}, 'slow');
				setMessage(3);
			}
		});
	}
	
	var onloadExec = function(){
		setMessage(1);
		bindEvents();
	}
	
	return {
		init:onloadExec
	}
}

/*==========================================RESERVATION SELECTION, selectReservation NAMESPACE=====================================================*/
var selectReservation = function(){
	
	var bookData = {};
	var noAllotment = false;
	var noAllotmentType = new Array();
	var roomSelectProgress = false; //room selection progress for progressbar
	var host = 'http://www.joliejungle.com/'
	log('cambiar: '+host);
	
	var setMessage = function(step){
		var message = $('p#progressMsg');
		switch(step){
			case 5:
				message.text($('li#book_step_5').text());
				break;
			case 6:
				message.text($('li#book_step_6').text());
				break;
			case 7:
				message.text($('li#book_step_7').text());
				break;
			default:
				message.text($('li#book_step_5').text());
		}
	}
	
	//hides all room prices and descriptions at init and displays first room type in navigation
	var hideRoomPricesDescriptions = function(){
		$('p.roomType').hide();
		$('div.roomDescrip').hide();
		$('a.roomTypeSelect')[0].click();
	}
	
	//hides all room descriptions and pictures
	var showHideRoomDescriptions = function(roomType){
		$('div.roomDescrip').hide().removeClass('activeDescription');
		$('div#'+roomType).show().addClass('activeDescription');
	}
	
	//shows room types and executes calculateTotal()
	var showHideRoomTypes = function(roomClass){
		$('p.roomType').hide().removeClass('activeRoom');
		$('p.'+roomClass).show().addClass('activeRoom');
		calculateTotal();
	}
	
	//calculates total and inserts it in page
	var calculateTotal = function(){
		var prices = $('p.activeRoom').find('span.roomCost');
		var total = 0;
		prices.each(function(index) {
			total += parseInt($(this).text());
		});
		$('span#totalCost').text(total);
	}
	
	//gets booking data to continue with user registration.
	var getBookingData = function(){
		//tye of room that's gonna be booked
		bookData.roomType = $('a.activeRoomType').attr('href').substr(10);
		var count = 0;
		if (noAllotment){
			if (noAllotmentType.hasInArray(bookData.roomType)) {
				alert('There is no vacancy on '+noAllotmentType.length+' dates that you chose, please change the date or the room type');
				return false;
			}else{
			 	bookData.checkin = $('p#checkin').text();
			 	bookData.checkout = $('p#checkout').text();
				return true;
			 }
		}else{
		 	bookData.checkin = $('p#checkin').text();
		 	bookData.checkout = $('p#checkout').text();
		 	return true;
		 }
	}
	
	var capturePersonalData = function(){
		loadValidationRules();
		if ($('div#personalDetails form').valid() && $('input#terms').is(':checked')) {
			var personalData = {
				name: $('input#name').val(),
				lastname: $('input#lastname').val(),
				email: $('input#email').val(),
				tel: $('input#tel').val(),
				country: $('input#country').val(),
				address: $('textarea#address').val(),
				city: $('input#city').val(),
				zip: $('input#zip').val()
			}
			var bookComments = $('textarea#comments').val();
			if (personalData) {
				var button = $('button#submitPersonalDetails');
				button.attr('disabled', 'disabled');
				//saving personal details msg
				$.ajax({
					url: host+'reservaciones/registroUsuario/',
					type: 'POST',
					dataType: 'json',
					data: personalData,
					complete: function(xhr, textStatus) {
						button.removeAttr('disabled');
					},
					success: function(data, textStatus, xhr) {
						bookData.userId = data.user;
						confirmBookAndPay(bookComments);
					},
					error: function(xhr, textStatus, errorThrown) {

					}
				});
			}
		}else{
			return false;
		}
	}
	
	//gets personal user data to login and proceed with booking
	var goToPersonalDataCapture = function(){
		$('button#toPersonalData').attr('disabled', 'disabled');
		//animate booking pane and go to personal details pane
		$('div.reservData').fadeOut('slow', function() {
			$('div#personalDetails').fadeIn('slow');
		});
	}
	
	var confirmBookAndPay = function(bookComments){
		$.ajax({
			url: host+'reservaciones/confirmAndBook/',
			type: 'POST',
			dataType: 'json',
			data: {
				userId: bookData.userId,
				checkin: bookData.checkin,
				checkout: bookData.checkout,
				roomType: bookData.roomType,
				comments: bookComments
			},
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) {
				var returnUrl = $('input#returnUrl').val();
				$('input#returnUrl').val(returnUrl+"/"+data.reservationId);
				$('form#paypalSubmitForm').dialog({
					width:400,
					modal:true
				});
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
	}   
	    
	//checks if there's a date with no allotment and stores the type of room that's unavaliable
	var checkNoAllotment = function(){
		var noAllotmentArray = new Array();
		$.each($('ul#dateList li').has('p.noAllotment'), function(index, val) {
			noAllotmentRoomType = $(this).find('span.roomType').text();
			if (!noAllotmentType.hasInArray(noAllotmentRoomType)) {
				noAllotmentType.push(noAllotmentRoomType);
			};
		});
		if(noAllotmentType.length > 0){
			noAllotment = true;
		}
	}
	
	//Jquery validation rules
	var loadValidationRules = function(){
		$('div#personalDetails form').validate({
			rules: {
				name: {required:true},
				lastname: {required:true},
				email: {required:true, email:true},
				tel: {required:true},
				address: {required:true},
				city: {required:true},
				zip: {required:true},
			}
		});
	}
	
	//animates de progress bar
	var setProgress = function(progressPctg){
		var progress = $('div#progress');
		//if (progress.width() < progressPctg) {
			progress.animate({width: progressPctg}, 'slow');
		//}
	}
	
	//binds all events in page
	var bindEvents = function(){
		//select room types to display prices and enable or disable book button if no allotment
		$('a.roomTypeSelect').live('click',function(event) {
			event.preventDefault();
			var roomType = $(this).attr('href').substr(1);
			var roomTypeName = $(this).text();
			$('a.roomTypeSelect').removeClass('activeRoomType');
			$(this).addClass('activeRoomType');
			showHideRoomTypes(roomType);
			showHideRoomDescriptions(roomType);
			if (noAllotmentType.hasInArray(roomType.substr(9))) {
				$('button#toPersonalData').text($('p#noAvailability').text());
				$('p#roomTypeTotal').addClass('hidden');
				$('button#toPersonalData').addClass('inactive');
				$('button#toPersonalData').attr('disabled', 'disabled');
				$('span#totalRoomType').text('');
			}else{
				$('button#toPersonalData').text($('p#buttonText').text());
				$('p#roomTypeTotal').removeClass('hidden');
				$('button#toPersonalData').removeClass('inactive');
				$('button#toPersonalData').removeAttr('disabled');
				$('span#totalRoomType').text(roomTypeName);
			}
			if (roomSelectProgress) {
				setProgress(600);
				setMessage(6);
			}else{
				setProgress(400);
				roomSelectProgress = true;
			}
		});
		//executes booking
		$('button#toPersonalData').live('click',function(event) {
			event.preventDefault();
			if (getBookingData()) { //verifies allotment and dates
				$('input#paypalName').val($.trim($('p#roomTypeTotal').text()));
				$('input#paypalAmount').val($.trim($('span#totalCost').text()));
				goToPersonalDataCapture();
				setProgress(800);
				setMessage(7);
			};
		});
		$('button#backRoomSel').live('click', function(event) {
			event.preventDefault();
			$('button#toPersonalData').removeAttr('disabled');
			//animate booking pane and go to personal details pane
			$('div#personalDetails').fadeOut('slow', function(){
				$('div.reservData').fadeIn('slow');
			});
			setProgress(600);
			setMessage(6);
		});
		$('button#captureDataAndBook').live('click',function(event) {
			event.preventDefault();
			capturePersonalData();
		});
	}
	
	var onloadExec = function(){
		bindEvents();
		hideRoomPricesDescriptions();
		checkNoAllotment();
		setMessage(5);
	}
	
	return {
		init:onloadExec
	}
}
/*============================================== Control Panel =====================================================*/
var backOffice = function(){
	
	var host = 'http://www.joliejungle.com/';
	
	var bindEvents = function(){
		//inline edits
			$('.editableData').live('click', function(event) {
				var elem = $(this);
				if (!elem.hasClass('editing')){
					var origVal = $.trim(elem.html());
					elem.addClass('editing')
						.empty()
						.append('<input class="inlineEdit" type="text" name="" value="'+origVal+'" />');
					elem.find('input').fadeIn('slow', function() {
						elem.find('input').focus();
					});
				}
			}).live('blur', function(event) {
				var elem = $(this);
				if (elem.hasClass('editing')){
					elem.removeClass('editing');
					var pDataToSend = $.trim(elem.find('input').val());
					elem.find('input').remove();
					elem.append(pDataToSend);
					//campo de la db para enviar
					var method = $.trim(elem.closest('table').siblings('p.hidden').text());
					var field = elem.closest('td').attr('class');
					var id = elem.closest('tr').attr('id').substr(9);
					$.post(
						host+'backoffice/'+method,	
						'cat_room_id='+$.trim(id)+'&'+field+'='+pDataToSend,
						function(data, textStatus, xhr) {
							
						}
					);
				}
			});
		
		//creates tabs
		$('div#tabs').tabs();
		//calendars
		$('input.date').datepicker({
			numberOfMonths: 2
		});
		//confirm links for deletion
		$('a.confirm').live('click', function(event) {
			event.preventDefault();
			var answer = confirm('Está seguro de querer eliminar este elemento? No se podrá cancelar la eliminación.');
				if (answer){
					var kind = $(this).closest('table').attr('id');
					var itemId = $.trim($(this).closest('tr').children('td').first().text());
					var row = $(this).closest('tr');
					deleteItemRow(kind, itemId, row);
				}else{
					return false;
				}
		});
		//Activate a not confirmed season
		$('button.activateNotConfirmed').live('click', function(event) {
			event.preventDefault();
			var reserveId = $.trim($(this).closest('tr').find('td.reserveId').text());
			activateUnconfirmedReserve(reserveId);
		});
		//Delete season confirm
		$('button.deleteSeason').live('click', function(event) {
			event.preventDefault();
			var answer = confirm('Está seguro de querer eliminar esta temporaa? No se podrá cancelar la eliminación.');
				if (answer){
					var seasonId = $.trim($(this).closest('tr').attr('id'));
					var row = $(this).closest('tr');
					deleteSeason(seasonId, row);
				}else{
					return false;
				}
		});
		//Blocks dates for maintenance
		$('button#blockRoom').live('click', function(event) {
			var start = $('input#startBlock').val();
			var end = $('input#endBlock').val();
			var roomType = $('select#roomType').val();
			if (start == '' || end == '') {
				return false;
			};
			$.ajax({
		   		url: host+'backoffice/checkDatesForBlocking/',
		   		type: 'POST',
		   		dataType: 'json',
		   		data: {
					checkIn: start,
					checkOut: end,
		   		},
		   		complete: function(xhr, textStatus) { },
		   		success: function(data, textStatus, xhr) { 
			 		if (verifyDatesforBlock(data, roomType)) {
						blockDates(start, end, roomType);
					};
				},
		   		error: function(xhr, textStatus, errorThrown) { }
			});
		});
		//saves a season
		$('button#saveSeason').live('click', function(event) {
			addSeason();
		});
		//activate seasons in table
		$('button.activateSeason').live('click', function(event) {
			var seasonId = $.trim($(this).closest('tr').attr('id'));
			activateSeasonPanel(seasonId);
		});
		//save season prices
		$('button#saveSeasonPrices').click(function() {
			activateSeason();
		});
	}
	
	var activateUnconfirmedReserve = function(reserveId){
		$.getJSON(host+'backoffice/activateUnconfirmedReserve/'+reserveId, function(json, textStatus) {
			window.location.reload();
		});
	}
	
	var activateSeason = function(){
		var seasonId = $('div#seasonActivate').find('input#seasonId').val();
				
		$('tr.roomType').each(function(index) {
			var roomCat = $(this).attr('id').substr(8);
			var	price = $(this).find('input.seasonPriceInput').val();
			$.ajax({
				url: host+'backoffice/setSeasonPrice/',
				type: 'POST',
				dataType: 'json',
				data: {
					seasonId:seasonId,
					roomCat:roomCat,
					price: price
				},
				complete: function(xhr, textStatus) { },
				success: function(data, textStatus, xhr) {
					console.log(data);
				},
				error: function(xhr, textStatus, errorThrown) { }
			});
		});
	}
	
	var activateSeasonPanel = function(seasonId){
		$('div#seasonActivate').find('input#seasonId').val(seasonId);
		$('div#seasonActivate').dialog({
			width: 500,
			modal: true
		});
	}
	
	var addSeason = function(){
		$.ajax({
			url: host+'backoffice/newSeason/',
			type: 'POST',
			dataType: 'json',
			data: {
				season_name: $('input#seasonName').val(),
			    date_season_start: $('input#seasonStart').val(),
			    date_season_end: $('input#seasonEnd').val(),
			    season_comments: $('input#seasonDescrip').val()
			},
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) {
				if (data.status) {
					window.location.reload();
				};
				notify(data);
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
	}
	
	var deleteSeason = function(seasonId, row){
		$.ajax({
			url: host+'backoffice/deleteSeason/'+seasonId,
			type: 'GET',
			dataType: 'json',
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) {
				if (data.status) {
					row.fadeOut('slow');
				};
				notify(data);
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
	}
	
	var verifyDatesforBlock = function(data, roomType){
		//Method for getting size of object
		Object.size = function(obj) {
		    var size = 0, key;
		    for (key in obj) {
		        if (obj.hasOwnProperty(key)) size++;
		    }
		    return size;
		};
		//contains dates that are already booked by the system
		var unavailable = new Object();
		//goes through the object to see if there are no allotment dates
		$.each(data, function(date, obj) {
 			$.each(obj, function(roomCat, allotment) {
 				if (roomCat == roomType) {
					if (allotment == 0) {
						var objProperty = date;
						unavailable[date] = allotment;
					};
				};
 			});
 		});
		var size = Object.size(unavailable);
		if (size > 0) {
			var datesString = '';
			$.each(unavailable, function(index, val) {
				datesString += index+' ';
			});
			var notifyMsg = {
				status: 0,
				msg: 'Todas las habitaciones están reservadas en las siguientes fechas: '+datesString
			}
			notify(notifyMsg);
			return false;
		}else{
			return true;
		}
	}
	
	var blockDates = function(start, end, roomType){
		$.ajax({
			url: host+'backoffice/blockRoomDates/',
			type: 'POST',
			dataType: 'json',
			data: {
				start: start,
				end: end,
				roomType: roomType
			},
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) { 
				window.location.reload();
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
		
	}
	
	var notify = function(data){
		if (data.status) {
			$('<p class="confirmation">'+data.msg+'</p>').dialog({
				modal:true,
				buttons:{
						Ok: function() {
							$( this ).dialog( "close" );
						}
					}
			});
		}else{
			$('<p class="error">'+data.msg+'</p>').dialog({
				modal:true,
				buttons:{
						Ok: function() {
							$( this ).dialog( "close" );
						}
					}
			});
		}
	}
	
	var deleteItemRow = function(kind, itemId, row){
		switch(kind){
			case 'reservas':
				cancelReservation(itemId, row);
				break;
			case 'clientes':
				deleteClient(itemId, row);
				break;
			case 'block':
				cancelReservation(itemId, row);
				break;
		}
	}
	
	var cancelReservation = function(reserveId, row){
		$.ajax({
			url: host+'backoffice/cancelReserve/'+reserveId,
			type: 'GET',
			dataType: 'json',
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) {
				notify(data);
				if (data.status) {
					row.fadeOut('slow');
				};
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
	}
	
	var deleteClient = function(clientId, row){
		$.ajax({
			url: host+'backoffice/deleteClient/'+clientId,
			type: 'GET',
			dataType: 'json',
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) {
				notify(data);
				if (data.status) {
					row.fadeOut('slow');
				};
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
	}
	var deleteBlock = function(itemId, row){
		$.ajax({
			url: host+'backoffice/deleteClient/'+clientId,
			type: 'GET',
			dataType: 'json',
			complete: function(xhr, textStatus) { },
			success: function(data, textStatus, xhr) {
				notify(data);
				if (data.status) {
					row.fadeOut('slow');
				};
			},
			error: function(xhr, textStatus, errorThrown) { }
		});
	}
	
	var onloadExec = function(){
		bindEvents();
	}
	
	return {
		init:onloadExec
	}
}
/*==============================================objects example=====================================================*/
