﻿if(Ext.QuickTips)
	Ext.QuickTips.init();
if (NP == undefined) 
{
    var NP = {
    }
}
NP.Login = function(config){

	Ext.applyIf(this, {
		/**
	 * @see NP.Object/ClassName
	 * @property ClassName
	 */
		ClassName: 'NP.Login',
		
		/**
	 * @private
	 * @property win
	 * @projectDescription popouts a modal window and is used as the container for all the
	 * components
	 */
		/**
	 * represent the text that will be shown when the mask is active
	 */
		MaskText: "Logging in...",
		
		/**
	 * @property ExternalControls
	 * @projectDescription use prebuilt controls as the main login window
	 */
		ExternalControls: false,
		
		/**
	 * @property LaunchNewWin
	 * @projectDescription launch the main application in a new window
	 */
		LaunchNewWin: false,
		
		/**
	 * @property PasswordField
	 * @projectDescription Password Field
	 */
		/**
	 * @property UserField
	 * @projectDescription User Field
	 */
		/**
	 * @property RegButton
	 * @projectDescription Registration Button
	 */
		/**
	 * @property ForgotButton
	 * @projectDescription Forgot password Button
	 */
		/**
	 * @property UserButton
	 * @projectDescription User Button
	 */
		Domain: 'customer\\'
	});
	
	
	NP.Login.superclass.constructor.call(this, config);
	
		
	/**
	 * @see NP.Object/Url
	 * @property Url
	 */
	this.Url = this.BaseUrl + '/broker.asmx/Login';
};

Ext.extend(NP.Login, NP.PopoutWindow, {
	/**
	 * @property Opco
	 */
	Opco: 4,
	Message: function(title,data){
		if(data.length >0 && data !=' ')
			Ext.example.msg(title, data);
		//Ext.Msg.alert(title, data);
	},
	/**
	 * @method Creates the controls that will be added to the tab control
	 */
	OnCreateTabItems: function(items, buttons){
		//-------------------Buttons-----------------------------------
		this.LoginButton= new Ext.Button({
			text: 'Login',
			id: 'btnSubmit'
		});
		this.LoginButton.on("click", this.Click, this);
		
		this.RegButton = new Ext.Button({
			text: 'Register'
		});
		this.RegButton.on('click',this.RegisterClick, this);
		
		this.ForgotButton = new Ext.Button({
			text: 'Forgot Password'
		});
		this.ForgotButton.on('click',this.ForgotPwdClick, this);
		
		//----------------------------Textbox---------------------------------
		this.UserField = new Ext.form.TextField({
	        xtype: 'textfield',
	        id: 'username',
	        fieldLabel: 'Username',
	        allowBlank: false,
	        blankText:'Enter your username',
	        minLength: 3,
			maxLength: 32
		});
		
		//txtUser.on('keypress', this.TriggerEnterClick);
		
		this.PasswordField = new Ext.form.TextField({
            xtype: 'textfield',
            id: 'password',
            fieldLabel: 'Password',
            inputType: 'password',
            allowBlank: false,
            enableKeyEvents: true, 
            minLength: 6,
		   	ControlToClick:	'btnSubmit',
            maxLength: 32,
            minLengthText: 'Password must be at least 6 characters long.'
        });
		this.PasswordField.on('keypress', this.TriggerEnterClick);
		
		this.RememberMe = new Ext.form.Checkbox({
			boxLabel: 'Remember Me?',
			id: 'chk_Login_rememberMe'
		});
		
	},
	/**
	 * @see NP.Object/CreateTab
	 * @method CreateTab
	 */
	CreateTab: function(){
		var itemsData = NP.Login.superclass.CreateTab.call(this);
		
		if(this.ExternalControls)
			return itemsData;
		//-----------------------Containers---------------------------------------
		//--------------------------------header-------------------------------
		var box= new Ext.BoxComponent({
            xtype: 'box',
            autoEl: { 
                tag: 'div',
                html: '<div class="app-msg"><span><h1><span style="color:black;">my</span>Neopost</h1> Sign-On with your myNeopost user name and password</span></div>'
            }
		});
		
		this.Tab = new Ext.FormPanel({ 
            xtype: 'form',
            id: 'login-form',
            bodyStyle: 'padding:15px; background:transparent',
            border: false,
            url:this.Url,
            items: [box,this.UserField, this.PasswordField, this.RememberMe],
            buttons: [this.LoginButton, this.RegButton,this.ForgotButton]
        });
		//this.LoadMask= new Ext.LoadMask(Ext.getBody(), {msg:this.MaskText});
		//------------------------------------------------------------------------------
	},
	
	GetData: function(){
		NP.Login.superclass.GetData.call(this);
		Ext.getCmp('username').focus(false,1000);
    },
	/**
	 * @property LoadMask
	 */
    LoadMask: null,//new Ext.LoadMask(Ext.getBody(), {msg:this.MaskText}),
	/**
	 * @method CBFailure the method that is called if the server request fails
	 * @param {Object} response
	 * @param {Object} proxy
	 */
	CBFailure: function(response, proxy){
		try {
			var data = this.ParseResponseText(response);
			
			if(data.toLowerCase() =='sy')
				data = 'An unexpected error occured. Please try again later.';
				
			NP.MessageBox('Login Failed', data,true);
		} 
		catch (e) {
		
		}
		this.SetDisabled(false);
		//this.LoadMask.hide();
	},
	StartApp: function(token){
		if (this.LaunchNewWin) 
			NP.NewWindow(token, "870", "680", cookie.GetLocation(), "Neopost");
		else {
		
			NP.Token = token;
			NP.StartMainApp();
		}
	},
	/**
	 * @method CBSuccess the method that is called if the server request is successful
	 * @param {Object} response
	 * @param {Object} store
	 * @param {Object} param
	 */
	CBSuccess: function(response, store, param){
		//-----------Change application state---------------------------------
		this.SetDisabled(false);
		this.SetModal(false);
		//this.LoadMask.hide();
		//--------------------------------------------------------------------
		var data = this.ParseResponseText(response);
		if (data.indexOf(" ") == -1) {
			//---------------------Set Backup cookie-------------------------
			var date = new Date();
			date.setMinutes(date.getMinutes() + 30, 0, 0);
			
			var cookie = new NP.Cookie();
			cookie.SetCookie("NPUserProfile1", data, date.getFullYear(), date.getMonth(), date.getDay(), "/");
			
			var token = cookie.GetCookie("NPUserProfile1");
			
			if(this.RedirectSuccessCB)
				return this.RedirectSuccessCB();
				
			//--Refresh browser to add additional sittings---
			if ((sc_mode = cookie.GetCookie("website#sc_mode")) && sc_mode == "preview" && this.AllowRefresh) {
				delete cookie;
				var path = document.location.href.replace("#", "") + "?l=1";
				//document.location.pathname="default.aspx";
				document.location.href = path;
				return;	
			}
			//-------------------------Launch Main App---------------------------------
			if (!token) 
				token = data;
			else 
				token = "";
			
			this.StartApp(token);	
			delete cookie;
			this.Hide();
		}
		else {
		
			if (data.indexOf("Migration Failed") != -1) {
				this.Hide();
				//-----------------------Re-Register User--------------------------
				var muser = new NP.MigrateUser({
					CBSuccess: function (response, store, param){
						var data = this.ParseResponseText(response);
						
						if (data.indexOf("Migration Failed") != -1) {
							
							var indexP = data.indexOf('::disablePoc');
							if (indexP != -1) {
								this.Items.PocControl.setDisabled(true);
								indexP+= 13;
								
								var pp = data.substring(indexP,data.substring(indexP).indexOf("::")+ indexP);
								this.Items.PocControl.setValue(pp);
							}
							else
								this.Items.PocControl.setDisabled(false);
								
							this.Message('Migration Failed', data);
						}
						else {
							//---------------------Set Backup cookie-------------------------
							var date = new Date();
							date.setMinutes(date.getMinutes() + 30, 0, 0);
							
							var cookie = new NP.Cookie();
							cookie.SetCookie("NPUserProfile1", data, date.getFullYear(), date.getMonth(), date.getDay(), "/");
							
							var token = cookie.GetCookie("NPUserProfile1");
							
							document.location.href = this.BaseUrl + "/myNeopost.aspx";
						}
					},
					CBFailure: this.CBFailure
				});
				muser.Show();
				var indexP = data.indexOf('::disablePoc');
				if (indexP != -1) {
					muser.Items.PocControl.setDisabled(true);
					indexP+= 13;
					
					var pp = data.substring(indexP,data.substring(indexP).indexOf("::")+ indexP);
					muser.Items.PocControl.setValue(pp);
				}
				else
					muser.Items.PocControl.setDisabled(false);
				
				//-------------------------------------------------------------------
			}
			else 
				this.Message('Login Failed',data);
				
		}
	},
	/**
	 * @method Click represents the onclick event handler for the login button
	 * @param {Object} sender
	 * @param {Object} e
	 */
	Click: function(sender, e){
		this.SetDisabled(true);
	    //this.LoadMask.show();
		
		var params= Ext.getCmp('login-form').getForm().getValues();
		
		if(this.UserField.getValue()== "" || this.PasswordField.getValue() == ""  || this.UserField.getValue())
		{
			
			return;
		}
		params.opco = this.Opco;
		params.username = this.Domain + this.UserField.getValue();
		params.password = this.PasswordField.getValue();
		params.persist = this.RememberMe.getValue();
		
		this.SendTextRequest(params, this.CBSuccess, this.CBFailure);
	},
	/**
	 * @method RegisterClick represents the onclick event handler for the register button
	 * @param {Object} sender
	 * @param {Object} e
	 */
	RegisterClick: function(sender,e){
		reg = new NP.Reg();
		this.Hide();
				
		reg.Show();
	},
	ForgotPwdClick: function(sender,e){
		fog = new NP.ForgotPWD();
		this.Hide();
				
		fog.Show();
	},
	Hide: function(){
		NP.Login.superclass.Hide.call(this);
		
		try {
			if (this.Tab) 
				this.Tab.hide();
		}
		catch(e){}
	}	
});

NP.CustomLogin = function(config){
	config = config || {};
	if(!config.cid)
		config.cid='NP.CustomLogin';
	
	NP.CustomLogin.superclass.constructor.call(this, config);
	/**
	 * @see NP.Object/ClassName
	 * @property ClassName
	 */
	this.ClassName = 'NP.CustomLogin';
	
	this.ExternalControls = true;
	this.AllowRefresh= true;
	
	/**
	 * @method SetDisabled: enable or disable the popout window
	 * @param {Object} status
	 */
	this.SetDisabled = function(status){
		if(status)
			this.Mask();
		else
			this.UnMask();
	};
	
	if(config.cid==this.ClassName)
		this.InitComponent();
}

Ext.extend(NP.CustomLogin, NP.Login, {
	/**
	 * @method CreateMisc
	 * @see NP.Panel/CreateMisc
	 */
	CreateMisc: function(){
		if (this.LoginButton) {
			this.LoginButton.removeAllListeners();
			this.LoginButton.on("click", this.Click, this);
		}
		if (this.RegButton) {
			this.RegButton.removeAllListeners();
			//this.RegButton.on('click', this.RegisterClick, this);
		}
	},
	/**
	 * @method Creates the controls that will be added to the tab control
	 */
	OnCreateTabItems: function(items, buttons){
		this.FindControls();
		if(!this.Tab) return;
		
		this.ExternalControls=true;
		this.LaunchNewWin = false;
		
		this.AddEvents();
		//this.Tab.show();
	},
	FindControls: function(){
		var hdnShowLeftLogin = Ext.get('hdnShowLeftLogin') || Ext.get(Ext.query("*[id$=hdnShowLeftLogin]")[0]);
		
		this.InvitationTab = document.getElementById(this.ElementID) || Ext.query("."+this.ElementID)[0];
		
		this.bkInviteTab = Ext.get(document.getElementById('divInvitationControl'));
	
		var logTab = document.getElementById('tbleftLogin') || Ext.query(".tbleftLogin")[0];
		
		logTab = logTab || (document.getElementById('tbhomeLogin') || Ext.query(".tbhomeLogin")[0]);
		
		if(hdnShowLeftLogin)
			logTab = this.InvitationTab;
		else
			this.InvitationTab= Ext.get(this.InvitationTab);
			
		if(!logTab) return;
			
		var as= logTab.getElementsByTagName("a");
		var a=null;
	
		if(as.length>0)
			a= as[0];
			
		this.Tab= Ext.get(logTab);
		this.PasswordField = Ext.get(document.getElementsByName('password')[0]);
		this.UserField = Ext.get(document.getElementsByName('ssousername')[0]);
		
		this.FindLoginButton(logTab.getElementsByTagName("input"));
		
		this.RegButton = Ext.get(a);
		this.DisplayMsg= Ext.query("*[id$=np_spMsg]")[0];//document.getElementById("np_spMsg");
		
		this.RememberMe = Ext.get(document.getElementsByName('chk_Login_rememberMe')[0]);
	},
	FindLoginButton: function(inputs){
			for (var i = 0; i < inputs.length; i++) {
				if (inputs[i].type == 'submit') {
					this.LoginButton = Ext.get('btnLoginSubmit') || Ext.get(inputs[i]);
					break;
				}
			}
	},
	AddEvents: function(){
		if (this.PasswordField) {
			this.PasswordField.removeAllListeners();
			
			this.PasswordField.on('click', this.ClearMask);
			this.PasswordField.on('focus', this.ClearMask);
			this.PasswordField.on('blur', this.ResetMask);
			this.PasswordField.ControlToClick = this.LoginButton //? (this.LoginButton.name || this.LoginButton.id) : 'Submit'; 
			this.PasswordField.on('keypress', this.TriggerEnterClick);
		}
		
		if (this.UserField) {
			this.UserField.removeAllListeners();
			
			this.UserField.on('click', this.ClearMask);
			
			this.UserField.on('click', function() {
				 	var npcookie = new NP.Cookie();
					
					if (!npcookie.GetCookie('MyNeoJuneReReg')) {
					
					var noticeHTML = '<div class="notice" ID="myNeoNotice"><h3 style="padding:7px 5px 0px 10px;">IMPORTANT NOTICE TO CUSTOMERS:</h3><div class="notice3"><strong>Effective July 3rd, 2011:</strong> All previously-registered customers of myNeopost and/or neoShop must re-register their accounts in order to access our new system. Simply complete the <a href="/Customers/Register.aspx#regForm" style="color:#c00010;">registration form</a> to access your account. If you have already re-registered on or after July 3rd, you may disregard this message and simply log in.<br /><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td valign="bottom"><a href="/Customers/Register.aspx#regForm" class="grey_button">Register Now</a></td><td align="right" valign="bottom" class="smalltext"><a href="#" onClick="setUserWindowHide();"><img src="shared/grey-arrow-list.jpg" width="4" height="11" align="absmiddle" /> I have already re-registered - don\'t show this message again.</a></td></tr></table></div></div>';
					
					reregWindow = new Ext.Window({
						id: 'RegNoticeWin',
						title: 'User Registration',
						width: 500,
						height: 220,
						html: noticeHTML,
						modal: true,
						anchorToTarget: true,
						target: Ext.query(".leftlogin")[0]
					});
								
					reregWindow.show();
												
					} 
				 });
				 
				 
			this.UserField.on('focus', this.ClearMask);
			this.UserField.on('blur', this.ResetMask);
		}
	},
	/**
	 * @method Click represents the onclick event handler for the login button
	 * @param {Object} sender
	 * @param {Object} e
	 */
	Click: function(sender, e){
		sender.stopPropagation();
		sender.stopEvent();
		this.Mask();
		
		var usrStatus = this.UserField.dom.getAttribute("clickedStatus");
		var pwdStatus = this.PasswordField.dom.getAttribute("clickedStatus");
		
		
		if (!usrStatus || usrStatus == "undefined") {
		
			if (this.UserField.getValue() != 'username') {
			
			}
			else {
				this.Message('Neopost USA.', 'Please enter a valid username and password');
				return;
			}
		}
		
		if (!pwdStatus || pwdStatus == "undefined") {
			this.Message('Neopost USA.', 'Please enter a valid username and password');
			return;
		}
		
		if (this.UserField.getValue() == "" || this.PasswordField.getValue() == "" || this.UserField.getValue().toLowerCase() == "username") {
			this.Message('Neopost USA.', 'Please enter a valid username and password');
			return;
		}
		
		var s = '{0}/sso/auth?v=v1.4&site2pstoretoken={1}&appctx=&p_cancel_url={0}&locale=';
		s = String.format(s, ssoUrl, ssoVer)
		
		this.Login(this.UserField.getValue(), this.PasswordField.getValue(), this.Opco || 4, s, this.Tab.dom.parentNode);
		
		return true;
	},
	Login: function(uname, pwd,opco,s, pEl){
		
		var formEl = document.createElement("form");
		formEl.setAttribute("id", Ext.id());
		formEl.setAttribute("action",s);
		formEl.setAttribute("method", 'POST');
		formEl.style.display='none';
		
		userEl = document.createElement("input");
		userEl.setAttribute("type",'text');
		userEl.setAttribute("name",'ssousername');
		userEl.value = uname;
		
		
		pwdEl = document.createElement("input");
		pwdEl.setAttribute("type",'text');
		pwdEl.setAttribute("name",'password');
		pwdEl.value = pwd;
		
		
		actionEl = document.createElement("input");
		actionEl.setAttribute("type",'text');
		actionEl.setAttribute("name",'p_action');
		actionEl.value = 'OK';
		
		
		opcoEl = document.createElement("input");
		opcoEl.setAttribute("type",'text');
		opcoEl.setAttribute("name",'opco');
		opcoEl.value = opco;
		
		
		formEl.appendChild(userEl);
		formEl.appendChild(pwdEl);
		formEl.appendChild(actionEl);
		
		if(pEl.id =='')
			pEl.id= Ext.id();
			
		pEl.appendChild(formEl);
		
		formEl.submit();
	},
	/**
	 * @method RegisterClick represents the onclick event handler for the register button
	 * @param {Object} sender
	 * @param {Object} e
	 */
	RegisterClick: function(sender,e){
		reg = new NP.Reg();
		this.Hide();
				
		reg.Show();
	},
	ForgotPwdClick: function(sender,e){
		fog = new NP.ForgotPWD();
		this.Hide();
				
		fog.Show();
	},
	Message: function(title, data){
		try {
			if (this.DisplayMsg) 
				this.DisplayMsg.innerHTML = data;
			else 
				NP.CustomLogin.superclass.Message.call(this, title, data);
		}
		catch(e){}
		NP.UnMask();
	},
	ResetMask: function(sender){
		if (this.dom.name.toLowerCase().match("pass")) {
			if (this.dom.value.toLowerCase() == "password" || this.dom.value == "") {
				var id = this.dom.name;
				try {
					this.dom.type = "text";
				} 
				catch (e) {
				}
				
				this.dom.value = "password";
				this.dom.setAttribute("clickedStatus", "undefined");
			}
		}
		else 
			if (this.dom.name.toLowerCase().match("user")) {
				if (this.dom.value.toLowerCase() == "username" || this.dom.value == "") {
					this.dom.value = "username";
					this.dom.setAttribute("clickedStatus", "undefined");
				}
			}
	},
	ClearMask: function(sender){
		if (this.dom.getAttribute("clickedStatus") == "undefined" || this.dom.getAttribute("clickedStatus") == undefined) {
			this.dom.setAttribute("clickedStatus", "1");
			this.dom.value = "";
			
			if (this.dom.name.toLowerCase().match("pass")) {
				var id = this.dom.name;
				try {
					this.dom.type = "password";
				} 
				catch (e) {
				}
				var n = setTimeout("document.getElementsByName('" + id + "')[0].focus()", 100);
			}
		}
	},
	Hide: function(){
		NP.CustomLogin.superclass.Hide.call(this);
		
		if(this.InvitationTab)
			this.InvitationTab.hide();
		
		if(this.bkInviteTab)
			this.bkInviteTab.hide();
				
		this.Message('', '');
		
		if (NP.RunningApps['NP.GreetingPanel']) 
			NP.RunningApps['NP.GreetingPanel'].Show();
		
		if (this.ClassName != 'NP.CustomLogin.Invitation') {
			if (NP.RunningApps['NP.CustomLogin.Invitation']) 
				NP.RunningApps['NP.CustomLogin.Invitation'].Hide();
		}
	},
	Show: function(){
		NP.CustomLogin.superclass.Show.call(this);
		
		if(this.InvitationTab)
			this.InvitationTab.show();
			
		if(NP.RunningApps['NP.GreetingPanel'])
			NP.RunningApps['NP.GreetingPanel'].Hide();
	},
	/**
	 * @method CreateWindow: create a pop out window container
	 */
	CreateWindow: function(){
	}	
});

NP.AppsLogin = Ext.extend(NP.CustomLogin, {
	FindControls:function(){
		this.AllowRefresh = false;
		var logTab = document.getElementById(this.ElementID) || Ext.query("."+this.ElementID)[0];
		if(!logTab) return;
			
		var as= logTab.getElementsByTagName("a");
		var a=null;
	
		if(as.length>0)
			a= as[0];
			
		this.Tab= Ext.get(logTab);
		var inputs =logTab.getElementsByTagName("INPUT");
		
		this.UserField = Ext.get(inputs[0]);
		this.PasswordField = Ext.get(inputs[1]);
		this.LoginButton = Ext.get(logTab.getElementsByTagName("BUTTON")[0]);//Ext.get('btnLoginSubmit');
		this.DisplayMsg= Ext.query("*[id$=np_spMsg]")[0];
	},
	Show: function(){
		NP.CustomLogin.superclass.Show.call(this);
		
		this.Tab.slideIn();
	},
	Hide: function(){
		NP.CustomLogin.superclass.Hide.call(this);
		
		this.Tab.slideOut();
	},
	/**
	 * @method CreateWindow: create a pop out window container
	 */
	CreateWindow: function(){
	},
	StartApp: function(token){
		var cookie = new NP.Cookie();
		var hdn = cookie.GetCookie("np_apps_view");
		var el = Ext.get(document.getElementById('btnAppsLogin'));
		var divMsg = Ext.get(document.getElementById('divAppsLeftMsg'));
        var hdnAppValue = Ext.query("*[id$=hdnAppValue]")[0];

		if(hdn && hdn!=""){
			//hide the login button
			el.dom.setAttribute('display','none');
			el.dom.style.display = 'none';
			
			divMsg.dom.setAttribute('display','none');
			divMsg.dom.style.display = 'none';
			
			delete el;
			delete hdn;
			delete cookie;
			delete divMsg;
			return;
		}
		
		if(hdnAppValue)
			NP.Token = hdnAppValue.value;

		if (!NP.Token) {
			if (!token || token === "") {
			
				NP.Token = (cookie.GetCookie("NPUserProfile") ? cookie.GetCookie("NPUserProfile") : cookie.GetCookie("NPUserProfile1"));
				delete cookie;
			}
			else 
				NP.Token = token;
		}
		
		var cb;
	    //----------------------------Start Application------------------------------------
		if (NP.Token && NP.Token != "") {
			el.update('Get App');
			divMsg.update('Add this App to your iMeter!');
			
			/*var t= Ext.get(document.getElementById('sp_AppName'));
			t.update(document.getElementById('h3_title').innerHTML);
			*/
			var t =document.getElementById('h3_title').innerHTML
			
			cb= function(sender, ev){
				if (NP.RunningApps['NP.SignUp']) {
					try {
						NP.RunningApps['NP.SignUp'].Hide();
						NP.RunningApps['NP.SignUp'].Dispose();
					}
					catch(ee){}
				}
				
				var divSign = new NP.SignUp({Name: t.RTrim()});
				divSign.Show();
			};
			
			if(this.ClassName =='NP.CustomLogin')
				cb();
		}
		else {
			cb = function(sender, ev){
				divMsg.hide();
				
				if (!NP.RunningApps['NP.AppsLogin']) {
					var login = new NP.AppsLogin({
						ElementID: 'divAppsLogin'
					});
				}
				
				login.Show();
			};
		};
		
		el.removeAllListeners();
		el.on('click',cb);
	}
})

NP.SignUp = function(config){
	config = config || {};
	if(!config.cid)
		config.cid='NP.SignUp';
	
	NP.SignUp.superclass.constructor.call(this, config);
	
	/**
	 * @property Url
	 * @projectDescription the url that is used to preform ajax request
	 */
	this.Url = this.BaseUrl + '/broker.asmx/PerformOperationJson';
	
	/**
	 * @see NP.Object/ClassName
	 * @property ClassName
	 */
	this.ClassName = 'NP.SignUp';
	if(config.cid==this.ClassName)
		this.InitComponent();
}
Ext.extend(NP.SignUp, NP.Login, {
	AppId: [],
	/**
	 * @method Creates the controls that will be added to the tab control
	 */
	OnCreateTabItems: function(items, buttons){
		this.AppId = Ext.get('np_ImeterAppID');
		this.AppId = this.AppId.getValue();
		
		//-------------Items-------------------------------------------
		this.Items.Name = new  Ext.form.TextField({
            fieldLabel: 'Name',
			text: 'Name',
            //anchor:'99%',
			allowBlank: false
        });
		
		this.Items.Email = new Ext.form.TextField({
			fieldLabel: 'Email',
			vtype: 'email',
			allowBlank: false
		});
		
		this.Items.Phone = new Ext.form.TextField({
			fieldLabel: 'Phone',
			allowBlank: false
		});
		
		var storeApps = new Ext.data.ArrayStore({
	        fields: ['SERIAL_NBR','ADDRESS_ID'],
	        idIndex: 0
	    });
		
		this.Items.Combo = new Ext.form.ComboBox({
            typeAhead: true,
            store: storeApps,
            mode:'local',
            triggerAction: 'all',
            lazyRender:true,
            selectOnFocus:true,
            forceSelection: true,
            //width:160,
            displayField: 'SERIAL_NBR',
            //anchor:'98%',
            fieldLabel: 'Meter',
			editable : false
        });
		this.Items.UseNeopost = new  Ext.form.Checkbox({
			fieldLabel: 'Use info from myNeopost',
			checked: true
		});
		
		this.Items.UpdateNeopost = new Ext.form.Checkbox({
			fieldLabel: 'Update myNeopost with this information',
			checked: false
		});
		
		this.Items.SignUp = new Ext.Button({
			fieldLabel: 'Submit',
			text: 'Submit',
			scope: this,
			handler: function(){
				this.SignUp();
			}
		});
		
		this.Items.CancelButton = new Ext.Button({
			fieldLabel: 'Cancel',
			text: 'Cancel',
			scope: this,
			handler: function(){
				this.Hide();
				this.Dispose();
			}
		});
		
		this.Items.MeterMsg= new Ext.BoxComponent({
            xtype: 'box',
            autoEl: { 
                tag: 'div',
                html: '<div class="app-msg" style="text-align:center;"><span style="font-weight:bold;">Note: </span><span>Please select the meter that you would like to apply this app to.</span></div>'
            }
		});
		
		//return { Items: [this.Items.UseNeopost,this.Items.Name,this.Items.Email, this.Items.Phone, this.Items.Combo, this.Items.UpdateNeopost], Buttons: [this.Items.SignUp]};
		return { Items: [this.Items.UseNeopost, this.Items.Name,this.Items.Email, this.Items.Phone, this.Items.Combo, this.Items.UpdateNeopost, this.Items.MeterMsg], Buttons: [this.Items.SignUp, this.Items.CancelButton]};
	},
	
	CreateTab: function(){
		this.ExternalControls =true;
		var itemData = NP.SignUp.superclass.CreateTab.call(this);

		this.Tab = new Ext.FormPanel({ 
            xtype: 'form',
            bodyStyle: 'padding:15px;',
            border: false,
            url: this.Url,
			buttonAlign: 'right',
			labelAlign: 'right',
			labelWidth: 230,
			defaults: {align: 'left'},
        	defaultType: 'textfield',
			
            items: itemData.Items,
			buttons: itemData.Buttons
        });
		this.Width= 633;
	},
	/**
	 * @method CreateWindow: create a pop out window container
	 */
	CreateWindow: function(){
		//NP.SignUp.superclass.CreateWindow.call(this);
		this.win = new Ext.Window({
			width: this.Width,
			buttonAlign: 'right',
			autoHeight: this.AutoHeight,
			disabled: false,
			x: 339,
			y: 295,
			//clS:'TEST',
			title: 'Get the ' + this.Name,
			closeAction: 'hide',
			items: this.Tab
		});
		
		this.win.show();
		this.win.el.slideIn('b');
	},
	/**
	 * @method CreateWindow: create a pop out window container
	 */
	/*CreateWindow: function(){ },*/
	Init: function(){
		NP.SignUp.superclass.Init.call(this);
		//this.GetData();
	},
	/*Mask: function(){
		if(this.Tab)
			this.Tab.mask();
	},
	UnMask: function(){
		if(this.Tab)
			this.Tab.unmask();
	},*/
	GetData: function(){
		try {
			this.Items.Name.focus(false, 1000);
		}
		catch(e){}
		
		this.Mask();
		
		var params = {
            token:NP.Token,
            settings: "{\"isToken\":\"false\",\"isXml\":\"true\",\"xAction\":\"91\",\"ActionGroup\":\"32\"}", 
            paramList: this.Params
        };
		//-------------------------------set request----------------------------
		this.SendTextRequest(params,function(response, data){
			var json = this.ParseResponseJson(response);
			var data = null;
			
			try {
				data = Ext.util.JSON.decode(json);
				if (!data) {
					throw {
						message: "JsonReader.read: Json object not found"
					};
				}
				if (data.rows.indexOf("Access denied") != -1) {
					NP.MessageBox("Neopost USA", data.rows, true);
					
					this.Hide();
					this.Dispose();
					return;
				}
				this.Items.Name.setValue(data.rows[1]);
				this.Items.Email.setValue(data.rows[2]);
				this.Items.Phone.setValue(data.rows[3]);
				
				if (data.rows[4] === true) {
					var rows = Ext.util.JSON.decode(data.rows[0]);
					var store = this.Items.Combo.getStore();
					store.add(new store.recordType({SERIAL_NBR: 'All',ADDRESS_ID:'All'}));
					
					for (var i = 0; i < rows.length; i++) 
						store.add(new store.recordType(rows[i]))
						
					this.Items.Combo.setValue("All");
				}
				else {
					this.Tab.remove(this.Items.Combo,true);
					this.Tab.remove(this.Items.MeterMsg,true);
				}
				
			} 
			catch (ee) {
			
			}
			
			this.UnMask();
		});
    },
	SignUp: function(){
		if (!this.Tab.getForm().isValid())
			return; 
			
		var appID= this.AppId;
		var params = {
            token:NP.Token,
            settings: "{\"isToken\":\"false\",\"isXml\":\"true\",\"xAction\":\"92\",\"ActionGroup\":\"32\"}", 
            paramList: [this.Items.Name.getValue(),this.Items.Phone.getValue(),this.Items.Email.getValue(),this.Items.Combo.getValue(),appID,this.Items.UpdateNeopost.getValue()]
        };
		this.Mask();
		
		//-------------------------------set request----------------------------
		this.SendTextRequest(params,function(response, data){
			var json = this.ParseResponseJson(response);
			try {
				if (json.indexOf('successfully') == -1) {
					NP.MessageBox('Neopost USA', this.ParseJson(json).rows, true);
					return;
				}
				
				Ext.Msg.show({
				   title:'Thank you for choosing the ' + this.Name +' ',
				   msg: 'An email confirming your account information along with next steps to purchasing this powerful app has been sent to the email address provided. ',
				   buttons: Ext.Msg.OK,
				   animEl: this.win.id
				});
				
				this.Hide();
				this.Dispose();
			}
			catch(ee){
				NP.MessageBox('Neopost USA', ee.message,true);
			}
			this.UnMask();
		}, function(a,b,c){
			this.UnMask();
		});
	}
});

function setUserHide(){
	var expire = new Date(Date.getTime() + 365 * 24 * 60 * 60 * 1000);
	
	Ext.util.Cookies.set('MyNeoJuneReReg', 'true', expire);
}


function setUserWindowHide(){
	
	var now = new Date();
	var then = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	
	Ext.util.Cookies.set('MyNeoJuneReReg', 'true', then, '/', 'neopostinc.com');
	
	reregWindow.hide(true);
	
	setUserHide();
}

