var gui = {};
gui.grid = null;
gui.classesGrid = [];
gui.cookies = new Ext.state.CookieProvider();

Ext.onReady(function(){


  /*
   * Cookie state
   */
  gui.cookies = new Ext.state.CookieProvider();
  Ext.state.Manager.setProvider(gui.cookies);

  document.getElementsByTagName("h1")[0].innerHTML = gui.gs("Analytical server FMI");

  /*
   * Panely
   */

  /*
   * Import/Export Panel
   */
  gui.importExportPanel = new Ext.Panel({
            title: gui.gs("Import/Export"),
            //layout:'table',
            id:"importExportTab",
            width:"100%",
            layoutConfig: {
                columns: 1
            }
            });
    
  gui.importExportPanel.add({
    html: gui.gs("<p><b>File saving:</b><br/>") });


 gui.uploadForm = new Ext.form.FormPanel({
                frame:true,
                title:gui.gs("Import training areas (GML)"),
                bodyStyle:'padding:5px 5px 0',
                width: "100%",
                name:"uploadForm",
                fileUpload:true,
                url:"upload.php",
                defaultType: 'textfield',
                enctype : 'multipart/form-data',
                items: [
                    {
                        name: 'inputFile',
                        id: "inputFile",
                        inputType:"file",
                        labelStyle:"width:50px",
                        style:"margin-left: -50px",
                        fieldLabel: gui.gs("File"),
                        width: 75,
                        style: "width: 75px;",
                        size: 25
                    },
                    new Ext.form.Checkbox({
                        name: 'fileDeleteOrig',
                        id: "fileDeleteOrig",
                        fieldLabel:gui.gs("Delete allready digitized training areas"),
                        labelStyle:"width:150px",
                        checked:false
                    })
                ],
                buttons: [  new Ext.Button({
                                text: gui.gs("Read from harddrive"),
                                handler: 
                                        function() {
                                        gui.uploadForm.getForm().submit({
                                            waitMsg: 'Please Wait....',
                                            reset: false,
                                            failure: function(uploadForm, action){
                                                Ext.MessageBox.alert('Error', action.result.info);
                                            },
                                            success: function(uploadForm, action){
                                                //Ext.MessageBox.alert('Confirm', action.result.filename);
                                                gui.parseImportedFile(action.result.filename);
                                            } 
                                        })
                                        }
                                    })
                        ],
                reader: new Ext.data.XmlReader({
                            record: "file",           // The repeated element which contains row information
                            id: "fileName"                 // The element within the row that provides an ID for the record (optional)
                            }, 
                            Ext.data.Record.create([ {name: 'fileName'} ])
                            )
                });

  gui.importExportPanel.add(gui.uploadForm);

  gui.importForm = new Ext.form.FormPanel({
                frame:true,
                //title:"Importovat z URL",
                bodyStyle:'padding:5px 5px 0',
                defaultType: 'textfield',
                width: "100%",
                name:"importForm",
                items: [
                    {
                        name: 'inputURL',
                        id: "inputURL",
                        value:"http://",
                        fieldLabel: gui.gs("URL"),
                        labelStyle:"width:50px",
                        style:",margin-left:-60px",
                        width: 200
                    },
                    new Ext.form.Checkbox({
                        name: 'urlDeleteOrig',
                        id: "urlDeleteOrig",
                        fieldLabel: gui.gs("Delete allready digitized training areas"),
                        labelStyle:"width:150px",
                        checked:false
                    })
                ],
                buttons: [  new Ext.Button({
                                handler:uhul.parseFromGML,
                                text:gui.gs("Read from server"),
                                handler:function() {
                                   OpenLayers.loadURL(
                                       document.getElementById("inputURL").value,
                                       "", null, 
                                       uhul.loadNewTrainingAreas);}
                                })
                        ]
                });
  gui.importExportPanel.add(gui.importForm);

  gui.exportForm = new Ext.FormPanel({
                 frame:true,
                 title: gui.gs("Export"),
                 bodyStyle:'padding:5px 5px 0',
                 defaultType: 'textfield',
                 width: "100%",
                 name:"exportForm",
                 items: [
                     new Ext.form.ComboBox({
                         store: gui.formatStore,
                         fieldLabel: gui.gs('File format'),
                         emptyText:"GML",
                         labelSeparator:'',
                         displayField:'title',
                         hiddenName:'outputFileFormat',  
                         valueField:'format', 
                         typeAhead: false,
                         mode: 'local',
                         width: 150,
                         listWidth: 150,
                         forceSelection:false,
                         selectOnFocus:true,
                         lazyRender:true,
                         allowBlank:false
                     }),
                     {
                         name: 'outputFileFormat',
                         id: "outputFileFormat",
                         inputType:"hidden"
                     }
                 ],
                 buttons: [  new Ext.Button({
                                 handler:uhul.onExportTrainingAreas,
                                 text:gui.gs("Save")
                                 })
                         ]
                 });

  gui.importExportPanel.add(gui.exportForm);

  /*
   * Calculation Panel
   */
  gui.calculationTabPanel = new Ext.Panel({
            title: gui.gs("Calculation"),
            id:"calculationTabPanel",
            width:"100%",
            layoutConfig: {
                columns: 1
            }
            });
  /*
   * vlastni klasifikace
   */
  gui.calculationTabPanel.add(
        new Ext.FormPanel({
            frame:true,
            bodyStyle:'padding:5px 5px 0',
            defaultType: 'textfield',
            width: "100%",
            title: gui.gs("Classification calculation"),
            items: [
                {
                    name: 'classifyVarianta',
                    id: "classifyVariant",
                    fieldLabel: gui.gs("Variant")
                },
                {
                    name: 'maxsig',
                    id: "maxsig",
                    fieldLabel: gui.gs("Maximal number <br/> of subsignatures"),
                    value: 10
                },
                {
                    name: 'blocksize',
                    id: "blocksize",
                    fieldLabel:gui.gs("Submatrix size"),
                    value: 128
                },
                /*
                {
                    name: 'variantNote',
                    id: "variantNote",
                    fieldLabel:"Poznámka"
                },
                */
                new Ext.form.Checkbox({
                    name: 'maxlikeClassification',
                    id: "maxlikeClassification",
                    fieldLabel:gui.gs("Use maximum likelihood (instead of SMAP)"),
                    checked:false
                }),
                {
                    name: 'unsupClass',
                    id: "unsupClass",
                    fieldLabel:gui.gs("Number of classes for unsupervised classification")
                }
                
            ],
            buttons: [ 
                        new Ext.Button({
                            text:gui.gs("Classify"),
                            handler:uhul.onClassifyClicked
                            })
                    ]
    })
  );

  /*
   * postprocessing
   */
  gui.classifiedLayersStore = new Ext.data.SimpleStore({
        fields: [
           {name: 'layerid', type: "string"},
           {name: 'name', type: 'string'}
        ],
        id:0
    });

  gui.neigbhborsStore = new Ext.data.SimpleStore({
        fields: [
           {name: 'method', type: 'string'},
           {name: 'name', type: 'string'}
        ],
        data :  [
        ["average","Average"],
        ["median","Median"],
        ["mode","Modus"],
        ["minimum","Minimum"],
        ["maximum","Maximum"],
        ["stddev","Standard deviation"],
        ["sum","Sum"],
        ["variance","Variance"],
        ["diversity","Diversity"],
        ["interspersion","Interspresion"]
        ]
    });

  gui.classifiedLayersComboBox =   new Ext.form.ComboBox({
                    store: gui.classifiedLayersStore,
                    displayField:'name',
                    typeAhead: true,
                    mode: 'local',
                    hiddenName:'classedLayerId',  
                    valueField:'layerid', 
                    triggerAction: 'all',
                    emptyText:gui.gs("Select layer..."),
                    selectOnFocus: true,
                    width:130,
                    fieldLabel:gui.gs("Classified layer")
                });

  gui.postprocessingMethodsComboBox =   new Ext.form.ComboBox({
                    store: gui.neigbhborsStore,
                    displayField:'name',
                    typeAhead: true,
                    mode: 'local',
                    hiddenName:'neigbhborsMethod',  
                    valueField:'method', 
                    triggerAction: 'all',
                    emptyText:gui.gs("Select method..."),
                    selectOnFocus: true,
                    fieldLabel:gui.gs("Postprocessing method")
                });

  gui.calculationTabPanel.add(
        new Ext.FormPanel({
            frame:true,
            bodyStyle:'padding:5px 5px 0',
            defaultType: 'textfield',
            width: "100%",
            title: gui.gs("Postprocessing"),
            items: [
               // {
               //     name: "cLayerId",
               //     inputType:"hidden",
               //     fieldLabel:gui.gs("Layer id")
               // },
                {
                    name: 'neigbhborsMethod',
                    id: "neigbhborsMethod",
                    inputType:"hidden",
                    value: "mode"
                },
                {
                    name: 'postprocessedVariant',
                    id: "postprocessedVariant",
                    fieldLabel:gui.gs("Variant")
                },
                gui.classifiedLayersComboBox,
                /* gui.postprocessingMethodsComboBox, */
                {
                    name: 'matrixSize',
                    id: "matrixSize",
                    fieldLabel: gui.gs("Matrix size"),
                    value: 3
                }
            ],
            buttons: [ 
                        new Ext.Button({
                            text:gui.gs("Postprocess"),
                            handler:uhul.onPostprocess
                            })
                    ]
    })
  );


  /*
   * Training classes Panel
   */
  gui.trainingClassesPanel = new Ext.Panel({
            title: gui.gs("Classes"),
            //layout:'table',
            id:"classesTab",
            width:"100%",
            layoutConfig: { columns: 1 }
            });

  gui.trainingClassesPanel.add({id:"classesGridDiv"});


  /*
   * Training areas Panel
   */
  gui.trainingAreasPanel = new Ext.Panel({
            title: gui.gs("Training areas"),
            //layout:'table',
            id:"trainingAreasPanel",
            width:"100%",
            layoutConfig: {
                columns: 1
            }
            });

  gui.classesComboBox =   new Ext.form.ComboBox({
                    store: gui.classesStore,
                    displayField:'label',
                    typeAhead: true,
                    mode: 'local',
                    hiddenName:'classNr',  
                    valueField:'class', 
                    triggerAction: 'all',
                    emptyText:gui.gs("Select class..."),
                    selectOnFocus: true,
                    name: 'classLabel',
                    id: "classLabel",
                    width: 150,
                    fieldLabel:gui.gs("This area class")
                });

  gui.trainingAreasPanel.add(
        new Ext.FormPanel({
            frame:true,
            bodyStyle:'padding:5px 5px 0',
            defaultType: 'textfield',
            width: "100%",
            title: gui.gs("Area attributes"),
            items: [
                {
                    name: 'areaId',
                    id: "areaId",
                    inputType:"hidden"
                },
                {
                    name: 'areaExists',
                    id: "areaExists",
                    inputType:"hidden"
                },
                gui.classesComboBox,
                {
                    name: 'classNr',
                    id: "classNr",
                    inputType:"hidden"
                },
                {
                    name: 'classColor',
                    id: "classColor",
                    inputType:"hidden"
                },
                {
                    name: 'areaNote',
                    id: "areaNote",
                    fieldLabel:gui.gs("Note")
                },
                new Ext.form.Checkbox({
                    name: 'useFeature',
                    id: "useFeature",
                    fieldLabel:gui.gs("Use for classification"),
                    checked:true
                })
            ],
            buttons: [ 
                        new Ext.Button({
                            text:gui.gs("Set attributes"),
                            handler:uhul.setAreaAttribute
                            })
                    ]
    })
  );


  /*
   * HACK, HACK, HACK
   * Přidání záznamu "Nová třída" do Comboboxu s patřičným chováním
   */
  gui.classesComboBox.onLoad = function(){
        if(!this.hasFocus){
            return;
        }

        if (!this.newClassRecord) {
            this.newClassRecord = new Ext.data.Record({
                    "class":"",
                    label:"<span style='font-style:italic;'>"+gui.gs("New class")+"</span>",
                    color:"ffffff"
                    });
        }
        try {
            gui.classesStore.remove(this.newClassRecord);
        }
        catch (e) {}
        gui.classesStore.add(this.newClassRecord);

        if(this.store.getCount() > 0){
            this.expand();
            this.restrictHeight();
            if(this.lastQuery == this.allQuery){
                if(this.editable){
                    this.el.dom.select();
                }
                if(!this.selectByValue(this.value, true)){
                    this.select(0, true);
                }
            }else{
                this.selectNext();
                if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
                    this.taTask.delay(this.typeAheadDelay);
                }
            }
        }else{
            this.onEmptyResults();
        }
        //this.el.focus();
    };

    gui.classesComboBox.onSelect = function(record, index){
        if(this.fireEvent('beforeselect', this, record, index) !== false){
            if (record != this.newClassRecord) {
                this.setValue(record.data[this.valueField || this.displayField]);
                this.collapse();
                this.fireEvent('select', this, record, index);
            }
            else {
                this.collapse();
                gui.classifyTabPanel.activate("classesTab");
                gui.addNewRecordToClassTable();
            }
        }
    };
    gui.classesComboBox.on("collapse",
            function(e) {
                gui.classesStore.remove(gui.classesComboBox.newClassRecord)
            });


    
  /*
   * Classify panel
   */
  gui.classifyTabPanel = new Ext.TabPanel({
                        title: gui.gs("Classification"),
                        tabName:"classifyTab",
                        deferredRender:false,
                        border:false,
                        activeTab:0,
                        tabPosition:'top',
                        items:[
                            gui.trainingAreasPanel,
                            gui.trainingClassesPanel,
                            gui.calculationTabPanel,
                            gui.importExportPanel
                            ]
                    });

  /*
   * Help
   */
  /*
  gui.helpPanel
    */
  /*
   * Tab panel on the right side of the gui
   */
    gui.layerSwitcherTab = new Ext.Panel({
                id:"layerSwitcherTab",
                title: gui.gs("Layers"),
                tabName:"layerSwitcherTab",
                autoScroll:true
                });
  var tabPanel = new Ext.TabPanel({
                        deferredRender:false,
                        border:false,
                        activeTab:0,
                        tabPosition:'top',
                        items:[
                            gui.layerSwitcherTab,
                            gui.classifyTabPanel
                            ]
                    });


    
  /*
   * Page viewport
   */
  gui.viewport = new Ext.Viewport({
        layout:'border',
        items:[
         new Ext.BoxComponent({ // raw
                    region:'north',
                    el: 'north',
                    defaults : {bodyStyle:'padding:10px'}
                }),

                {
                region:'center',
                contentEl:"map",
                title: gui.gs("Map"),
                collapsible: false,
                split:true,
                layout:'fit',
                margins:'0 5 0 5'
                },
         new Ext.BoxComponent({ // raw
                    region:'south',
                    el: 'south',
                    defaults : {bodyStyle:'padding:10px'}
                }),
            {
                region:'east',
                contentEl:"tabs",
                title: gui.gs("Tools"),
                collapsible: true,
                split:true,
                width: 300,
                minSize: 175,
                maxSize: 400,
                layout:'fit',
                margins:'0 5 0 0',
                items: tabPanel
                }//east
        ]
        }
    );

  // events
  tabPanel.on("tabchange",gui.onGuiTabChanged);

    gui.loadmask  = new Ext.LoadMask(document.getElementById("map"),{msg:gui.gs("Initializing map...")});
    gui.loadmask.show();

    gui.loadClasses();
});

/**
 * Adjust map toolbar, when guitab has changed
 */
gui.onGuiTabChanged = function(e) {
    try {
        switch (e.activeTab.tabName) {
            case "layerSwitcherTab": 
                uhul.addButtons();
                break;
            case "classifyTab": 
                uhul.addButtons("digit");
                break;
        }
    } catch (e) {};
};

gui.formatStore = new Ext.data.SimpleStore({
        fields: ['format', 'title'],
        data :  [
        ['text/xml', 'GML'],
        ['application/zip', 'ESRI Shapefile']
        ]
});

gui.downloadGeoTIFF = function() {
    Ext.get("outputWPSFormat").dom.value = "image/tiff";
    sazp.calculateVisibility();
    Ext.get("outputWPSFormat").dom.value = "image/png";

};

gui.loadClasses = function() {
    gui.classesGrid = [];

    function color(val){
        var background = "#"+val;
        var red = parseInt(val.substr(0,2),16);
        var green = parseInt(val.substr(2,2),16);
        var blue = parseInt(val.substr(4,5),16);
        var textColor =  "#000000";
        if (red+green+blue < 382.50) {
            textColor = "#FFFFFF";
        }
        
        return '<span style="padding: 3px; background:'+
                background+'; color: '+textColor+'">' +
                val + '</span>';
    }

    var colorField = new Ext.form.ColorField({
                showHexValue:true,
                defaultColor:"FF9900"});
 
    var cm = new Ext.grid.ColumnModel([{
            id:'class', 
            header:gui.gs("Class"), 
            width:"50px",
            sortable: true,
            dataIndex:"class"//,
            //editor: new Ext.form.TextField({
            //    vtype: "alphanum",
            //    allowBlank: false})
        },
        {
            header: gui.gs("Description"),
            sortable: false,
            dataIndex: 'label',
            editor: new Ext.form.TextField({allowBlank: false})
        },
        // {
        //     header: "Barva",
        //     sortable: false,
        //     dataIndex: 'color',
        //     editor: new Ext.form.TextField({allowBlank: false})
        // }
        {
            header: gui.gs("Color"),
            width: "75px",
            sortable: false,
            dataIndex: 'color',
            renderer: color,
            editor: colorField
            }]);

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    gui.Cls = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'class', type: 'int'},
           {name: 'label', type: 'string'},
           {name: 'color', type: "string"}
      ]);

    gui.classesStore = new Ext.data.SimpleStore({
        fields: [
           {name: 'class', type:"int"},
           {name: 'label', type: 'string'},
           {name: 'color', type: 'string'}
        ],
        id: 0
    });


    // create the editor grid
    gui.grid = new Ext.grid.EditorGridPanel({
        store: gui.classesStore,
        cm: cm,
        //autoExpandColumn: "color",
        title: gui.gs("Available classes"),
        frame:true,
        renderTo: "classesGridDiv",
        clicksToEdit:1,
        stripeRows: true,
        height:250,
        tbar: [{
                text: gui.gs("Add class"),
                handler : function(){
                    gui.addNewRecordToClassTable();
                }
            },{
                text: gui.gs("Delete selected class"),
                handler : function(){
                    gui.grid.stopEditing();
                    var index = gui.grid.getSelectionModel().getSelectedCell()[0];
                    var record = gui.classesStore.getAt(index);
                    gui.classesStore.remove(record);
                }
            }
            ]
    });
    gui.classesStore.loadData(gui.classesGrid);
    gui.classesComboBox.store = gui.classesStore;
    gui.grid.on("afteredit", uhul.updateFeatuers)
};

/**
 * @class Ext.form.ColorField
 * @extends Ext.form.TriggerField
 * Provides a very simple color form field with a ColorMenu dropdown.
 * Values are stored as a six-character hex value without the '#'.
 * I.e. 'ffffff'
 * @constructor
 * Create a new ColorField
 * <br />Example:
 * <pre><code>
var cf = new Ext.form.ColorField({
	fieldLabel: 'Color',
	hiddenName:'pref_sales',
	showHexValue:true
});
</code></pre>
 * @param {Object} config
 */
Ext.form.ColorField = function(config){
    Ext.form.ColorField.superclass.constructor.call(this, config);
	this.on('render', this.handleRender);
};

Ext.extend(Ext.form.ColorField, Ext.form.TriggerField,  {
    /**
     * @cfg {Boolean} showHexValue
     * True to display the HTML Hexidecimal Color Value in the field
     * so it is manually editable.
     */
    showHexValue : false,
	
	/**
     * @cfg {String} triggerClass
     * An additional CSS class used to style the trigger button.  The trigger will always get the
     * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-color-trigger'
     * which displays a calendar icon).
     */
    triggerClass : 'x-form-color-trigger',
	
    /**
     * @cfg {String/Object} autoCreate
     * A DomHelper element spec, or true for a default element spec (defaults to
     * {tag: "input", type: "text", size: "10", autocomplete: "off"})
     */
    // private
    defaultAutoCreate : {tag: "input", type: "text", size: "10",
						 autocomplete: "off", maxlength:"6"},
	
	/**
	 * @cfg {String} lengthText
	 * A string to be displayed when the length of the input field is
	 * not 3 or 6, i.e. 'fff' or 'ffccff'.
	 */
	lengthText: "Color hex values must be either 3 or 6 characters.",
	
	//text to use if blank and allowBlank is false
	blankText: "Must have a hexidecimal value in the format ABCDEF.",
	
	/**
	 * @cfg {String} color
	 * A string hex value to be used as the default color.  Defaults
	 * to 'FFFFFF' (white).
	 */
	defaultColor: 'FFFFFF',
	
	maskRe: /[a-f0-9]/i,
	// These regexes limit input and validation to hex values
	regex: /[a-f0-9]/i,

	//private
	curColor: 'ffffff',
	
    // private
    validateValue : function(value){
		if(!this.showHexValue) {
			return true;
		}
		if(value.length<1) {
			this.el.setStyle({
				'background-color':'#' + this.defaultColor
			});
			if(!this.allowBlank) {
				this.markInvalid(String.format(this.blankText, value));
				return false
			}
			return true;
		}
		if(value.length!=3 && value.length!=6 ) {
			this.markInvalid(String.format(this.lengthText, value));
			return false;
		}
		this.setColor(value);
        return true;
    },

    // private
    validateBlur : function(){
        return !this.menu || !this.menu.isVisible();
    },
	
	// Manually apply the invalid line image since the background
	// was previously cleared so the color would show through.
	markInvalid : function( msg ) {
		Ext.form.ColorField.superclass.markInvalid.call(this, msg);
		this.el.setStyle({
			'background-image': 'url(../lib/resources/images/default/grid/invalid_line.gif)'
		});
	},

    /**
     * Returns the current color value of the color field
     * @return {String} value The hexidecimal color value
     */
    getValue : function(){
        return this.curColor || this.defaultValue || "FFccFF";
        return this.curValue || this.defaultValue || "FFFFFF";
    },

    /**
     * Sets the value of the color field.  Format as hex value 'FFFFFF'
     * without the '#'.
     * @param {String} hex The color value
     */
    setValue : function(hex){
        Ext.form.ColorField.superclass.setValue.call(this, hex);
        this.setColor(hex);
    },
	
    /**
    * Sets the current color and changes the background.
    * Does *not* change the value of the field.
    * @param {String} hex The color value.
    */
    setColor : function(hex) {
            this.curColor = hex;
            var red = parseInt(hex.substr(0,2),16);
            var green = parseInt(hex.substr(2,2),16);
            var blue = parseInt(hex.substr(4,5),16);
            var textColor = "#000000";
            if (red+green+blue < 382.50) {
                textColor = "#FFFFFF";
            }
            
            this.el.setStyle( {
                    'background-color': '#' + hex,
                    'background-image': 'none',
                    'color': textColor
            });
            if(!this.showHexValue) {
                    this.el.setStyle({
                            'text-indent': '-100px'
                    });
                    if(Ext.isIE) {
                            this.el.setStyle({
                                    'margin-left': '100px'
                            });
                    }
            }
    },
    
    handleRender: function() {
            this.setDefaultColor();
    },
    
    setDefaultColor : function() {
            this.setValue(this.defaultColor);
    },

    // private
    menuListeners : {
        select: function(m, d){
            this.setValue(d);
        },
        show : function(){ // retain focus styling
            this.onFocus();
        },
        hide : function(){
            this.focus();
            var ml = this.menuListeners;
            this.menu.un("select", ml.select,  this);
            this.menu.un("show", ml.show,  this);
            this.menu.un("hide", ml.hide,  this);
        }
    },
	
	//private
	handleSelect : function(palette, selColor) {
		this.setValue(selColor);
	},

    // private
    // Implements the default empty TriggerField.onTriggerClick function to display the ColorPicker
    onTriggerClick : function(){
        if(this.disabled){
            return;
        }
        if(this.menu == null){
            this.menu = new Ext.menu.ColorMenu();
			this.menu.palette.on('select', this.handleSelect, this );
        }
        this.menu.on(Ext.apply({}, this.menuListeners, {
            scope:this
        }));
        this.menu.show(this.el, "tl-bl?");
    }
});

gui.parseImportedFile = function(filename) {
    OpenLayers.loadURL("/mapserv/tmp/"+filename, "", null, uhul.loadNewTrainingAreas);
};

/*
 * translations
 * get string
 */
gui.gs = function(id) {

  if (!gui.cookies.get("language") || gui.cookies.get("language") == "cz"){
    language = "cz";
  }
  else {
    language = "en";
  }

  if (!gui.langStore) {

 }

  if (!gui.langStore) {
    gui.langStore = new Ext.data.SimpleStore({
                            fields: ['en', 'cz'],
                            data :  translation
                            });
  }

  try {
    var index =  gui.langStore.find("en",id,0,true,true);
    var strings = gui.langStore.getAt(index);

    return gui.langStore.getAt(index).data[language];
  }
  catch(e) {
    return id;
  }

};


gui.switchLanguage = function(lang) {
    if (lang != "cz") {
        lang = "en"
    }

  if (gui.cookies.get("language") != lang) {
    gui.cookies.set("language", lang);
    window.location.reload();
  }

};

gui.addNewRecordToClassTable = function(id,label,color) {
    if (!id) {
        id = gui.grid.getStore().data.items.length+1;
    }
    if (!color) {
        color = "ffffff";

    }
    if (!label)  {
        label = "";
    }
    var c = new gui.Cls({
        "class": id,
        label: label,
        color: color
    });

    gui.grid.stopEditing();
    gui.classesStore.insert(gui.grid.getStore().data.items.length, c);
    gui.grid.startEditing(gui.grid.getStore().data.items.length-1, 1);
}

