function configureTinyMCEEditor( id, content ) {
	// tinymce may not be initialized yet
	var intv = setInterval( function() {
		if( typeof(tinyMCE) != "undefined" ) {
			var editor = 
				tinyMCE.getInstanceById( $(this.container).find("textarea[name='" + id + "']").attr("id") )[0];
			if( editor != null ) {
				clearTimeout( intv );
				editor.settings.convert_urls = 0;
				if( content != null )  { editor.setContent( content ); }
			}
		} 
	}, 250);	
	return ;
}

function jqGridStupidBugBGone( dumbArray ) {
	if( ! dumbArray[0] )	{
		var smartArray = new Array();
		for( var i=1; i<dumbArray.length;i++ ) {
			smartArray.push( dumbArray[i] );
		}
		return smartArray;
	}
	return dumbArray; // Array not dumb
}

function makeMMDDYYYFormat(value) {
	var dateArray = value.split("-");
	
	return dateArray[1] + "/" + dateArray[2] + "/" + dateArray[0];
}

function simpleDateFormatter(cellvalue, options, rowObject) {
	if(cellvalue==null || cellvalue.length==0) {
		return "";
	}
	
	return makeMMDDYYYFormat(cellvalue.split("T")[0]);
}

function dateTimeFormatter(cellvalue, options, rowObject) {
	if(cellvalue==null || cellvalue.length==0) {
		return "";
	}
	
	var dateTimeArray = cellvalue.split("T");
	
	return makeMMDDYYYFormat(dateTimeArray[0]) + " " + dateTimeArray[1];
}

function getDateFromDBVar(val) {
	return val.split("T")[0];
}

function getTimeFromDBVar(val) {
	return val.split("T")[1];
}

function getFormattedTime(timeLeft) {
	var hours = Math.floor(timeLeft/3600);
	var minutes = Math.floor(timeLeft/60)-(hours*60);
	var seconds = timeLeft-(hours*60)-(minutes*60);
	
	return (hours>0 ? (hours<10 ? "0" + hours : hours) + ":" : "") +
	       (minutes>0 ? (minutes<10 ? "0" + minutes : minutes) + ":" : "") + 
	       (seconds<10 ? "0" + seconds : seconds);
}

//Return new array with duplicate values removed
function nunique( array ) {
    var a = [];
    var l = array.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (array[i] === array[j])
          j = ++i;
      }
      a.push(array[i]);
    }
    return a;
}

function unique( array, comparator ) {
    var a = [];
    var l = array.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if ( comparator(array[i], array[j] )==0 ) {
          j = ++i;
        }
      }
      a.push(array[i]);
    }
    return a;
}

function getShortDate(s) {
	var dateParts = s.split("-");
	
	return new Date((new Date()).getFullYear(),dateParts[0]-1,dateParts[1]-1);
}

function getDate(s) {
	var dateParts = s.split("-");
	var monName = dateParts[1].toUpperCase();
	var monNumber = 0;
	
	if(monName=="JAN") { monNumber = 0;
	} else if(monName=="FEB") { monNumber = 1;
	} else if(monName=="MAR") { monNumber = 2;
	} else if(monName=="APR") { monNumber = 3;
	} else if(monName=="MAY") { monNumber = 4;
	} else if(monName=="JUN") { monNumber = 5;
	} else if(monName=="JUL") { monNumber = 6;
	} else if(monName=="AUG") { monNumber = 7;
	} else if(monName=="SEP") { monNumber = 8;
	} else if(monName=="OCT") { monNumber = 9;
	} else if(monName=="NOV") { monNumber = 10;
	} else if(monName=="DEC") { monNumber = 11;
	}
		
	return new Date(dateParts[2],monNumber,dateParts[0]-1);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

String.prototype.startsWith = function(str) { 
	return (this.match("^"+str)==str);
};

String.prototype.endsWith = function(str) { 
	return (this.match(str+"$")==str);
};

function dateColumn( val ) {
	return val.split("T")[0];
}

function imageColumn( val ) {
	var src = "";
	if( val == null )
		src = LT.image( "no-image.gif" );
	else 
		src = LT.action("/resource/image?id=" + val);
	var html = "<img src=\"" + src + "\" style=\"max-width: 300px; max-height: 25px;\" />"; 
	return html;
}

function validateEmail(elementValue) {   
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;   
	return emailPattern.test(elementValue);   
}  


function validateNumeric(myfield, e, dec) {
	var key;
	var keychar;

	if (window.event) {
	   key = window.event.keyCode;
	} else if (e) {
	   key = e.which;
	} else {
	   return true;
	}
	
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) ) {
	   return true;
	} else if ((("0123456789").indexOf(keychar) > -1)) {
	   return true;
	} else if (dec && (keychar == ".")) {
	   myfield.form.elements[dec].focus();
	   return false;
	} else {
	   return false;
	}
}

function validateZIP(myfield, e, dec) {
	var key;
	
	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}
	
	var reZip = new RegExp(/(^\d{1,5}$)|(^\d{5}-\d{0,4}$)/);
	
	return reZip.test(myfield.value + String.fromCharCode(key));
}

var selectors = 0;

function ImageFileSelector( image, input ) {
	var me = this;
	selectors++;
	var namePrefix = "image_" + selectors + "_";
	
	this.image = image;
	this.input = input;
	
	this.imageForm = document.createElement( "form" );
	this.fileInput = document.createElement( "input" );
	this.elementInput = document.createElement( "input" );
	this.inputInput = document.createElement( "input" );
	
	this.elementInput.name = "elementId";
	this.elementInput.value = $(image).attr("id");
	this.elementInput.type = "hidden";
	
	this.inputInput.name = "inputId";
	this.inputInput.value = $(input).attr("id");
	this.inputInput.type = "hidden";
	
	this.fileInput.id = namePrefix + "input";
	this.fileInput.type = "file";
	this.fileInput.name = "file";
	$(this.fileInput).css("width","100%");
	this.imageForm.id = namePrefix + "form";
	
	this.imageForm.appendChild( this.fileInput );
	this.imageForm.appendChild( this.elementInput );
	this.imageForm.appendChild( this.inputInput );
	image.parent().append( this.imageForm );
	
	$(this.fileInput).addClass("file");
	$(me.imageForm).attr("enctype","multipart/form-data");
	$(me.imageForm).attr("method","post");
	$(me.imageForm).attr("action",LT.action("resource/upload"));
	
	this.formSubmit = function( event ) {
		var me = event.data.me;
		$(me.imageForm).ajaxSubmit( me.options );
		return false;
	};
	$(this.fileInput).bind( "change", {"me":me}, this.formSubmit);
}

function BillWidget( container, bill ) {
	this.bill = bill;
	this.container = container;
	this.element = $("#bill-widget-template").clone();
	$(this.element).show();
	$(container).append( this.element );
	
	$(this.element).find("div[class*='ui-bill-number']").html( bill.billNumber );
	$(this.element).find("div[class*='ui-bill-title']").html( bill.title );
	$(this.element).find("div[class*='ui-bill-description']").append( bill.purpose );
	
	try {
	for( var j=0; j<2; j++ ) {
		var action = $("#bill-widget-action-template").clone();
		$(action).append( bill.history[j].description + " "
				+ dateFormat( bill.history[j].actionDate, "m/dd/yyyy" ) );
		$(this.element).find("div[class*='ui-bill-actions']").append( action );
	} } catch( e ) {
		
	}
}

function TagWidget( container, tag ) {
	var spandId = tag.name.replace(/[^a-zA-Z 0-9]+/g,'').replace(/\s+/g,'');
	var spanTag = "<span id=\"" + spandId + "\" class=\"ui-tag-remove ui-icon ui-icon-circle-close\" ></span>";
	
	this.tag = tag;
	this.container = container;
	this.element = $("#tag-widget-template").clone();
	$(this.element).show();
	$(container).append( this.element );
	
	$(this.element).find("div[class*='ui-tag-name']").html( spanTag + tag.name );
	$(this.element).css("background-color", tag.backgroundColor );
	$(this.element).css("color", tag.textColor );
	
	$(this.element).find("span[id*='" + spandId + "']").live('click', function(e) {
		e.preventDefault;
		$(this).parent().parent().hide(3000, function() {
			// alert(tag.name + " was removed");	
		});
	});
}

function attachment(id, name) {
	this.id=id;
	this.name=name;
}

function AttachmentWidget( container, attachment, idField, removeable ) {
	var spandId = attachment.name.replace(/[^a-zA-Z 0-9]+/g,'').replace(/\s+/g,'');
	var spanTag = "<span id=\"" + spandId + "\" class=\"ui-attachment-remove ui-icon ui-icon-circle-close\" ></span>";
	
	this.attachment = attachment;
	this.container = container;
	this.idField = idField;
	
	$("#" + idField).val($("#" + idField).val() + "," + attachment.id);
	this.element = $("#lt-templates").find("div[template='attachment-widget-template']").clone().removeAttr("template");
	$(this.element).show();
	$(container).append( this.element );
	
	$(this.element).find("div[class*='ui-attachment-name']").html( spanTag + attachment.name );
	$(this.element).find("div[class*='ui-attachment-id']").html( attachment.id );
	
	if(removeable) {
		$(this.element).find("span[id*='" + spandId + "']").live('click', function(e) {
			e.preventDefault;
			$(this).parent().parent().hide(3000, function() {
				var ids = $("#" + idField).val().split(",");
				var newIds = "";
				
				for(i=0;i<ids.length;i++) {
					if(ids[i]!=attachment.id) {
						newIds = newIds + ids[i] + ",";
					}
				}
				$("#" + idField).val(newIds);
			});
		});
	} else {
		$(this.element).find("span[id*='" + spandId + "']").remove();
	}
}

function RecipientWidget( container, recipient, enableRemoval ) {
	var spandId = recipient.displayText.replace(/[^a-zA-Z 0-9]+/g,'').replace(/\s+/g,'');
	var spanTag = "<span id=\"" + spandId + "\" class=\"ui-recipient-remove ui-icon ui-icon-circle-close\" ></span>";
	
	this.recipient = recipient;
	this.container = container;
	
	this.element = $("#lt-templates").find("div[template='recipient-widget-template']").clone().removeAttr("template");
	$(this.element).show();
	$(this.container).append( this.element );
	
	var nameText = "";
	
	if(enableRemoval) {
		nameText = spanTag + recipient.displayText;
	} else {
		nameText = recipient.displayText;
	}
	
	$(this.element).find("div[class*='ui-recipient-name']").html( nameText );
	$(this.element).find("div[class*='ui-recipient-email']").html( recipient.emailAddress );
	
	if(enableRemoval) {
		$(this.element).find("span[id*='" + spandId + "']").live('click', function(e) {
			e.preventDefault;
			$(this).parent().parent().hide(300, function() {
				removeRecipient(recipient);
			});
		});
	}
}

function Recipient(displayText, emailAddress, personType) {
	this.displayText = displayText;
	this.emailAddress = emailAddress;
	this.personType = personType;
}

function updateImage( elementName, inputElement, id ) {
	$("#"+elementName).attr( "src", LT.action("resource/image?id=" + id ));
	$("#"+inputElement).val( id );
}

function buildUrl(action) {
	return window.location.protocol + "//" +
		   window.location.host	+ 
		   LT.action(action);
}

function adminOption(action,image,description) {
	this.action = action;
	this.image = image;
	this.description = description;
}
