﻿Ext.onReady(function(){
    var countries = [ ['US','USA'],['GB','United Kingdom'],['CA','Canada'],['AU','Australia'],['NZ','New Zealand'],['DE','Germany'],['NL','Netherlands'],['CH','Switzerland'],['SE','Sweden'],['','-----------------------'],
                      ['AF','Afghanistan'],['AX','Åland Islands'],['AL','Albania'],['DZ','Algeria'],['AS','American Samoa'],['AD','Andorra'],['AO','Angola'],['AI','Anguilla'],['AQ','Antarctica'],['AG','Antigua and Barbuda'],
                      ['AR','Argentina'],['AM','Armenia'],['AW','Aruba'],['AT','Austria'],['AZ','Azerbaijan'],['BS','Bahamas'],['BH','Bahrain'],['BD','Bangladesh'],['BB','Barbados'],['BE','Belgium'],['BZ','Belize'],['BJ','Benin'],
                      ['BM','Bermuda'],['BT','Bhutan'],['BO','Bolivia'],['BA','Bosnia and Herzegovina'],['BW','Botswana'],['BV','Bouvet Island'],['BR','Brazil'],['IO','British Indian Ocean Territory'],['BN','Brunei Darussalam'],
                      ['BG','Bulgaria'],['BF','Burkina Faso'],['BI','Burundi'],['KH','Cambodia'],['CM','Cameroon'],['CV','Cape Verde'],['KY','Cayman Islands'],['CF','Central African Republic'],['TD','Chad'],['CL','Chile'],
                      ['CN','China'],['CX','Christmas Island'],['CC','Cocos (Keeling) Islands'],['CO','Colombia'],['KM','Comoros'],['CK','Cook Islands'],['CR','Costa Rica'],['HR','Croatia'],['CY','Cyprus'],['CZ','Czech Republic'],
                      ['DK','Denmark'],['DJ','Djibouti'],['DM','Dominica'],['DO','Dominican Republic'],['EC','Ecuador'],['EG','Egypt'],['SV','El Salvador'],['GQ','Equatorial Guinea'],['ER','Eritrea'],['EE','Estonia'],['ET','Ethiopia'],
                      ['FK','Falkland Islands (Malvinas)'],['FO','Faroe Islands'],['FJ','Fiji'],['FI','Finland'],['FR','France'],['GF','French Guiana'],['PF','French Polynesia'],['TF','French Southern Territories'],
                      ['GA','Gabon'],['GM','Gambia'],['GE','Georgia'],['GH','Ghana'],['GI','Gibraltar'],['GR','Greece'],['GL','Greenland'],['GD','Grenada'],['GP','Guadeloupe'],['GU','Guam'],['GT','Guatemala'],
                      ['GG','Guernsey'],['GN','Guinea'],['GW','Guinea-Bissau'],['GY','Guyana'],['HT','Haiti'],['HM','Heard and McDonald Islands'],['HN','Honduras'],['HK','Hong Kong'],['HU','Hungary'],['IS','Iceland'],['IN','India'],
                      ['ID','Indonesia'],['IE','Ireland'],['IM','Isle of Man'],['IL','Israel'],['IT','Italy'],['JM','Jamaica'],['JP','Japan'],['JE','Jersey'],['JO','Jordan'],['KZ','Kazakhstan'],['KE','Kenya'],['KI','Kiribati'],
                      ['KR','Korea, South'],['KW','Kuwait'],['KG','Kyrgyzstan'],['LA','Laos'],['LV','Latvia'],['LB','Lebanon'],['LS','Lesotho'],['LI','Liechtenstein'],['LT','Lithuania'],['LU','Luxembourg'],['MO','Macao'],
                      ['MK','Macedonia, Former Yugoslav Republic of'],['MG','Madagascar'],['MW','Malawi'],['MY','Malaysia'],['MV','Maldives'],['ML','Mali'],['MT','Malta'],['MH','Marshall Islands'],['MQ','Martinique'],
                      ['MR','Mauritania'],['MU','Mauritius'],['YT','Mayotte'],['MX','Mexico'],['FM','Micronesia, Federated States of'],['MD','Moldova'],['MC','Monaco'],['MN','Mongolia'],['ME','Montenegro'],
                      ['MS','Montserrat'],['MA','Morocco'],['MZ','Mozambique'],['MM','Myanmar'],['NA','Namibia'],['NR','Nauru'],['NP','Nepal'],['AN','Netherlands Antilles'],['NC','New Caledonia'],['NI','Nicaragua'],
                      ['NE','Niger'],['NG','Nigeria'],['NU','Niue'],['NF','Norfolk Island'],['MP','Northern Mariana Islands'],['NO','Norway'],['OM','Oman'],['PK','Pakistan'],['PW','Palau'],['PS','Palestinian Territory'],
                      ['PA','Panama'],['PG','Papua New Guinea'],['PY','Paraguay'],['PE','Peru'],['PH','Philippines'],['PN','Pitcairn Island'],['PL','Poland'],['PT','Portugal'],['PR','Puerto Rico'],['QA','Qatar'],['RE','Réunion'],['RO','Romania'],['RU','Russia'],
                      ['RW','Rwanda'],['GS','S. Georgia and S. Sandwich Isls.'],['KN','Saint Kitts & Nevis'],['LC','Saint Lucia'],['VC','Saint Vincent and The Grenadines'],['WS','Samoa'],['SM','San Marino'],['ST','Sao Tome and Principe'],['SA','Saudi Arabia'],
                      ['SN','Senegal'],['RS','Serbia'],['SC','Seychelles'],['SL','Sierra Leone'],['SG','Singapore'],['SK','Slovakia'],['SI','Slovenia'],['SB','Solomon Islands'],['SO','Somalia'],['ZA','South Africa'],['ES','Spain'],['LK','Sri Lanka'],['SH','St. Helena'],
                      ['PM','St. Pierre and Miquelon'],['SR','Suriname'],['SJ','Svalbard and Jan Mayen Islands'],['SZ','Swaziland'],['TW','Taiwan'],['TJ','Tajikistan'],['TZ','Tanzania'],['TH','Thailand'],['TL','Timor-Leste'],['TG','Togo'],['TK','Tokelau'],['TO','Tonga'],
                      ['TT','Trinidad and Tobago'],['TN','Tunisia'],['TR','Turkey'],['TM','Turkmenistan'],['TC','Turks and Caicos Islands'],['TV','Tuvalu'],['UM','U.S. Minor Outlying Islands'],['UG','Uganda'],['UA','Ukraine'],['AE','United Arab Emirates'],['UY','Uruguay'],
                      ['UZ','Uzbekistan'],['VU','Vanuatu'],['VA','Vatican City'],['VE','Venezuela'],['VN','Vietnam'],['VG','Virgin Islands, British'],['VI','Virgin Islands, U.S.'],['WF','Wallis and Futuna Islands'],['EH','Western Sahara'],['YE','Yemen'],['ZM','Zambia'] ];
    var states = [ ['AL', 'Alabama'],['AK', 'Alaska'],['AZ', 'Arizona'],['AR', 'Arkansas'],['CA', 'California'],['CO', 'Colorado'],['CT', 'Connecticut'],['DE', 'Delaware'],['DC', 'District of Columbia'],['FL', 'Florida'],['GA', 'Georgia'],['HI', 'Hawaii'],['ID', 'Idaho'],
                   ['IL', 'Illinois'],['IN', 'Indiana'],['IA', 'Iowa'],['KS', 'Kansas'],['KY', 'Kentucky'],['LA', 'Louisiana'],['ME', 'Maine'],['MD', 'Maryland'],['MA', 'Massachusetts'],['MI', 'Michigan'],['MN', 'Minnesota'],['MS', 'Mississippi'],['MO', 'Missouri'],
                   ['MT', 'Montana'],['NE', 'Nebraska'],['NV', 'Nevada'],['NH', 'New Hampshire'],['NJ', 'New Jersey'],['NM', 'New Mexico'],['NY', 'New York'],['NC', 'North Carolina'],['ND', 'North Dakota'],['OH', 'Ohio'],['OK', 'Oklahoma'],['OR', 'Oregon'],
                   ['PA', 'Pennsylvania'],['RI', 'Rhode Island'],['SC', 'South Carolina'],['SD', 'South Dakota'],['TN', 'Tennessee'],['TX', 'Texas'],['UT', 'Utah'],['VT', 'Vermont'],['VA', 'Virginia'],['WA', 'Washington'],['WV', 'West Virginia'],['WI', 'Wisconsin'],['WY', 'Wyoming'] ];
    var keysizes = [ ['1024', '1024'], ['2048', '2048 (more secure)'] ];

    var infoText = null;
    
    var helpText = new Ext.form.TextArea({
        name: 'help',
        width: 280,
        height: 200,
        hidden: true,
        readOnly: true,
        disabledClass: "help-disabled",
        focusClass: 'x-form-item',
        cls: 'help-enabled',
        value: '&nbsp;'
    });

    var form = new Ext.form.Form({
        id: 'easy-form',
        labelAlign: 'left',
        labelWidth: 55,

        reader : new Ext.data.XmlReader({
            record : 'domain',
            success: '@success' }, 
            [ 'o','ou','l','st','c' ] ),
        
        action: 'openssl.htm'
    });
        
    var countryStore = new Ext.data.SimpleStore({
        fields: ['countryCode', 'countryName'],
        data : countries,
        id: 0
    });

    var cValue = Ext.get('easycsr_c').dom.value;
    var ip_country = Ext.get('ip_country').dom.value;
    if( cValue == '' ) {
        cValue = ip_country;
        if( cValue == '' ) {
            cValue = 'US';
        }
    }

    var stateStore = new Ext.data.SimpleStore({
        fields: ['abbr', 'state'],
        data : states,
        id: 0
    });

    var stValue = Ext.get('easycsr_st').dom.value;
    if( stValue == '' ) {
        var ip_state = Ext.get('ip_state').dom.value;
        var state_record = stateStore.getById(ip_state);
        if( state_record != undefined ) {
            stValue = state_record.get('state');
        }
    }

    var cnUsedToBe = '';
    
    var cnField = new Ext.form.TextField({
        fieldLabel: 'Common Name',
        name: 'cn',
        value: Ext.get('easycsr_cn').dom.value,
        
        onFocus: function() {
            cnUsedToBe = cnField.getValue();
            last_field = 'cn';
            helpText.hide();
            var d = infoText.dom.innerHTML = "<b>Common Name</b> (required)<br/><br/>Your Exchange server's fully qualified domain name.  If you are not sure what name to use, please refer to the notes below.<br/><br/>To secure mail.example.com, your common name or one of your subject alternative names must be <b>mail.example.com</b>.<br/><br/>Less commonly, you may also enter the IP address or short name of your internal server.  For example, appserver1 or 192.168.1.200.";
            //cnField.selectText();
        }
        
    });

    var sansField = new Ext.form.TextArea({
        fieldLabel: 'Subject Alternative Names',
        name: 'sans',
        value: Ext.get('easycsr_sans').dom.value
    });
    
    var oField = new Ext.form.TextField({
        fieldLabel: 'Organization',
        name: 'o',
        value: Ext.get('easycsr_o').dom.value,
        selectOnFocus: true
    });

    oField.on('focus', function() {
        if( last_field == 'o' ){
            oField.selectText();
        }
        helpText.hide();
        infoText.dom.innerHTML = '<b>Organization name</b><br/><br/>The exact legal name of your organization.  Example: "DigiCert, Inc."<br/><br/>Less commonly, if you do not have a legal registered organization name, you must enter your own full name here.';
        last_field = 'o';
    });

    var ouField = new Ext.form.TextField({
        fieldLabel: 'Department',
        name: 'ou',
        value: Ext.get('easycsr_ou').dom.value,
        onFocus: function() {
            last_field = 'ou';
            helpText.hide();
            infoText.dom.innerHTML = '<b>Department</b> (optional) <br/><br/>Many people leave this field blank.  This is the department within your organization which you want to appear in the certificate.  It will be listed in the certificate\'s subject as Organizational Unit, or "ou."<br/><br/>Common examples:<br/><br/><ul><li>Web Administration</li><li>Web Security</li><li>Marketing</li><li>Engineering</li><li>Information Technology</li>';
            //ouField.selectText();
        }
    });

    var lField = new Ext.form.TextField({
        fieldLabel: 'City',
        name: 'l',
        value: Ext.get('easycsr_l').dom.value,
        onFocus: function() {
            last_field = 'l';
            helpText.hide();
            infoText.dom.innerHTML = '<b>City</b><br/><br/>The city where your organization is legally located.';
            //lField.selectText();
        }
    });

    var stLabel = 'State';
    if( ip_country == 'CA' ) stLabel = 'Province';
    
    var stField = new Ext.form.TextField({
        fieldLabel: stLabel,
        name: 'st',
        value: stValue
    });

    var stateHelp = "<b>State or Province</b><br/><br/>The state or province where your organization is legally located.";
    var stateIsCombo = false;
    
    if( ip_country == 'US' ) {
        stateIsCombo = true;
        stField = new Ext.form.ComboBox({
            name: 'st',
            fieldLabel: 'State',
            store: stateStore,
            displayField:'state',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            selectOnFocus:true,
            forceSelection: false,
            value: stValue
        });
        stateHelp = "<b>State</b><br/><br/>Your IP appears to be in the USA, so we've provided a States dropdown list for your convenience.  But if you're creating a CSR for a location outside of the USA, you can enter anything into the list.  It will accept any state name you type.";
    }

    stField.on('focus', function() {
        last_field = 'st';
        helpText.hide();
        infoText.dom.innerHTML = stateHelp;
        //stField.selectText();
    });

    var cField = new Ext.form.ComboBox({
        hiddenName:'c',
        fieldLabel: 'Country',
        store: countryStore,
        displayField:'countryName',
        valueField: 'countryCode',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus:true,
        forceSelection:true,
        value: cValue
    });
    
    cField.on('focus',function() {
        last_field = 'c';
        helpText.hide();
        infoText.dom.innerHTML = '<b>Country</b><br/><br/>We guessed your country based on your IP address, but if we guessed wrong, please choose the correct country.  If your country does not appear in this list, there is a chance we cannot issue certificates to organizations in your country.';
        cField.selectText();
    });

    var reader = new Ext.data.XmlReader(
        { record : 'domain', success: "@success" }, 
        [ 'o','ou','l','st','c' ] 
    );

    var sherlock = new Ext.data.HttpProxy({
        timeout: 3000,
        url: 'lookup.php'
    });
   
    function sherlockReturns(o,args,succeeded) {
        if( succeeded === false ) 
            return;

        var record = o.records[0];
        
        if( record.get('o') == '' )
            return;

        oField.setValue(record.get('o'));
        ouField.setValue(record.get('ou'));
        lField.setValue(record.get('l'));
        stField.setValue(record.get('st'));
        cField.setValue(record.get('c'));

        oField.getEl().frame();
        ouField.getEl().pause(0.5);
        ouField.getEl().frame();
        lField.getEl().pause(1);
        lField.getEl().frame();
        stField.getEl().pause(1.5);
        stField.getEl().frame();
        cField.getEl().pause(2);
        cField.getEl().frame();
    }
      
    sansField.on('focus', function() {
        var field_was = last_field;
        last_field = 'san';
        helpText.hide();
        infoText.dom.innerHTML = '<b>Subject Alternative Names</b> (optional)<br/><br/>One per line, or comma separated, either way is fine.<br/><br/>Microsoft recommends including your Exchange server\'s NetBIOS name, its FQDN, and autodiscover.yourdomain.com.';

        var oValue = oField.getValue();
        var cnValue = cnField.getValue();

        if( field_was == 'cn' && 
            oValue == '' && 
            cnValue != '' && 
            cnValue != cnUsedToBe && 
            //cnValue.match(/([a-z0-9\-]+\.)+(com|org|net|edu|uk|de|se|au|nz|ca)$/i) ) 
            cnValue.match(/([a-z0-9\-]+\.)+([a-z]{2,4})$/i) ) 
        {
            sherlock.load({ cn: cnValue }, reader, sherlockReturns, this, {test:1}); 
        }

        /*
        if (field_was == 'cn') {
            //form.load({url:'https://www.digicert.com/easy-csr/lookup.php', params:{cn:cnValue}, waitMsg:'Checking'});
            sherlock.load({ cn: cnValue }, reader, sherlockReturns, this, {test:1}); 
        }
        */
    });
    
    var ksValue = Ext.get('easycsr_ks').dom.value;
    if( ksValue == '' ) {
        ksValue = '1024';
    }

    var ksField = new Ext.form.ComboBox({
        fieldLabel: 'Key Size',
        hiddenName:'ks',
        store: new Ext.data.SimpleStore({
            fields: ['keysize', 'desc' ],
            data : keysizes
        }),
        displayField:'desc',
        valueField: 'keysize',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus:true,
        value: ksValue
    });

    ksField.on('focus', function() {
        last_field = 'ks';
        helpText.hide();
        infoText.dom.innerHTML = '<b>Key Size</b><br/><br/>DigiCert recommends 1024 bits.<br/><br/>1024 and 2048 bit keys are most common.  Key sizes smaller than 1024 are considered insecure.';
        ksField.selectText();
    });

    form.column({width:375, labelWidth:110}); // open column, without auto close
    //var details = form.fieldset(
    form.fieldset(
        { id: 'details', 
          legend:'Certificate Details',
          style: 'height: 310px' },
          
        cnField, 
        sansField,
        oField,
        ouField,
        lField,
        stField,
        cField,
        ksField
    );

    /*
    var submit = form.addButton({
        text: 'Generate',
        disabled:false,
    });
    */

    form.end(); // closes the last container element (column, layout, fieldset, etc) and moves up 1 level in the stack

    form.column(
        {width:315, style:'margin-left:10px', clear:true}
    );

    form.fieldset(
        { id: 'information', 
          legend:'Information', 
          hideLabels: true,
          style: 'height: 310px' },
          
        helpText
    );
    form.end();
 
    form.applyIfToFields({
        width:235
    });

    // Replace the guts of the easy-form with the live version
    Ext.get('csr-form').dom.innerHTML = '';
    form.render('csr-form');

    var details = Ext.get('details');
    var c = details.createChild({
        tag:'div', 
        align: 'right',
        style:'margin-right: 5px' 
    });

    form.waitMsgTarget = details;
    
    var theButton = new Ext.Button(c, {
        text: 'Generate',
        onClick: function(){
            form.submit({url:'exchange2007.htm', method: 'POST'});
            //infoText.highlight('ff3333', { attr: 'color', duration: 3 });
            
            var cn = cnField.getValue();
            var fn = cn.replace(/\./g, '_');
            var fn = fn.replace(/^\*/, 'star');
            var ks = ksField.getValue();
            var c = cField.getValue();
            var st = stField.getValue();
            var l  = lField.getValue();
            var ou = ouField.getValue();
            var o = oField.getValue();

            // Take out commas
            o = o.replace(/,/, '');
            ou = ou.replace(/,/, '');
            st = st.replace(/,/, '');
            l = l.replace(/,/, '');
            
            infoText.dom.innerHTML = String.format('<p style="color:#2F2F4F">Now just copy and paste this command into Exchange Management Shell.  Your CSR will be written to c:\\{0}.csr.</p>', fn);

            var ou_cmd = String.format(", ou={0}", ou);
            if( ou == "" ) {
                ou_cmd = "";
            }

            var sansValue = sansField.getValue();
            sansValue = sansValue.replace(/[,;\n\r]/g, ' ');
            sansValue = sansValue.replace(/ +/g, ' ');
            sansValue = sansValue.replace(/ +$/g, ''); // thanks for the bug reports Scott and Dan!
            var sansArray = sansValue.split(" ");
            var sans = sansArray.join(", ");
            var sansOption = '';
            if (sans != '') {
                sansOption = String.format('-DomainName {0}', sans);
            }

            var command = String.format('New-ExchangeCertificate -GenerateRequest -Path c:\\{0}.csr -KeySize {1} -SubjectName "c={2}, s={3}, l={4}, o={5}{6}, cn={7}" {8} -PrivateKeyExportable $True', 
            fn, ks, c, st, l, o, ou_cmd, cn, sansOption);
            
            helpText.show();
            helpText.focus();
            helpText.setRawValue(command);
            helpText.selectText();
            helpText.getEl().frame();
        }
    });

    var information = Ext.get('information');
    infoText = information.createChild({tag:'div',style:"margin-bottom:5px;font-size: 12px;color: #222;"}, helpText.getEl() );

    cnField.focus();

    //Ext.get("csr_form").slideIn();

    setTimeout(function(){cnField.focus();}, 600);
});

