Ext.onReady(function()
{
  Ext.QuickTips.init();
  createLoginForm();

  createSignUpForm();
  createForgotPasswordForm();

  if( findURLValue("activate") == 'true' )
  {
    Ext.DomHelper.applyStyles('divActivate','display:block;');

  }
});


function createSignUpForm()
{
  var edtCompanyName = new Ext.form.TextField(
  {
    renderTo:'edtCompanyName',
    width:190,
    id:'signupCompany',
    name:'signupCompany',
    allowBlank:false,
    maxLength: 200,
    group:2,
    listeners:{'focus':processfocus}
  });

  var edtEmailAddress = new Ext.form.TextField(
  {
    renderTo:'edtEmailAddress',
    width:190,
    id:'signupAddress',
    name:'signupAddress',
    allowBlank:false,
    maxLength: 50,
    group:2,
    listeners:{'focus':processfocus}
  });

  var edtPassword = new Ext.form.TextField(
  {
    renderTo:'edtPassword',
    width:190,
    id:'signupPassword',
    name:'signupPassword',
    inputType:'password',
    allowBlank:false,
    maxLength: 100,
    group:2,
    listeners:{'focus':processfocus}
  });

  var btnSignUp = new Ext.Button(
  {
    renderTo:'btnSignUp',
    text:'Sign-Up',
    minWidth:75,
    handler:doSignUp
  });
}

function createForgotPasswordForm()
{
  var edtForgotEmailAddress = new Ext.form.TextField(
  {
    renderTo:'edtForgotEmailAddress',
    width:190,
    id:'forgetAddress',
    name:'forgetAddress',
    maxLength: 50,
    allowBlank:false,
    group:3,
    listeners:{'focus':processfocus}
  });

  var btnSignUp = new Ext.Button(
  {
    renderTo:'btnForgotPassword',
    text:'Submit',
    minWidth:75,
    handler:doForgetPassword

  });
}

function processfocus(oSrc)
{
  switch(oSrc.group)
  {
    case 1:
      Ext.getCmp('signupCompany').clearInvalid();
      Ext.getCmp('signupAddress').clearInvalid();
      Ext.getCmp('signupPassword').clearInvalid();
      Ext.getCmp('forgetAddress').clearInvalid();
      break;
    case 2:
      Ext.getCmp('loginUsername').clearInvalid();
      Ext.getCmp('loginPassword').clearInvalid();
      Ext.getCmp('forgetAddress').clearInvalid();
      break;
    case 3:
      Ext.getCmp('signupCompany').clearInvalid();
      Ext.getCmp('signupAddress').clearInvalid();
      Ext.getCmp('signupPassword').clearInvalid();
      Ext.getCmp('loginUsername').clearInvalid();
      Ext.getCmp('loginPassword').clearInvalid();
      break;
  }

}

function createLoginForm()
{
  var login = new Ext.FormPanel(
    {
      renderTo:'divLogin',
      labelWidth:80,
      url:'http://portal.weldco-beales.com/NavWebService/NavWebService.php?method=login',
      frame:true,
      height:270,
      width:420,
      defaultType:'textfield',
      monitorValid:true,
      layout:'absolute',
      id:'frmLogin',
      title:'Portal Login',
      items:[
      {
        xtype:'label',
        x:5,
        y:15,
        text:'To access the Portal, please enter your Email and Password below:',
        cls:'qText qBlueText qTextMedium'
      },
      {
        xtype:'label',
        x:10,
        y:50,
        text:'Email Address:',
        cls:'qText qBlackText qTextMedium'
      },
      {
        x:100,
        y:47,
        width:225,
        id:'loginUsername',
        name:'loginUsername',
        allowBlank:false,
        maxLength:50,
        style:'position:absolute',
        group:1,
        listeners:{'focus':processfocus}
      },
      {
        xtype:'label',
        x:10,
        y:75,
        text:'Password:',
        cls:'qText qBlackText qTextMedium'
      },
      {
        x:100,
        y:72,
        width:225,
        id:'loginPassword',
        name:'loginPassword',
        inputType:'password',
        allowBlank:false,
        maxLength: 100,
        style:'position:absolute',
        group:1,
        listeners:{'focus':processfocus}

      },
      {
        xtype: 'container',
        x:10,
        y:115,
        autoEl: {},
        items: {xtype: 'button',minWidth:75,text: 'Login',handler:doLogin}
      },
      {
        xtype:'label',
        x:10,
        y:200,
        html:"Privacy Policy and Terms of Service&nbsp;<a class='qText qRedLink' href='./Weldco_Companies_Terms_of_Service.htm' target='_blank' alt='Sign Up'>&nbsp;<span class='qTriangle'>u</span>&nbsp;click here</a>",
        cls:'qText qBlueText qTextSmall'
      },
      {
        xtype: 'box',
        x:320,
        y:200,
        autoEl: {tag: 'img', src: './img/Weldco-Logo-small.gif'}
      },
      {
        name:'method',
        inputType:'hidden',
        value:'login'
      }
      ]
    });



    Ext.getCmp('loginUsername').focus(false, 50);

    this.map = new Ext.KeyMap
    (
      "frmLogin",
      [
        {
          key : [10, 13],
          scope:this,
          fn : doLogin
        }
      ]
  );
}

function doLogin()
{
  Ext.getCmp('loginUsername').validate();
  Ext.getCmp('loginPassword').validate();

  if( ! Ext.getCmp('loginUsername').isValid() )
  {
    Ext.getCmp('loginUsername').focus();
    return;
  }
  if( ! Ext.getCmp('loginPassword').isValid() )
  {
    Ext.getCmp('loginPassword').focus();
    return;
  }


  Ext.getCmp('frmLogin').getForm().submit(
  {
    method:'POST',
    waitTitle:'Connecting',
    waitMsg:'Sending data...',
    success:function()
    {
      var redirect = getRedirect();
      if( redirect == "" )
        redirect = 'PortalHome.php?site=0';

      window.location = redirect;
    },
    failure:function(form, action)
    {
      if(action.failureType == 'server')
      {
        //obj = Ext.util.JSON.decode(action.response.responseText);
        showError('Login failed.<br/>Please re-enter your Username and Password and try again.',"Login Failed");
      }
      else
      {
      	displayGenericError("I'm sorry, we are unable to process you request at this time.");
      }

      Ext.getCmp('frmLogin').getForm().reset();
    }
  });
}//doLogin()


function doSignUp()
{
  Ext.getCmp('signupCompany').validate();
  Ext.getCmp('signupAddress').validate();
  Ext.getCmp('signupPassword').validate();

  if( ! Ext.getCmp('signupCompany').isValid() )
  {
    Ext.getCmp('signupCompany').focus();
    return;
  }
  if( ! Ext.getCmp('signupAddress').isValid() )
  {
    Ext.getCmp('signupAddress').focus();
    return;
  }
  if( ! Ext.getCmp('signupPassword').isValid() )
  {
    Ext.getCmp('signupPassword').focus();
    return;
  }

  // do a submit here
  var callbacks = { success: pass, failure: fail,timeout: 15000};
  var postData = "meta=0&method=createlogin" +
                  "&company=" + Ext.getCmp('signupCompany').getValue() +
                  "&email=" + Ext.getCmp('signupAddress').getValue() +
                  "&password=" + Ext.getCmp('signupPassword').getValue();


  Ext.lib.Ajax.request('POST', m_sNavServiceURL, callbacks, postData);

  function pass(o)
  {
    obj = Ext.util.JSON.decode(o.responseText);
    resetSignUp();
    if( obj.success )
      showInfo("Your request is being processed.<br/>Please check your Email to proceed with the activation process.","Success");
    else
      showInfo("We were unable to confirm your Email address in our records.  Someone from our Sales department has been notified and will be in contact with you shortly.<br/><br/>" + m_sSupportContact);
  }
  function fail(o)
  {
    resetSignUp();
    displayGenericError("I'm sorry, we are unable to process your request at this time.");
  }
}//doSignUp()

function doForgetPassword()
{
  Ext.getCmp('forgetAddress').validate();

  if( ! Ext.getCmp('forgetAddress').isValid() )
  {
    Ext.getCmp('forgetAddress').focus();
    return;
  }


  // do a submit here
  var callbacks = { success: pass, failure: fail,timeout: 15000};
  var postData = "meta=0&method=resetpassword" +
                  "&email=" + Ext.getCmp('forgetAddress').getValue();


  Ext.lib.Ajax.request('POST', m_sNavServiceURL, callbacks, postData);

  function pass(o)
  {
    obj = Ext.util.JSON.decode(o.responseText);
    resetSignUp();
    if( obj.success )
      showInfo("Your request has been processed.<br/>Please check your Email to retrieve your new temporary password.","Success");
    else
      displayGenericError(obj.error);
  }
  function fail(o)
  {
    resetSignUp();
    displayGenericError("I'm sorry, we are unable to process your request at this time.");
  }
}


function resetSignUp()
{
  Ext.getCmp('signupCompany').setValue('');
  Ext.getCmp('signupAddress').setValue('');
  Ext.getCmp('signupPassword').setValue('');
  Ext.getCmp('signupCompany').clearInvalid();
  Ext.getCmp('signupAddress').clearInvalid();
  Ext.getCmp('signupPassword').clearInvalid();
}


function getRedirect()
{
  var sRedirectURL = "";
  var iIndex = location.search.substr(1).toLowerCase().indexOf("redirect=");
  if( iIndex != -1 )
  {
    sRedirectURL = location.search.substr(1).toLowerCase().substring(iIndex+9);
  }

  return sRedirectURL;
}//getRedirect()

