App = {};
App.__require_map = {};

App.require = function() {
    for(var i=0; i < arguments.length; i++) {
        App.add_one_require(App.resource_root + arguments[i]);
    }
}

App.add_one_require = function(src) {
    if (App.__require_map[src])
        return;
    
    App.__require_map[src] = true;
    try {
        extension = src.match(/.*?\.(js|css)/i)[1]; 
    } catch(e) {
        throw ("Can only require .css or .js files, not whatever this is: " + src) ;
    }
    if (extension == 'js')
        document.write('<script type="text/javascript" src="' + src + '"></script>\n');
    else if (extension == 'css')
        document.write('<link rel="stylesheet" href="' + src + '" type="text/css"/>');
}

App.lastResponse = null;

App.onAjaxComplete = function(conn, response, options)
{
    App.lastResponse = response;
    
    if (options.panel && options.panel.el)
        options.panel.el.unmask();
    
    response.json = Ext.util.JSON.decode(response.responseText);
}

App.onAjaxException = function(conn, response, options)
{
    App.lastResponse = response;
    
    if (options.panel && options.panel.el)
        options.panel.el.unmask();
    
    // if (this.testing)
    //     throw new Error(response.responseText);
    // else if (this.debug && typeof(console) != 'undefined')
    // {
    //     console.group("Server Error")
    //     console.log(response.responseText);
    //     console.groupEnd();
    // }
    if (response.responseText)
        Ext.Msg.alert("Server Error", "There was an error on the server.  If this problem persists please contact support.");
    else
        Ext.Msg.alert("Server Unresponsive", "There was an error talking to the server; it may be down or unreachable.  If this problem persists please contact support.");
    
    return true;
}

App.onAjaxRequest = function(conn, options)
{
    options.url = this.urls[options.url] || options.url;
    
    if (options.panel && options.panel.el && options.mask)
        options.panel.el.mask(options.mask, 'x-mask-loading');
}

Ext.Ajax.on('requestcomplete', App.onAjaxComplete, App);
Ext.Ajax.on('requestexception', App.onAjaxException, App);
Ext.Ajax.on('beforerequest', App.onAjaxRequest, App)

App.setup = function(config)
{
    if (Ext.isIE6) {
        window.alert("You are using Internet Explorer 6.0. Use this site at your own risk! We recommend you upgrade to the latest version of Internet Explorer or go to Downloads to download a form to submit your property via email.");
    } 
    var self = App;
    
    self.config = config;
    self.root = config.root || "";
    self.resource_root = config.resource_root || self.root + "/static"
    self.init = config.init || null;
    self.urls = config.urls || {};
    self.testing = config.testing || false;
    self.debug = config.debug || false;
    self.authenticated = config.authenticated || false;
    self.username = config.username || null;
    
    if (self.config.require)
        self.require.apply(this, self.config.require);
    
    for(var i = 0; i < config.stores.length; i++)
    {
        var store = config.stores[i];
        
        self[store.name] = new Ext.data.SimpleStore({
            data: store.data,
            fields: store.fields
        });
    }

    self.utilityServiceStore = new Ext.data.SimpleStore({
	data: [['V', 'Vacant Units and Common Area'],['O', 'Occupied Units and Common Area']],
        fields:['value', 'label']
    });
    
    Ext.chart.Chart.CHART_URL = self.resource_root + '/js/ext/resources/charts.swf';
    
    Ext.onReady(self.__init__, self);
}

App.__init__ = function()
{
    Ext.Msg.minWidth = 300;
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side'; // turn on validation errors beside the field globally
        
    if (this.init)
        this.init();
}

App.checkTestHash = function()
{
    var hash = window.location.hash.split('|');
    if (this.authenticated && this.debug && this.test && hash[0] == '#test')
        this.test.apply(this, hash.splice(1));
}

// TODO: move to a utilities file?
var getFormHelpText = function(helpField, modelName) {
    var result = '';
    var store = null;
    if (modelName == 'ApartmentIE') {
        store = App.aptieHelpTextStore;
    } else if (modelName == 'OfficeBuildingIE') {
        store = App.obieHelpTextStore;
    } else if (modelName == 'ShoppingCenterIE') {
        store = App.scieHelpTextStore;
    } else if (modelName == 'CCPIE') {
        store = App.ccpieHelpTextStore;
    } else if (modelName == 'ConventionalApartment' || modelName == 'FederallyAssistedApartment' ) {
        store = App.aptHelpTextStore;
    } else if (modelName == 'ShoppingCenter') {
        store = App.scHelpTextStore;
    } else if (modelName == 'OfficeBuilding') {
        store = App.obHelpTextStore;
    } else if (modelName == 'CCP') {
        store = App.ccpHelpTextStore;
    }
    if (store) {
        var idx = store.find('help_field', helpField);
        if (idx >= 0) {
            result = store.getAt(idx).get('help_text');
        }
    }
    return result;
}

