/*
 * Views are intended to interact with and render the presentation layer.
 * In this ident a render() method is used to repaint various portions of the UI
 * Note that these render() methods can be called automatically when the model
 * is updated via an observer pattern.  The call to "addObserver" allows the view
 * to subscribe to changes in the model and repaint portions of the UI when the
 * underlying model changes.
 *
 * Note also that the view can be used to obtain and set specific elements in the
 * DOM.  This centralizes the DOM access into one class so if element IDs, class names,
 * etc. change they can be altered here instead of throughout the code.  Note that
 * the controller and commands can access these helper methods as well to access
 * content from the UI.
 *
 */
if (!esg) var esg = {};
if (!esg.ident) esg.ident = {};


esg.ident.views = {
	
	model : esg.ident.model,
    controller: esg.ident.controller,
	secureCookie: {},
	failDelayHandle: {},
    
	createCookie: function () {
			this.secureCookie = new Hash.Cookie(this.model.identData.cookieName, {
                path: '/',
                duration: 0,
                secure: true
            }); 
	},
	clearSecureCookie: function () {
        Cookie.dispose(this.model.identData.cookieName,{path: '/'});
	},
	setUpCookie: function () {
		this.createCookie();
		this.secureCookie.combine(this.model.identData.cookieParams);
	},
	clearCookies: function() {
		/* clean up cookies here */
        Cookie.dispose('DYN_EMAIL',{path: '/',domain: 'ofoto.com'});
        Cookie.dispose('DYN_USER_ID',{path: '/',domain: 'ofoto.com'});
        Cookie.dispose('DYN_USER_CONFIRM',{path: '/',domain: 'ofoto.com'});
		Cookie.dispose('ANON_UPLOAD',{path:'/'});
		Cookie.dispose('savedView',{path:'/'});
		this.clearSecureCookie();
	},
	scriptInsert: function(){
		var uid = 'uid='+ parseInt(Math.random() * 1000000000);
		var src = this.model.identData.url;
		var query = this.model.identData.callArgs;
		var script = document.createElement('script'); 
		
		if ($chk(query)) query = $H(query).toQueryString()+'&'+uid;
		script.type = 'text/javascript'; 
		script.src = 'https://'+document.location.host+src+"?"+((query)?query:uid);
		$(document.head).appendChild(script);
	},
	setFailDelay: function() { 
		// We need to store the model.identData.defaultFail as it was when this delay was set up
		var failHandlePass = esg.ident.controller.execute.pass(esg.ident.model.identData.defaultFail);
		esg.ident.views.failDelayHandle =(function(){failHandlePass()}).delay(25000);
	},
	properRedirect: function(url) {
		(window.location == url)?window.location.reload():window.location.replace(url);
	},
	signInRedirect: function(joined) {
		var redirectPath = window.location.toString();
		var url = window.location.pathname.toString();

		// is this the share speedbump dialog?
		if (esg.ident.model.signInRoot.replace(/"/g,'') == esg.ident.views.shareSignInDialogObj.root + '-signin' || esg.ident.model.joinRoot.replace(/"/g,'') == esg.ident.views.shareSignInDialogObj.root + '-join') {
			esg.ident.views.shareSignInDialogObj.afterSignIn(joined);
			return;
		}

		// is this the share identity dialog?		
		if (esg.ident.model.signInRoot.replace(/"/g,'') == esg.ident.views.shareIdentityContentDialogObj.root + '-signin' || esg.ident.model.joinRoot.replace(/"/g,'') == esg.ident.views.shareIdentityContentDialogObj.root + '-join') {
			esg.ident.views.shareIdentityContentDialogObj.afterSignIn(joined);
			if (url.contains("albumNotFound.jsp")){ //SHARE-153: Case2
			   	redirectPath = "http://" + document.location.host + "/gallery/creativeapps/photoPicker/albums.jsp";  		
				this.properRedirect(redirectPath);
			}			
			return;
		}		

		// this is the stand alone identity dialog post submit redirect logic for join.jsp and signin.jsp.		
		if (esg.ident.model.signInRoot.replace(/"/g,'') == esg.ident.views.landingIdentityServicesDialogObj.root + '-signin' || esg.ident.model.joinRoot.replace(/"/g,'') == esg.ident.views.landingIdentityServicesDialogObj.root + '-join') {
			esg.ident.views.landingIdentityServicesDialogObj.afterSignIn(joined);
			redirectPath = "http://" + document.location.host + esg.ident.views.landingIdentityServicesDialogObj.dynamicRedirect;  		
			this.properRedirect(redirectPath);
		
			return;
		}

		// If special sign-in dialog, set redirectPath
		$each([this.reorderSignInDialogObj,this.L2SigninDialogObj], function(dialog,index) {
			redirectPath = (esg.ident.model.signInRoot == dialog.dialogId) ? 
	                        (dialog.redirect ? dialog.redirect : redirectPath)
	                        : redirectPath;
		}.bind(this));

		if (esg.ident.model.signInRoot == this.anonUploadDialogObj.dialogId || esg.ident.model.joinRoot.contains(this.anonUploadDialogObj.dialogId)) { //redirect is same in case of signin/join for anonupload speedbump
			this.anonUploadDialogObj.afterSignIn();
			return;
		}
        // end special sign-in cases
		
		if (!joined && (
			url.contains("printsWelcome.jsp") ||
            url.contains("buyprints.jsp") ||
			url.contains("prints.jsp") ||
			url.contains("addCardAndEnvelope.jsp") ||
			url.contains("LandingPage.jsp")  ||
			url.contains("albumNotFound.jsp") ||
			url.contains("index.jsp") ||
			url.contains("welcome.jsp") ||
			url.contains("printConfig.jsp"))) {
			redirectPath = "http://" + document.location.host + "/gallery/storagestatus.jsp?path=" + encodeURIComponent("http://" + document.location.host + "/gallery/creativeapps/photoPicker/albums.jsp"); 		
		}
		else if (url.contains("slideshowFinishPage.jsp")) {
			esg.share.controller.execute('redeemShare', {
				'shareToken' : esg.share.model.shareToken,
				'callBack' : 'anonymousSaveSlideShow2'
			});
			return;
		}
		else if (joined) {
			redirectPath = "http://" + document.location.host + "/gallery/thanks.jsp";
		}
		else {
			redirectPath = "http://" + document.location.host + "/gallery/storagestatus.jsp?path="+encodeURIComponent(redirectPath);
		}
		this.properRedirect(redirectPath);
	}
};

/*Sign In Module Starts here */

esg.ident.views.signIn = {
	
	signInObj: {
		root: function() {return (esg.ident.model.signInRoot.length < 1)?esg.ident.model.signInRoot:"-"+esg.ident.model.signInRoot},
		emailId: function(){
			return $('emailId'+this.root()).value;
		},
		pwd: function(){
			return $('pwd'+this.root()).value;
		}
	},
	validateError: function (root,txt) {
		//IE is having problems with Moot $Element resolution
		var msg = document.getElementById('errorMsg-'+root);
		var email = $('emailId-'+root);
		msg.style.display = '';
		msg.innerHTML="";
		//IE is also having probls with innerHTML assignments
		var tnode = document.createTextNode(txt);
		msg.appendChild(tnode);
		email.addClass('errorstate');
		//if(email.disabled != true) email.focus();		
		esg.ident.views.signIn.render.redraw('.button-area')//this is done to resolve IE6 redraw rendering bug
		
	},
	validate : function(){
		var root = esg.ident.model.signInRoot;
		// reset error states on inputs
		$$('input').removeClass('errorstate');	
		var signInObj = this.signInObj;
		var emailRegEx = /^ *[A-Za-z0-9](([_\.\-\+]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,}) *$/; // Source: http://regexlib.com/REDetails.aspx?regexp_id=333
		var redraw = esg.ident.views.signIn.render.redraw;
		var validateError = this.validateError;
		var validateFn = function()
		{	
			if (!signInObj.emailId() || signInObj.emailId() == "Email" || !emailRegEx.test(signInObj.emailId())) {	
				validateError(root, "The email address you entered is invalid. Please try again.");
			}
			else if (!signInObj.pwd() || $('pwd-'+root).type == "text") {	// if the password field is blank or is of type text, this means the password has not been entered
				validateError(root, "Invalid password. Please try again.");
			}
			else {
				//on successful validation, pass the obj to controller for ajax call
				$('errorMsg-'+root).style.display = '';

				// hacks because IE is terrible :(			
				var msg = document.getElementById('errorMsg-'+root);
				msg.innerHTML = '';
				var inner = new Element('span', { 'class' : 'loading', 'html' : "Signing in"});
				msg.appendChild(inner);
				
				if ($("signInBtn-"+root))
					$("signInBtn-"+root).disabled=true;
				redraw('.button-area')//this is done to resolve IE6 redraw rendering bug	
				if ($('signInBtnAnchor-'+root))
					$('signInBtnAnchor-'+root).addClass('disabledbutton');
				if (root == esg.ident.views.L2SigninDialogObj.dialogId)
			    	esg.ident.controller.execute("callL2SignIn",signInObj);
             	else
                	esg.ident.controller.execute("callSignIn",signInObj);
							
			}
		};
		validateFn.delay(500);
	}
};

esg.ident.views.signIn.assignEvents = function(uid){
	
	/* Join Event Handlers Start */
		var append = ($chk(uid)) ?'-'+uid : "";
		
		if (Cookie.get("last_login_email")) {
			$("emailId"+append).style.color = "#000";
			$("emailId"+append).value = Cookie.get("last_login_email");
			if(append == '-L2signin'){
				$("emailId"+append).style.display = 'none';
			}
		}
						
		$("signInBtn"+append).addEvent('click', function(){ // Sign In Button - Click Event handler
			esg.ident.controller.execute("signIn",{root:uid});
		}.bind(this));
	
		$('forgotPwdLink'+append).addEvent('click', function(event) {
			event.stop(); //Tries to resolve TREL-252
			esg.ident.views.properRedirect("http://" + document.location.host + "/gallery/ma_reset_password.jsp");
		});

		if(append=='-share-signIn' || append=='-share-signin' || append=='-shareIdentity-signin' || append=='-landingIdentity-signin') //Currently  share signin forms don't have separate <input type='submit'> fields
		{
			$('signInFrameBody'+append).addEvent('keypress',function(event){ // Sign In Button - Keyboard Enter Event handler
				if(event.key == 'enter')
				{
					esg.ident.controller.execute("signIn",{root:uid});
				}
			}.bind(this));
		}

		$('signInFrameForm'+append).addEvent('submit',function(event){ // Needed to fix Safari bug GALRONE-142 
				event.stop();
		});
	
		$('emailId'+append).addEvents // Event Handlers for Email Address Field
		(
			{
				select: function(event){
					if(!Browser.Engine.trident) // IE hangs for select event
						esg.utility.eraseField(this,event);
				},
				focus: function(event){
					esg.utility.eraseField(this,event);
				},
				blur: function(event){
					esg.utility.populateField(this,"Email address",event);
				},
				keydown: function(event){										
					esg.utility.eraseField(this,event);
				},
				keyup: function(event){
					esg.utility.populateField(this,"Email address",event);					
				},
				mousedown: function(event){
					esg.utility.eraseField(this,event);
				},
				mouseup: function(event){
					esg.utility.eraseField(this,event);
				}
			}
		);				
		$('pwdText'+append).addEvents(
			{
				'keydown': function(event){			
					esg.utility.erasePwdField(this,$('pwd'+append),event);
				},
				'keyup': function(event){
					esg.utility.populatePwdField(this,this.getParent().removedChild,event);
				},				
				'select': function(event){
					if(!Browser.Engine.trident)
						esg.utility.erasePwdField(this,$('pwd'+append),event);
				},
				'focus': function(event){
					esg.utility.erasePwdField(this,$('pwd'+append),event);
				},
				'blur': function(event){
					esg.utility.populatePwdField(this,this.getParent().removedChild,event);
				},
				'mousedown': function(event){			
					esg.utility.erasePwdField(this,$('pwd'+append),event);
				},
				'mouseup': function(event){			
					esg.utility.erasePwdField(this,$('pwd'+append),event);
				}
			}
		);
		$('pwd'+append).addEvents(				
			{
				'keyup': function(event){			
					esg.utility.populatePwdField(this,this.getParent().removedChild,event);					
				}
			}			
		);
		
		if ($("frame-close-link"+append)) {
			$("frame-close-link"+append).addEvent('click', function(e){ // Click Event Handler for Close Frame Icon	
				$('signInFrameForm'+append).reset(); //Reset Form				
				esg.utility.populatePwdField($('pwd'+append),($('pwd'+append).getParent().removedChild ? $('pwd'+append).getParent().removedChild : $('pwdText'+append)));
				$('errorMsg'+append).style.display='none'; // Clear any error messages
				$$('input').removeClass('errorstate');
				if(Cookie.get("last_login_email")) // If the cookie for last_login_email exists, add this to the emailId field
				{
					$("emailId"+append).value = Cookie.get("last_login_email");				
				}
				else
				{			
					$("emailId"+append).value=""; // reset Email
					esg.utility.inValue($("emailId"+append),"Email address");
				}
				//if(!(Cookie.get("signin_ignore"))) {
					// create a cookie to keep the signin module closed if the user closes it
					//Cookie.write('signin_ignore', 1, {path: '/', duration:(1/48)});
				//} 
				$('signInFrame').tween('height', '0');
				$('joinFrame').tween('height', '0');				
			});
		}
};

var SigninDialogBase = new Class({
	dialogId: "element id for base element to loadSignInContents goes here",
	customDialogSetup: function (){},
	displayCloseLink: false,
	alreadyDisplayed: false,
	display: function(callback,redirect){
		if(redirect) this.redirect = redirect;
		this.callback = (callback===undefined)?function (){}:callback;
		this.customDialogSetup();

	},
	redirectCall: function() {
		if (this.redirect) 
			esg.ident.views.properRedirect(this.redirect);
		else
			esg.viewUtil.modalBox.hide(this.dialogId);
	},
    loadSignInContents: function(root){
		if (($(this.dialogId)) && !this.alreadyDisplayed)
		{
			// First, create multiply used form with unique element IDs

			var body = new Element('div', {'id':"signInFrameBody-"+root,'class':"signInFrameBody"});			
			var form = $('signInFrameForm-'+root);
			
			form.setStyle('display','block');			
			var pwdText = new Element('input',{'type':'text', 'id':'pwdText-'+root, 'value':'Password', 'class':'pwdText'});
			pwdText.inject($('pwd-'+root),'before');	
			$('emailId-'+root).set({'value':'Email address'}); //value is added as FF was replicating the earlier email entry in the input field
			
			if(this.displayCloseLink) {
				form.appendChild(new Element('p'));
				var img = new Element('img',{'src':'/A/Kodak_Gallery_Media/ECBO/images/closeFrame.gif','alt':'Close','title':'Close'});
				var frameClose = new Element('a',{'class':'frame-close-link','id':'frame-close-link-'+root,'href':'javascript:void(0);'});
				frameClose.appendChild(img);
				form.appendChild(frameClose);
			}
			body.appendChild(form);
			$(this.dialogId).appendChild(body);			
			
			// Then, assign events and do some post-creation DOM positioning
			esg.ident.views.signIn.assignEvents(root);
			
			this.alreadyDisplayed = true;
		}
	},
	
	updateModel : function() {
		var model = esg.ident.model;
		if (model.isAnon) model.isAnon = false;
		model.member = Cookie.read('user_id');
		model.login = Cookie.read('DYN_EMAIL');
		
		// also update the tabs
		if ($('subtabheader'))
			$('subtabheader').set('html', esg.viewUtil.getTabbedNavBarContents());	
	}	
});

var PullDownSignInDialog = new Class ({

	Extends: SigninDialogBase,
	dialogId : "signInFrame",
    customDialogSetup: function() {
		this.displayCloseLink = true;
		this.loadSignInContents('pulldown');
    }
});

var AnonSignInDialog = new Class ({

	Extends: SigninDialogBase,
	dialogId : "anonsignin-speedbump",
	customDialogSetup: function() {
		
			$("btnAnoncontinue").removeEvents();
			$("btnAnoncontinue").addEvent('click',function(e){
				e.stop();
				this.closeDialog();
				if (this.cancelCallback)
					this.cancelCallback();
			}.bind(this));
			$("btnAnonsignin").removeEvents();
			$("btnAnonsignin").addEvent('click',function(e){
				e.stop();
				this.closeDialog();
				this.callback();
				esg.ident.views.renderFrame.checkClick(e);			
			}.bind(this));
			esg.viewUtil.modalBox.show(this.dialogId);
	},
	closeDialog: function(){
		esg.viewUtil.modalBox.hide(this.dialogId);
	}
});

var L2SigninDialog = new Class ({

	Extends: SigninDialogBase,
	dialogId : "L2signin",
	L2CookieCheck: function() {
		if (Cookie.get("L2",{path:'/'})==1)  { //the user has already signed in
				this.callback();
				this.redirectCall();
		}					
	},
	closeDialog: function(){
		if (Browser.Engine.trident4) {
			esg.ident.viewUtil.modalBox.hide('L2signin-speedbump');
		}
		else {
			esg.viewUtil.modalBox.hide('L2signin-speedbump');
		}
	},
	customDialogSetup: function() {
		$('closeL2signin').removeEvents();
		$('closeL2signin').addEvent('click',function(e){
			e.stop();
			this.closeDialog();
		}.bind(this));	
		this.displayCloseLink = false;
		this.loadSignInContents(this.dialogId);
		
		//reset the contents in signIn form
		var append = "-" + this.dialogId;
		$('errorMsg'+append).style.display = 'none'; // Clear any error messages
		$$('input').removeClass('errorstate');

		if (!Cookie.get("L2",{path:'/'}) || Cookie.get("L2",{path:'/'})==0) {		
			if (Browser.Engine.trident) {
				// IE6 fix
				esg.ident.viewUtil.modalBox.show('L2signin-speedbump');
			}
			else {
				esg.viewUtil.modalBox.show('L2signin-speedbump');
			}
		}
		else {
			this.L2CookieCheck();
		}
		
	}
  		
});

esg.ident.viewUtil = {};
esg.ident.viewUtil.modalBox = {
	/* 
	 * This code was adapted from a "Lightbox" article - http://particletree.com/features/lightbox-gone-wild/
	 */
	/**
	 * Show a <code>div</code> in a modal dialog. Requires that the page contains
	 * an (empty) <code>div</code> of class <code>modal_overlay</code>. 
	 * The modal_overlay should follow other markup, so that it renders after
	 * and covers other elements, preventing clicks outside the dialog.
	 * 
	 * @param {String} modalDiv the unique id of the dialog <code>div</code>
	 */
    show: function(modalDiv, skipOverlay){		
		this.modalDivId = modalDiv;
		var overlay = $('modal_overlay');
		var parentDiv = $('principal') || document.body;
		
		if (!overlay) {
			overlay = new Element('div', { 'id' : 'modal_overlay'});
			parentDiv.appendChild(overlay);
		}
        if (Browser.Engine.trident4) {
            // IE6 - must handle items that IE6 CSS can't support
            this.prepareIE('100%', 'hidden');	
			this.hideSelects('none');
        }
		
		parentDiv.appendChild($(modalDiv));
		$(modalDiv).setStyle('display', 'block');
		this.centerElement(modalDiv,parentDiv);
		
		if (!skipOverlay) {
			overlay.setStyle('display', 'block');
			overlay.setStyle('width', '100%');
			(function(){overlay.setStyle('height', document.getScrollSize().y);}).delay(10);
			overlay.setStyle('z-index', '1000');
		}
		
		(function(){$(modalDiv).setStyle('z-index', parseInt(overlay.getStyle('z-index')) + 10);}).delay(50);
		
    },

	/**
	 * Hide a currently displayed dialog.
	 * 
	 * @param {String} modalDiv the unique id of the dialog <code>div</code>
	 */
    hide: function(modalDiv,skipOverlay){
       if (Browser.Engine.trident4) {
            // IE6 - must handle items that IE6 CSS can't support;
            this.prepareIE("auto", "auto");
			this.hideSelects('block');
        }
		
		if (!skipOverlay) {
			$("modal_overlay").setStyle('display', 'none');
			// skipOverlay is used for double dialogs, so we want to keep the selects hidden still
        }
		if($(modalDiv)) $(modalDiv).setStyle('display', 'none');
    },
    prepareIE: function(height, overflow){
        bod = document.getElementsByTagName('body')[0]; //huh?
        bod.style.height = height;
        bod.style.overflow = overflow;
    },
    setScroll: function(x, y){
        window.scrollTo(x, y);
    },
  
    hideSelects: function(display){
		// This function is used to hide select elements in IE6 that do not respect
		// the ZOrder and therefore will "bleed through" a modal dialog.  This function
		// hides the select elements while the modal dialog is displayed.
		
		// to avoid CSS overrides when visible:
		if (display == 'block' || display == 'inline')
			display = '';		
			
		$$('select').each(function(item) {
			// Check to see if this select element is inside the modal DIV
			// If so, we do not wish to hide it.)
	            item.setStyle('display', display);
		});
    },
     centerElement: function(elem,parent) {

     	elem=$(elem); //for IE: DECTWO-93
		parent=$(parent); //for IE: DECTWO-93
		
		var left = parseInt((parent.getSize().x - elem.getSize().x) / 2);
		var top = parseInt(document.getScroll().y + ((window.getSize().y - elem.getSize().y) / 2));
			
    	elem.setStyle('left', left + 'px');
        elem.setStyle('top', top + 'px'); 
     }
    
};

var ReorderSignInDialog = new Class ({

	Extends: SigninDialogBase,
	dialogId : "reordersignin",
	customDialogSetup: function() {
		this.displayCloseLink = false;
		var mailParam = esg.utility.getQsValue('email'); 
		this.loadSignInContents(this.dialogId);
		if(!$("btnReorderCancel")) {
			var cancelBtn = new Element('a',{'href':'#','id':'btnReorderCancel','class':'linkbutton secondarybutton float_l','html':'<span>Cancel</span>'});
			cancelBtn.inject($('signInBtnAnchor-reordersignin'),'before');
        }
		$("btnReorderCancel").removeEvents();
		$("btnReorderCancel").addEvent('click', function(){ // Click Event Handler for Close Frame Icon	
			esg.viewUtil.modalBox.hide('reordersignin-speedbump');
			this.callback();
		}.bind(this));
		var e = esg.utility.getQsValue("email");
		if (e != null) {
		 	$("emailId-reordersignin").style.color = "#000";
		 	$("emailId-reordersignin").value = e;
			$("emailId-reordersignin").disabled = true;
		}
		esg.viewUtil.modalBox.show('reordersignin-speedbump');
	}
});	

var AnonUploadDialog = new Class ({

	Extends: SigninDialogBase,
	dialogId : "anonupload",
	defaultView: Cookie.get("last_login_email") ? 'signIn' : 'join',
	customDialogSetup: function() {
		if (!$('anonupload')) {
			// we need to load the dialog
			
			var div = new Element('div', {
				'id' : 'anonupload-speedbump',
				'class' : 'dialogbox'
			});
			
			var root = $('principal') || document.body;
			
			root.appendChild(div);
			
			$("anonupload-speedbump").set('load',{method:'get',onSuccess: (function(){
				this.classRef.customDialogSetup();
			}).bind({'classRef' : this})});

			$("anonupload-speedbump").load('/A/html/anonymousUploadFrame.html');				
			
			return;
		}		
		this.displayCloseLink = false;		
		$('closeAnonUploadSpeedBumpDlg').removeEvents(); //avoid duplicating event handlers; else these will run twice!
		$('closeAnonUploadSpeedBumpDlg').addEvent('click',function(e){
			e.stop();			
			this.callback=function(){};//no callback required
			
			//remove join contents - this is equivalent to resetting the join contents
			if($('joinFrameBody-anonupload-join'))
				$('joinFrameBody-anonupload-join').dispose();
			var joinFrameContainer = new Element('div',{'id':'joinFrameBody-container'});
			joinFrameContainer.inject($('anonupload'));
			
			this.closeDialog();
		}.bind(this));
		$$('#signInJoinToggler li').removeEvents(); //avoid duplicating event handlers; else these will run twice!
		$$('#signInJoinToggler li').addEvents({
			'click': function(e){
				e.stop();
				//take care of signIn / join tabs rendering
				$$('#signInJoinToggler li').removeClass('current');
				this.addClass('current');
				//take care of signIn / join content rendering				
				$$('#anonupload>div').addClass('collapsed');
				if (this.id == 'signInTab') {
					$('signInFrameBody-anonupload').removeClass('collapsed');
					$('anonupload-speedbump').removeClass('joinActive');
					$('emailId-anonupload').focus();
					
					// update tab indexes so the hidden field doesn't get included
					$$('#signInFrameForm-anonupload input').each(function(e){
						if (e.style.display != 'hidden') 
							e.tabIndex = 1
					});
					
				}
				else {
					$('joinFrameBody-anonupload-join').removeClass('collapsed');
					$('anonupload-speedbump').addClass('joinActive');
					
					// hack for IE6 + IE7					
					if (Browser.Engine.trident && esg.utility) // redraw joinInfo in IE6/IE7 as this does not get rendered sometimes.
						esg.utility.redrawInIE6("#joinFrameBody-anonupload-join .joinInfo");
					$('joinFName-anonupload-join').focus();
				}
			}
		});	
		
		this.loadJoinContents();		
		this.loadSignInContents(this.dialogId);	

		if (this.defaultView == 'join') {
			$('signInTab').removeClass('current');
			$('joinTab').addClass('current');
			$('anonupload-speedbump').addClass('joinActive');
			if($('joinFrameBody-anonupload-join'))
				$('joinFrameBody-anonupload-join').removeClass('collapsed');			
		}
		else {
			$('signInTab').addClass('current');
			$('joinTab').removeClass('current');
			$('anonupload-speedbump').removeClass('joinActive');
			if($('signInFrameBody-anonupload'))
				$('signInFrameBody-anonupload').removeClass('collapsed');			
		}

		// If this signin/join dialog is opened from the flex app, the modalBox stack 
		// gets 'corrupted'/out of sync because all origina HTML elements in the DOM
		// loaded then replaced by the Flash player when it goes into full display mode.
		// This will prevent this case for the slideshow flex app when this speedbumb is shown.
		if ($('slideShow')) {
			esg.viewUtil.modalBox.modalStack.empty(); // hide old rogue references, if any.
			esg.viewUtil.modalBox.topInModalStack = null;
		}
		
		// position the SignIn dialog so it will be centered vertically when the user switches to the Join tab
		$('anonupload-speedbump').setStyle('top', document.getScroll().y + Math.max(50, (document.getSize().y - 430) / 2));
		
		esg.viewUtil.modalBox.show('anonupload-speedbump', {
			skipPositioning : true
		});		
		
		//reset the contents in signIn form
		var append = "-"+this.dialogId;
		$('signInFrameForm'+append).reset(); //Reset Form				
		esg.utility.populatePwdField($('pwd'+append),($('pwd'+append).getParent().removedChild ? $('pwd'+append).getParent().removedChild : $('pwdText'+append)));		
		$('errorMsg'+append).style.display='none'; // Clear any error messages
		$$('input').removeClass('errorstate');
		if(Cookie.get("last_login_email")) // If the cookie for last_login_email exists, add this to the emailId field
		{
			$("emailId"+append).value = Cookie.get("last_login_email");				
			$("emailId"+append).setStyle('color','#000000');
			(function(){$("emailId"+append).focus()}).delay(500);
		}
		else
		{			
			$("emailId"+append).value=""; // reset Email
			esg.utility.inValue($("emailId"+append),"Email address");
		}				
	},
	rootCustomize: function(main,appnd) {
		var idReplace = function(member,appnd) {
			if (member.get('id') && !member.get('id').contains('-'+appnd))//do not append if the id already has the required suffix
				member.set('id',member.get('id')+'-'+appnd);

			var kids = member.getChildren();
			if ($chk(kids))
			{
				kids.each(function(item, index){idReplace(item,appnd)},this);
			} 
		};
		idReplace(main,appnd); 
	},
	loadJoinContents: function(){
		var container = $('joinFrameBody-container'); 
		if (container)
		{				
			container.set('load', {
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){						
					var combinedUID = "anonupload-join";
					this.rootCustomize(container,combinedUID);
					esg.ident.views.join.assignEvents(combinedUID);
					$('joinFrameBody-anonupload-join').replaces(container);

					if (this.defaultView == 'join') //creating new Elements is slower than loading of html in IE6 
						(!Browser.Engine.trident) ? $('signInFrameBody-anonupload').addClass('collapsed') : (function(){$('signInFrameBody-anonupload').addClass('collapsed')}).delay(10);
					else
						$('joinFrameBody-anonupload-join').addClass('collapsed');

					//make certain rendering changes in join form if required
					if(!$('joinPwdText-anonupload-join-holder'))
						$('joinPwdText-anonupload-join').getParent('div').set('id','joinPwdText-anonupload-join-holder');
					if(!$('joinRePwdText-anonupload-join-holder'))
						$('joinRePwdText-anonupload-join').getParent('div').set('id','joinRePwdText-anonupload-join-holder');
					if(!$('password-rules-anonupload-join').getPrevious('#joinRePwdText-anonupload-join-holder'))
						$('password-rules-anonupload-join').inject($('joinRePwdText-anonupload-join-holder'),'after');
					if (this.defaultView == 'join')
						(function(){$('joinFName-anonupload-join').focus()}).delay(10);
                }.bind(this) 
			});
			container.load('http://' + document.location.host + '/A/html/identJoinFrame.html');
		}
	},
	closeDialog: function(){
		esg.viewUtil.modalBox.hide('anonupload-speedbump');
		this.callback();
	},
	afterSignIn: function() {		
		var anonUploadStatus = Cookie.get('ANON_UPLOAD',{path:'/'});
		if(anonUploadStatus && anonUploadStatus == 1) //If user signs in thru' anon upload speed bump, clear the now unnecessary ANON_UPLOAD cookie
		{
			Cookie.remove('ANON_UPLOAD',{path:'/'});
		}
		if (esg.ident.model.isAnon) esg.ident.model.isAnon = false;

		if (this.successCallback) {
			this.updateModel();
			this.successCallback();
			esg.viewUtil.modalBox.hide('anonupload-speedbump');
		}
		else {
			// if we have a callback function, call closeDialog which invokes the callback
			if (this.callback)
				this.closeDialog();
			else {
				// otherwise, send the browser to the redirect URL. If none is
				// provided, reload the page.
				if (!this.redirect || this.redirect == "")
					this.redirect = window.location.href;
				this.redirectCall();
			}
		}
	}
});


var ShareIdentityContentDialog = new Class ({
	Extends: SigninDialogBase,
	dialogId: 'signin',
	root: "shareIdentity",
	containerId: "shareIdentityContent",
	dialogIds: $H({'signin':'shareIdentityContentSignInDiv','join':'shareIdentityContentJoinDiv'}),
	defaultView: Cookie.get("last_login_email") ? 'signIn' : 'join',
	customDialogSetup: function() {
		this.loadSignInContents();
	},
	display: function(dialogId, callback) {
		this.dialogId = dialogId || this.dialogId;
		this.customDialogSetup();
		this.callback = (callback===undefined)?function (){}:callback;		
	},
	rootCustomize: function(main,appnd) {
		var idReplace = function(member,appnd) {
			if (member.get('id'))
				member.set('id',member.get('id')+'-'+appnd);

			var kids = member.getChildren();
			if ($chk(kids))
			{
				kids.each(function(item, index){idReplace(item,appnd)},this);
			} 
		};
		idReplace(main,appnd); 
	},
	loadSignInContents: function(){
		var container = $(this.dialogIds.get(this.dialogId)); 
		if ((container))
		{	
			var newContainer = container.clone();
			newContainer.store('dialogId',new String(this.dialogId));
			newContainer.set('load', {
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){					
					var newId = newContainer.retrieve('dialogId');
					var combinedUID = this.root+"-"+newId;
					this.rootCustomize(newContainer.getFirst(),combinedUID);
					newContainer.addClass('landingPage');
					if (newId.match('join') && ($defined(this.defaultView) && this.defaultView != 'join')) newContainer.addClass('collapsed');
					if (newId.match('signin') && ($defined(this.defaultView) && this.defaultView != 'signIn')) newContainer.addClass('collapsed');				
					if(container.parentNode) //This if condition is added to prevent js error - el.parentNode is null - inside mootools replaces method.
						newContainer.replaces(container);
					if ($('signInFrameBody-'+combinedUID)) $('signInFrameBody-'+combinedUID).setStyle('background','none');
					if ($('joinFrameBody-'+combinedUID)) $('joinFrameBody-'+combinedUID).setStyle('background','none');
					if ($('frame-close-link-'+combinedUID)) $('frame-close-link-'+combinedUID).destroy();
					newContainer.set('id',container.get('id'));
					newContainer.getElements('form').setStyle('display','block');
					newContainer.getElements('form').addClass('clearfix');
					switch(newId+'') {
						case 'join':
							esg.ident.views.join.assignEvents(combinedUID);
						break;
						case 'signin':
							esg.ident.views.signIn.assignEvents(combinedUID);
						break;
						default:
							// do nothing
						break;
					}
                }.bind(this)
			});
			newContainer.load('http://' + document.location.host + '/A/html/ident'+((this.dialogId.match('signin'))?'SignIn':'Join')+'Frame.html');
		}
	},
	
	afterSignIn: function(joined) {
		this.updateModel();
		if (this.callback)
			this.callback(joined);
	}	

		
	
});

var ContentSignInDialog = new Class ({

	Extends: SigninDialogBase,
	containerId: "contentSignIn",
	dialogId : "contentSignInDiv",
	customDialogSetup: function() {
        if (this.css) {
			if(!($(this.dialogId).hasClass(this.css)))
				$(this.dialogId).addClass(this.css)	
		}
		this.loadSignInContents(this.dialogId);
		$(this.dialogId).addClass('landingPage');
		$('signInFrameBody-contentSignInDiv').setStyle('background','none');
	},
	display: function(css,dialogId){
		if (dialogId) this.dialogId = dialogId;
		if(css) this.css = css;
		this.customDialogSetup();
	}	
});

var ShareSignInDialog = new Class ({
	Extends: ShareIdentityContentDialog,
	dialogId: 'signIn',
	root: 'share',
	containerId: "shareSignInDialog",
	defaultView: 'signIn',
	dialogIds: $H({'signin':'shareSignIn','join':'shareJoin'}),
	customDialogSetup: function() {
		this.loadSignInContents();
	},
	display: function(dialogId, callback, defaultView) {
		this.dialogId = dialogId || this.dialogId;
		this.customDialogSetup();
		this.callback = (callback===undefined)?function (){}:callback;
		this.defaultView = defaultView || this.defaultView;
	},
	rootCustomize: function(main,appnd) {
		var idReplace = function(member,appnd) {
			if (member.get('id'))
				member.set('id',member.get('id')+'-'+appnd);

			var kids = member.getChildren();
			if ($chk(kids))
			{
				kids.each(function(item, index){idReplace(item,appnd)},this);
			} 
		};
		idReplace(main,appnd); 
	},
	loadSignInContents: function(){
		var container = $(this.dialogIds.get(this.dialogId)); 
		if ((container))
		{	
			var newContainer = container.clone();
			newContainer.store('dialogId',new String(this.dialogId));
			newContainer.set('load', {
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){			
					var newId = newContainer.retrieve('dialogId');
					var combinedUID = this.root+"-"+newId;
					this.rootCustomize(newContainer.getFirst(),combinedUID);
					newContainer.addClass('landingPage');
					if (newId.match('join') && this.defaultView != 'join') newContainer.addClass('collapsed');
					if (newId.match('signin') && this.defaultView != 'signIn') newContainer.addClass('collapsed');					
					newContainer.replaces(container);
					if ($('signInFrameBody-'+combinedUID)) $('signInFrameBody-'+combinedUID).setStyle('background','none');
					if ($('joinFrameBody-'+combinedUID)) $('joinFrameBody-'+combinedUID).setStyle('background','none');
					if ($('frame-close-link-'+combinedUID)) $('frame-close-link-'+combinedUID).destroy();
					newContainer.set('id',container.get('id'));
					newContainer.getElements('form').setStyle('display','block');
					switch(newId+'') {
						case 'join':
							esg.ident.views.join.assignEvents(combinedUID);
							if ($('shareSignInButton')) {
								$('joinBtnAnchor-' + combinedUID).destroy();
							}							
						break;
						case 'signin':
							esg.ident.views.signIn.assignEvents(combinedUID);
							if ($('shareSignInButton')) {
								$('signInBtnAnchor-' + combinedUID).destroy();
							}
						break;
						default:
							// do nothing
						break;
					}
                }.bind(this)
			});
			newContainer.load('http://' + document.location.host + '/A/html/ident'+((this.dialogId.match('signin'))?'SignIn':'Join')+'Frame.html');
		}
	},
	
	afterSignIn: function(joined) {
		this.updateModel();
		this.updatePersistentCart();
		if (this.callback)
			this.callback(joined);
	},
	
	updatePersistentCart : function() {
		// load cart and then replace it
		var persistentHolder = $('persistentholder');
		
		if (!persistentHolder) // doesn't exist on this page
			return;
		
		var persistentHolderNew = new Element('div');
		persistentHolderNew.set('load', { 
			'onSuccess' : function() {
				persistentHolderNew = persistentHolderNew.getChildren()[0];
				persistentHolder.set('html', persistentHolderNew.get('html').trim());
			}
		});
		persistentHolderNew.load('http://' + document.location.host + '/gallery/includes/persistentCart.jsp');
	}
});

var LandingIdentityServicesDialog = new Class ({
	Extends: ShareIdentityContentDialog,
	root: "landingIdentity",
	containerId: "landingIdentityContent",
	dialogIds: $H({'signin':'landingIdentityContentSignInDiv','join':'landingIdentityContentJoinDiv'}),
	defaultView: null,
	dynamicRedirect: "/gallery/welcome.jsp",
	customDialogSetup: function() {
		this.loadSignInContents();
	},
	display: function(dialogId, dynamicRedirect,callback) {
		this.dialogId = dialogId || this.dialogId;
		this.dynamicRedirect = dynamicRedirect || this.dynamicRedirect;
		this.dynamicRedirect = (this.dialogId == 'join')?"/gallery/thanks.jsp":this.dynamicRedirect;
		this.customDialogSetup();
		this.callback = (callback===undefined)?function (){}:callback;		
	},
	
	afterSignIn: function(joined) {
		this.updateModel();
		if (this.callback)
			this.callback(joined);
	}
});

var IE6WarningDialog = new Class ({

	Extends: AnonSignInDialog,
	dialogId : "IE6Warning-speedbump",
	display : function() {
		this.customDialogSetup();		
	},
    customDialogSetup: function() {
		this.loadSignInContents();	
    },
	loadSignInContents: function(){
		var dialogDOMhandle = $(this.dialogId);
		if (!(dialogDOMhandle)) {
			dialogDOMhandle = new Element('div', {
				'class' : 'dialogbox',
				'id' : this.dialogId});
			
			if ($('principal')) 
				$('principal').appendChild(dialogDOMhandle)
			else 
				$(document.body).appendChild(dialogDOMhandle)
			
			dialogDOMhandle.set(	
				'load', {
					'onSuccess': (function(){
						var closeLinkDOMHandle = $('closeIE6WarningHeader');
						closeLinkDOMHandle.addEvent('click',function(e){
							e.stop();
							// using the common viewUtil modalBox functions
							esg.viewUtil.modalBox.hide(this.dialogId);
						}.bind(this));
						Cookie.write('IE6Warned',1,{path: '/'});
						esg.viewUtil.modalBox.show(this.dialogId);
					}).bind(this)
				}	
			);
			dialogDOMhandle.load('/A/html/IE6WarningSpeedbump.html');		
		};
	}	
});

esg.ident.views.pullDownDialogObj = new PullDownSignInDialog();
esg.ident.views.anonSignInDialogObj = new AnonSignInDialog();
esg.ident.views.anonUploadDialogObj = new AnonUploadDialog();
esg.ident.views.L2SigninDialogObj = new L2SigninDialog()
esg.ident.views.reorderSignInDialogObj = new ReorderSignInDialog();
esg.ident.views.contentSignInDialogObj = new ContentSignInDialog();
esg.ident.views.shareIdentityContentDialogObj = new ShareIdentityContentDialog();
esg.ident.views.shareSignInDialogObj = new ShareSignInDialog();
esg.ident.views.landingIdentityServicesDialogObj = new LandingIdentityServicesDialog();
esg.ident.views.IE6WarningDialogObj = {};

/*	Sign out Module Starts here  */

esg.ident.views.signOut = {
	redirectUser: function(parms) {
            var dest = "http://" + document.location.host + "/gallery/welcome.jsp"; 
			esg.ident.views.properRedirect(dest);
	}
};



/*	Sign out Module Ends here  */

/* Sign In and Join Frame Rendering Methods */

esg.ident.views.renderFrame = 
{
	checkClick: function (e){		
		var target = (e && e.target) || (event && event.srcElement); // target is assigned the object that had the event triggered on it 			
		if(esg.ident.views.renderFrame.checkParent(target)) //if true then click is outside the frame or link is toggled
		{			
			$('signInFrame').tween('height', '0');
			$('joinFrame').tween('height', '0');
			
			if (Browser.Engine.trident4) {
				document.body.className = document.body.className.replace(' hideSelect','');
			}
									
		}			
	},
	checkParent: function (target){
		while(target.parentNode)
		{
			if(target==$('signInFrame') || target==$('joinFrame')) //if click is inside the frame area, do nothing
			{				
				return false;
			}
			else if(target==$('btnAnonsignin')) //if click is on the sign in link in the anonymous signin dialog, show the sign in frame
			{
				$('joinFrame').tween('height', '0');				
				
				// TODO : needs to get height:auto after the animation is completed, to allow for long error messages
				$('signInFrame').tween('height', '150');
				
				if (Browser.Engine.trident4) {
					document.body.className = document.body.className.replace(' hideSelect','');
				}
									
				return false;				
			}
			else if(target==$('showSignInFrame') && Cookie.get("ANON_UPLOAD")==1) //if click is on the sign in link with the ANON_UPLOAD cookie set to 1, close the frames as the popup dialog will handle this scenario
			{
				break;				
			}
			else if(target==$('showSignInFrame') && Cookie.get("ANON_UPLOAD")!=1) //if click is on the sign in link and ANON_ULOAD cookie does not exist or is not set to 1, then toggle sign in frame
			{
				//alert('signInFrame: '+$('signInFrame').getSize().y);
				if($('signInFrame').getSize().y!=1)
				{					
					break;					
				}
				else
				{
					$('joinFrame').tween('height', '0');				
					
					// TODO : needs to get height:auto after the animation is completed, to allow for long error messages
					$('signInFrame').tween('height', '150');	
					
					if (Browser.Engine.trident4) {
						document.body.className = document.body.className + ' hideSelect';
					}
									
					return false;
				}
			}			
			else if(target==$('showJoinFrame') || target==$('landingJoinLink')) //if click is on the join link, toggle join frame
			{
				//alert('joinFrame: '+$('joinFrame').getSize().y);
				if($('joinFrame').getSize().y!=1 && $('joinFrame').getSize().y!=15)
				{					
					break;					
				}
				else
				{
					$('signInFrame').tween('height', '0');		
					
					// TODO : needs to get height:auto after the animation is completed, to allow for long error messages
					$('joinFrame').tween('height', '430');

					if (Browser.Engine.trident4) {
						document.body.className = document.body.className + ' hideSelect';
					}
											
					return false;
				}
			}			
			target=target.parentNode;
		}
		return true;
	}
};

esg.ident.views.signIn.render = {
	signInSucceed: function() {
		Cookie.remove('ANON_UPLOAD',{path:'/'});
		Cookie.dispose('signin_ignore',{path:'/'});
		esg.ident.views.signInRedirect(false);
	},
	L2SignInSucceed: function() {
		Cookie.set('L2', 1, {path: '/', duration:(1/48)});	// L2 cookie expires in 1/48 days = 30 minutes -GALRONE-84
		if (esg.ident.views.L2SigninDialogObj.callback != undefined)
		{
			esg.ident.views.L2SigninDialogObj.callback();
		}

		if (esg.ident.views.L2SigninDialogObj.redirect != undefined)
		{
			esg.ident.views.properRedirect(esg.ident.views.L2SigninDialogObj.redirect);	
		}
	},
	signInFail: function(response){
		var root = function() {return (esg.ident.model.signInRoot.length < 1)?esg.ident.model.signInRoot:"-"+esg.ident.model.signInRoot};
		var emailField = $('emailId'+root());
		if(response && response.error)
		{
			if(response.error == "invalidCredentials") {
				$('errorMsg'+root()).style.display = '';
				var msg = document.getElementById('errorMsg'+root());			
				msg.innerHTML = '';

				var inner;
				if (emailField.style.display == 'none')
					inner = document.createTextNode("Invalid password. Please try again.");
				else
					inner = document.createTextNode("The email address and/or password you entered are invalid. Please try again.");
				msg.appendChild(inner);
				
				if ($("signInBtn"+root()))
					$("signInBtn"+root()).disabled=false;
				if ($("signInBtnAnchor"+root()))
					$("signInBtnAnchor"+root()).removeClass('disabledbutton');
				if($('pwd'+root()))
				{
					$('pwd'+root()).value='';
					if (emailField && emailField.get('tabindex') > 0) // add tab index for pwd field only if emailId has one
						$('pwd'+root()).set('tabindex', emailField.get('tabindex')+1);
				}
				try {
					$('pwd'+root()).focus(); // First focus on pwd field and then immediately focus emailId. This is equivalent to creating a blur event on pwd field, which would result in showing the pwdText
					emailField.focus();
				} catch (err) { } //IE7 has some focus issues with L2 signin
			}
		}
		else
		{
			$('errorMsg'+root()).style.display = '';			
			
			// hacks because IE is terrible :(			
			var msg = document.getElementById('errorMsg'+root());
			msg.innerHTML = '';
			var inner = document.createTextNode("Sorry, there was a server error. Please try again later.");
			msg.appendChild(inner);
			
			if($("signInBtn-"+root))
			{
				$("signInBtn"+root()).disabled=false;
				$("signInBtnAnchor"+root()).removeClass('disabledbutton');
				$('pwd'+root()).value='';
				try {
					$('pwd'+root()).focus(); // First focus on pwd field and then immediately focus emailId. This is equivalent to creating a blur event on pwd field, which would result in showing the pwdText
					emailField.focus();
				} catch (err) { } //IE7 has some focus issues with L2 signin
			}
		}
	},
	redraw: function (className) {
		if(Browser.Engine.trident==true && Browser.Engine.version==4) //IE6 trident engine version = 4
		{				
			(function(){			
			$$(className).setStyle('display','none');
			$$(className).setStyle('display','block');
			}).delay(100);
		}
	}
};

esg.ident.views.join = {
	validate : function(parms){
		var root = (esg.ident.model.joinRoot.length < 1)?esg.ident.model.joinRoot:"-"+esg.ident.model.joinRoot;		
		var joinObj = esg.ident.views.join.joinObj;
		if(parms=="joinOnOrder")
		{
			if(Cookie.get('DYN_EMAIL')){
				joinObj.setDynEmail(esg.utility.CookieWithoutEncDec.get('DYN_EMAIL'));
			}
			if(Cookie.get('EK_S')){			
				joinObj.setEK_S(esg.utility.CookieWithoutEncDec.get('EK_S'));
			}
		}
		var emailRegEx = /^[A-Za-z0-9](([_\.\-\+]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/; // Source: http://regexlib.com/REDetails.aspx?regexp_id=333
		var fNameRegEx = /^([a-zA-Z0-9\s\.\'\-]{1,30})$/;
		var pwdRegEx = /^([a-zA-Z0-9]{6,15})$/;
		//Validation Code
		$$('input').removeClass('errorstate');	
		if(!joinObj.fName() || joinObj.fName()=="First name")
		{	
			$('errorMsg'+root).style.display = '';		
			$('errorMsg'+root).innerHTML = "Please enter first name.";
			$('joinFName'+root).addClass('errorstate');
			$('joinFName'+root).focus();
		}
		else if(!fNameRegEx.test(joinObj.fName())){	
			$('errorMsg'+root).style.display = '';
			$('errorMsg'+root).innerHTML = "First name can only contain letters, spaces, periods and apostrophes.";
			$('joinFName'+root).addClass('errorstate');
			$('joinFName'+root).focus();
		}
		else if(!joinObj.emailId() || joinObj.emailId()=="Email address")
		{
			$('errorMsg'+root).style.display = '';		
			$('errorMsg'+root).innerHTML = "Please enter your email address (e.g. test@test.com)";
			$('joinEmail'+root).addClass('errorstate');
			$('joinEmail'+root).focus();
		}
		else if(!emailRegEx.test(joinObj.emailId()) || joinObj.emailId().substring(0,5)=="anon_"){
			$('errorMsg'+root).style.display = '';		
			$('errorMsg'+root).innerHTML = "Please enter a valid email address (e.g. test@test.com)";
			$('joinEmail'+root).addClass('errorstate');
			$('joinEmail'+root).focus();
		}
		else if(!joinObj.pwd() || $('joinPwd'+root).type=="text")
		{
			$('errorMsg'+root).style.display = '';		
			$('errorMsg'+root).innerHTML = "Please enter a password";
			$('joinPwdText'+root).addClass('errorstate');
			$('joinPwdText'+root).focus();
		}
		else if(!pwdRegEx.test(joinObj.pwd())){	
			$('errorMsg'+root).style.display = '';
			$('errorMsg'+root).innerHTML = "Password can contain only alphanumeric characters and should be 6-15 characters long.";
			$('joinPwd'+root).addClass('errorstate');
			$('joinPwd'+root).focus();
		}
		else if(!joinObj.rePwd())
		{
			$('errorMsg'+root).style.display = '';		
			$('errorMsg'+root).innerHTML = "Please re-enter your password";
			$('joinRePwdText'+root).addClass('errorstate');
			$('joinRePwdText'+root).focus();
		}		
		else if(joinObj.pwd() != joinObj.rePwd()){	
			$('errorMsg'+root).style.display = '';
			$('errorMsg'+root).innerHTML = "The password fields do not match. Please re-enter your password.";
			$('joinPwd'+root).addClass('errorstate');
			$('joinPwd'+root).focus();
		}
		else if($('terms'+root).checked==false)
		{
			$('errorMsg'+root).style.display = '';		
			$('errorMsg'+root).innerHTML = "You must agree to our Terms of Service to continue.";
			$('terms'+root).focus();
		}										
		else{
			//on successful validation, pass the obj to controller for ajax call			
			//alert("sucess");			
			$$('input').removeClass('errorstate');	
			$('errorMsg'+root).style.display = '';
			$('errorMsg'+root).innerHTML = "<span class='loading'>Joining. Please wait.</span> ";
			if($("joinBtn"+root))
			{			
				$("joinBtn"+root).disabled=true;
				$("joinBtnAnchor"+root).addClass('disabledbutton');
			}
			esg.ident.controller.execute("callJoin",joinObj);					
		}	
		
	}
};

esg.ident.views.join.render = {
	joinSucceed: function() {
		Cookie.remove('ANON_UPLOAD',{path:'/'});
		if(esg.ident.views.join.joinObj.getDynEmail && esg.ident.views.join.joinObj.getDynEmail()) // if user is trying to join from check out page, post the form
			{if($('billingForm')) $('billingForm').submit();} 
		else esg.ident.views.signInRedirect(true);
	},
	joinFail: function(response){
		var root = function() {return (esg.ident.model.joinRoot.length < 1)?esg.ident.model.joinRoot:"-"+esg.ident.model.joinRoot};
		if(response && response.error){				
			if(response.error=="duplicateUser") 
			{
				$('errorMsg'+root()).style.display = '';				
				$('errorMsg'+root()).innerHTML = "The email address you entered is already registered. Please try again.";	
				if($("joinBtn"+root()))
				{
					$("joinBtn"+root()).disabled=false;			
					$("joinBtnAnchor"+root()).className='linkbutton';
				}
				$('joinEmail'+root()).addClass('errorstate');
				$('joinEmail'+root()).focus();
			}else 
				this.joinFailServerErrorMsgDisplay();
		} else 
			this.joinFailServerErrorMsgDisplay();
	},
	joinFailServerErrorMsgDisplay: function(){
		var root = function() {return (esg.ident.model.joinRoot.length < 1)?esg.ident.model.joinRoot:"-"+esg.ident.model.joinRoot};
		$('errorMsg'+root()).style.display = '';				
		$('errorMsg'+root()).innerHTML = "Server error! Please try again later.";			
		if($("joinBtn"+root()))
		{
			$("joinBtn"+root()).disabled=false;			
			$("joinBtnAnchor"+root()).className='linkbutton';
		}
		$('joinFName'+root()).focus();
	}
};

esg.ident.views.join.joinObj = {
	root: function() {return (esg.ident.model.joinRoot.length < 1)?esg.ident.model.joinRoot:"-"+esg.ident.model.joinRoot},
	dynEmail: this.dynEmail,
	EK_S: this.EK_S,
	fName : function(){
		return $('joinFName'+this.root()).value;
	},
	emailId : function(){
		return $('joinEmail'+this.root()).value;
	},
	pwd : function(){
		return $('joinPwd'+this.root()).value;
	},
	rePwd : function(){
		return $('joinRePwd'+this.root()).value;
	},
	terms : function(){		
		return $('terms'+this.root()).checked;				
	},
	splOffers : function(){
		return $('splOffers'+this.root()).checked;
	},
	getDynEmail : function(){
		return this.dynEmail;
	},
	getEK_S : function(){
		return this.EK_S;		
	},
	setDynEmail : function(arg){
		this.dynEmail = arg;
	},
	setEK_S : function(arg){
		this.EK_S = arg;
	}
};

esg.ident.views.join.assignEvents = function(uid) {
	/* Join Event Handlers Start */
    var append = ($chk(uid)) ?'-'+uid : "";
	if ($("joinBtn"+append)) {		
		$("joinBtn"+append).addEvent('click', function(event){ // Create Button - Click Event handler			
			event.stop();
			esg.ident.controller.execute("join",{root:uid});
		}.bind(this));

		$('joinFrameBody'+append).addEvent('keypress',function(event){ // Create Button - Keyboard Enter Event handler
			if(event.key == 'enter')
				{
					esg.ident.controller.execute("join",{root:uid});
				}
		}.bind(this));
		
		$('joinFrameForm'+append).addEvent('submit',function(event) {// Needed to fix Safari bug GALRONE-142 	
					event.stop();			
		});																			
		$('joinFName'+append).addEvents // Event Handlers for First Name Field
		(
			{				
				select: function(event){
					if(!Browser.Engine.trident) // IE hangs for select event
						esg.utility.eraseField(this,event);
				},
				focus: function(event){
					esg.utility.eraseField(this,event);
				},
				blur: function(event){
					esg.utility.populateField(this,"First name",event);
				},
				keydown: function(event){										
					esg.utility.eraseField(this,event);
				},
				keyup: function(event){
					esg.utility.populateField(this,"First name",event);					
				},
				mousedown: function(event){
					esg.utility.eraseField(this,event);
				},
				mouseup: function(event){
					esg.utility.eraseField(this,event);
				}
			}
		);
		$('joinEmail'+append).addEvents // Event Handlers for Email Address Field
		(
			{				
				select: function(event){
					if(!Browser.Engine.trident) // IE hangs for select event
						esg.utility.eraseField(this,event);
				},
				focus: function(event){
					esg.utility.eraseField(this,event);
				},
				blur: function(event){
					esg.utility.populateField(this,"Email address",event);
				},
				keydown: function(event){										
					esg.utility.eraseField(this,event);
				},
				keyup: function(event){
					esg.utility.populateField(this,"Email address",event);					
				},
				mousedown: function(event){
					esg.utility.eraseField(this,event);
				},
				mouseup: function(event){
					esg.utility.eraseField(this,event);
				}
			}
		);							
		$('joinPwdText'+append).addEvents(
			{
				'keydown': function(event){			
					esg.utility.erasePwdField(this,$('joinPwd'+append),event);
				},
				'select': function(event){
					if(!Browser.Engine.trident)
						esg.utility.erasePwdField(this,$('joinPwd'+append),event);
				},
				'focus': function(event){
					esg.utility.erasePwdField(this,$('joinPwd'+append),event);
				},
				'blur': function(event){
					esg.utility.populatePwdField(this,$('joinPwdText'+append));
				},
				'mousedown': function(event){			
					esg.utility.erasePwdField(this,$('joinPwd'+append),event);
				},
				'mouseup': function(event){			
					esg.utility.erasePwdField(this,$('joinPwd'+append),event);
				}
			}
		);
		$('joinPwd'+append).addEvents(				
			{
				'keyup': function(event){			
					esg.utility.populatePwdField(this,$('joinPwdText'+append));
				}
			}			
		);						
		$('joinRePwdText'+append).addEvents(
			{
				'keydown': function(event){			
					esg.utility.erasePwdField(this,$('joinRePwd'+append),event);
				},
				'select': function(event){
					if(!Browser.Engine.trident)
						esg.utility.erasePwdField(this,$('joinRePwd'+append),event);
				},
				'focus': function(event){
					esg.utility.erasePwdField(this,$('joinRePwd'+append),event);
				},
				'blur': function(event){
					esg.utility.populatePwdField(this,$('joinRePwdText'+append));
				},
				'mousedown': function(event){			
					esg.utility.erasePwdField(this,$('joinRePwd'+append),event);
				},
				'mouseup': function(event){			
					esg.utility.erasePwdField(this,$('joinRePwd'+append),event);
				}
			}
		);
		$('joinRePwd'+append).addEvents(				
			{
				'keyup': function(event){			
					esg.utility.populatePwdField(this,$('joinRePwdText'+append));
				}
			}			
		);

		if ($('joinTerms'+append)) {
			$('joinTerms'+append).addEvent('click', function(){			
				window.open('http://' + document.location.host + '/gallery/footerLinksContent.jsp?pageID=600010','terms');	
			});
		}		


		if($("frame-close-link"+append)) {			
			$("frame-close-link"+append).style.visibility = 'visible';
			$("frame-close-link"+append).addEvent('click', function(){				
				$('joinFName'+append).value="";// reset first name
				esg.utility.inValue($('joinFName'),"First name"); 
				$('joinEmail'+append).value="";// reset email			
				esg.utility.inValue($('joinEmail'),"Email address"); 
				$('joinPwdText'+append).style.display = "inline"; // reset password input field type to text
				$('joinPwd'+append).style.display = "none";
				$('joinPwd'+append).value="";
				$('joinRePwdText'+append).style.display = "inline"; 
				$('joinRePwd'+append).style.display = "none";
				$('joinRePwd'+append).value="";
				$('errorMsg'+append).style.display='none'; // Clear any error messages		
				$$('input'+append).removeClass('errorstate');
				$('signInFrame'+append).tween('height', '0');
				$('joinFrame'+append).tween('height', '0');				
			});			
		}
	}
	/* Join Event Handlers End */
	
	
	
	
};

window.addEvent('domready', function() {
  	if ($("showJoinFrame")) {
			$("showJoinFrame").removeEvents();
			$("joinFrame").removeEvents();

			$("joinFrame").set('load',{method:'get',onSuccess: function(){
				esg.ident.views.join.assignEvents("");	
			}});

			$("joinFrame").load('/A/html/joinFrame.html');
		
			$("showJoinFrame").addEvent('click', function(){
				document.onclick = esg.ident.views.renderFrame.checkClick; // this is to handle clicks outside the div area
			});		
	}

	if ($("showSignInFrame")) {		
			esg.ident.views.pullDownDialogObj.display(); //$("signInFrame")
			$("showSignInFrame").addEvents({
				click: function(){
					var showSignInFramePostDisplay = function () {
						document.onclick = esg.ident.views.renderFrame.checkClick; // this is to handle clicks to toggle frame open/close	
					};
					if (Cookie.get("ANON_UPLOAD") && ($('signInFrame').getSize().y == 1))				
						esg.ident.views.anonSignInDialogObj.display(showSignInFramePostDisplay, document.location);
					else 
						showSignInFramePostDisplay();
				}
			});		
	}
	
	// signin module updates 10.14 -- undoing 10/29
	/*if(!(Cookie.get("signin_ignore")) && !(window.location.pathname.toString().contains("memberLandingPage.jsp")) && !(window.location.pathname.toString().contains("albumNotFound.jsp"))) {
		console.log("opening signin frame");
		if ($('signInFrame'))
			$('signInFrame').tween('height', '150');
	}*/
	

  /* Sign Out Event Handlers Start */
	/*------------------------------------------------------------*/


	if ($("signOutLink")) {
		$("signOutLink").removeEvents();
		$("signOutLink").addEvent('click', function(e) {
            e.stop();

			// If we're on the albums page with the photo tray, save/clear the playlist
			// first, then daisy-chain the callSignOut method to be called afterwards.
			if (window.location.pathname.toString().contains("albums.jsp")) {
				esg.photoPicker.controller.execute('saveAndContinue', {navigateTabURL: 'javascript:esg.ident.controller.execute(\'callSignOut\')'});
			}
			// If we're on the Print Configurator page, save the line items and user preferences to
			// the session before signing out so that they get associated with the signed in user. If
			// we relied on the onbeforeunload saving the session, we'd be too late.
			else if (window.location.pathname.toString().contains("printConfig.jsp")) {
				esg.printConfig.controller.execute('savePhotoListToSession', {
                	navigateToURL: 'javascript:esg.ident.controller.execute(\'callSignOut\')'
            	});
			}
			else {
				esg.ident.controller.execute('callSignOut');
			}
		})
	}

	
    /* Sign Out Event Handlers End */

	if($("btnL2Signin")) {
		$("btnL2Signin").addEvent('click', function(event){
			event.preventDefault();
			esg.ident.views.L2SigninDialogObj.display(function (){},"https://" + document.location.host +"/gallery/ma_billing_info.jsp");
		});
	}
	if($("btnL2SigninMa")) {
		$("btnL2SigninMa").addEvent('click', function(event){
			event.preventDefault();
			esg.ident.views.L2SigninDialogObj.display(function (){},"https://" + document.location.host +"/gallery/ma_billing_info.jsp");
		});
	}
	
	if($("btnL2SigninPersonalMa")){
		$("btnL2SigninPersonalMa").addEvent('click',function(event){
			event.preventDefault();
			esg.ident.views.L2SigninDialogObj.display(function(){},"https://" + document.location.host +"/gallery/ma_personal_information.jsp");
		});
	}
	
	if($("btnL2SigninPersonal")){
		$("btnL2SigninPersonal").addEvent('click',function(event){
			event.preventDefault();
			esg.ident.views.L2SigninDialogObj.display(function(){},"https://" + document.location.host +"/gallery/ma_personal_information.jsp");
		});
	}

	if($("btnAnonUpload")) {
		$("btnAnonUpload").addEvent('click', function(event){
			event.preventDefault();
			esg.ident.views.anonUploadDialogObj.display(function(){alert("Usage example: esg.ident.views.anonUploadDialogObj.display(function(){alert(\"Shagadelic, Baby!\");});");});
		});
	}
	
    /* Check Out Page cart.jsp Handlers Start */

		if ($("btnL2SignInCheckout") && $("btnL2SignInCheckout2")) {
		if(document.location.search.contains("isValidationSuccess=true") && (esg.ident.model.isAnon == false))
		{
                        esg.ident.views.L2SigninDialogObj.display(function (){document.location.replace("https://" + document.location.host +"/gallery/purchase/billing.jsp");});
		} else if(document.location.search.contains("isValidationSuccess=true")){
			document.location.replace("https://" + document.location.host +"/gallery/purchase/billing.jsp");
		}
	}	
	 /* Check Out Page cart.jsp Handlers End */
	
	/* Pay Now Button for TOS storagestatus.jsp Handlers Start */
	
	if ($("btnL2SignInPaynow")) {
	
			$("btnL2SignInPaynow").addEvent('click',function(event){
				event.preventDefault();
				esg.ident.views.L2SigninDialogObj.display(function(){$('storageForm').submit();},"");
			});

	}
	if ($("btnL2SignInPaynow2")) {
		
			$("btnL2SignInPaynow2").addEvent('click',function(event){
				event.preventDefault();
				esg.ident.views.L2SigninDialogObj.display(function(){$('storageForm').submit();},"");
			});
		
	}

   

/* Join Through Order - Event Handlers Start */
	if ($("nextBtnCheckOut")) {				
		$("nextBtnCheckOut").addEvent('click', function(){			
			if ($("joinPwd").value!="" || $("joinRePwd").value!="" ) // If user enters password, ONLY then execute join-on-the-fly; else continue without interruption
			 {
				esg.ident.controller.execute("join","joinOnOrder");
			 }
			 else 
			 {
				validateBilling();
			 }
		});
		$("nextBtnCheckOut2").addEvent('click', function(){			
			if ($("joinPwd") && ($("joinPwd").value!="" || $("joinRePwd").value!="") ) // If user enters password, ONLY then execute join-on-the-fly; else continue without interruption
			 {
				esg.ident.controller.execute("join","joinOnOrder");
			 }
			 else 
			 {
				validateBilling();
			 }
		});
	
	}
	
	if ($('joinTerms')) {
		$('joinTerms').addEvent('click', function(){			
			window.open('http://' + document.location.host + '/gallery/footerLinksContent.jsp?pageID=600010','terms');	
		});
	}
	// For IE6 users, give them a warning on slow performance
	if (Browser.Engine.trident4) {
		// Check to see if certain state conditions don't apply
		if (!esg.ident.model.isAnon) {
			if (!Cookie.read('IE6Warned', {path: '/'})) {
				var exemptedPages = ["Main.jsp"];
				if (!exemptedPages.contains(window.location.pathname.toString())){
				 	esg.ident.views.IE6WarningDialogObj = new IE6WarningDialog();
				 	(function(){
						esg.ident.views.IE6WarningDialogObj.display();
					}).delay(100);
				 }
			}	
		}
	}	
  		
});

