// JavaScript Document
//
// * LabXUploader 0.1.3
// * http://www.labx.com
// *
// * Copyright (c) 2010 LabX
// *
// * Date: Jan 13 2010
// * TESTED ON
// * ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
// * FF 3.5.5
// * MSIE 6/7/8
// * Chrome 3.0.x
// * Safari 4.0.4
// *
// * DEPENDENCIES
// * ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
// * jQuery JavaScript Library v1.3.2
// * http://jquery.com/
// *
// * USE
// * ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
// * use image defaults:
// * $('#element').LabXUploader();
// * set defauls:
// * $('#element').LabXUploader(
// *		fileType: { 
// *			Type: "image",
// *			Icon: "url",
// *			Ext: "(jpg|gif|png)"
// *		},
// *		fileProcessImage: "url",
// *		emptyIcon: "url",
// *		errorIcon: "url",
// *		url: "url",
// *		title: true,
// *		titleFieldName: "Title",
// *		fileFieldName: "FileName",	
// *		addtionalField: "",
// *		additionalFieldBefore: true,
// *		addFile: true,
// *		addFileBTN: true,
// *		callback: {
// *			BeforeUpload: function(_UploaderOBJ,_Form) {},
// *			UploadSuccessful: function(_Form,_MSG) {},
// *			UploadFailed: function(_Form,_MSG) {},
// *			Init: function(_UploaderOBJ) {},
// *			AddFile: function(_UploaderOBJ,_NewForm) {}
// *		}
// * );
// *
// * CallBack Variables
// * ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
// * _Form 			: returns the actual form which is used in the procress
// * _MSG  			: returns the string that is retuned from the submit process
// * _UploaderOBJ 	: returns the master group object holding all the sub forms
// * _NewForm 		: returns the newly created form
// * 
// * HISTORY
// * ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
// * Modified Jan 13 2010
// * - Inserted Callbacks for both Sucessful and Failed Uploads
// * - Inserted Callback for after Init and AddFile is completed
// * - Inserted Callback for Before Upload starts
// * Modified Jan 7 2010
// * - moved form tags to only wrap the file and upload button
// * - all fields can now be named
// * - upon upload, related input fields get the filename appended to there names
// * 
(function($) {
	$.fn.LabXUploader = function(options) {
		return new LabXUploaderCore().init(this,options);
	};
	function LabXUploaderCore() {
		return {
			defaults : {
				fileType: { 
					Type: "image",													// string: the name of the Accepted File type | default: "image"
					Icon: "/core/images/icons/attach_image.png",					// url: the path and file of the image to use for the icon when upload is completed
					Ext : "(jpg|gif|png)"											// string: the accepted file extentions | default: "(jpg|gif|png)"
				},
				fileProcessImage: "/core/images/loading_hbar.gif",					// url: the path and file of the image to use when uploading
				emptyIcon: "/core/images/icons/attach_paperclip.png",				// url: the path and file of the image to use for the icon before upload
				errorIcon: "/core/images/icons/attach_paperclip_fail.png",			// url: the path and file of the image to use for the icon is upload fails
				url: "/?fa=coreUtilities.uploadFile",								// url: the url of the server side upload file
				title: true,														// boolean: show a title field | default: true
				titleFieldName: "relatedUploadField_photoTitle",					// string: the fieldname for the title field
				fileFieldName: "FileName",											// string: the fieldname for the title field
				additionalField: "",												// string: any additional fields to be added to the form. | default: ""
				additionalFieldBefore: true,										// boolean: list an additional field before the title. | default: true
				addFile: true,														// boolean: show to "Add File" button | default: true
				addFileBTN: false,													// boolean: show Add File as Button instead of a Link | default: true
				callback: {
					BeforeUpload: function(_UploaderOBJ,_Form) {},					// function: This custom function is executed before an upload occures.
					UploadSuccessful: function(_Form,_MSG) {
						_Form.find('.btnFile_Remove').show();
					}, 																// function: This custom function is exicuted on sucessfull upload.
					UploadFailed: function(_Form,_MSG) { alert('Upload Failed.  Please Try Again'); },			// function: This custom function is executed on a failed upload
					Init: function(_UploaderOBJ) { 
						$(_UploaderOBJ).find(".btnUpload").after("\n\t\t<div class='btnFile_Remove_block'><a href='' class='btnFile_Remove'><span>Remove File</span></a></div>");
						$(_UploaderOBJ).find(".btnFile_Remove").hide();
					}, 																// function: This custom function is executed once Init has completed
					AddFile: function(_UploaderOBJ,_NewForm) {} 					// function: This custom function is executed After the Addfile Button has been clicked
				}
			}, // Close defaults
		 	init: function(form,options){
				// -------------------------------------------------------------
				// init
				// -------------------------------------------------------------
				var _Me = form;
				var opts = $.extend({},LabXUploaderCore().defaults, options);
				if (opts.title) {
					if (opts.additionalFieldBefore) {
						opts.additionalField = opts.additionalField + "\n\t\t<div class='FileTitle'><label for='" + opts.titleFieldName + "'>Title: </label><input type='text' name='" + opts.titleFieldName + "' /></div>";
					}
					else {
						opts.additionalField = "<div class='FileTitle'><label for='" + opts.titleFieldName + "'>Title: </label><input type='text' name='" + opts.titleFieldName + "' /></div>\n\t\t" + opts.additionalField;
					}
				}
				_Me.html("\n<div class='LabXUploaderUserInput'>\n\t<div id='LabXUploader1' class='LabXUploaderUserInputGroup'>\n\t\t<div class='LabXUploaderIcon'><img src='" + opts.emptyIcon + "' /></div>\n\t\t<div class='UploaderFormInputElements'>\n\t\t\t" + opts.additionalField + "\n\t\t\t<form action='' method='post' enctype='multipart/form-data'>\n\t\t\t\t<div class='FileName'><label for='" + opts.fileFieldName + "'>File: </label><input type='file' name='" + opts.fileFieldName + "' /></div>\n\t\t\t\t<div class='btnUpload'><button name='btnUpload'>Upload</button></div>\n\t\t\t</form>\n\t\t</div>\n\t</div>\n</div>\n");
				if (opts.addFile) {
					if (opts.addFileBTN) {
						_Me.append("<div class='btnAddFileDiv'><button name='btnAddFile' class='btnAddFile'>Add File</button></div>\n");
					}
					else {
						_Me.append("<div class='btnAddFileDiv'><a href='' class='btnAddFile'>Add File</a></div>\n");
					}
				}
				opts.callback.Init(_Me);
		
				// -------------------------------------------------------------
				// events
				// -------------------------------------------------------------
				_Me.find('.btnAddFile').click( function() {
					var _CurCount = _Me.find('.LabXUploaderUserInput').find('input[type="file"]').size() + 1;
					var _Obj = _Me.find('.LabXUploaderUserInput').find('.LabXUploaderUserInputGroup:first').clone(true)
					_Me.find('.LabXUploaderUserInput').append(_Obj);
					_Obj.find('input').val("").removeAttr('disabled').removeAttr('checked').removeAttr('selected').show();
					_Obj.find('input').each( function() {
						var _thisName = $(this).attr('name');
						if (_thisName.indexOf("_") > 0) {
							$(this).attr('name',_thisName.substring(0,_thisName.indexOf("_")));
						}
					});
					_Obj.find('button').show();
					_Obj.find('iframe').remove();
					_Obj.attr('id',_Obj.attr('id').substr(0,(_Obj.attr('id').length-1)) + _CurCount);
					_Obj.find('.LabXUploaderStatus').remove();
					_Obj.find('img').attr('src',opts.emptyIcon);
					_Obj.show();

					opts.callback.AddFile(_Me,_Obj);
					return false;
				}); // Close btnAddFile.click
				_Me.find('button[name="btnUpload"]').click( function() {
					var _Form = $(this).parents('.LabXUploaderUserInputGroup:first');
					var _UploadForm = $(this).parents('form:first');
					opts.callback.BeforeUpload(_UploadForm,_Form);
					if (_Form.find('input[name="' + opts.fileFieldName + '"]').val() != "") {
						ExtRegEx = new RegExp("\." + opts.fileType.Ext + "$","gi");
						if (ExtRegEx.test(_Form.find('input[name="' + opts.fileFieldName + '"]').val())) {
							_Form.find('input[name="' + opts.fileFieldName + '"]').hide().after("<span class='LabXUploaderStatus'></span>");
							_Form.find('.LabXUploaderStatus').html("<img src='" + opts.fileProcessImage + "' alt='processing' />");
							UploadFile(_UploadForm,opts.url);
							_Form.find('input').attr('disabled','disabled');
							_Form.find('button').hide();
							_Form.find('.iFrameUploader').load( function() {
								var _ReturnMSG = $(this).contents().find('body').html().replace(/^\s+|\s+$/g,"");
								if (_ReturnMSG.match(/(error|fail|sorry)/gi)) {
									// Returned Page contained the Error/Fail/Sorry... Assume there was a problem
									_Form.find('input').removeAttr('disabled').show();
									_Form.find('button').show();
									_Form.find('.LabXUploaderStatus').remove();
									_Form.find('img').attr('src',opts.errorIcon);
									opts.callback.UploadFailed(_Form,_ReturnMSG);
								}
								else {									
									if (_Form.find('img').attr('src') != opts.fileType.Icon) {
										_Form.find('.LabXUploaderStatus').html("<strong>Uploaded: </strong>" + _Form.find('input[name="' + opts.fileFieldName + '"]').val());
										_Form.find('img').fadeOut(400, function() {
											$(this).attr('src',opts.fileType.Icon).fadeIn(500);
										});
									}
									var _FileNameReturn = _ReturnMSG.replace(/^\s+|\s+$/g,"");
									_UploadForm.append("<input type='hidden' name='thisFileName' class='thisFileName' value='" + _FileNameReturn + "' />");
									_Form.find('input[name!="' + opts.fileFieldName + '"]').removeAttr('disabled');
									_Form.find('input[type!="file"]').each( function() {
										// Change the Name of all Associated fields to contain the FileName of the uploaded file
										$(this).attr("name",$(this).attr("name") + "_" + _FileNameReturn);
									});
									opts.callback.UploadSuccessful(_Form,_ReturnMSG);
								}
							});
						} // END IF test(RegEx)
						else {
							alert("'" + _Form.find('input[name="' + opts.fileFieldName + '"]').val() + "' is not a valid " + opts.fileType.Type);
						}
					} // END IF val() != ""
					else {
						alert("Please select a " + opts.fileType.Type + " to upload");
					}
					return false;
				});
			} // CLOSE .init
		}// Close Return
	
		function UploadFile(_Form,_Url) {
			var _thisID = "iFrameUploader" + new Date().getTime();
			_Form.append("<iframe src='' id='" + _thisID + "' name='" + _thisID + "' class='iFrameUploader' src='javascript:false' style='position: absolute; top: -1000px; left: -1000px; width: 0; height: 0;'></iframe>");
			$(_Form).attr('action', _Url);
			$(_Form).attr('method', 'POST');
			$(_Form).attr('target', _thisID);
			if(_Form.encoding) {
				_Form.encoding = 'multipart/form-data';				
			}
			else {				
				_Form.enctype = 'multipart/form-data';
			}			
			$(_Form).submit();		
		} // Close UploadFile
	} // Close LabXUploaderCore
})(jQuery);
