/* */
//Proj4js.libPath = 'proj4js/';
window.addEvent('load', function(){
    /* main layout of the page */
    new Jx.Layout('thePage');
    $('thePage').resize();
    new Jx.Layout('header', {bottom: null, height: 100});
    new Jx.Layout('main', {top: 100, bottom: 30});
    new Jx.Layout('footer', {top: null, bottom: 0, height: 30});
    window.fireEvent('draw');
});

function drawApplication() {

    /* layout the application space */

    /* create toolbars */

    /* create child jx items */
    var addLayerDialog_TabBox = new Jx.TabBox({scroll: false}).add([
        new Jx.Tab({label:'WMS',content: 'addWMSLayer'}),
        new Jx.Tab({label:'Library',content: 'libraryContent'}),
        new Jx.Tab({label:'Upload CSV',content: 'cvsUpload'})
    ]);
    var addLayerDialog = new Jx.Dialog({
        id: 'addLayer',
        label: 'Add Layer',
        modal: false,
        resize: true,
        width:400,
        height:400,
        content: addLayerDialog_TabBox
    });

    var classificationDialog = new Jx.Dialog({
        id: 'classificationDialog',
        label: 'Classification',
        modal: false,
        resize: true,
        width:550,
        height:500,
        content: 'Classification'
    });

    var legendBar = new Jx.Toolbar({
        id: 'LegendToolbar',
        scroll: false,
        position: 'top'
    }).add([
        new Jx.Button({ label:'Add',
                                    id: '',
                                    image: 'images/icons.png',
                                    imageClass: 'add',
                                    onClick: function(){
                                        addLayerDialog.open()
                                        }
                                }),

        new Jx.Button({ label:'Class',
                                    image: 'images/icons.png',
                                    imageClass: 'theme',
                                    id: '',
                                    onClick: function(){
                                        classificationDialog.open()
                                        }
                                }),
        new Jx.Field.Combo({
	    readonly:true,
            items: [
                {label: 'Legend'},
                {label: 'Layers'}],
            onChange: function(combo){
                if ($('Layers') && $('Legend')) {
                    if (combo.getValue() == 'Layers') {
                        $('Layers').setStyle('display','block');
                        $('Legend').setStyle('display','none');
                    } else {
                        $('Layers').setStyle('display','none');
                        $('Legend').setStyle('display','block');
                    }
                }
            }
        })]);

//    var featureBar = new Jx.Toolbar({
//        id: 'FeatureToolbar',
//        position: 'top'
//    }).add(
//        new Jx.Button({label:'Add Feature'}));

//    var searchBar = new Jx.Toolbar({
//        id: 'SearchToolbar',
//        position: 'top'
//    }).add(
//        new Element('input', {'id':'searchBox'}));

    var statusBar = new Jx.Toolbar({
        id: 'Statusbar',
        scroll: false,
        position: 'bottom'
    });

    var menuBar = new Jx.Toolbar({
        id: 'Menubar',
        scroll: false,
        position:'top'
    });

    var navBar = new Jx.Toolbar({
        id: 'NavigationToolbar',
        scroll: false,
        position:'top'
    });

    var queryBar = new Jx.Toolbar({
        id: 'QueryToolbar',
        scroll: false,
        position: 'top'
    });

    /* create panels */
    var mapPanel = new Jx.Panel({
        id: 'MapPanel',
        contentId: 'Map',
        hideTitle: true,
        toolbars: [navBar]
    });
    mapPanel.content.appendChild($('scalebar'));
    mapPanel.content.appendChild($('copyright'));
    mapPanel.content.appendChild($('mapBusy'));

    var legendPanel = new Jx.Panel({
        id: 'LegendPanel',
        content: '<div id="Legend"></div><div id="Layers"></div>',
        hideTitle: true,
        toolbars: [legendBar]
    });

//    var featurePanel = new Jx.Panel({
//        id: 'FeaturePanel',
//        hideTitle: true,
//        toolbars: [featureBar]
//    });

//    var searchPanel = new Jx.Panel({
//        id: 'SearchPanel',
//        hideTitle: true,
//        toolbars: [searchBar]
//    });

    var queryPanel = new Jx.Panel({
        //contentId: 'QueryPanel',
        content: '<div id="QueryParams"></div><div id="QueryResults"></div>',
        hideTitle: true,
        toolbars: [queryBar]
    });

    /* create the main panel */
    var mainFrame = new Jx.Panel({
        id: 'MainFrame',
        hideTitle: true,
        toolbars: [statusBar]
    }).addTo('main');

    /* split into 3 columns and put the content into them */
    var leftColumn = new Jx.TabBox({id: 'LeftColumn', scroll: false}).add([
        new Jx.Tab({label: 'Legend', content: legendPanel})
//        new Jx.Tab({label: 'Features', content: featurePanel}),
//        new Jx.Tab({label: 'Search', content: searchPanel})
    ]);

    var centerColumn = new Jx.Panel({
        id: 'CenterColumn',
        hideTitle: true,
        content: mapPanel,
        toolbars: [menuBar]
    });

    var rightColumn = new Jx.TabBox({id: 'RightColumn', scroll: false}).add([
        new Jx.Tab({label:'Tasks', contentId: 'TaskPane'}),
        new Jx.Tab({label:'Query', content: queryPanel})]);

    var splitter = new Jx.Splitter(mainFrame.content, {
        prepareBar: function(i) {
            var o = new Element('div', {
                'class': 'jxSplitBar'+this.layout.capitalize() + ' ' + this.barOptions[i]['class'],
                'title': this.barTitle
            });
            return o;
        },
        elements: [leftColumn, centerColumn, rightColumn],
        containerOptions: [{width:225},null,{width:300}],
        barOptions: [
            {snap:'before', 'class':'leftBar'},
            {snap:'after', 'class':'rightBar'}
        ]});

    /* last step is to trigger initial layout of everything */
    $('thePage').resize({forceResize: true});

    new Jx.Layout('Legend');
    new Jx.Layout('Layers');
    $('Layers').setStyle('display','none');

    Fusion.registerForEvent(Fusion.Event.FUSION_INITIALIZED, function() {
        $('thePage').resize({forceResize: true});
        $('thePage').style.visibility = 'visible';
        var measureResult = new Element('span', {id:"MeasureResult"});
        var measureWidget = Fusion.getWidgetsByType('Measure')[0];
        statusBar.add(new Jx.Toolbar.Item(measureResult));
        statusBar.add(new Jx.Button({
            label: 'Clear',
            onClick: function() {
              measureWidget.control.cancel();
            }
        }));
        measureWidget.registerForEvent(Fusion.Event.MEASURE_CLEAR, function() {
            $('MeasureResult').set('html', '');
        });
        measureWidget.registerForEvent(Fusion.Event.MEASURE_SEGMENT_UPDATE, function() {
            var unitAbbr = Fusion.unitAbbr(measureWidget.units);
            var value = measureWidget.totalLength;
            measureResult.set('html', 'Distance: '+value+unitAbbr+', Area: '+measureWidget.totalArea+unitAbbr+'<sup>2</sup>');
        });
        measureWidget.registerForEvent(Fusion.Event.MEASURE_COMPLETE, function() {
            var unitAbbr = Fusion.unitAbbr(measureWidget.units);
            measureResult.set('html', 'Distance: '+measureWidget.totalLength+unitAbbr+', Area: '+measureWidget.totalArea+unitAbbr+'<sup>2</sup>');
        });

        var map = Fusion.getMapByIndice(0);
        //$('QueryResults').style.display = 'none';
        $('QueryParams').style.display = 'none';
        //map.registerForEvent(Fusion.Event.MAP_SELECTION_ON, function () {
        //    $('QueryResults').style.display = 'block';
        //    $('QueryParams').style.display = 'none';
        //});
        //map.registerForEvent(Fusion.Event.MAP_SELECTION_OFF, function () {
        //    $('QueryResults').style.display = 'none';
        //    $('QueryParams').style.display = 'block';
        //});
        $('Legend').resize();
    });
    Fusion.registerForEvent(Fusion.Event.FUSION_ERROR, fusionError);
    Fusion.initialize({
        applicationDefinitionURL: applicationDefinitionURL
    });
};

function fusionError(eventId, error) {
    console.log('Fusion Error: ' + error.toString());
}

function logOut() {
    new Request.JSON({
      url: '../api/mapsherpa.php',
      method: 'POST',
      data: 'request=logout',
      onComplete: function(json) {
        if (json.success) {
          (function(){
            window.location.reload(true);
          }).delay(1);
        }
      }
    }).send();
}

function drawLogin() {
    var info = new Jx.Notice.Information({
        content: 'Please sign in with your username and password.'
    });
    var succeeded = new Jx.Notice.Success({
        content: 'Sign in successful, loading application ...'
    });
    var failed = new Jx.Notice.Error({
        content: 'Sign in failed.  Please check your user name and password and try again.'
    });
    var incomplete = new Jx.Notice.Error({
        content: 'Invalid or missing username and/or password.  Please check your username and password and try again.'
    });

    var formBox = new Element('div', {
        'id': 'loginForm',
        'class':'formBox'
    }).inject('main');

    var form = new Jx.Form({
        name: 'login',
        formClass: 'jxFormInlineblock'
    }).addTo(formBox);


    var fieldSet1 = new Jx.Fieldset({
        legend: 'Sign in',
        id: 'FieldSet1'
    }).addTo(form);

    var notifier = new Jx.Notifier({
        parent: fieldSet1
    });

    new Jx.Field.Text({
        id: 'Username',
        name: 'Username',
        label: 'User Name',
        required: true,
        value: '',
        validatorClasses: 'minLength:3 maxLength:15'
    }).addTo(fieldSet1);

    new Jx.Field.Password({
        id: 'Password',
        name: 'Password',
        label: 'Password',
        overtext: {},
        required: true,
        validatorClasses: 'minLength:5 maxLength:15',
        value: ''
    }).addTo(fieldSet1);

    notifier.add(info);

    new Jx.Field.Button({
        defaultAction: true,
        buttonOptions: {
          label: 'Sign in',
          onClick: function(obj,evt){
              notifier.remove(info);
              notifier.remove(failed);
              notifier.remove(incomplete);
              if (form.isValid()) {
                var values = form.getValues();
                new Request.JSON({
                  url: '../api/mapsherpa.php',
                  method: 'POST',
                  data: 'request=login&username='+values.Username + '&password='+values.Password,
                  onComplete: function(json) {
                    if (json.success) {
                        notifier.add(succeeded);
                        (function(){
                          window.location.reload(true);
                        }).delay(1);
                      } else {
                          notifier.add(failed);
                      }
                  }
                }).send();
              } else {
                  notifier.add(incomplete);
              }
          }
        }
    }).addTo(fieldSet1);


    /* add rules for username and password as we discover what they should
     * be
     */

    var plugin = new Jx.Plugin.Form.Validator({
        fields: {
            Username: {
                validators: ['minLength:3']
            },
            Password: {
                validators: ['minLength:3']
            }
        },
        fieldDefaults: {
            validateOnBlur: true,
            validateOnChange: true
        },
        validateOnSubmit: true,
        suspendSubmit: false
    });
    plugin.attach(form);

    $('thePage').resize({forceResize: true});

    $('Username').focus();
}

