/**
*  Returns the full url rather than a relative one, expects url to start with context name
*/
function getFullURL(url,contextPath)
{
  if ( url.indexOf("http") == 0 )
  {
	return url;
  }
  var fullURL = document.location.toString();
  var idx = fullURL.lastIndexOf(contextPath);	  
  var returnURL = fullURL.substring(0,idx)+url;
  return returnURL;
}



function _appendParameter(url,param)
{
  var idx = url.lastIndexOf("?");
  var joiner = "&";
  if (idx==-1)
  {
	joiner = "?";
  }
  
  return url + joiner + param;
}

function _getAJAX_Data(url)
{
	data = "";
	var spl = url.split("?");
	data = spl[1];
	return data;
}
function _getAJAX_URL(url)
{
	var ret = "";
	var spl = url.split("?");
	ret = spl[0];
	return ret;
}

function MakeAJAXRequest(divname, requrl, message, rmethod, pUseEffects)
{
	MakeAJAXRequestAdv(divname, requrl, "loading", message, rmethod, pUseEffects);
}

/**
 * 
 * @param {string} divname - Id of element to update with result of request 
 * @param {string} requrl - URL to make ajax request to including parameter list 
 * @param {string} message - Message to display. This requires a div with id loadingDiv + 'Message'
 * @param {Object} loadingDiv - Id of the element to make visible during request processing
 * @param {Object} rmethod - GET or POST
 * @param {Object} pUseEffects - Whether to fade in/out divname
 */
function MakeAJAXRequestAdv(divname, requrl, loadingDiv, message, rmethod, pUseEffects)
{
	
	var	url = _appendParameter(requrl,"decorator=ajax");
	
	var ajaxRequest = {
		bodyElement : jq.selectId(divname),
		loadingElement : jq.selectId(loadingDiv),
		loadingMessageElement : jq.selectId(loadingDiv + "Message"),
			data : _getAJAX_Data(url),
			url : _getAJAX_URL(url),
		reqMethod : "post",
		useEffects : pUseEffects != undefined ? pUseEffects : true,
				
		
		go : function () {
			if ( this.data == "" )
			{
			  this.reqMethod = 'get';
			}
			
			if (message)
			{
				// this will do nothing if the element does not exist
				this.loadingMessageElement.html(message);
			}
			
			if (this.useEffects)
			{
			  var that = this;
			  this.bodyElement.fadeOut("slow",
			  	function () {
					that._doAJAX_Request();
					});
			}
			else
			{
			  this._doAJAX_Request("");
			}
		},
		/**
		 * 
		 * @param {Object} obj
		 */
		_doAJAX_Request : function (obj)	{
			var that = this;
			this.loadingElement.toggle();
			jq.ajax({type: this.reqMethod,
			  url: this.url,
			  data: this.data,
			  dataType: "html", 
			  success: function (response) {
				that.bodyElement.html(response);
				if (that.useEffects)
				{
				  that.bodyElement.fadeIn("slow");			
				}
				if (that.loadingElement.size() > 0) {
					that.loadingElement.toggle();
				}
				if (that.loadingMessageElement.size() > 0)
				{
				  that.loadingMessageElement.html("");
				}
				
			  },
			  error: function() {
				if (that.loadingMessageElement.size() > 0)
				{
				  that.loadingMessageElement.html("An error has occured sending the request");
				}
				else {
					alert("An error has occured sending the request");
				}
			  }
			  });
			  
	
		}
		
		
	};
	ajaxRequest.go();
}
		
function findPos(obj)
{
	var curleft = 0,curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while ((obj = obj.offsetParent)) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}	

function varitext(text){
	text=document;
    print(text);
}

var debug = function(){
	var debugPanel = null;
	jq(document).ready(function(){
		debugPanel = jq('#debug');
	});
	
	return {
		log:function(msg)
		{
			var d = new Date();
			var themsg = d+' - '+msg+'<br />';
			
			if (debugPanel!=null && debugPanel != undefined)
			{
				debugPanel.prepend(themsg);
			}
			else{
				alert(themsg);
			}
		},
		object:function(obj,alert)
		{
			var rtn = "{\n";
			
			for (key in obj)
			{
				if (obj.hasOwnProperty(key))
				{
					rtn+=key+"="+obj[key]+"\n";
				}
			}
			
			rtn+="}";
			
			debug.log(rtn);
			
			if (alert!=null && alert==true)
			{
				alert(rtn);
			}
			
		}
	}	
}();

/**
 * function to display help conectually based on the page being viewed or key passed in
 */
function displayHelp(helpKey)
{
	var helpText = "No help is available for this page.";
	var helpTitle = "Help";

	//TODO Display help box at mouse with help contents
	var helpCnt = jq('#helpContainer');

	helpCnt.html('');
	helpCnt.append('<div class="close"></div>');	
	helpCnt.append('<h1>'+helpTitle+'</h1>');
	helpCnt.append('<p class="body">Loading</p>');
	
	if (helpKey != undefined)
	{
		
		jq('p.body',helpCnt).load(helpKey,{decorator:'ajax'});
	}
	else
	{
		//Work out potential page name
		var loc = window.location.href;
		
		var match  = loc.match(new RegExp("\\"+servletPath+"\\/(.*?)(\\.|\\?)"));
		
		if (match)
		{
			var pageLoc = match[1];
			pageLoc = contextPath+servletPath+'/content/help/help-' + pageLoc.replace(/\//g,'-') + '.html';
	
			jq.ajax({url:pageLoc,data:'decorator=ajax',
				success:function(html)
				{
					jq('p.body',helpCnt).html(html);
				},
				error:function()
				{
					jq('p.body',helpCnt).html(helpText);
				}
				}
			);
		}
		else
		{
			jq('p.body',helpCnt).html(helpText);
		}
	}
	
	jq('.close',helpCnt).click(function(e){
		helpCnt.hide();
	});
	
	var screenWidth = jq('body').outerWidth();
	var divWidth = helpCnt.outerWidth();
	var left  = (screenWidth - divWidth )/ 2;
	helpCnt.css('left',left+'px');
	
	helpCnt.show();
	
	
}

function toggleMeasurementSystem(measurementSystem)
{
	if(!measurementSystem)
	{
		// default to metric
		measurementSystem = 'metric';
	}
	
	if (measurementSystem == 'metric')
	{
		jQuery("td[id^=imperial]").hide();
		jQuery("td[id^=metric]").show();
	}
	else if (measurementSystem == 'imperial')
	{
		jQuery("td[id^=metric]").hide();
		jQuery("td[id^=imperial]").show();
	}
	
	jQuery("input:radio[name^=measurement_system][value=" + measurementSystem + "]").attr("checked", true);
	
	// Set a cookie so that user gets what they last selected, next time - valid for 3 years
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*1095);
	document.cookie = 'measurement_system=' + escape(measurementSystem) + '; expires=' + expire.toGMTString();
}


(function($){
$.selectId = function (input) {
	if ( typeof(input ) == "string" ) {
		return $("#" + input.replace(/(\.|\[|\])/g, "\\$1"));
	}
	else {
		return $(input);
	}
}

$.fn.shake = function() {
	
	return this.each(function(){
  
	var elem = $(this);
	var oldStyle = {
		top: elem.css('top'),
		left: elem.css('left'),
		position: elem.css('position') 
	};
	
	elem.css('position','relative');
	elem.animate({left:"+=20px"}, 50)
		.animate({left:"-=40px"}, 100)
		.animate({left:"+=40px"}, 100)
		.animate({left:"-=40px"}, 100)
		.animate({left:"+=40px"}, 100)
		.animate({left:"-=20px"}, 50, "swing", function () {
			// reset css back to original values
			elem.css(oldStyle);
		});
	});
}	

$.focusFirst= function(formId) {
	$(document).ready( function () {
		$(":input:not([readonly=true]):first", "#" + formId).focus().select();
	});
}	

$.fn.tableAlternator = function(oddClass, evenClass) {
			this.each(function () {
				$("tr:not(.noHighlight):even > td",this).addClass(evenClass);
				$("tr:not(.noHighlight):odd > td",this).addClass(oddClass);
			});
		}


$.periodicalUpdater = {

    options: {
		url: "heartbeat_default.asp",
		delay: 10000,
		div_id: "test_div",
		data: {}
    },
	
	beatfunction:  function(){
	
	},
	
	timeoutobj:  {
		id: -1
	},

    set: function(options, onbeatfunction) {
		if (this.timeoutobj.id > -1) {
			clearTimeout(this.timeoutobj);
		}
        if (options) {
            $.extend(this.options, options);
        }
        if (onbeatfunction) {
            this.beatfunction = onbeatfunction;
        }

		this.beat();
    },

    beat: function() {
		$("#" + this.options.div_id).load(this.options.url, this.options.data);
		this.timeoutobj.id = setTimeout("jQuery.periodicalUpdater.beat();", this.options.delay);
        this.beatfunction();
    }
};


$.fn.hint = function () {
  return this.each(function (){
    // get $ version of 'this'
    var t = $(this); 
    // get it once since it won't change
    var title = t.attr('title'); 
    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      t.blur(function (){
	  	
        if (t.val() == '' || t.val() == title) {
          t.val(title);
          t.addClass('blur');
        }
      });
      // on focus, set value to blank if current value 
      // matches title attr
      t.focus(function (){
        if (t.val() == title) {
          t.val('');
          t.removeClass('blur');
        }
      });

      // clear the pre-defined text when form is submitted
      t.parents('form:first').submit(function(){
          if (t.val() == title) {
              t.val('');
              t.removeClass('blur');
          }
      });

      // now change all inputs to title
      t.blur();
    }
  });
}

/*
 * Force a table column to be a certain width by wrapping the contents of each
 * cell  
 */
$.fn.forceWidth = function(columnIdx, width) {
		return this.each(function(){
			
			/* TD's in IE that don't have a colspan attribute will still return
			 * true for the selector [colspan=1], but in Firefox this will fail
			 * Therefore select both colspan=1 and non existent colspan attribute 
			 */
			var q = $("td,th", this).filter("[colspan=1],:not([colspan])").filter(":nth-child("+columnIdx+")");
			
			q.each(function(){
				var wrappingDiv = $("<div></div>");
				wrappingDiv.width(width);
				wrappingDiv.css("overflow", "hidden").css("white-space", "nowrap");
				
				var cell = $(this);
				
				wrappingDiv.attr("title", cell.text());
				$(this).contents().wrap(wrappingDiv);
				
				// if any inputs are in the cell then make them smaller
				cell.find(":text").each(function() {
					if ( $(this).width() > (width-10) ) {
						$(this).width(width-10);	
					}
				});
				
			});
		});
}

})(jQuery);	