// global App class
var App = new function() {
  // init public scope
  this.root = '';
  this.helpers = {
	logOut : function() {
	  var btn = $('#logout');
	  var ht = $('html')[0]; 
	  if (btn.size()) {
		btn[0].onclick = function(e) {
		  ht.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';  
		  if (confirm('Are you sure you want to log out?')) {
			return true;
		  } else {
			ht.style.filter = '';
			return false;
		  }
		};
	  }
	},
	
	loadFocus : function() {
	  var f = $('#loadfocus');
	  if (f.size()) {
		try {
		  f[0].focus();
		} catch (e) {};
	  }
	  return true;
	},
	
	confirmSave : function(m) {
	  return confirm('Are you sure you want to save' + (m.length ? ' ' : '') + m + '?\nConfirm all changes are correct before proceeding.');
	},	
	
	confirmDelete : function(m) {
	  return confirm('Are you sure you want to delete' + (m.length ? ' ' : '') + m + '?\nThis is cannot be reversed!');
	},
	
	confirmSend : function(m) {
	  return confirm('Are you sure you want to send' + (m.length ? ' ' : '') + m + '?');
	},
	
	confirmDefault : function(m) {
	  return confirm('Are you sure you want to' + (m.length ? ' ' : '') + m + '?');
	}	
  };
  
  this.init = function() {
	$(function() {
	  // get the root url
	  App.root = $('#logo').attr('href');
			   
	  // init helpers
	  App.helpers.loadFocus();
	  App.helpers.logOut();
	  //start tabs
	  App.initTabs();
	  // set up login form
	  App.initLogin();
	  // init misc
	  App.initMisc();
	});	  
  };
  this.initTabs = function () {
	if (!$.tabs) { return false; }
	// start any tabs
	$('.tabs').not('.normal').tabs({selectedClass: 'selected', fxSlide: true, fxFade: false, fxSpeed: 'fast'});
  };
  this.initLogin = function () {
	var $f = $('#user-login form'), $m, v = $('#ul_user, #ul_pass').get(), i;

	$f.bind(
	  'submit', 
	  function() { 
	    for (i = 0; i < v.length; i++) {
		  if (!/^[^\s]{4,16}$/.test(v[i].value)) {
			$m = ($m ? $m : $('div.message', $f.prepend('<div class="message">Invalid format, please correct</div>')).hide()).fadeIn(1500);
			return false;
		  }
		}
	  }
	);
  };
  this.initMisc = function () {
	// set click handlers
	$('.confirmsave').bind( 'click', function() { 
	  return App.helpers.confirmSave( this.title ); 
	});
	$('.confirmdelete').bind( 'click', function() { 
	  return App.helpers.confirmDelete( this.title ); 
	});
	$('.confirmsend').bind( 'click', function() { 
	  return App.helpers.confirmSend( this.title ); 
	});
	$('.confirmdefault').bind( 'click', function() { 
	  return App.helpers.confirmDefault( this.title ); 
	});	
	// set messages to show
	$('.message').hide().fadeIn(1500);
	// fix bg flicker in IE 6
	try {
	  document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {};	  
  };
};
App.init();