Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str);
};

Ext.apply(Ext.form.VTypes, {
    password: function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },
    passwordText : 'Passwords do not match'
});


Ext.apply(Ext.form.VTypes, {
    numeric: function(val, field) {
        var objRegExp = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
        return objRegExp.test(val);
    },
    numericText: 'Only numbers are allowed'
});

var reqFieldSep = "<span style='color:red;'>*</span>";

var errorMsgFieldReq = "This field is required";

var comboNotSelected = "- None Specified -";

// Contact Info
var stateStore = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data: [
        ["",  comboNotSelected],
        ["AL", "Alabama"],
        ["AK", "Alaska"],
        ["AS", "American Samoa"],
        ["AZ", "Arizona"],
        ["AR", "Arkansas"],
        ["CA", "California"],
        ["CO", "Colorado"],
        ["CT", "Connecticut"],
        ["DE", "Delaware"],
        ["DC", "District of Columbia"],
        ["FM", "Federated Micronesia"],
        ["FL", "Florida"],
        ["GA", "Georgia"],
        ["GU", "Guam"],
        ["HI", "Hawaii"],
        ["ID", "Idaho"],
        ["IL", "Illinois"],
        ["IN", "Indiana"],
        ["IA", "Iowa"],
        ["KS", "Kansas"],
        ["KY", "Kentucky"],
        ["LA", "Louisiana"],
        ["ME", "Maine"],
        ["MH", "Marshall Islands"],
        ["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"],
        ["MP", "Mariana Islands"],
        ["OH", "Ohio"],
        ["OK", "Oklahoma"],
        ["OR", "Oregon"],
        ["PW", "Palau"],
        ["PA", "Pennsylvania"],
        ["PR", "Puerto Rico"],
        ["RI", "Rhode Island"],
        ["SC", "South Carolina"],
        ["SD", "South Dakota"],
        ["TN", "Tennessee"],
        ["TX", "Texas"],
        ["UT", "Utah"],
        ["VT", "Vermont"],
        ["VI", "Virgin Islands"],
        ["VA", "Virginia"],
        ["WA", "Washington"],
        ["WV", "West Virginia"],
        ["WI", "Wisconsin"],
        ["WY", "Wyoming"]
    ]
});

var countryStore = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data: [
        ["2378", comboNotSelected],
        ["2185", "Afghanistan"],
        ["2186", "Albania"],
        ["2187", "Algeria"],
        ["2188", "Andorra"],
        ["2189", "Angola"],
        ["2190", "Antarctica"],
        ["2191", "Antigua and Barbuda"],
        ["2192", "Argentina"],
        ["2193", "Armenia"],
        ["2373", "Aruba"],
        ["2194", "Australia"],
        ["2195", "Austria"],
        ["2196", "Azerbaijan"],
        ["2197", "Bahamas"],
        ["2198", "Bahrain"],
        ["2199", "Bangladesh"],
        ["2200", "Barbados"],
        ["2201", "Belarus"],
        ["2202", "Belgium"],
        ["2203", "Belize"],
        ["2204", "Benin"],
        ["2372", "Bermuda"],
        ["2205", "Bhutan"],
        ["2206", "Bolivia"],
        ["2207", "Bosnia Hercegovina"],
        ["2208", "Botswana"],
        ["2209", "Brazil"],
        ["2210", "Brunei Darussalam"],
        ["2211", "Bulgaria"],
        ["2212", "Burkina Faso"],
        ["2213", "Burundi"],
        ["2214", "Cambodia"],
        ["2215", "Cameroon"],
        ["2216", "Canada"],
        ["2217", "Cape Verde"],
        ["2379", "Cayman Islands"],
        ["2218", "Central African Republic"],
        ["2219", "Chad"],
        ["2220", "Chile"],
        ["2221", "China"],
        ["2222", "Colombia"],
        ["2223", "Comoros"],
        ["2226", "Costa Rica"],
        ["2227", "Cote d'Ivoire"],
        ["2228", "Croatia"],
        ["2229", "Cuba"],
        ["2230", "Cyprus"],
        ["2231", "Czech Republic"],
        ["2232", "Denmark"],
        ["2233", "Djibouti"],
        ["2234", "Dominica"],
        ["2235", "Dominican Republic"],
        ["2236", "Ecuador"],
        ["2237", "Egypt"],
        ["2238", "El Salvador"],
        ["2239", "Equatorial Guinea"],
        ["2240", "Eritrea"],
        ["2241", "Estonia"],
        ["2242", "Ethiopia"],
        ["2243", "Fiji"],
        ["2244", "Finland"],
        ["2245", "France"],
        ["2246", "Gabon"],
        ["2248", "Georgia"],
        ["2249", "Germany"],
        ["2250", "Ghana"],
        ["2251", "Greece"],
        ["2252", "Greenland"],
        ["2253", "Grenada"],
        ["2376", "Guam"],
        ["2371", "Guatemala"],
        ["2255", "Guinea"],
        ["2256", "Guinea-Bissau"],
        ["2257", "Guyana"],
        ["2258", "Haiti"],
        ["2259", "Honduras"],
        ["2377", "Hong Kong SAR"],
        ["2260", "Hungary"],
        ["2261", "Iceland"],
        ["2262", "India"],
        ["2263", "Indonesia"],
        ["2264", "Iran"],
        ["2265", "Iraq"],
        ["2266", "Ireland"],
        ["2267", "Israel"],
        ["2268", "Italy"],
        ["2269", "Jamaica"],
        ["2270", "Japan"],
        ["2271", "Jordan"],
        ["2272", "Kazakhstan"],
        ["2273", "Kenya"],
        ["2274", "Korea; Democratic People's Republic Of (North)"],
        ["2275", "Korea; Republic Of (South)"],
        ["2276", "Kuwait"],
        ["2277", "Kyrgyzstan"],
        ["2278", "Lao People's Democratic Republic"],
        ["2279", "Latvia"],
        ["2280", "Lebanon"],
        ["2281", "Lesotho"],
        ["2282", "Liberia"],
        ["2284", "Liechtenstein"],
        ["2285", "Lithuania"],
        ["2286", "Luxembourg"],
        ["2287", "Macau"],
        ["2288", "Macedonia"],
        ["2289", "Madagascar"],
        ["2290", "Malawi"],
        ["2291", "Malaysia"],
        ["2292", "Mali"],
        ["2293", "Malta"],
        ["2294", "Mauritania"],
        ["2295", "Mauritius"],
        ["2296", "Mexico"],
        ["2297", "Micronesia; Federated States of"],
        ["2299", "Monaco"],
        ["2300", "Mongolia"],
        ["2301", "Morocco"],
        ["2302", "Mozambique"],
        ["2303", "Myanmar"],
        ["2304", "Namibia"],
        ["2305", "Nepal"],
        ["2306", "Netherlands"],
        ["2307", "New Zealand"],
        ["2308", "Nicaragua"],
        ["2309", "Niger"],
        ["2310", "Nigeria"],
        ["2311", "Norway"],
        ["2312", "Oman"],
        ["2313", "Pakistan"],
        ["2314", "Palau"],
        ["2315", "Panama"],
        ["2316", "Papua New Guinea"],
        ["2317", "Paraguay"],
        ["2318", "Peru"],
        ["2319", "Philippines"],
        ["2320", "Poland"],
        ["2321", "Portugal"],
        ["2374", "Puerto Rico"],
        ["2322", "Qatar"],
        ["2323", "Romania"],
        ["2324", "Russian Federation"],
        ["2325", "Rwanda"],
        ["2326", "Saint Lucia"],
        ["2327", "San Marino"],
        ["2328", "Saudi Arabia"],
        ["2329", "Senegal"],
        ["2331", "Seychelles"],
        ["2332", "Sierra Leone"],
        ["2333", "Singapore"],
        ["2334", "Slovakia"],
        ["2335", "Slovenia"],
        ["2336", "Solomon Islands"],
        ["2337", "Somalia"],
        ["2338", "South Africa"],
        ["2339", "Spain"],
        ["2340", "Sri Lanka"],
        ["2341", "Sudan"],
        ["2342", "Suriname"],
        ["2343", "Swaziland"],
        ["2344", "Sweden"],
        ["2345", "Switzerland"],
        ["2375", "Taiwan"],
        ["2348", "Tajikistan"],
        ["2349", "Tanzania"],
        ["2350", "Thailand"],
        ["2351", "Togo"],
        ["2352", "Trinidad and Tobago"],
        ["2353", "Tunisia"],
        ["2354", "Turkey; Republic of"],
        ["2355", "Turkmenistan"],
        ["2356", "Uganda"],
        ["2357", "Ukraine"],
        ["2358", "United Arab Emirates"],
        ["2359", "United Kingdom"],
        ["1", "United States"],
        ["2360", "Uruguay"],
        ["2361", "Uzbekistan"],
        ["2362", "Vatican City"],
        ["2363", "Venezuela"],
        ["2364", "Vietnam"],
        ["2367", "Yugoslavia"],
        ["2368", "Zaire"],
        ["2369", "Zambia"],
        ["2370", "Zimbabwe"]
    ]
});

var whereDidYouHearStore = [
    'Referral',
    'LinkedIn',
    'ExecuNet',
    'TopConsultant',
    'ISM',
    'WebSearch',
    'Craigslist',
    'Other'
];

var preferredContactStore = new Ext.data.SimpleStore({
    fields: ['value'],
    data : [
        ["Home Phone"],
        ["Work Phone"],
        ["Mobile Phone"],
        ["Other Phone"],
        ["Email"],
        ["Alternate Email"]
    ]
});

var unavailableReasonStore = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data : [
        ["0", "- Select One -"],
        ["1", "On Assignment"],
        ["2", "Employed Full-Time"],
        ["3", "Taking Time Off"],
        ["4", "Retired"],
        ["5", "Other "]
    ]
});


// Staffing
var jobPreferenceStore = [
    'Project Consulting',
    'Full-time',
    'Interim Management',
    'Staff Augmentation'
];

var travelPreferenceStore = [
    'Full-time or part-time travel ok',
    'Part-time travel ok',
    'Not able to travel'
];

var yearsExperienceStore = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data: [
        ["0",  comboNotSelected],
        ["1", "0 - 5 Years"],
        ["2", "6 - 10 Years"],
        ["3", "11 - 15 Years"],
        ["4", "16 - 20 Years"],
        ["5", "20+ Years"]
    ]
});

// Experience
var industryExperienceStore = new Ext.data.SimpleStore({
    fields: ['value'],
    data: [
        ["Accounting/Tax"],
        ["Aerospace and Defense"],
        ["Agriculture/Agribusiness"],
        ["Airlines/Travel"],
        ["Automotive"],
        ["Banking"],
        ["Biotech/Life Science/Pharma"],
        ["Business Services"],
        ["Chemicals"],
        ["Construction"],
        ["Consulting"],
        ["Consumer Products"],
        ["Consumer Services"],
        ["Education"],
        ["Energy and Utilities"],
        ["Engineering"],
        ["Food/Beverage"],
        ["Government/Non-Profit"],
        ["Healthcare"],
        ["High Tech"],
        ["Industrial Manufacturing"],
        ["Insurance"],
        ["Marketing/PR/Advertising"],
        ["Media and Entertainment"],
        ["Medical Devices"],
        ["Mining"],
        ["Other Financial Services"],
        ["Paper"],
        ["Real Estate"],
        ["Restaurant/Hotels"],
        ["Retail"],
        ["Software/Internet"],
        ["Telecommunications"],
        ["Transportation/Logistics/Distribution"],
        ["Other"]
    ]
});

var experienceStore = [
    'None',
    'Little',
    'Some',
    'Considerable',
    'Expert'
];

var consultingExperienceStore = [
    'Major consulting firm experience',
    'Boutique consulting firm experience',
    'Independent consulting experience',
    'Internal corporate consulting experience',
    'No consulting experience'
];

function getFormSpacer(bodyStyle) {
    return {
        xtype: 'panel',
        border: false,
        html: '&nbsp;',
        bodyStyle: bodyStyle
    };
}

function getCheckBoxGroup(label, columns, fieldName, store, value) {
    var items = [];
    for (var i = 0; i < store.length; i++)
        items[i] = {boxLabel: store[i], id: fieldName + "_" + i, name: fieldName + "_" + i, inputValue: store[i], checked: getCheckBoxValue(store[i], value)};

    return {
        xtype: 'checkboxgroup',
        fieldLabel: label,
        labelSeparator: reqFieldSep,
        items: items,
        width: 360,
        columns: columns
    };
}

function getCheckBoxGroupValue(fieldNamePattern) {
    var result = "";
    for (var i = 0; i < 100; i++) {
        var field = Ext.get(fieldNamePattern + "_" + i);
        if (!field)
            break;
        if (field.dom.checked)
            result = result + field.getValue() + ",";
    }
    return result.length == 0 ? undefined : result.substring(0, result.length - 1);
}

function getRadioGroup(label, fieldName, store, value, onChangeHandler) {
    var items = [];
    var selected = false;

    var chkBox = function(index, label, fieldName, value, checked) {
        return new Ext.form.Radio({index: index, boxLabel: label, name: fieldName, inputValue: value, checked: checked, handler: onChangeHandler});
    };

    if (store instanceof Array)
        for (var i = 0; i < store.length; i++) {
            items[i] = chkBox(i, store[i], fieldName, store[i], store[i] == value);
            selected |= items[i].checked;
        }
    else {
        i = 0;
        store.each(function(entry) {
            var item = chkBox(i++, entry.data.text, fieldName, entry.data.value, entry.data.value == value);
            items.push(item);
            selected |= item.checked;
        });
    }

    if (!selected)
        items[0].checked = true;
    return {
        xtype: 'radiogroup',
        fieldLabel: label,
        labelSeparator: reqFieldSep,
        allowBlank: false,
        items: items,
        columns: 1
    };
}

function getExperienceBlock(label, fieldName, value, ids) {
    ids = ids || [];
    var block = {
        xtype: 'radiogroup',
        fieldLabel: label,
        width: 360,
        columns: [65, 65, 65, 105, 60],
        items: [
            {boxLabel: experienceStore[0], name: fieldName, inputValue: experienceStore[0], checked: experienceStore[0] == value},
            {boxLabel: experienceStore[1], name: fieldName, inputValue: experienceStore[1], checked: experienceStore[1] == value},
            {boxLabel: experienceStore[2], name: fieldName, inputValue: experienceStore[2], checked: experienceStore[2] == value},
            {boxLabel: experienceStore[3], id: ids[0], name: fieldName, inputValue: experienceStore[3], checked: experienceStore[3] == value},
            {boxLabel: experienceStore[4], id: ids[1], name: fieldName, inputValue: experienceStore[4], checked: experienceStore[4] == value}
        ]
    };
    for (var i = 0; i < block.items.length; i++)
        if (block.items[i].checked)
            return block;

    block.items[0].checked = true;
    return block;
}

function getCommBlock(title, name, categoryValues, titles, namePattern, values, widths) {
    widths = widths || [190,170,120];
    var items = [];
    for (var i = 0; i < titles.length; i++) {
        if (titles[i])
            items[i] = {boxLabel: titles[i], id: namePattern + "_" + i, name: namePattern + "_" + i, inputValue: titles[i], checked: (values && values.indexOf(titles[i]) >= 0)};
        else
            items[i] = getFormSpacer();
    }
    return {
        xtype:'fieldset',
        checkboxToggle: {tag: 'input', type: 'checkbox', name: name, value: title},
        title: title,
        autoHeight:true,
        collapsed: !(categoryValues && categoryValues.indexOf(title) >= 0),
        onCheckClick: function() {
            this[this.checkbox.dom.checked ? 'expand' : 'collapse']();
            if (!this.checkbox.dom.checked) {
                var checkBoxes = this.items.get(0).items;
                for (var i = 0; i < checkBoxes.length; i++)
                    checkBoxes.get(i).setValue(false);
            }
        },
        items: [{
            xtype: 'checkboxgroup',
            width: 480,
            labelSeparator: '',
            columns: widths,
            vertical: true,
            items: items
        }]
    };
}

// value = csv options
function getCheckBoxValue(value, values) {
    if (value == 'null')
        return false;
    values = values.split(",");
    for (var i = 0; i < values.length; i++)
        if (value.toUpperCase() == values[i].trim().toUpperCase())
            return true;
    return false;
}

function submitButton(wnd, params) {
    params = params || {};
    return [{
        text: params.caption || "Submit",
        handler:function() {
            var form = wnd.formPanel.getForm();
            if (form.isValid() && typeof params.onBeforeSubmit == "function" && !params.onBeforeSubmit())
                return;
            form.submit({
                url: window.location.pathname,
                method: 'POST',
                params: {regPageCompleted: window.regPageCompleted, enrolled: window.enrolled ? 1 : 0},
                waitMsg:'Working ...',
                success: params.onSuccess
            });
        }
    }];
}

function showDialog(title, fileName) {
    var win = new Ext.Window({
        layout: 'fit',
        width: 500,
        height: 400,
        title: title,
        plain: true,
        items: {
            xtype: 'panel',
            autoScroll: true,
            autoLoad: function() {
                return fileName;
            }
        },

        buttons: [{
            text: 'Close',
            handler: function() {
                win.close();
            }
        }]
    });
    win.show();
}

function showContainer(f) {
    f.setVisible(true);
    f.enable();
    // show entire container and children (including label if applicable)
    f.getEl().up('.x-form-item').setDisplayed(true);
}

function hideContainer(f) {
    f.disable(); // for validation
    f.setVisible(false);
    // hide container and children (including label if applicable)
    f.getEl().up('.x-form-item').setDisplayed(false);
}

