Ext.onReady(function () {
  //ww.el.alertDetails(ww.f);
  //ww.f.show_question();
  Ext.apply(ww, {
    main: function () {
      Ext.QuickTips.init();
      Ext.apply(ww.v, {
        //lnUptOccp: ww.f.getLink_UpdateOccp(),
        validKey: '',
        validEmail: '',
        validNric: ''
      });
      ww.el.auto_manipulate(ww.v);
    },
    v: {
      window: new Ext.Window({
        animateTarget: 'kpPassword_display',
        width: 620, baseCls: 'x-plain',
        closable: false, border: false, resizable: false,
        draggable: true, modal: true, autoScroll: true,
        headerStyle: {padding: '5px', background: 'url(/img/common/password.jpg)', height: '20px', 'text-align': 'right' },
        bodyStyle: 'padding: 10px; background: #FFF',
        footerStyle: {padding: '0px', 'border-top': '1px solid #ccc', background: '#FFF' },
        title: '<img id="kpl_custClose" style="cursor: pointer;" src="/admin/img/ext/s.gif" width="58px" height="15px" onClick="ww.v.window.hide();"/>',
        items: new Ext.FormPanel({ baseCls: 'x-plain', items: [ww.q.frmPart, ww.q.frmQuest] }),
        buttons: [
          new Ext.ww.Button({btnType: 'image', imgSrc: '/admin/img/ext/submit.gif', buttonWidth: "74px",
            handler: function(){ this.ownerCt.formSubmit(); }
          }),
          new Ext.ww.Button({btnType: 'image', imgSrc: '/admin/img/ext/reset.gif', buttonWidth: "65px",
            handler: function(){ this.ownerCt.formReset(); }
          })
        ],
        _response: {
          succ: function (f, r) {
            var msg = [
              '<table><tbody>',
              '<tr><td style="font-size: 12px">&nbsp;</td></tr>',
              '<tr><td style="font-size: 14px">',
                '<b>Thank you for completing the questionnaire.</b>',
              '</td></tr>',
              '[ADDITIONAL_MSG]', 
              '<tr><td style="font-size: 12px">&nbsp;</td></tr>',
              '<tr><td style="font-size: 12px">[CONTENTS]</td></tr>',
              '</tbody></table>'
            ]
            var addMsg = [
              '<tr><td style="font-size: 12px">&nbsp;</td></tr>',
              '<tr><td style="font-size: 12px">',
                'Your Keppel Nights password will be sent to your email address. You can use this password to purchase your Keppel Nights ticket directly from the ticketing agent. Thank you for your support of Keppel Nights! ',
              '</td></tr>',
            ]
            msg = msg.join('');
            addMsg = addMsg.join('');
            
            ww.v.validEmail = f.findField("FREmail").getValue();
            ww.v.validKey = r.key;
            ww.v.msg = r.display;
            
            var birthYear = f.findField("FRDOB_Year").getValue();
            var currentAge = parseInt(new Date().format('Y')) - parseInt(birthYear);
            //var occupation = f.findField("FROccupation").getValue();
            //occupation = occupation.toString().toLowerCase();
            
            isAdditionalMsg = true;
            //if (currentAge < 55) {
            //  if ((occupation.indexOf('student')==-1) && (occupation.indexOf('national service')==-1)) isAdditionalMsg = false;
            //}
            
            var toDisplay = msg.replace('[CONTENTS]', r.msg);
            toDisplay = toDisplay.replace('[ADDITIONAL_MSG]', (isAdditionalMsg)?addMsg:'');
            ww.msgbox.info(toDisplay, { fn: function (btn) {
              ww.v.window.formReset();
              ww.v.window.hide();
              //ww.f.updatePassword(ww.v.msg);
            } });
          },
          errExist: function (f, r) {
            //ww.v.validEmail = f.findField("FREmail").getValue();
            ww.v.validNric = f.findField("FRNric").getValue();
            ww.v.validKey = r.key;
            ww.v.msg = r.msg;
            //ww.msgbox.warning('NRIC "' + ww.v.validNric + '" already exist in the records.',
            ww.msgbox.warning('Sorry, you can only use the Keppel Nights password twice. However, we will send you a MadAboutArts card that entitles you to a 10% discount on future ticket purchases of any show staged by promoters and museums under the Keppel Nights scheme. If your postal address is different from your submitted address, pls contact us at kn@mica.gov.sg with the correct address so that we can send you the card. Thank you for your support of Keppel Nights!<br/><br/>', {
              fn: function (btn) {
                ww.v.window.formReset();
                ww.v.window.hide();
                //ww.f.updatePassword(ww.v.msg);
              }
            });
          }
        },
        formSubmit: function () {
          var oForm = this.items.get(0).getForm();
          var PRCPerformanceIDValue = oForm.findField("PRCPerformanceIDText").getValue();
          if(oForm.isValidElseAlert()) {
            oForm.submit({
              url: '/questionnaire/q_action.asp', params: {type: 'subf', FRAQuestionSetID: ww.qsid, PRCPerformanceID: PRCPerformanceIDValue},
              waitMsg: 'Submitting...',
              success: function(frm, oAction) {
                if (oAction.result) {
                  var res = oAction.result||{};
                  switch (res.msgCode) {
                    case 'submited':ww.v.window._response.succ(frm, res); break;
                    case 'exist':ww.v.window._response.errExist(frm, res); break;
                    case 'usedup':ww.v.window._response.errExist(frm, res); break;
                    default: ww.msgbox.err('Unexpected error: Please try again later!');
                  }
                } else {
                  ww.msgbox.err('Unexpected error: Please try again later!');
                }
              }
            });
          }
        },
        formReset: function () {
          this.items.get(0).getForm().reset();
        },
        manipulate: function () {
          this.on('show', function () {
            this.footer.setStyle(this.footerStyle);
            this.header.setStyle(this.headerStyle);
          });
        }
      }),
      frmEmail: new Ext.FormPanel({
        frame: false, baseCls: 'x-plain',
        labelWidth: 20, defaultType: 'textfield',
        style: 'padding: 5px;',
        items: [{fieldLabel: '<b>Nric</b>', name: 'email', vtype:'email', width: 180, allowBlank: false},
                {fieldLabel: '<b>Shows</b>', name: 'email2', vtype:'email', width: 180, allowBlank: false}],
        _request: function () {
          var oForm = this.getForm();
          if(oForm.isValidElseAlert()) {
            oForm.submit({
              url: '/questionnaire/q_action.asp', params: {type: 'reqc'},
              waitMsg: 'Sending your request...',
              success: function(frm, oAction) {
                if (oAction.result) {
                  var res = oAction.result||{};
                  if (res.msgCode != 'failed') ww.v.frmEmail._response.succ(frm, res);
                    else ww.v.frmEmail._response.failed(frm, res);
                } else {
                  ww.msgbox.err('Unexpected error');
                }
              }
            });
          }
        },
        _response: {
          succ: function (f, r) {
            ww.v.validEmail = f.findField("email").getValue();
            ww.v.validKey = r.msgCode;
            ww.f.updatePassword(r.msg);
          },
          failed: function (f, r) {
            var email = f.findField("email").getValue();
            ww.msgbox.warning('Nric "' + email + '" doesn\'t exist in the records.<br/><br/>Please verify your nric.' );
          }
        }
      }),
      lnFormPop: Ext.apply(Ext.get('kp_formQuest'), {
        fnHandler_onClick: function(E) {
          ww.f.show_question();
        },
        manipulate: function () {
          this.on('click', this.fnHandler_onClick);
          
          //ww.f.show_question();
        }
      }),
      lnReqSession: Ext.apply(Ext.get('kp_requestPassword'), {
        fnHandler_onClick: function(E) {
          this.up('div').hide({ duration: 0.5, callback: ww.v.lnReqSession.construct.requestLink });
          var el = ww.v.lnFormPop;
          el.hide({ duration: 0.3, callback: ww.v.lnReqSession.construct.requestSession });
        },
        construct: {
          requestSession: function () {
            ww.f.removeHandler_passArea();
            var elPassArea = ww.v.lnFormPop;
            elPassArea.dom.innerHTML = '';
            elPassArea.setStyle({cursor:''});
            ww.v.frmEmail.render(elPassArea);
            elPassArea.show({duration: .5});
          },
          requestLink: function () {
            var elBottom = ww.v.lnReqSession.up('div');
            ww.v.lnReqSession.remove();
            elBottom.dom.innerHTML = 'Enter your nric and click <a id="kp_submitRequest" style="cursor: pointer;">here</a> for your promo code.';
            elBottom.show();
            ww.v.elBottom = elBottom;

            Ext.fly('kp_submitRequest').on('click', function () { ww.v.frmEmail._request() });
            ww.v.frmEmail.getForm().findField("email").on('specialkey', function(f, E) {
              if (E.getKey()==13) ww.v.frmEmail._request();
            });
          }
        },
        manipulate: function () {
          this.on('click', this.fnHandler_onClick);
        }
      })
    },
    f: {
      ajax_requestForUpdate: function () {
        Ext.Ajax.request({
          url: '/questionnaire/q_action.asp', params: {type: 'uptpart', key: ww.v.validKey},
          success: function () { ww.msgbox.info('Email sent. Kindly check your email, and click the activate link to change your particulars.') },
          failure: function () { ww.msgbox.err('Unexpected error: Please try again later!'); }
        });
      },
      updatePassword: function (msg) {
        var dom = Ext.get('kpPassword_display').up('td').dom;
        Ext.fly('kpPassword_display').remove();
        if (ww.v.elBottom) ww.v.elBottom.remove();
        dom.innerHTML = msg;
        //ww.v.lnUptOccp = ww.f.getLink_UpdateOccp();
        ww.v.lnUptOccp.manipulate();
      },
      manipulate_others: function () {
        var oForm = ww.v.window.items.get(0).getForm();
        var txtFirst = oForm.findField("FRFirstName");
        var txtLast = oForm.findField("FRLastName");
        if (txtFirst) txtFirst.el.dom.setAttribute('maxlength', txtFirst.maxLength);
        if (txtLast) txtLast.el.dom.setAttribute('maxlength', txtLast.maxLength);

        var tabs = Ext.getCmp('kpl_questTab');
        tabs.items.each(function (tab) {
          tab.items.each(function (q) {
            if (q.id.indexOf('grp_Q')>-1) {
              q.items.each(function (cb) {
                if (cb.boxLabel=='hideME') cb.hide();
                if (cb.boxLabel.indexOf('Others (') > -1) {
                  var pos = cb.el.getXY();
                  var sName=cb.name;
                  var elOtherCmp = Ext.get('x-form-el-' + sName + '_Other').up('div');
                  var newPos = [
                    pos[0]+148, (pos[1]+cb.el.getComputedHeight()) - 56
                  ];
                  if (q.id.indexOf('grp_Q1')>-1) {   //for question 1 -> others -> when on even column
                    newPos = [300,-10];
                    elOtherCmp.setXY(newPos);
                    elOtherCmp.applyStyles({position:'relative', left:'300px', top:'-10px'});
                  } else {
                    elOtherCmp.setXY(newPos);
                  }
                  
                  cb.on('check', function (E, b) {
                    var sName=this.name;
                    var elTxt = Ext.getCmp(sName + '_Other');
                    if (b) {
                      elTxt.enable();
                      elTxt.show();
                    } else {
                      elTxt.disable();
                      elTxt.hide();
                    }
                  });
                }
              });
            }
          });
        });
      },
      show_question: function () {
        ww.v.window.show();
        if (!ww.v.formShowB4) {
          ww.f.manipulate_others();
          ww.v.formShowB4 = true;
        }
      },
      /*getLink_UpdateOccp: function () {
        return (Ext.apply(Ext.get('kpl_UpdateOcc'), {
          fnHandler_onClick: function(E) {
            var msg = [
              '<table><tbody>',
              '<tr><td style="font-size: 12px">An email will be sent to "' + ww.v.validEmail + '" with an activate link to update your particulars.</td></tr>',
              '<tr><td style="font-size: 12px">Click "Yes" to proceed, "No" to exit</td></tr>',
              '</tbody></table>'
            ]
            ww.msgbox.show('Request for update of personal particulars',
              msg.join(''),
              Ext.Msg.INFO, Ext.Msg.YESNO, {
              fn: function (b) {
                if (b=='yes') ww.f.ajax_requestForUpdate();
              }
            });
          },
          manipulate: function () {
            ww.f.removeHandler_passArea();
            this.on('click', this.fnHandler_onClick);
          }
        }));
      },*/
      removeHandler_passArea: function () {
        if (ww.v.lnFormPop) ww.v.lnFormPop.un('click', ww.v.lnFormPop.fnHandler_onClick);
      }
    }
  });

  function getQueryParam(sname) {
    var url = window.location.toString();
    url.match(/\?(.+)$/);
    var params = RegExp.$1;
    var params = params.split("&");
    var queryStringList = {};
    for(var i=0;i<params.length;i++){
      var tmp = params[i].split("=");
      if (tmp[0] == sname) {return unescape(tmp[1])};
    }
    return "";
  }

  ww.main.call(this);
  if (getQueryParam('dpPopup')=='yes') ww.f.show_question();
});