/* ocms-signInTransmogrifier.js */
//	2011-Feb-10  now with support for change password panels

(function () {
	if (typeof OCMS === "undefined") {
		/* OCMS becomes a global var */
		OCMS = {};
	}
	
	if (OCMS.signInTransmogrifier === undefined) {
		OCMS.signInTransmogrifier = function (args) {

			var selector = args.selector || args,
				newTemplate = args.newTemplate || null;
				
			var	settings = {
					addClasses: false,
					text: {user: null, password: null, signIn: null, forgot: null},
					attrs: {user: null, password: null, signIn: null, forgot: null}
			};
				
				if (typeof args === "object") {
					$.extend(true, settings, args);
				} // else -- not supported!
				
			var	$signin = null,
				newSignIn = "",
				ids = [null, null, null, null],
				$tds = null,
				tdsContent = [],
				$errDiv = null,
				$errMsgDiv = null,
				errorClass = '',
				errorMessage = '';
					

			$signin = $(selector);
			if ($signin.size() === 1) {
				
				// before we gather up td's into this jQuery collection, look for, save, and
				// then remove the error message information
				// if present it will be in a table that precedes the regular sign in table

				$errDiv = $signin.find('div.message');
				if ($errDiv.length === 1) {
					
					errorClass = $errDiv.removeClass('message').attr('class');
					$errMsgDiv = $errDiv.find('div.messageText');
					$errMsgDiv.find('span').remove().end()
							.find('h4').remove().end()
							.find('br').remove();
					errorMessage = $errMsgDiv.text().trim();
					errorMessage.replace(/sername/, 'ser name');
					
					//Crude statement to remove the weird ID showing with this error message
					if (errorMessage.indexOf('Validation Error: Value is required.') > 0){
						
						errorMessage = 'Validation Error: Value is required.';
						
					}
					
					
					// errorMessage and errorCass will be appended to tdsContent[] later
					$errDiv.remove();
				} else {
					// perhaps it's a change password form (different div.class)
					$errDiv = $signin.find('cp-errors');
					if ($errDiv.length === 1) {
						errorMessage = $errMsgDiv.text().trim();
						$errDiv.remove();					
					}
				}
				
				$tds = $signin.find("td");
				// this is what we're expecting
				// (first row) 
				// 0 : label for username
				// 1 : input[text] for username
				// (second row)
				// 2 : label for password
				// 3 : input[password] for password
				// (third row)
				// 4 : <empty>
				// 5: input[submit]
				// (fourth row)
				// 6 : <empty>
				// 7 : <empty>
				// (fifth row)
				// 8 : <empty>
				// 9 : span a "Forgot Your password?"
				
				var fieldInfo = [
					/* user: */		{	attrs: settings.attrs.user,
										text: settings.text.user,
										clas: "txtUser"
									},
					/* password: */	{	attrs: settings.attrs.password, 
										text: settings.text.password,
										clas: "txtPassword"
									},
					/* signIn: */ 	{	attrs: settings.attrs.signIn, 
										text: settings.text.signIn,
										clas: "butSignIn"
									},
					/* forgot: */	{	attrs: settings.attrs.forgot, 
										text: settings.text.forgot,
										clas: "forgotPassword"
									}
				];
				
				$tds.find("[id]").each(function (nIt) {
					var $this = $(this),
						info = fieldInfo[nIt];
						
					ids[nIt] = $this.attr("id");
					if (settings.addClasses) {
						$this.addClass(info.clas);
					}
					if (typeof info.attrs === "object") {
						$this.attr(info.attrs);
					}
					
					// experimental! -- complete with hard-wired assumptions
					// input[type=text] VALUEs are not displayed after the .replaceWith()

					if (typeof info.text === "string") {
// $fail				if ($this.is("input")) {
						var el = $this.get(0);
						if (el.tagName.toLowerCase() === "input") {
// $fail					$this.val(info.text);
							el.value = info.text;
						} else {
							if (el.tagName.toLowerCase() === "label") {
								el.innerHTML = info.text;
							} else {
								if (el.tagName.toLowerCase() === "span") {
									// span#some:long:id a "Forgot Your Password?"
									el.children[0].innerHTML = info.text;
								}
							}
						}
					}
				});

				if (newTemplate) {
					// copy the contents of each td into an array for insertion into the template
					$tds.each(function (nIt) {
						tdsContent.push($(this).html());
					});
					tdsContent.push(errorMessage);		// 10
					tdsContent.push(errorClass);		// should be at offset 11 -- currently meaningless
				
					var numerics = null;
					
					var txtSelector='';
					if (selector.attr('id')!=null){txtSelector= '#' + selector.attr('id')}
					else if (selector.attr('class')!=null){txtSelector='.'+selector.attr('class')}
					
					// how many rows in the change password table (two flavours of Change Password panel)
					var $nRows = $(txtSelector + ' tr');
					
					
					switch ($nRows.length) {						
						case 1 || ($('.messageTable').length && 3):
							
							numerics = {
								forgotPasswordLabel:			'{0}',
								forgotPassword:				'{1}',
								btnForgotPassword:			'{2}',
								errorMessage:				'{3}' //4
							}
							break;

						case 3:
							// change password when new user -- three rows in the table
							numerics = {
								newPasswordLabel:		'{0}',
								newPassword:			'{1}',
								confirmPasswordLabel:		'{2}',
								confirmPassword:		'{3}',
								changePassword:			'{5}',
								errorMessage:			'{6}'
							}
							break;

						case 4:
							// change password when signed in -- four rows in the table	
							numerics = {
								oldPasswordLabel:		'{0}',
								oldPassword: 			'{1}',
								newPasswordLabel:		'{2}',
								newPassword:			'{3}',
								confirmPasswordLabel:		'{4}',
								confirmPassword:		'{5}',
								changePassword:			'{7}',
								errorMessage: 			'{8}'
							}									
							break;
							
						case 5:
							numerics = {
								userLabel:	 	"{0}",
								user: 			"{1}",
								passwordLabel: 		"{2}",
								password: 		"{3}",
								signIn: 		"{5}",
								forgot: 		"{9}",
								errorMessage: 		'{10}',
								errorMessageClass: 	'{11}'
							};
							
							break;

						default:
							// not expecting this!
					}
						
					
					// change these text targets in the provided template to their
					// numeric position in the tdsContent array
					newTemplate = newTemplate.supplant(numerics);
				
				
					// create new sign in markup from template and original content
					newSignIn = newTemplate.supplant(tdsContent);

					// update the DOM with the new markup
					$signin.find("table").replaceWith(newSignIn);
					
/*					
	input[type=text] do NOT seem to display their VALUE after the .replaceWith()
	
					$tds.find("[id]").each(function (nIt) {
						var info = fieldInfo[nIt];
							
						// experimental! -- complete with hard-wired assumptions
						if (typeof info.text === "string") {
							if (this.tagName.toLowerCase() === "input") {
								this.value = info.text;
							} else {
								if (this.tagName.toLowerCase() === "label") {
									this.innerHTML = info.text;
								} else {
									if (this.tagName.toLowerCase() === "span") {
										// span#some:long:id a "Forgot Your Password?"
										this.children[0].innerHTML = info.text;
									}
								}
							}
						}
					});
*/					
					
				}				
			}

			return {
				ids: {
						user: ids[0],
						password: ids[1],
						signIn: ids[2],
						forgot: ids[3]
					}					
			}
		}	// signInTransmogrifier
	}	// OCMS.signInTransmogrifier === undefined
})();
