// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
// Namespace function
function namespace(ns) {
  ns = ns.split('.');
  var cur = window, i;
  while ( i = ns.shift() ) {
    if ( !cur[i] ) cur[i] = {};
    cur = cur[i];
  }
}
// declare namespaces
namespace('hpk');
namespace('hpk.trip');
namespace('hpk.datepicker');
namespace('hpk.flash');
namespace('hpk.forms');
namespace('hpk.hintedInput');
namespace('hpk.flights');
namespace('hpk.tasks');
namespace('hpk.alerts');
namespace('hpk.users');
namespace('hpk.lists');

$(document).ready(function() {
  // new comment trigger clickers
  $('a.new_comment').click(function() {
    var trigger = $(this);
    var listOptionId = $(this).attr('href').match(/\/list_options\/(\d+)\//)[1];
    var newCommentDiv = $('#new_comment_' + listOptionId);
    
    trigger.hide();
    newCommentDiv.show();
    // hide fields again when focus is lost and nothing was entered
    $('#comment_body', newCommentDiv).focus()
    .blur(function() {
      if($(this).val() == '') {
        newCommentDiv.hide();
        trigger.show();
      }
    });
    
    return false;
  });
  
  
  // set up hinted input fields
  $('input.hinted').each(function() {
    hpk.hintedInput.blur(this);
  }).focus(function() {
    hpk.hintedInput.focus(this);
  }).blur(function() {
    hpk.hintedInput.blur(this);
  }).parents('form').submit(function() {
    $('input.hinted', this).each(function() { hpk.hintedInput.focus(this) });
  });
  
  if ($('#flashes').length > 0) {
    hpk.flash.hide(3500);
    $('#flashes').click(hpk.flash.hide);
  }
  
  hpk.datepicker.init();

	// 'More Trips' tab option
	$('#trip_tabs #more_trips').mouseenter(function() {
		$('ul', this).show();
	}).mouseleave(function() {
		$('ul', this).hide();
	});
  
  // init hoverable items
  $('.hoverable').mouseover(function() {
  	$(this).addClass('mouseover');
  }).mouseleave(function() {
  	$(this).removeClass('mouseover');
  })
  
  // Tooltips by George
 
  
   $('#sidebar_components ul li h3').tipsy({gravity: 'e', delayIn: 500,});
  
  initAutoResize('.list_option_text', 32);
  initAutoResize('textarea#comment_body', 50);

	$("#expand_menu").click(function () {
	
	$("#sidebar_tasks h4").toggle("blind", {}, 300);
	$("#sidebar_components ul li ul").toggle("blind", {}, 300);
	});   
  
});

// initialise an auto resize field
function initAutoResize(selector, extraSpace) {
  $(selector).autoResize({
    // On resize:
    onResize : function() {
      $(this).css({opacity:0.8});
    },
    // After resize:
    animateCallback : function() {
      $(this).css({opacity:1});
    },
    // Quite slow animation:
    animateDuration : 300,
    // More extra space:
    extraSpace : extraSpace
  });
}

// add authenticity token to ajax requests
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

// votable action 
function vote(action_link, value) {
  $.ajax({
    type:"POST",
    url:$(action_link).attr('href'),
    data:"value="+value,
    dataType:"script"
  });
  return false;
}

// date picker defaults
$.datepicker.setDefaults({
	dateFormat: "d M yy",
	firstDay: 1,
	showOn : 'button',
	buttonImage: "/images/date_picker.png",
	buttonImageOnly: true,
	showAnim: 'blind'
})

// initialise pickers on the page
hpk.datepicker.init = function() {
	// date pickers...
	$('.date_picker').datepicker({
		onSelect : function(dateText, input) {
			var selectedDate = hpk.datepicker.parse(dateText);
			var _this = $(input);
			var prefix = _this.attr('id').match(/(\w+)(start_date|end_date)$/);
			if (prefix != null) {
				var isStartDate = prefix[2] == 'start_date';
				var isEndDate   = prefix[2] == 'end_date';
				if (isStartDate) {
					var endDateField = $('#'+ prefix[1] + 'end_date');
					var endDate = endDateField.datepicker('getDate');
					if (endDate == null || selectedDate > endDate) {
						endDateField.datepicker('setDate', selectedDate);
					};
				} 
				else if (isEndDate) {
					var startDateField = $('#'+ prefix[1] + 'start_date');
					var startDate = startDateField.datepicker('getDate');
					if (startDate == null || selectedDate < startDate) {
						startDateField.datepicker('setDate', selectedDate);
					};
				}
			};
		},
		beforeShow : function(input) {
			var _this = $(input);
			var dateEntered = hpk.datepicker.parse(_this.val());
			_this.datepicker('setDate', dateEntered);
		}
	})
	.each(function() {
		var _this = $(this);
		_this.val(hpk.datepicker.format(_this.datepicker('option','dateFormat'), _this.val()));
	})
	.blur(function() {
		var _this = $(this);
		_this.val(hpk.datepicker.format(_this.datepicker('option','dateFormat'), _this.val()));
	});
	
	$('.time_picker').each(function() {
		if (this._trigger == null) {
			var img = document.createElement('img');
			img.setAttribute('src','/images/time_picker.png');
			img.setAttribute('class','time_trigger');
			img._picker = this;
			this._trigger = img;
			$(this).after(img);
		}
		// Note: It's possible to set a handle and handleEvent 
		// but it ignores the disabled status of the input field.
		$(this._trigger).click(function() {
			var picker = $(this._picker);
			if (!picker.attr('disabled')) {
				picker.timepickr('show');
				var l=picker.position().left;
				picker.next('.ui-timepickr').css('left',l);
			}
		});
	}).timepickr({
		trigger:'',
		resetOnBlur:false
	});
};

// Parse dates - send in a string value of the date
hpk.datepicker.format = function(format, value) {
	try {
		var parsedDate;
		var timeStamp = Date.parse(value);
		if (isNaN(timeStamp))
			parsedDate = $.datepicker.parseDate("yy-mm-dd", value);
		else
			parsedDate = $.datepicker.parseDate("@", timeStamp);
		return $.datepicker.formatDate(format, parsedDate);
	} catch(e) {
		return value;
	}
};

// Parse date from string - return JS date object
hpk.datepicker.parse = function(value) {
	var date = new Date();
	date.setTime(Date.parse(value));
	return date;
}

hpk.datepicker.toggleTimes = function(checkbox) {
	var prefix = checkbox.id.match(/(\w+)use_times$/)[1];
	$('#'+prefix+'start_time').attr('disabled', !checkbox.checked);
	$('#'+prefix+'end_time').attr('disabled', !checkbox.checked);
};

/** flash messaging **/

// hide flash messages
hpk.flash.hide = function(delay) { 
  if (delay != null) {
    hpk.flash.timeout = setTimeout(function() { hpk.flash.hide() }, delay);
  }
  else {
		var flashes = $('#flashes');
		flashes.animate({
			duration: 'slow',
			top: -(flashes.height() + 15)
		},
		{
			complete: function() { flashes.remove() }
		});
  }
};

hpk.hintedInput.focus = function(field) {
  var _this = $(field);
  if (_this.hasClass('empty')) {
    _this.val('');
    _this.removeClass('empty');
  };
};

hpk.hintedInput.blur = function(field) {
  var _this = $(field);
  if (_this.val() == '') {
    _this.val(_this.attr('title'));
    _this.addClass('empty');
  };
};

function log(message) {
  try { console.log(message) } catch(e) {};
}

// form controls
hpk.forms.newRandomID = function() {
	return 'x' + Math.floor(Math.random() * Math.pow(10,10));
};
hpk.forms.listOptionExtras = function(id, show) {
	var extras = $('#list_option_extras_' + id);
	if (show) {
		$('.actions', extras).hide();
		$('.content', extras).fadeIn('fast');
	};
};
hpk.forms.addListOption = function() {
	var id = hpk.forms.newRandomID();
	var option = newListOption.replace(/NEW_RECORD/g, id);
	$('#new_list_options').append(option);
	hpk.datepicker.init();
	// show/hide appropriate fields for list type
	hpk.forms.showHideExtraDecisionFields(hpk.forms.getSelectedListDecisionType());
	$('#list_option_' + id).hide().fadeIn('fast');
	initAutoResize('#list_option_' + id + ' .list_option_text');
};
hpk.forms.removeListOption = function(id) {
	$('#list_option_' + id).fadeOut('fast', function() {
		$(this).remove();
	});
}
// show/hide extra flight fields
hpk.forms.toggleFlightFields = function() {
	if (hpk.forms.extraFlightFieldsHidden) {
		$('form .extras').slideDown();
		$('#toggle_hidden_fields_fieldset a span').text('Hide extra fields');
		hpk.forms.extraFlightFieldsHidden = false;
	}
	else {
		$('form .extras').slideUp();
		$('#toggle_hidden_fields_fieldset a span').text('Show more fields');
		hpk.forms.extraFlightFieldsHidden = true;
	}
};
// show extra date fields for decisions
hpk.forms.showListDecisionDates = function(trigger) {
  $(trigger).hide();
  $(trigger).siblings('.date').slideDown('fast'); 
};
hpk.forms.showHideExtraDecisionFields = function(listDecisionType) {
  var type = listDecisionType.underscore();
  if (type == 'when_list') {
    $('#question_dates').hide();
    $('.when_list_option_fields').show();
    $('.idea_list_option_fields').hide();
  }
  else {
    $('#question_dates').show();
    $('.when_list_option_fields').hide();
    $('.idea_list_option_fields').show();
  }
};
hpk.forms.getSelectedListDecisionType = function() {
  return $('#list_type_field input[type=checkbox]:checked').length == 0 ? 'IdeaList' : 'WhenList';
};
// FLIGHTS


hpk.tasks.done = function(taskElement) {
	if (taskElement.nodeName == 'A') {
		var input = $(taskElement).siblings('input');
		var value = Math.abs(input.val() - 1);
		input.val(value);
	};
	var form = $(taskElement).parents('form');
	$.ajax({
		type:"POST",
		url:form.attr('action'),
		data:form.serializeArray(),
		dataType:"script"
	});
};

hpk.alerts.dismiss = function(alertId) {
	var dismiss = $('#alert_' + alertId + ' a.dismiss');
	if (dismiss.hasClass('disabled')) {return false};
	dismiss.addClass('disabled');
	$.ajax({
		type:"POST",
		url:'/alerts/'+alertId,
		data:{'_method':'delete'},
		dataType:"script"
	});
}

hpk.users.changePassword = function() {
	$('#obfuscated_password').hide().after(passwordFields);
};

// Prototype extensions
String.prototype.strip = function() {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
};

String.prototype.underscore = function() {
  return this.replace(/::/, '/')
    .replace(/([A-Z]+)([A-Z][a-z])/,'$1_$2')
    .replace(/([a-z\d])([A-Z])/,'$1_$2')
    .replace("-", "_")
    .toLowerCase();
};

// Convert a string value into a number
function toNumber(num) {
  var re = RegExp("[^0-9.]","g");
  return Number(num.replace(re,''));
}
// Replace a text field's value with a rounded value to decimal places
hpk.forms.round = function(text_field) {
  text_field.value = toNumber(text_field.value).toFixed(2);
};

hpk.lists.showEarlierComments = function(tripId, listOptionId) {
	var option = $('#list_option_' + listOptionId);
	if ($('.loader', option).length == 0) {
		$('.show_earlier_comments', option).append('<span class="loader"><img src="/images/loader_kitt.gif" /></span>');
		// fetch the comments
		$.ajax({
			type:"GET",
			url:"/list_options/" + listOptionId + "/comments",
			data:{ 'trip_id':tripId },
			dataType:"script"
		});
	}
};



