// Common javascript used by every page on MANAGE and APP site goes here
// PUT ALL NEW SHARED CODE IN SHARED.JS - NOT THIS FILE PLEASE!!!
$(document).ready(function() {

//	var referrerList = ["Bookabach.co.nz", "HolidayHouses.co.nz", "HolidayHomes.co.nz","BachCare.co.nz","Takeabreak"];
//	var referrerList = '';	
	
	/*
$("input#booking-referrer").autocomplete({
			source: ['hello','cruel','world']
	});
	
*/
	// Loads a view into a div using ajax
	$('div.ajax-load').each(function(index) {
		var url = $(this).attr("data-url");
		var div = $(this);
		var d = 0; //msec

		$.get(url, {
			ajax: 1
		}, function(data) {
			$(div).append(data);
			$(div).removeClass('ajax-load');
		});
	});


	// Show quick start toggles
	$('#show-quick-start').show();
	$("label[for='show-quick-start']").show();

	// Persistent checkbox saves to session via ajax
	$("input.persistent-checkbox").click(function(e) {
		var varName = $(this).attr('title');
		var checkBoxId = $(this).attr('id');

		/* toggle the page session variable */
		_toggleVariable(varName, function(state) {
			$("input#" + checkBoxId).attr('checked', state);
		});
		return false;
	});

	$("#useMemberAddressf, #useMemberAddresst").change(function() {
		if($(this).val() == "False") {
			$('.member-address').each(function() {
				$(this).addClass("disabled");
			})
		}
		else {
			$('.member-address').each(function() {
				$(this).removeClass("disabled");
			})
		};
	});



	$("input#enabledYN").click(function(e) {
		var isEnabled = $(this).attr('checked');
		
		var theControl = "";
		if(!isEnabled) {
			theControl = $('.enabled');
			theControl.removeClass('enabled').addClass('disabled');
		}
		else {
			theControl = $('.disabled');
			theControl.removeClass('disabled').addClass('enabled');
		}
	});

	// Persistent html control values using html5 custom data attributes
	// (data-) saves to session via ajax 
	$(".persistent-variable").click(function(e) {
		var varName = $(this).attr('data-name');
		var varValue = $(this).attr('data-value');

		/* set the session variable */
		_setVariable(varName, varValue);
		//return false;	
	});

	$("div.mini-menu:not('#search-drop-down') li").click(function() {
		window.location.href = $(this).find('a').attr('href');
	});


	// initial text 
	$(".initial-text").each(function() {
		if($(this).val() == '') {
			$(this).val($(this).attr('title'));
			$(this).click(function() {
				$(this).val('');
				$(this).unbind('click');
			})
		}
	});

	// date pickers
	$(".date-field").each(function() {
		var defaultDate = new Date($(this).text());
		if(defaultDate == 'NaN') {
			defaultDate = '';
		}
		$(this).datepicker({
			defaultDate: defaultDate,
			showOn: 'button',
			buttonImage: 'http://s1.bookabach.co.nz/images/calendar-icon.png',
			buttonImageOnly: true,
			gotoCurrent: true,
			dateFormat: "dd-M-yy"
			//minDate:'0'
		});
	});


	$('.live-datepicker-trigger').live('click', function() {
		var defaultDate = new Date($(".date-field-live").text());
		if(defaultDate == 'NaN') {
			defaultDate = '';
		}
		$(".date-field-live").datepicker({
			defaultDate: defaultDate,
			showOn: 'focus',
			buttonImage: 'http://s1.bookabach.co.nz/images/calendar-icon.png',
			buttonImageOnly: true,
			gotoCurrent: true,
			dateFormat: "dd-M-yy",
			beforeShow: function() {
				$("#ui-datepicker-div").css("z-index", $(this).parents(".ui-dialog").css("z-index") + 1);
			}
		}).focus();
	});

	//tidy up the datepicker icon
	$('.ui-datepicker-trigger').attr('alt', 'Select date from calendar').attr('title', 'Select date from calendar').css("vertical-align", "middle");



	// Expanding section expand/collapse
	$('.expander-body').hide();
	$('div.expander-header').click(function() {

		var bodyId = $(this).parent().attr("id");

		var isOpened = $('div#' + bodyId + ' div.expander-header').hasClass('opened');

		if(isOpened) {
			$('div#' + bodyId + ' div.expander-header').removeClass('opened');
			$('div#' + bodyId + ' div.expander-body').hide();
		}
		else {
			$('div#' + bodyId + ' div.expander-header').addClass('opened');
			$('div#' + bodyId + ' div.expander-body').show();
		}
		
		// don't follow any links on header 
		return false;

	});


	//Hide Expanding list items on start up	
	$('li.expander').each(function() {
		var expandClass = $(this).attr("data-expand-class");
		$('li.' + expandClass).addClass('hide');
	});


	// Expanding list items
	$('li.expander').click(function() {
		var expandClass = $(this).attr("data-expand-class");
		$('li.' + expandClass).toggleClass('hide');
		$(this).toggleClass('opened');
	});




	// Expanding box expand/collapse
	$('.expander-box .box-body').hide();
	$('.expander-box .box-header').click(function() {

		var bodyId = $(this).parent().attr("id");

		$('div#' + bodyId + ' div.box-body').toggle('blind');

		var isOpened = $('div#' + bodyId + ' div.box-header').hasClass('opened');

		if(isOpened) {
			$('div#' + bodyId + ' div.box-header').removeClass('opened');
		}
		else {
			$('div#' + bodyId + ' div.box-header').addClass('opened');
		}
	});

	// we are actually starting in the open state for these.
	$('div.box-header').addClass('opened');

	$('.expander-trigger').click(function() {
		var bodyId = $(this).attr("data-target");
		$('div#' + bodyId + ' div.box-body').toggle('blind');
		$('div#' + bodyId + '  div.box-header').addClass('opened');
		return true;

	});

	$('.expander-box-white .box-header ').click(function() {
		var bodyId = $(this).parent().attr("id");

		$('div#' + bodyId + ' div.box-body').toggle('blind');

		var isOpened = $('div#' + bodyId + ' div.box-header').hasClass('opened');

		if(isOpened) {
			$('div#' + bodyId + ' div.box-header').removeClass('opened');
		}
		else {
			$('div#' + bodyId + ' div.box-header').addClass('opened');
		}

	});


	// Initialise Show/Hide optional fields
	$("div#show-hide-optional").append("<a href='##'>Hide optional</a>");

	// Show/hide optional fields
	$('div#show-hide-optional a').toggle(function() {
		$("li.optional").hide(200);
		$(this).text('Show optional');
		return false;
	}, function() {
		$("li.optional").show(200);
		$(this).text('Hide optional');
		return false;
	});

	//Show/Hide help
	$("div#help-link a").click(function() { /* toggle the page session variable */
		_toggleVariable('showRelatedHelp', function(state) {
			if(state) {
				$("div#related-help").slideDown();
				$("div#help-link a").text('Hide help');
			} else {
				$("div#related-help").slideUp();
				$("div#help-link a").text('Show help');
			}
		});
		return false;
	});


	// Property selector list on navigation
	$('a#property-selector').click(function() {

		$('div#property-picker').toggle();

		//$('a#property-selector').toggleClass('button-drop-down-white-selected');
		return false;
	});

	// Help window dialog
/*
	$('div#help-pop-up').dialog({
		autoOpen: false,
		width: 600,
		title: 'Help article',
		buttons: {
			"Ok": function() {
				$(this).dialog("close");
			}				
		}
	}); 
*/

/*
	$('div#related-help ul li a').click(function(e){
		$.get(this+"?ajax=true", function(data){
			$("div#help-pop-up").empty();
			$("div#help-pop-up").append(data);
			$('div#help-pop-up').dialog('open');
		});
		return false; 
	});
*/




	$('div#show-modal-message #continue-button').live("click", function(e) {
		$("div#show-modal-message").dialog('close');
		return false;
	});




	$('.add-attachment').live("click", function(e) {
		var $parentObject = $(this).parents('#options-for-' + $(this).attr("id"));
		$parentObject.empty();
		$parentObject.addClass("search-field-loading").css("padding", "0 0 31px 0");
		$.get(this + '/' + String((new Date()).getTime()).replace(/\D/gi, ''), function(data) {
			$(data).insertBefore('.email-body');
			$("div#pop-edit").dialog('close');
		});
		return false;
	});

	$('.remove-attachment').live("click", function(e) {
		var $parentObject = $(this).parents('li');
		$parentObject.empty();
		$parentObject.addClass("search-field-loading").css("padding", "0 0 31px 0");
		$.get(this + '/' + String((new Date()).getTime()).replace(/\D/gi, ''));
		$parentObject.remove();
		return false;
	});


	$('.select-image').live("click", function(e) {
		$("#logo-image-container").empty();
		$(this).empty();
		$(this).blur();
		$(this).addClass("search-field-loading").css("padding", "15px 15px 0 0");
		$.get(this + '/' + String((new Date()).getTime()).replace(/\D/gi, ''), function(data) {
			$("#logo-image-container").append(data);
			$("div#pop-edit").dialog('close');
		});
		return false;
	});

	$('.add-locale').live("click", function(e) {
		$.get(this + '/' + String((new Date()).getTime()).replace(/\D/gi, ''), function(data) {
			$(data).insertBefore('#add-locale-label');
		});
		return false;
	});

	$('.remove-locale').live("click", function(e) {

		var $theSelect = $(this).prev('select');
		var $theLabel = $theSelect.prev('label');
		$theSelect.remove();
		$theLabel.remove();
		$(this).remove();
		return false;
	});



	$('.directory-listing-category').live("change", function(e) {
		var categoryId = this.value;
		if(categoryId != 0) {
			$("#services-provided-list").empty();
			$("#services-provided-list").append('<li class="search-field-loading">&nbsp;</li>');

			// add rnd string to end to stop ie caching xmlhttp
			var $url = "/directory/category-services-provided/" + categoryId + '/' + String((new Date()).getTime()).replace(/\D/gi, '');
			$.get($url, function(data) {
				$("#services-provided-list").replaceWith(data);
			});
		}
	});

	$('#listing-status ul li a.ajaxify').live("click", function(e) {
		var $parentObject = $(this).parents('#listing-status');
		$parentObject.removeClass("pause");
		$parentObject.removeClass("play");
		$parentObject.addClass("search-field-loading").css("padding", "0 0 0 30px");
		$parentObject.find("ul li").css("color", "#BFBFBF");

		var listingId = $(this).attr("data-listingId");
		// add rnd string to end to stop ie caching xmlhttp
		var $url = "/listing/doStatusAjax/" + listingId + '/' + String((new Date()).getTime()).replace(/\D/gi, '');

		$.get($url, function(data) {
			$parentObject.removeClass("search-field-loading");
			$parentObject.replaceWith(data);

		});
		return false;
	});


	$('#template-selector').change(function(e) {
		var templateId = this.value;
		var bookingId = $('#id').val();
		if(bookingId === undefined) {
			// lower case has been mucked up by coldfusion?
			bookingId = $('#ID').val();
		}
		if(this.selectedIndex == 0) {
			$('#edit-template-link').hide();
		}
		else {
			$('#edit-template-link').show();
		}
		var $url = "/templates/ajaxGetTemplateContent?templateId=" + templateId + "&bookingId=" + bookingId;
		$.get($url, function(data) {
			$('#email-body').val(data);
			swapTemplateLink(templateId, 'copy-template-link');
			swapTemplateLink(templateId, 'edit-template-link');
		});
	});

	$('input#item-qty , input#item-amount , #item-unit').live("change", function(e) {
		if($('#item-unit').val() == "%") {
			$('input#item-ext-amount').val($('input#item-qty').val() / 100 * $('input#item-amount').val());
		}
		else {
			$('input#item-ext-amount').val($('input#item-qty').val() * $('input#item-amount').val());
		}

	});
	
	//Show/Hide supplemental message in Edit Payment Term
	$('#edit-payment-terms #relative-to').live("change", function(e) {
		if ($('#relative-to').val() == 'dateAccepted') {
			$('#one-night-minimum').show();
		} else {
			$('#one-night-minimum').hide();
		}
	});



//Show-Hide on input value change... data value can be delimited by pipes (|)
	/*
	$('.show-hide-on-input input').live("change", function(e) {
		var cls = $(this).parents('.show-hide-on-input').attr("data-class");
		var v = $(this).parents('.show-hide-on-input').attr("data-value").split("|");
		console.log(v);
		for(i=0; i <= v.length; i++){
			if ($(this).val() == v[i]) {
				$('.' + cls).show('fast');
				break;
			}
			else {
				$('.' + cls).hide('fast');
			}
		}
	});
*/
	
	$('#move-right').click(function() {
		return !$('#left-move-select option:selected').appendTo('#right-move-select');
	});
	
	$('#move-left').click(function() {
		return !$('#right-move-select option:selected').appendTo('#left-move-select');
	});


	$('#move-right').click(function() {
		return !$('#left-move-select option:selected').appendTo('#right-move-select');
	});
		
// extras form , ensure the properties in the box are selected.

    $('#edit-extra').submit(function() {
	        $('#right-move-select').find('option').each(function() {
	            $(this).attr('selected', 'selected');
	        });
	  });

	$('.ajax-calculate-rental').live("click", function(e) {
		var bookingId = $(this).attr("data-bookingId");
		var context = $(this).attr("data-context");
		$("#valueTD" + bookingId).empty();
		$("#valueTD" + bookingId).addClass("search-field-loading");
		$.get('/finance/calculateQuotationAjax/' + bookingId + '/' + context, function(data) {

			$("#valueTD" + bookingId).removeClass("search-field-loading");
			$("#valueTD" + bookingId).append(data);

			if(context == "reports") {
				// Sum em
				var sumTotal = 0;
				$(".bk-rental-value").each(function(index) {
					cellValue = this.innerHTML.replace(",", "").replace("$", "").replace("*", "").replace("-", "").trim();
					if(!isNaN(parseFloat(cellValue))) {
						sumTotal += parseFloat(cellValue);
					}
				});
				$("#bk-total-value").html(dollarFormat(sumTotal));
			}
		});
		return false;
	});

// table-view-ajax-action
	/*
	$('a.table-view-ajax-action').live("click", function(e) {
		var bookingId = $(this).attr("id");
		var even = $("#table-view-row-" + bookingId).hasClass("even");
		$("#table-view-row-" + bookingId).removeClass("even");
		$("#table-view-row-" + bookingId).removeClass("state-declined");
		$("#table-view-row-" + bookingId).removeClass("state-cancelled");
		//$("#table-view-row-"+bookingId).empty();
		//$("#table-view-row-"+bookingId).append("<td  id='table-view-row-loading' colspan='8'  ><div id='grey-loader'/></td>");
		$("#table-view-row-" + bookingId).addClass("grey-loader");

		$.get($(this).attr("href") + "&ajax=true", function(data) {
			$.get("/bookings/get-table-row-ajax/" + bookingId, function(row) {
				$("#table-view-row-" + bookingId).replaceWith(row);
				if(!even) {
					$("#table-view-row-" + bookingId).removeClass("even");
				}
				$("#table-view-row-" + bookingId).removeClass("selected");
			});
		});
		return false;
	});
*/


// table-view-ajax-action - full page spinner version to avoid muliple ajax requests at same time
	$('a.table-view-ajax-action').live("click", function(e) {
		
		$('body').prepend('<div id="modal"/>');
	
		
		var bookingId = $(this).attr("id");
		var even = $("#table-view-row-" + bookingId).hasClass("even");
		$("#table-view-row-" + bookingId).removeClass("even");
		$("#table-view-row-" + bookingId).removeClass("state-declined");
		$("#table-view-row-" + bookingId).removeClass("state-cancelled");
		//$("#table-view-row-"+bookingId).empty();
		//$("#table-view-row-"+bookingId).append("<td  id='table-view-row-loading' colspan='8'  ><div id='grey-loader'/></td>");
		//$("#table-view-row-" + bookingId).addClass("grey-loader");

			$.get($(this).attr("href") + "&ajax=true", function(data) {
				$.get("/bookings/get-table-row-ajax/" + bookingId, function(row) {
				$("#table-view-row-" + bookingId).replaceWith(row);
				if(!even) {
					$("#table-view-row-" + bookingId).removeClass("even");
				}
				$("#table-view-row-" + bookingId).removeClass("selected");
			
				$('#modal').remove();
			});
		});
	
		return false;

	});

	
	// new registration form : property categories
	$('select#accommodation-category').change(function(e){
		$('.description').hide();
		var $selected = $('select#accommodation-category option:selected');
		$('#cat-' + $selected.val()).show();		
				
		var canBeHosted = $selected.attr("data-can-be-hosted") == "YES";	
		var canBeSemiHosted = $selected.attr("data-can-be-semi-hosted") == "YES";
		var canBeNonHosted = $selected.attr("data-can-be-non-hosted") == "YES";
		
		// toggle disabled class to the li, disable and uncheck the radio			
		$('#hosted-option').toggleClass('disabled',!canBeHosted);
		if(canBeHosted){
			$('#hosted').removeAttr("disabled");			
		}
		else{
			$('#hosted').attr('checked', false);
			$('#hosted').attr("disabled",true);
		}
		
		$('#semi-hosted-option').toggleClass('disabled',!canBeSemiHosted);		
		if(canBeSemiHosted){
			$('#semi-hosted').removeAttr("disabled");
		}
		else{
			$('#semi-hosted').attr('checked', false);
			$('#semi-hosted').attr("disabled",true);
		}
		
		$('#non-hosted-option').toggleClass('disabled',!canBeNonHosted);
		if(canBeNonHosted){
			$('#non-hosted').removeAttr("disabled");
		}
		else{
			$('#non-hosted').attr('checked', false);
			$('#non-hosted').attr("disabled",true);
		}		
	}); 

	// country selector list on navigation
	$('a#country-selector,  a#country-selector-change').click(function(){
		$('div#country-picker').toggle();
		return false;
	});

});

//___________ ends doc ready____________

var dollarFormat = function(number) {
	number.toFixed(2);
	number += "";
	var parts = number.split('.');
	var integer = parts[0];
	// put 0 cents on if whole dollar
	var decimal = parts.length > 1 ? '.' + parts[1] : '.00';
	// put 0 on end for .4 , .5 etc
	decimal = decimal.length == 2 ? decimal + '0' : decimal;
	// chop precision down to 2: can't use .toFixed() because its a string not a float.
	decimal = decimal.length > 3 ? decimal.slice(0, 3) : decimal;
	var regex = /(\d+)(\d{3})/;
	while (regex.test(integer)) {

		integer = integer.replace(regex, '$1' + ',' + '$2');
	}
	return "$" + integer + decimal;
}



var swapTemplateLink = function(templateId, elementId) {
	var existingLink = "";
	if (elementId != undefined) {
		existingLink = $('#' + elementId).attr("href");		
		var newLink = existingLink.substring(0, existingLink.lastIndexOf("/") + 1);
		newLink += templateId;
		$('#' + elementId).attr("href", newLink);
	}
}

/*

(function($) {
	// convert a tags to buttons for Firefox!!!
	$.fn.aToButton = function(){
		return this.each(function(){
			var btn = document.createElement('button');
			$(btn).html($(this).html()).attr('href', $(this).attr('href') || '').attr('class', $(this).attr('class') || '').attr('title', $(this).attr('title') || '').bind('click', function(e){
				location.href = $(this).attr('href');
				return false;
			});
			$(this).replaceWith(btn);
		});
	}
	})(jQuery);
*/


