$(document).ready(function(){
    // show loading overlay for all ajax calls 
    //$.loading({onAjax: true, mask: true, img: '/images/loadingAjax.gif' align: 'center'});
  
  // make message box less prominent
  $(window).click(function() {
    $(".systemMessageBox:visible").fadeTo('slow', 0.5);
  });  
  $(".systemMessageBox").hover(function() {
    $(this).stop();
    $(this).fadeTo('fast', 1);
  }, function() {
    $(this).stop();
    $(this).fadeTo('slow', 0.5);
  });
  
	// add ajax e-mail to click event of e-mail links
	$(".emailLink").click(ajaxemail);
	
	// add form autotabbing
	// TODO: dynamic plugin loading
	$('.autotab').length > 0 ? $('.autotab').autotab_magic() : false;
	
	// automatic ajaxForms
	if(typeof $(".ajaxForm").ajaxForm != 'undefined')
	{
    $(".ajaxForm").ajaxForm({
      dataType: 'json',
      beforeSubmit: function(formData, jqForm) {
        $(jqForm[0]).loading({ mask: true, img: '/images/loadingAjax.gif', align: 'center' });
      },
      success: function(data, status, xhr, form) {
        $(form).loading(false);
      }
    });
	}
	
	// show flash messenger if it exists
	if ($("div#flashmessage").is(":hidden")) {
		$("div#flashmessage").slideDown("slow");
	}
	
	//Hover states for flash messenger close button
	$("div#flashmessage #fm p.close a").hover(
		function() {
			$("div#flashmessage #fm p.close").animate({backgroundColor:"#ffc8c8"}, 200);
		},
		function() {
			$("div#flashmessage #fm p.close").animate({backgroundColor:"#fbfbfb"}, 200);
		}
	);
	
	//Close button for flash messenger
	$("div#flashmessage #fm p.close a").click(function() {
		$("div#flashmessage").slideUp("slow");
		return false;
	});

	//focus on element with autofocus attribute
	$("[autofocus]").focus();
	
	// start date and time
	getDateTime("div.menuTopTextTime");
	setInterval("getDateTime('div.menuTopTextTime')", 1000);
	
//  generic datepicker
	$(document).ready(function() {
	  $('input.datepicker').datepicker({
	    dateFormat: 'yy-mm-dd', 
	    maxDate: '+0',
      onSelect: function(dateText, inst) {
	      inst.input.removeClass("blur");
	    }
    });
	});
	
	// use jqueryui dialog instead of new window 
	$(".dialog").bind('click', function() {
	  $dialogLink = $(this);
	  $dialogSelector = $('<div id="dialog['+$dialogLink.text()+']"></div>')
      .appendTo($(document))
      .dialog({
        autoOpen: false,
        width: 500,
        height: 500,
        title: $dialogLink.text()
      });
	  $dialogSelector.dialog('open').load($dialogLink.attr('href'), "");
	  return false;
	});
});

/**
 * get and/or display date and time
 * @param selector  string  slector for element to automatically set text as date and time
 * @return string   date and time
 */
function getDateTime(selector)
{
  var today = new Date();
  DateTimeString = today.toLocaleDateString() + " " + today.toLocaleTimeString();
  $(selector).text(DateTimeString);
  return DateTimeString;
}

/**
 * load e-mail link with ajax instead of opening new window
 */ 
function ajaxemail()
{
  $(".emailLink").loading({mask: true, img: '/images/loadingAjax.gif', align: 'center'});
  $.get($(this).attr('href'), "",
  function(data) {
    // TODO: localization?
    $(".emailLink").loading(false);
    alert('An e-mail has been sent to your address on file');
    }
  );
  return false;
}

// handle console when firebug isn't available
try {
  console.assert(1); // test for console
}
catch(e) {
  // console replacement
  console = {
  /**
   * stores console logged lines for use when console is available
   * @param  {String}  msg  text to log
   */
  log: function(msg) {
    consoleLogger.logged.push("log:"+msg);
  },
  debug: function(msg) {
    consoleLogger.logged.push("debug:"+msg);
  },
  warn: function(msg) {
    consoleLogger.logged.push("warn:"+msg);
  },
  error: function(msg) {
    consoleLogger.logged.push("error:"+msg);
  },
  /** intercept undefined methods */
  assert: function() {},
  dir: function() {},
  trace: function() {}
};
  
  // store logged items to get later
  consoleLogger = {
    logged: [],
    /**
     * dumps stored log lines to console
     */
    dump: function() {
      for(i=0;i<this.logged.length;i++) {
        errLevel = this.logged[i].substring(0, this.logged[i].indexOf(':'));
        eval("console."+errLevel+"('"+this.logged[i].substring(this.logged[i].indexOf(':')+1)+"')");
      }
      this.logged = [];
    }
  }; 
}

function setLang(lang) {
    $.ajax({url: "/ajax/setlang",
            cache: false,
            type: 'POST',
            data: {'lang':lang},
            dataType: 'json',
            success: function(data, textStatus) {
                         if (data.result == 'success') {
                             window.location.reload(false);
                         } else {
                             // fail or error response
                             window.alert( 'Error response from AJAX function: '+data.reason );
                         }
                     },
            error: function(XMLHttpRequest, testStatus, errorThrown) {
                       $("#information").loading(false);
                       window.alert( 'AJAX request error' );
                   }
           });
}