/* oFormValidator and preloadImages are taken from Nationwide.com/js/stdFunctions.js
** oAccountModule is from Nationwide.com/js/accountModule.js
*/
oFormValidator = {
	oErrorMessage:'<div class="bubbleText"><p>Oops!<p>You missed something.</p><p>Please try again.</p><a href="#" class="errorCloseBtn"></a></div>',
	bHasError:null,
	
	init:function() {
	    jQuery('div#myAccount').css({"height":"160px"});
		jQuery('form').submit(function() {
			jQuery('.errorSubmit').remove();
			var oForm = jQuery(this).addClass('submit');
			var oFormSubmit = jQuery('.formButton > input.goBtn', this);
			jQuery('.req', this).each(function() {
				if (typeof jQuery(this).attr('value') === 'undefined' && !oFormValidator.bHasError) {
					oFormValidator.bHasError = 1;
				}
			});
			
			var oRadioPairs = {};
			var oRadioElements = jQuery('div.radioPair > .req', this);
			jQuery(oRadioElements).each(function() { oRadioPairs[jQuery(this).attr('name')] = 0; });
			jQuery(oRadioElements).each(function() {
				if (typeof jQuery(this).attr('checked') !== 'undefined') { oRadioPairs[jQuery(this).attr('name')] = 1; }
			});
			
			for (var key in oRadioPairs) {
//				alert(key + ":" + oRadioPairs[key]);
				if (oRadioPairs[key] === 0 || typeof oRadioPairs[key] === 'undefined') { oFormValidator.bHasError = 1; }
			}

			if (oFormValidator.bHasError) {
				var oErrorDiv = jQuery('<div></div>').addClass('errorSubmit').append(oFormValidator.oErrorMessage).insertAfter(jQuery(oFormSubmit));
				var oFormButton = jQuery('.formButton > input.goBtn', oForm);
				var leftOffSet = oFormValidator.findLeft(oFormButton.attr('class'));
				var rightOffSet = oFormValidator.findRight(oFormButton.attr('class'));
				var topOffSet = oFormValidator.findTop(oFormButton.attr('class'));
				var bottomOffSet = oFormValidator.findBottom(oFormButton.attr('class'));
				var displayType = oFormValidator.findDisplay(oFormButton.attr('class'));
				if (jQuery.browser.msie) {
					leftOffSet = oFormValidator.findIELeft(oFormButton.attr('class')) !== 0 ? oFormValidator.findIELeft(oFormButton.attr('class')) : leftOffSet;
					rightOffSet = oFormValidator.findIERight(oFormButton.attr('class')) !== 0 ? oFormValidator.findIERight(oFormButton.attr('class')) : rightOffSet;
					topOffSet = oFormValidator.findIETop(oFormButton.attr('class')) !== 0 ? oFormValidator.findIETop(oFormButton.attr('class')) : topOffSet;					
					bottomOffSet = oFormValidator.findIEBottom(oFormButton.attr('class')) !== 0 ? oFormValidator.findIEBottom(oFormButton.attr('class')) : bottomOffSet;					
				}
				else if (jQuery.browser.safari) {
					leftOffSet = oFormValidator.findMacLeft(oFormButton.attr('class')) !== 0 ? oFormValidator.findMacLeft(oFormButton.attr('class')) : leftOffSet;
					rightOffSet = oFormValidator.findMacRight(oFormButton.attr('class')) !== 0 ? oFormValidator.findMacRight(oFormButton.attr('class')) : rightOffSet;
					topOffSet = oFormValidator.findMacTop(oFormButton.attr('class')) !== 0 ? oFormValidator.findMacTop(oFormButton.attr('class')) : topOffSet;					
					bottomOffSet = oFormValidator.findMacBottom(oFormButton.attr('class')) !== 0 ? oFormValidator.findMacBottom(oFormButton.attr('class')) : bottomOffSet;					
				}
				if (topOffSet) { jQuery(oErrorDiv).css( "top",eval(topOffSet) ); }
				if (leftOffSet) { jQuery(oErrorDiv).css( "left",eval(leftOffSet) ); }
				if (rightOffSet) { jQuery(oErrorDiv).css( "right",eval(rightOffSet) ); }
				if (bottomOffSet) { jQuery(oErrorDiv).css( "bottom",eval(bottomOffSet) ); }
				if (displayType === "Right") { jQuery(oErrorDiv).addClass('bubbleRight'); }
				else { jQuery(oErrorDiv).addClass('bubbleLeft'); }
				jQuery(oErrorDiv).show("normal");
				jQuery('a.errorCloseBtn').click(function() {
					jQuery(oErrorDiv).hide("normal");
					return false;
				});
				setTimeout(function(){jQuery('div.errorSubmit').hide("normal");},10000);
				jQuery(oForm).removeClass('submit');
				oFormValidator.bHasError = 0;
				return false;
			}
		});
	},
	
	findTop:function(sCN){ return (/top(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findBottom:function(sCN){ return (/bottom(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findRight:function(sCN){ return (/right(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findLeft:function(sCN){ return (/left(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findDisplay:function(sCN){ return (/display(\w+)/i.test(sCN))?RegExp.jQuery1:"Left";},
	findIETop:function(sCN){ return (/ieTop(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findIEBottom:function(sCN){ return (/ieBottom(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findIERight:function(sCN){ return (/ieRight(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findIELeft:function(sCN){ return (/ieLeft(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findMacTop:function(sCN){ return (/macTop(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findMacBottom:function(sCN){ return (/macBottom(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findMacRight:function(sCN){ return (/macRight(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;},
	findMacLeft:function(sCN){ return (/macLeft(-{0,1}\d+)/i.test(sCN))?RegExp.jQuery1:0;}

};

/*global oAccountModule jQuery*/
/**
 * Account Module Object. Transitional states for login account module.
 */
oAccountModule =  {
  /* @var boolean Used to store whether module is open */
  bModuleOpen: null,
  /* @var object Stores which HTML element is currently open */
  oOpenEl: null,
  /* @var object Key/Value pairs for specific types of module displays */
  oOptTypes: { stnd:'standard', mrtg:'mortgage',bnk:'banking',nf:'nf',agri:'agribusiness',db:'definedbenefit',mutfnds:'mutfnds' },
  /* @var object Key/Value pairs for specific Login URLs */
  oLoginURLs: {
    stnd:'https://www.nationwide.com/access/web/login-control.x',
    bnk:'https://bankonline.nationwidebank.com/bankonline/login.do',
    nf:'https://isc.nwservicecenter.com/iApp/isc/cmd/Login',
    mrtg:'https://nationwideadvantagemortgage.com/cgi-bin/Weblink.plx',
    agri:'https://agportal.nationwideagribusiness.com/ag/insurance/!ut/p/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLN4j3DALJgFiO-pFQgXD9KLhkFEwySN9b39cjPzdVP0C_IDfCIMvEUREAkUJ5Fw!!/delta/base64xml/L0lDU0NUTzdvSko3dWFDU1lKQ2dwUkEhIS9vSG9RQUFJUUpBQU1ZeGpHTVVwakdLWXd4bUljRklVdUNBISEvNEpGaUNPc1RsRTZDdUEySnlpZEJYZnJDRlpzT2ZybUUvN19BXzM0OS8yL3dwcy5wb3J0bGV0cy5sb2dpbg!!',
    db:'https://nwprov.nwservicecenter.com/webapp/tdw/login.do',
    mutfnds:'https://www.websolcentral.com/WebSol2/index.cfm?CFID=1832035&CFTOKEN=26191260'
},
  /* @var object Key/Value pairs for specific SignUp URLs */
  oSignUpURLs: {
    base:'http://www.nationwide.com/account-access/sign-up.jsp',
    stnd:'https://www.nationwide.com/access/register/signon-standard.htm',
    bnk:'/online-bank-services.jsp',
    nf:'https://isc.nwservicecenter.com/iApp/isc/cmd/EstParticipant',
    mrtg:'https://www.nationwideadvantagemortgage.com/cgi-bin/weblink_form.plx',
    agri:'http://www.nationwideagribusiness.com/portal/portalLogin.htm',
    mutfnds:'https://www.websolcentral.com/WebSol2/index.cfm?CFID=1832035&CFTOKEN=26191260',
    db:'https://nwprov.nwservicecenter.com/webapp/tdw/'
},

  /**
   * Method
   * @param object to bind
   */
  init : function(oEl) {
    jQuery('div.accountModWrapper').css({"display":"block"});
    oEl.bind('change', function(){oAccountModule.decide(this);});
    // Next two lines added for close button.
    oAccountModule.closeButton = jQuery('#loginClose');
    oAccountModule.closeButton.bind('click', function() { 
		jQuery("select.fsOptions option:first-child").attr('selected','true');
 		jQuery('div#myAccount').css({"height":"160px"});
		oAccountModule.optReset(); return false;
	});
  },

  /**
   * Method
   * Sets display appropriate modules based on LI clicked.
   * If the value is unrecognized, assume it is a URL and attempt to go to it.
   * @param object LI element of that clicked
   */
  decide:function(oEl) {
    // Next two lines added for close button.
    jQuery("#myAccount input.req").val('');
    oAccountModule.closeButton.fadeIn('normal');
    this.optResetForm();
    switch(oEl.value) {
      case '1':
        jQuery('div#myAccount').css({"height":"380px"});
        this.optToggle(this.oOptTypes.nf, this.oLoginURLs.nf);
        this.optChangeSignUp(this.oSignUpURLs.nf);
        break;
      case '2':
        jQuery('div#myAccount').css({"height":"258px"});
        this.optToggle(this.oOptTypes.bnk, this.oLoginURLs.bnk);
        this.optChangeSignUp(this.oSignUpURLs.bnk);
        break;
      case '3':
        jQuery('div#myAccount').css({"height":"380px"});
        this.optToggle(this.oOptTypes.stnd, this.oLoginURLs.stnd);
        this.optChangeSignUp(this.oSignUpURLs.stnd);
        break;
      case '4':
        jQuery('div#myAccount').css({"height":"385px"});
        this.optToggle(this.oOptTypes.mrtg, this.oLoginURLs.mrtg);
        this.optChangeSignUp(this.oSignUpURLs.mrtg);
        break;
      case '5':
        jQuery('div#myAccount').css({"height":"270px"});
        this.optToggle(this.oOptTypes.mutfnds, this.oLoginURLs.mutfnds);
        this.optChangeSignUp(this.oSignUpURLs.mutfnds);
        break;
      case '10':
        jQuery('div#myAccount').css({"height":"380px"});
        this.optToggle(this.oOptTypes.agri, this.oLoginURLs.agri);
        this.optChangeSignUp(this.oSignUpURLs.agri);
        break;
      case '11':
        jQuery('div#myAccount').css({"height":"380px"});
        this.optToggle(this.oOptTypes.db, this.oLoginURLs.db);
        this.optChangeSignUp(this.oSignUpURLs.db);
        break;
      case '-1':
        /*
         * For the disabled divider, in case it is selected in IE
         * (where 'disabled' doesn't work on OPTIONs).
         * Fall through, to treat the same as 0 ('Select');
         * If gave the divider option value='0',
         * Firefox 2 sometimes defaulted to it on load.
         * TODO: Since IE doesn't support the disabled attribute on OPTIONs,
         * we may want to consider something like the JavaScript workaround at
         * http://elmicoxcodes.blogspot.com/2007/05/activating-option-disabled-in-ie.html
         */
      case '0':
        this.optReset();
        jQuery('div#myAccount').css({"height":"160px"});
        //jQuery('div.accountModWrapper').css({"display":"block"});
       break;
      default:
        // Assume the value is a URL to go directly to.
        window.location.href = oEl.value;
        break;
    }
  },

  /**
   * Method
   * Closes open options and resets appropriate params.
   */
  optReset:function() {
    // If there is no boolean found, return, logic not needed.
    this.optChangeSignUp(this.oSignUpURLs.base);
    if (!this.oOpenEl) { return; }
    this.oOpenEl.slideUp("fast");
    this.oOpenEl = null;
    this.bModuleOpen = null;
        oAccountModule.closeButton.fadeOut('normal');
        jQuery('div.accountModWrapper > div.uiWrap > div.formElms').slideUp("fast",function(){
			jQuery('div.accountModWrapper > div.uiWrap').removeClass('setUI');
            jQuery("select.fsOptions option:first-child").attr('selected','true');
		});
    jQuery('form.myAccountForm').attr('action','');
    jQuery('div#myAccount').css({"height":"160px"});
  },

  /**
   * Method
   * Clears all form fields when user switches to a different login type.
   */
  optResetForm:function() {
    for (var i in this.oOptTypes) {
      jQuery('div.accountModWrapper > div.uiWrap > div.formElms > div.' + this.oOptTypes[i] + 'Expand > input.text').attr('value','');
    }
  },

  /**
   * Method
   */
  optChangeSignUp:function(signUpType) {
    jQuery("li.signUp > a").attr("href",signUpType);
  },

  /**
   * Method
   * @param string Type of module to display
   * @param string URL of Form action
   */
  optToggle:function(sType,acctType) {
    jQuery('div.' + sType + 'Expand > form.myAccountForm').attr('action',acctType);
    if (this.bModuleOpen && jQuery('div.'+sType+'Expand').attr('class') === this.oOpenEl.attr('class')) {
      return;
    } else if(this.bModuleOpen) {
      this.oOpenEl.slideUp("fast");
    } else {
      jQuery('div.accountModWrapper > div.uiWrap > div.formElms').css({"display":"block"});
      jQuery('div.accountModWrapper > div.uiWrap > div.formElms > div.formButton').css({"display":"block"});
    }
    jQuery('div.accountModWrapper > div.uiWrap').addClass('setUI');
    jQuery('div.'+sType+'Expand').slideDown("fast");
    // Which module is open
    this.oOpenEl = jQuery('div.'+sType+'Expand');
    // Set boolean for open module
    this.bModuleOpen = 1;
  }
};

jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++) { jQuery("<img>").attr("src", arguments[i]); }
};

jQuery(document).ready(function() {
	oFormValidator.init();
	oAccountModule.init(jQuery('select.fsOptions'));
});