/*

	Created to allow patients to upload photos or files to doctors
	from their contact form. This is a universal script and should work
	for all doctor sites
*/

onload=Setup;

var __DEBUG = false;

//DEFINITIONS
var __FileUploadLimit				= 2; //Default, can be changed via the page

//EXPECTED OBJECT ID'S
var __ExpectedUploadDivContainerID	= 'divUploadContainer';
var __ExpectedUploadDivFormID		= 'divUploadForm';
var __ExpectedUploadDivProgressID	= 'divUploadProgress';
var __ExpectedUploadFormName		= 'frmUploadForm';
var __ExpectedUploadButtonID		= 'cmdUpload';
var __ExpectedUploadFileID			= 'ctrlUploadFile';
var __ExpectedUploadDivMessageID	= 'divUploadMessage';
var __ExpectedUploadDivFileList		= 'divUploadFileList';
var __ExpectedHiddenFieldFileListID	= 'MailAttachments';

//OPTIONAL OBJECT ID'S
var __OptionalHiddenFileLimitID		= 'MaxFileUpload'

//INTERNAL, DO NOT CHANGE
var __TempPostIFrameID				= 'tmpPostFrame';
var __TempHiddenFieldFileNameID		= 'UploadedFileName';
var __TempFormTarget				= __TempPostIFrameID;
var __TempFormAction				= '/asp/ps-upload/upload.asp';

//GLOBAL OBJECTS
var DivForm;
var DivProgress;
var UpMan;
var DivMsg;
var DivFileList;

////////////////////////////////////////////////////////////////////////////////////////////
//DivTag Object
////////////////////////////////////////////////////////////////////////////////////////////
//DivTag object def
function DivTag(ID){this.Obj = $(ID);}
DivTag.prototype.Hide = function() {this.Obj.style.display='none';};
DivTag.prototype.Show = function() {this.Obj.style.display='';};
DivTag.prototype.HTML = function(MSG) { this.Obj.innerHTML = MSG;};

////////////////////////////////////////////////////////////////////////////////////////////
//File Object
////////////////////////////////////////////////////////////////////////////////////////////
function UploadedFile(NameFromUser, NameOnServer, FileExt, SizeOfFile)
{
	this.UserFile = NameFromUser;
	this.ServerFile = NameOnServer;
	this.FileSize = SizeOfFile;
	this.FileExt = FileExt;
};

////////////////////////////////////////////////////////////////////////////////////////////
//Upload Manager
////////////////////////////////////////////////////////////////////////////////////////////
//UploadManager object def
function UploadManager(FormID) 
{
	try
	{
		this.OrigFormTarget = '';
		this.OrigFormAction = '';

		//Cheap way for finding the form that we need to be in. supports nested forms if need be
		if(document.forms[FormID] != undefined) 
		{
			this.upForm = document.forms[FormID];	
			this.OrigFormTarget = __TempFormTarget;
			this.OrigFormAction = __TempFormAction;
		} 
		else 
		{
				
			for (var i=0; i < document.forms.length ; i++ )
			{
				if(document.forms[i].elements.length > 0 ) 
				{
					for(var x=0; x<document.forms[i].elements.length; x++) 
					{
						if(document.forms[i].elements[x].name == __ExpectedHiddenFieldFileListID || 
							document.forms[i].elements[x].id == __ExpectedHiddenFieldFileListID) 
						{
							this.upForm = document.forms[i];
							this.OrigFormTarget = document.forms[i].target;
							this.OrigFormAction = document.forms[i].action;
							break;
						}
					}
				}
			}
		}

		if(this.upForm == undefined) 
		{
			throw('No form was found!');
		}
		
		if( this.upForm.enctype != "multipart/form-data" ) 
		{
			throw(this.upForm.name + ' does not have enctype set correctly! Set to \'ENCTYPE="multipart/form-data"\'');
		}

		this.Uploaded = new Array();
		this.Container = $(__ExpectedUploadDivContainerID);

		this.EmptyUploadObject = $(__ExpectedUploadFileID).cloneNode(false);
		this.EmptyUploadObject.onchange=InitiateUpload;
		this.EmptyUploadObject.onclick=InitiateUpload;

		$(__ExpectedHiddenFieldFileListID).value = "";
	}
	catch (ex)
	{
		alert("UploadManager Initialize()\n" + ex);
		return;
	}
	
};
UploadManager.prototype.Add = function(File) 
{
	this.Uploaded[this.Uploaded.length] = File; 
	$(__ExpectedHiddenFieldFileListID).value = this.ListToString();
};
UploadManager.prototype.ListToString = function() 
{
	var Out = '';
	for(var i=0; i < this.Uploaded.length; i++) 
	{
		Out = Out + this.Uploaded[i].ServerFile;	
		if((i+1) < this.Uploaded.length)
			Out = Out + ',';
	}
	
	return Out;
};
UploadManager.prototype.ListToDivTag = function(OBJ) 
{ 
	try
	{
		var Out = '';
		for(var i=0; i < this.Uploaded.length; i++) 
		{
			Out = Out + this.Uploaded[i].UserFile + "<br />";	
		}	

		OBJ.HTML(Out); 		
	}
	catch (ex)
	{
		alert("ListToDivTag()\n" + ex);
	}

};
UploadManager.prototype.Upload = function() 
{ 
	try
	{
		if(this.Uploaded.length >= __FileUploadLimit) 
		{ 
			DivMsg.HTML("You can only upload " + __FileUploadLimit + " file(s)"); 
			this.ShowForm(); 
			return; 
		}

		var NewFrm = document.createElement('iframe');
		NewFrm.setAttribute('id',__TempPostIFrameID);
		NewFrm.setAttribute('name',__TempPostIFrameID);
	
		if(!__DEBUG)
			NewFrm.style.display = 'none';

		this.Container.appendChild(NewFrm);
	
		if(self.frames[__TempPostIFrameID].name != __TempPostIFrameID) //Bug fix for IE
			self.frames[__TempPostIFrameID].name = __TempPostIFrameID;

		//Set new form properties
		this.upForm.target = __TempFormTarget;
		this.upForm.action = __TempFormAction;

		this.upForm.submit();
	}
	catch (ex)
	{
		alert("Upload()\n" + ex);
	}
	
};
UploadManager.prototype.AddElement = function(OBJ) 
{ 
	this.Container.appendChild(OBJ); 
};
UploadManager.prototype.CleanUp = function() 
{ 
	try
	{
		//Restore form properties
		this.upForm.target = this.OrigFormTarget;
		this.upForm.action = this.OrigFormAction;

		$(__ExpectedUploadFileID).parentNode.replaceChild(this.EmptyUploadObject,$(__ExpectedUploadFileID));	

		var RemFrm = $(__TempPostIFrameID); 
		this.Container.removeChild(RemFrm); 
	}
	catch (ex)
	{
		alert(ex);
	}	
};
UploadManager.prototype.ShowForm = function() 
{
	DivForm.Show(); DivProgress.Hide();
}
UploadManager.prototype.ShowProgress = function() 
{
	DivForm.Hide(); DivProgress.Show();
}

////////////////////////////////////////////////////////////////////////////////////////////
//Functions
////////////////////////////////////////////////////////////////////////////////////////////
function $(OBJ) {return document.getElementById(OBJ);}

function ObjectExists(ObjID) 
{
	return document.getElementById(ObjID) != undefined;
}

function Setup() 
{
	try
	{
		//Verify components exist - We do this instead of dynamically creating the objects
		//to give a little more control over design for the web guys.
		if(!ObjectExists(__ExpectedHiddenFieldFileListID)) throw("Expected object doesnt exist: '" + __ExpectedHiddenFieldFileListID + "'");
		if(!ObjectExists(__ExpectedUploadDivContainerID)) throw("Expected object doesnt exist: '" + __ExpectedUploadDivContainerID + "'");
		if(!ObjectExists(__ExpectedUploadDivFormID)) throw("Expected object doesnt exist: '" + __ExpectedUploadDivFormID + "'");
		if(!ObjectExists(__ExpectedUploadDivProgressID)) throw("Expected object doesnt exist: '" + __ExpectedUploadDivProgressID + "'");
		//if(!ObjectExists(__ExpectedUploadButtonID)) throw("Expected object doesnt exist: '" + __ExpectedUploadButtonID + "'");
		if(!ObjectExists(__ExpectedUploadFileID)) throw("Expected object doesnt exist: '" + __ExpectedUploadFileID + "'");
		if(!ObjectExists(__ExpectedUploadDivMessageID)) throw("Expected object doesnt exist: '" + __ExpectedUploadDivMessageID + "'");
		if(!ObjectExists(__ExpectedUploadDivFileList)) throw("Expected object doesnt exist: '" + __ExpectedUploadDivFileList + "'");

		//Define events
		//$(__ExpectedUploadButtonID).onclick=InitiateUpload;
		$(__ExpectedUploadFileID).onchange=InitiateUpload;
		$(__ExpectedUploadFileID).onclick=InitiateUpload;


		//Get file upload limit from page
		if(ObjectExists(__OptionalHiddenFileLimitID)) 
			__FileUploadLimit = parseInt($(__OptionalHiddenFileLimitID).value)

		DivMsg = new DivTag(__ExpectedUploadDivMessageID);
		DivForm = new DivTag(__ExpectedUploadDivFormID);
		DivProgress = new DivTag(__ExpectedUploadDivProgressID);
		DivFileList = new DivTag(__ExpectedUploadDivFileList);
		
		UpMan = new UploadManager(__ExpectedUploadFormName);
		
		var obj = document.createElement('input');
		obj.setAttribute('type','hidden');
		obj.setAttribute('name',__TempHiddenFieldFileNameID);
		obj.setAttribute('id',__TempHiddenFieldFileNameID);
		
		UpMan.AddElement(obj);

		UpMan.ShowForm();

	}
	catch (ex)
	{
		alert("Setup()\n" + ex);
		return;
	}
}

function InitiateUpload() 
{
	try
	{
		if($(__TempHiddenFieldFileNameID).value == $(__ExpectedUploadFileID).value)
			return;

		if($(__ExpectedUploadFileID).value.length < 3 ) 
		{
			DivMsg.HTML('Please select a file to upload!');
			return;
		}

		//Set file name here because the ASP stuff is crazy
		$(__TempHiddenFieldFileNameID).value = $(__ExpectedUploadFileID).value;

		UpMan.ShowProgress();
		UpMan.Upload();
	}
	catch (ex)
	{
		alert("InitiateUpload()\n" + ex);
	}
}

function CompleteUpload(UserFile, ServerFile) 
{
	try
	{
		var File = new UploadedFile(UserFile,ServerFile,"",0);

		DivMsg.HTML('Upload Complete');
		UpMan.Add(File);

		if(!__DEBUG)
			UpMan.CleanUp();

		UpMan.ShowForm();

		UpMan.ListToDivTag(DivFileList);				
	}
	catch (ex)
	{
		alert("CompleteUpload()\n" + ex);
	}

}

function UploadError(MSG) 
{
	DivMsg.HTML(MSG);

	if(!__DEBUG)
		UpMan.CleanUp();
	
	UpMan.ShowForm();
}
