var DEBUG = 1;

// create namespaces to separate functions
function namespace(ns) {
  ns = ns.split('.');
  var cur = window, i;
  while ( i = ns.shift() ) {
    if ( !cur[i] ) cur[i] = {};
    cur = cur[i];
  }
}
namespace('hpk');
namespace('hpk.cookies');
namespace('hpk.ledgers');
namespace('hpk.help');
namespace('hpk.forms');
namespace('hpk.purchases');
namespace('hpk.payments');
namespace('hpk.bulletin');

$(function() {
  // init hoverable items
  $('.hoverable').mouseenter(function() {
    $(this).addClass('mouseover');
  }).mouseleave(function() {
    $(this).removeClass('mouseover');
  });
  // hide flashes
  if ($('#flashes').length > 0) {
    setTimeout(function() {
      $('#flashes').fadeOut('fast', function() {
        $(this).remove();
      });
    }, 4000);
  };
});

// 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);
});

// serialize the form and submit via ajax
// TODO return true if script fails - this will fall back to 
// a standard form submission.
hpk.forms.remote = function(form) {
	log(">>> Submitting remote form")
	$.ajax({
		type:     "POST",
		url:      form.action,
		data:     $(form).serialize(),
		dataType: "script"
	});
	return false;
};

// Cookies
hpk.cookies.create = function(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
};

hpk.cookies.read = function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
};

hpk.cookies.erase = function(name) {
	hpk.cookies.create(name,"",-1);
};
// switch to a new ledger
hpk.ledgers.change = function(select_field) {
	var id = $(select_field).val();
	if (id != '0') {
		var match = window.location.pathname.match(/ledgers\/\d+(\/[a-z_]+)?/);
		var extra_path = match && match[1] ? match[1] : "";
		window.location = '/ledgers/' + id + extra_path;
	};
};
// 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);
};
// Show help panel
hpk.help.show = function() {
	log(">>> Showing help panel");
	if( $('#help_panel_content:visible').length == 1 ) { 
		log("- already visible");
		return; 
	};
	$('#help_panel_content').slideDown();
	$('#help_panel_link').text("Help");
	hpk.cookies.create("hide_help", "no");
};
// Hide the sidebar help panel
hpk.help.hide = function() {
	log(">>> Hiding help panel");
	$('#help_panel_content').slideUp();
	$('#help_panel_link').text("Help (click to open)");
	hpk.cookies.create("hide_help", "yes", 30);
};
// enable/disable button
hpk.forms.disableButton = function(button_id, text) {
	var button = $('#'+button_id);
	button.attr('disabled', true);
	$('.inner', button).text(text);
};
hpk.forms.disableAndSubmitButton = function(button, text) {
	var _this = $(button);
	hpk.forms.disableButton(_this.attr('id'), text);
	_this.parents('form').submit();
};
hpk.forms.enableButton = function(button_id, text)
{
	var button = $('#'+button_id);
	button.attr('disabled', false);
	$('.inner', button).text(text);
};
// Users
hpk.forms.addPerson = function(form) {
	log(">>> Adding person...");
	if ($('#new_user_email').val() == "") {
		log("- email empty");
	}
	else {
		$('#new_user_response').hide();
		hpk.forms.disableButton('new_user_button','Adding...');
		hpk.forms.remote(form);
	}
	return false;
};
// make resend invite form visible
hpk.forms.showInvite = function(userId) {
	$('#ledger_user_actions_' + userId).fadeOut('fast');
	$('#resend_invite_form_' + userId).slideDown('fast');
	return false;
};
hpk.forms.hideInvite = function(ledger_user_id) {
	$('#ledger_user_actions_' + ledger_user_id).fadeIn('fast');
	$('#resend_invite_form_' + ledger_user_id).slideUp('fast');
	return false;
};
hpk.forms.resendInvite = function(form) {
	var button = $('button', form);
	hpk.forms.disableButton(button.attr('id'), 'Sending...');
	return hpk.forms.remote(form);
};
hpk.forms.makeAdmin = function(checkbox) {
	var _this = $(checkbox);
	var match = _this.attr('id').match(/(\d+)$/);
	var userId = match[1];
	var path = "/ledgers/"+LEDGER+"/permissions";
	var data = {
		user_id : userId,
		_method : 'put',
		admin   : checkbox.checked
	};
	log(path);
	$('#admin_spinner_' + userId).show();
	_this.hide();
	$.ajax({ type:"POST", url:path, data:data, dataType:"script" });
}

// Display more purchase info
hpk.purchases.info = function(trigger) {
	var div = $(trigger).parents('div.joint_purchase,div.purchase');
	$(div).addClass('expanded');
}

// show/hide modified and deleted purchases or repayments
hpk.ledgers.toggleHiddenTransactions = function() {
  $('#listing_filter_form').submit();
};

hpk.bulletin.close = function(bulletinId) {
	$('#system_bulletin').fadeOut();
	hpk.cookies.create('last_bulletin', bulletinId, 365);
}

function log(message) {
	if( !DEBUG || RAILS_ENV == 'production') return;
	try { console.log(message) } catch(e) {};
}
