#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import pickle
import tempfile
import shutil
import time

from stocks import Stock_Class
from appconfig import Config
import functions
from model import Model
from minimclass import Minim
from minimpypreferences import PrefWin
from export import Export
from editvariable import EditVariable
from editallocation import EditAllocation
from viewer import Viewer

try:
    import pysvn
except:
    print("pysvn Not Availible")
    sys.exit(1)
    
try:
    import pygtk
    pygtk.require("2.0")
    import gobject
except:
    print("pygtk Not Availible")
    sys.exit(1)
try:
    import gtk
except:
    print("GTK Not Availible")
    sys.exit(1)

class ModelInteface(object):
    # invalid chars in trial title. Only applicable to network trials
    if os.name == 'posix':
        invalid_chars = '/'
    else:
        # Windows
        invalid_chars = '\\/:* ?"<>|'

    # translator function
    def _(self, key):
        # key must be supplied
        assert len(key) > 0
        # if key not in the dict, return the key itself
        if self.tr_dict.has_key(key):
            return self.tr_dict[key]
        else:
            return key.replace('_', '.')

    def query_trial_dismis(self):
        # this method checks whether the trial has unsaved data.
        # if there are unsaved data, prompt a warning.
        # output: True: means the dismis current state (e.g. start a new trial)
        # if the trial file name is set, it means that we have saved the data
        if self.trial_file_name:
            return True
        else:
            # empty trial file name: check if changes happend to the interface
            if len(self.group_liststore) or len(self.variable_liststore) or len(
                self.trial_title_entry.get_text()) or len(functions.get_text_buffer(self.trial_description_text)):
                msg = self._('query_trial_dismis_msg')
                dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
                dialog.set_title(self._('query_trial_dismis_dialog_title'))
                if dialog.run() == gtk.RESPONSE_NO:
                    dialog.destroy()
                    return False
                dialog.destroy()
        return True

    def delete_event(self, widget, event):
        # check if we have unsaved data and ask fir sure, if not cancel the close
        if not self.query_trial_dismis():
            # do not exit
            return True
        # delete temporary files and folders created by this application
        for item in self.used_temp_files:
            if tempfile._exists(item):
                try:
                    self.remove_temp_file(item)
                except:
                    pass
        self.window.destroy()
        gtk.main_quit()

    def group_cell_edited(self, cell, row, new_text, col):
        # edit group data
        # col = 0: group name
        if col == 0:
            # names must not be repeated
            for r in range(len(self.group_liststore)):
                if r != row and new_text == self.group_liststore[r][0]:
                    self.statusbar.pop(self.sb_context_id)
                    self.statusbar.push(self.sb_context_id, self._('statusbar_group_name_already_in_use'))
                    return False
            # empty cell not permitted
            if len(new_text) == 0:
                self.statusbar.pop(self.sb_context_id)
                self.statusbar.push(self.sb_context_id, self._('statusbar_group_name_can_not_be_empty'))
                return False
        # group allocation ration
        if col == 1:
            # must be digits
            if not new_text.isdigit():
                self.statusbar.pop(self.sb_context_id)
                self.statusbar.push(self.sb_context_id, self._('statusbar_allocation_ratio_must_be_an_integer'))
                return False
            # convert to integer 
            new_text = int(new_text)
            # should be within range
            adj = cell.get_property('adjustment')
            if adj.upper < new_text or new_text < adj.lower:
                self.statusbar.pop(self.sb_context_id)
                self.statusbar.push(self.sb_context_id, self._('statusbar_allocation_ratio_must_be_in_range').format(int(adj.lower), int(adj.upper)))
                return False
        # save the value
        self.group_liststore[row][col] = new_text
        # update the interface
        self.update_interface()

    def group_add_button(self, widget, data=None):
        # adding a group
        # name and allocation ratio default to 'Group n' and 1
        # name must be unique
        n = 1
        while True:
            group_name = 'Group {0}'.format(n)
            for row in range(len(self.group_liststore)):
                if self.group_liststore[row][0] == group_name:
                    break
            else:
                break
            n += 1
        self.group_liststore.append((group_name, 1))
        # update the interface
        self.update_interface()

    def group_delete_button(self, widget, data=None):
        # if a group is selected
        if self.group_treeview.get_cursor()[0]:
            # row of the selection
            row = self.group_treeview.get_cursor()[0][0]
            # remove the selected group
            self.group_liststore.remove(self.group_liststore.get_iter(row))
            self.update_interface()
        # nothing is selected
        else:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_please_select_a_group_first'))
            return False

    def variable_add_button(self, widget, data=None):
        # add avariable
        # choose a default name for this new variable
        # name must be unique. weight defaults to 1.0 and levels to 'Level 0, Level 1'
        n = 1
        while True:
            var_name = 'Variable {0}'.format(n)
            for row in range(len(self.variable_liststore)):
                if self.variable_liststore[row][0] == var_name:
                    break
            else:
                break
            n += 1
        self.variable_liststore.append((var_name, 1.0, 'Level 0,Level 1'))
        self.update_interface()
        # scroll down to the new variable
        row = len(self.variable_liststore) - 1
        functions.treeview_scroll_select_row(self.window, self.variable_treeview, row)
        EditVariable(self, row)

    def variable_delete_button(self, widget, data=None):
        # delete a var
        if self.variable_treeview.get_cursor()[0]:
            row = self.variable_treeview.get_cursor()[0][0]
            self.variable_liststore.remove(self.variable_liststore.get_iter(row))
            self.update_interface()
        else:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_select_a_variable_first'))
            return False

    def build_variable_combos_dialog(self):
        dlg = gtk.Dialog(title= self._('allocation_add'),
                                 parent=self.window,
                                 flags=gtk.DIALOG_MODAL,
                                 buttons=(gtk.STOCK_ADD, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
        dlg.set_size_request(450, 300)
        dlg.set_default_response(gtk.RESPONSE_OK)
        dlg.set_has_separator(True)
        lbl = gtk.Label(self._('select_variables_level'))
        dlg.vbox.pack_start(lbl)
        self.combo_vbox = gtk.VBox(False)
        functions.make_scrolling(self.combo_vbox, dlg.vbox)
        hb = gtk.HBox(False)
        self.case_properties_liststore, self.case_properties_treeview = functions.make_treeview(
        (str, str), [self._('name'), self._('value')],
        editable=True, edit_handler=self.case_properties_cell_edited)
        functions.make_scrolling(self.case_properties_treeview, hb)
        vbuttonbox = gtk.VButtonBox()
        vbuttonbox.set_layout(gtk.BUTTONBOX_START)
        button = gtk.Button(None, gtk.STOCK_ADD)
        button.connect("clicked", self.case_properties_add_button)
        vbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DELETE)
        button.connect("clicked", self.case_properties_delete_button)
        vbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DATE)
        button.connect("clicked", self.case_properties_date_button)
        vbuttonbox.pack_start(button, False, False)
        hb.pack_start(vbuttonbox, False, False)
        lbl = gtk.Label(self._('new_case_extra_properties'))
        dlg.vbox.pack_start(lbl, False, False)
        dlg.vbox.pack_start(hb, False, False)
        dlg.vbox.show_all()
        dlg.connect('response', self.handle_variable_add_dialog_respnse)
        return dlg

    def handle_variable_add_dialog_respnse(self, dialog, response_id):
        if response_id in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
            dialog.hide()
            return
        for cbo in self.variable_combos:
            if cbo.get_active() == -1:
                cbo.popup()
                return
        dialog.hide()

    def update_interface(self):
        # update the interface after change in groups and variable
        # first remove allocations columns
        n = len(self.allocations_treeview.get_columns())
        while n:
            n = self.allocations_treeview.remove_column(self.allocations_treeview.get_column(n-1))
        # then destroy the case selection widgets
        widgets = self.combo_vbox.get_children()
        for widget in widgets:
            widget.destroy()
        # selt the var combo list to empty
        self.variable_combos = []
        # a container table for var widgets
        table = gtk.Table(2, len(self.variable_liststore)+1)
        table.show()
        n = 0
        # adding variable widgets for selecting levels of new case
        for variable in self.variable_liststore:
            lbl = gtk.Label(variable[0])
            lbl.show()
            table.attach(lbl, 0, 1, n, n+1)
            cbo = gtk.combo_box_new_text()
            cbo.show()
            # populating each cbo with levels of variable
            for level in map(str.strip, variable[2].split(',')):
                cbo.append_text(level)
            cbo.set_active(0)
            # saving the cbo in a global list
            self.variable_combos.append(cbo)
            table.attach(cbo, 1, 2, n, n+1)
            n += 1
        # placing the table inside the self.combo_vbox
        self.combo_vbox.pack_start(table, False, False)
        # setting up allocation table, one col for each variable, 3 extra cols for
        # extra values (#, ui, group)
        types = ((int,) + (str,) * (len(self.variable_liststore) + 2))
        liststore = gtk.ListStore(*types)
        # first col for sequence number
        tvcolumn = gtk.TreeViewColumn('#')
        self.allocations_treeview.append_column(tvcolumn)
        cell = gtk.CellRendererText()
        tvcolumn.pack_start(cell, True)        
        tvcolumn.add_attribute(cell, 'text', 0)
        tvcolumn.set_resizable(True)
        tvcolumn.set_expand(True)
        tvcolumn.set_sort_column_id(0)
        # next col for UI
        tvcolumn = gtk.TreeViewColumn('UI')
        self.allocations_treeview.append_column(tvcolumn)
        cell = gtk.CellRendererText()
        tvcolumn.pack_start(cell, True)        
        tvcolumn.add_attribute(cell, 'text', 1)
        tvcolumn.set_resizable(True)
        tvcolumn.set_expand(True)
        tvcolumn.set_sort_column_id(1)
        # third col for group of subject
        tvcolumn = gtk.TreeViewColumn(self._('general_group'))
        self.allocations_treeview.append_column(tvcolumn)
        cell = gtk.CellRendererText()
        tvcolumn.pack_start(cell, True)        
        tvcolumn.add_attribute(cell, 'text', 2)
        tvcolumn.set_resizable(True)
        tvcolumn.set_expand(True)
        tvcolumn.set_sort_column_id(2)
        # remaining cols for selected levels of each variable
        # start at col 2 (third col)
        n = 2
        for variable in self.variable_liststore:
            n += 1
            tvcolumn = gtk.TreeViewColumn(variable[0])
            self.allocations_treeview.append_column(tvcolumn)
            cell = gtk.CellRendererText()
            tvcolumn.pack_start(cell, True)        
            tvcolumn.add_attribute(cell, 'text', n)
            tvcolumn.set_resizable(True)
            tvcolumn.set_expand(True)
            tvcolumn.set_sort_column_id(n)
        # set the model to the treeview
        self.allocations_treeview.set_model(liststore)
        self.allocations_treeview.show()
        # equivalent models of variable_combos
        variable_models = [cbo.get_model() for cbo in self.variable_combos]
        # now populating allocation table with subjects
        for row, record in enumerate(self.allocations):
            liststore.append()
            # first three rows for #, UI and group of the subject
            liststore[row][0] = row
            UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
            liststore[row][1] = str(record['UI']).zfill(UI_len)
            liststore[row][2] = self.group_liststore[record['allocation']][0]
            # remaining cols populate with the selected levels of each variable
            for col, variable_model in enumerate(variable_models):
                liststore[row][col+3] = variable_model[record['levels'][col]][0]

    def min_allocation_ratio_group_index(self):
        idx, r = 0, self.group_liststore[0][1]
        for i in range(len(self.group_liststore)):
            if self.group_liststore[i][1] < r:
                idx, r = i, self.group_liststore[i][1]
        return idx

    def get_minimize_case(self, new_case):
        # minimize a new case. Input is a new case
        # a model for holding the minimization parameters
        model = Model()
        model.groups = range(len(self.group_liststore))
        model.variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
        model.variables_weight = [self.variable_liststore[row][1] for row in range(len(self.variable_liststore))]
        model.allocation_ratio = [self.group_liststore[row][1] for row in range(len(self.group_liststore))]
        model.allocations = self.allocations
        model.prob_method = self.get_prob_method()
        model.distance_measure = self.get_distance_measure()
        model.high_prob = self.high_prob_spin.get_value()
        model.min_group = self.min_allocation_ratio_group_index()
        # a minimization object to do minimization. Setup based on the model and random as determined by
        # program configuration
        m = Minim(random=self.random, model=model)
        # build probabilities table depending on the current allocations,
        # var weights and group allocation ratios
        m.build_probs(model.high_prob, model.min_group)
        # the build the frequency table
        m.build_freq_table()
        # if an initial preload, add it to the current
        if self.initial_freq_table:
            self.add_to_initial(m.freq_table)
        # now do the actual minimization
        return m.enroll(new_case, m.freq_table)

    def add_to_initial(self, freq_table):
        # if an initial preload, add it to the current
        for row, group in enumerate(freq_table):
            for v, variable in enumerate(group):
                for l, level in enumerate(variable):
                    freq_table[row][v][l] += self.initial_freq_table[row][v][l]

    def remove_allocation(self, row=-1):
        # remove the selected allocation
        # row = -1 means the last allocation
        model = self.allocations_treeview.get_model()
        # list is empty
        if model == None or len(model) == 0:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
            return False
        # row = -1 is sufficient, no need to change into len(model) -1. Only to clear the issue
        if row == -1:
            row = len(model) -1
        ui = model[row][1]
        # UI of deleted case back into the pool
        # reorder the model to unsourted state
        model.set_sort_column_id(0, gtk.SORT_ASCENDING)
        # finding the new row which holds the ui
        for row in range(len(model)):
            # the selected subject still present in the list, so we got the row and exit the for loop
            if model[row][1] == ui:
                break
        else:
            # another user has changed the data
            functions.error_dialog(self.window, self._('non_updated_data'), self._('data_not_updated'))            
            return False
        del_case = self.allocations.pop(row)
        self.ui_pool.append(del_case['UI'])
        self.random.shuffle(self.ui_pool)
        path = (row,)
        iter = model.get_iter(path)
        # removing the selected subject
        model.remove(iter)
        self.set_progressbar_status()
        return True

    def allocations_delete(self, ui, prompt=False):
        # delete the subject with specified ui. No prompt by default
        if self.network_sync_dict['sync'] and self.trial_file_name:
            # update the network trial
            repo_path = self.update_network_trial()
        model = self.allocations_treeview.get_model()
        # empty model
        if model and len(model) == 0:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
            return False
        # check if the model has changed since the last save
        for row in range(len(model)):
            # the selected subject still present in the list, so we got the row and exit the for loop
            if model[row][1] == ui:
                break
        else:
            # another user has changed the data
            functions.error_dialog(self.window, self._('non_updated_data'), self._('data_not_updated'))            
            return False
        if prompt:
            msg = self._('allocations_delete_msg').format(ui)
            dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
            dialog.set_title(self._('allocations_delete_dialog_title'))
            if dialog.run() == gtk.RESPONSE_NO:
                dialog.destroy()
                return False
            dialog.destroy()
        # removing the selected subject
        self.remove_allocation(row)
        if self.network_sync_dict['sync']:
            path = repo_path
        else:
            path = self.trial_file_name
        self.save_trial(path)
        # if the list is empty, check if the user likes to unlock the trial
        if row != -1 and prompt:
            if model == None or len(model) == 0:
                if self.trial_file_name:
                    self.want_trial_unlock(True)

    def allocations_delete_button(self, widget, data=None):
        # event function for deleting selected subject
        model = self.allocations_treeview.get_model()
        # if list is empty, consider trial unlock
        if model and len(model) == 0:
            # unlock
            if self.trial_file_name:
                self.want_trial_unlock(True)
                return False
            # no unloack wanted. Say the list is empty and return
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
            return False
        # if a subject is selected, obtain the row and UI of it
        if self.allocations_treeview.get_cursor()[0]:
            selected_row = self.allocations_treeview.get_cursor()[0][0]
            selected_ui = model[selected_row][1]
        else:
            # no selection, exit
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_please_select_an_allocation_first'))
            return False
        # updating the model
        model = self.allocations_treeview.get_model()
        if model == None or len(model) == 0:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
            return False
        # It is required to select based on the UI of the selected row,
        # because another user may have changed the data or has deleted the selected recoded and
        # therefore the displayed data are not uptodate
        self.waiting_function(self.allocations_delete, (selected_ui, True))

    def allocations_clear(self):
        # clear subjects list
        if self.network_sync_dict['sync'] and self.trial_file_name:
            repo_path = self.update_network_trial()
        model = self.allocations_treeview.get_model()
        if model == None or len(model) == 0:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_allocation_table_is_empy'))
            return
        model = self.allocations_treeview.get_model()
        # first recycling the UIs
        for row in range(len(model)):
            self.ui_pool.append(self.allocations[row]['UI'])
        self.random.shuffle(self.ui_pool)
        # then clear the list
        model.clear()
        # and the aloocations list
        self.allocations = []
        if self.network_sync_dict['sync']:
            path = repo_path
        else:
            path = self.trial_file_name
        self.save_trial(path)

    def allocations_clear_button(self, widget, data=None):
        # event function for allocations clear
        self.waiting_function(self.allocations_clear, ())

    def add_one_allocation(self, add_random_case=False):
        ui = self.ui_pool.pop()
        new_case = {'levels': [], 'allocation': -1, 'UI': ui}
        # set the levels of this new case
        for cbo in self.variable_combos:
            # if random
            if add_random_case:
                new_case['levels'].append(self.random.choice(range(len(cbo.get_model()))))
            else:
                # appending the selected level to the levels of new case
                new_case['levels'].append(cbo.get_active())
        # we have our case, now minimize it
        m_group = self.get_minimize_case(new_case)
        # if no error, use the generated group
        if m_group > -1:
            # set the allocation of the new case
            new_case['allocation'] = m_group
            # append the new case to the list of subjects
            case_properties = self.get_case_properties()
            if case_properties:
                new_case['properties'] = case_properties
            self.allocations.append(new_case)

    def refresh_allocations_treeview(self):
        model = self.allocations_treeview.get_model()
        # now refresh the allocations treeview
        model.clear()
        # process one case each time
        for row, case in enumerate(self.allocations):
            model.append()
            # the seq (#)
            model[row][0] = row
            # UI
            UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
            model[row][1] = str(case['UI']).zfill(UI_len)
            # group
            model[row][2] = self.group_liststore[case['allocation']][0]
            # set the levels of each variable for this case
            for i, level in enumerate(case['levels']):
                # labels of levels in this variable
                cbo_model = self.variable_combos[i].get_model()
                # using this label
                model[row][3+i] = cbo_model[level][0]
        model.clear()
        # process one case each time
        for row, case in enumerate(self.allocations):
            model.append()
            # the seq (#)
            model[row][0] = row
            # UI
            UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
            model[row][1] = str(case['UI']).zfill(UI_len)
            # group
            model[row][2] = self.group_liststore[case['allocation']][0]
            # set the levels of each variable for this case
            for i, level in enumerate(case['levels']):
                # labels of levels in this variable
                cbo_model = self.variable_combos[i].get_model()
                # using this label
                model[row][3+i] = cbo_model[level][0]
        return model[-1][0], model[-1][1]

    def allocations_add_all(self):
        # for research: all remaining subjects will be minimized
        # first update the trial
        if self.network_sync_dict['sync'] and self.trial_file_name:
            repo_path = self.update_network_trial()
        model = self.allocations_treeview.get_model()
        # empty model
        if not model:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_groups_prognostic_factors_must_be_defined'))
            return False
        # empty UI pool
        if not self.ui_pool:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_trial_finished_or_not_saved'))
            return False
        # consume all UIs
        model.set_sort_column_id(0, gtk.SORT_ASCENDING)
        while self.ui_pool:
            self.add_one_allocation(add_random_case=True)
        row, ui = self.refresh_allocations_treeview()
        functions.treeview_scroll_select_row(self.window, self.allocations_treeview, row)
        if self.network_sync_dict['sync']:
            path = repo_path
        else:
            path = self.trial_file_name
        self.save_trial(path)

    def allocations_add_all_button(self, widget, data=None):
        # event function for adding all allocations
        self.waiting_function(self.allocations_add_all, ())

    def random_case_button(self, button, data=None):
        # generate a random case and set the variable widgets with it
        # go through every variable widget
        for cbo in self.variable_combos:
            # set its active text randomly
            item = self.random.choice(range(len(cbo.get_model())))
            cbo.set_active(item)
        self.allocations_add_button(None, None)

    def allocations_add(self):
        # add one allocation (uses self.add_one_allocation to complete its job)
        # we have to save the current selections of variable widgets prior to update. because
        # the network update resets all variable widgets
        cbo_selects = []
        # gor through each variable widget and capture its current value (level)
        for cbo in self.variable_combos:
            # if nothing is selected, warn and exit
            if cbo.get_active() == -1:
                self.statusbar.pop(self.sb_context_id)
                self.statusbar.push(self.sb_context_id, self._('statusbar_factor_levels_not_selected'))
                return False
            # capture the current selection
            cbo_selects.append(cbo.get_active())
        # update network trial
        if self.network_sync_dict['sync'] and self.trial_file_name:
            repo_path = self.update_network_trial()
            # restore the selections of variable widgets
            for i, cbo in enumerate(self.variable_combos):
                cbo.set_active(cbo_selects[i])
        model = self.allocations_treeview.get_model()
        # trial not initialized. factors and groups not defined
        if not model:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_groups_factors_defined_first'))
            return False
        # UI pool is empty
        if not self.ui_pool:
            # sample size completed
            if len(model):
                if not self.set_extra_sample_size():
                    return False
                self.allocations_add()
                return
            # trial not saved
            else:
                self.statusbar.pop(self.sb_context_id)
                self.statusbar.push(self.sb_context_id, self._('statusbar_trial_not_saved'))
                return False
        # add one allocation and get the row and UI of new subject
        self.add_one_allocation()
        row, ui = self.refresh_allocations_treeview()
        # report the new allocation and ask confirmation (may be it is safer to update
        # network trial, then delete the case). Ignore this if this is for research 
        if not self.config.getboolean('interface', 'batch_allocation'):
            if not self.report_allocation(model):
                # not confirmed, delete it.
                # recycle the UI
                del_case = self.allocations.pop(row)
                self.ui_pool.append(del_case['UI'])
                self.random.shuffle(self.ui_pool)
                # delete the new case from the allocations treeview and allocations list
                path = (row,)
                iter = model.get_iter(path)
                model.remove(iter)
                return
        # save the changes
        if self.network_sync_dict['sync']:
            path = repo_path
        else:
            path = self.trial_file_name
        self.save_trial(path)
        # scroll down to the new case
        functions.treeview_scroll_select_row(self.window, self.allocations_treeview, row)
        # if this was the last case, ask for sample size extension
        if len(self.ui_pool) == 0:
            self.end_trial()

    def trial_refresh(self):
        if self.network_sync_dict['sync'] and self.trial_file_name:
            repo_path = self.update_network_trial()

    def trial_refresh_button(self, widget, data=None):
        self.waiting_function(self.trial_refresh, ())

    def allocations_add_button(self, widget, data=None):
        if not self.trial_file_name: return
        if self.variable_combos_dialog.run() != gtk.RESPONSE_OK: return
        # event function for adding an allocation
        self.waiting_function(self.allocations_add, ())

    def report_allocation(self, model):
        # textual reporting of a new allocation and asking for confirmation
        column = self.allocations_treeview.get_columns()
        row = len(model)-1
        ret = ['\n']
        # obtaining all information of the new case
        for col, column in enumerate(column):
            if col == 2:
                group = model[row][col]
            else:
                ret.append(column.get_title() + ': {0}'.format(model[row][col]))
        ret.append('\n')
        ret.append('{0} {1}'.format(self._('enrolled_to'), group))
        # if dialog is not desired return here
        # display the dialog and ask to confirm the case
        msg = self._('allocating_new_case').format('\n'.join(ret))
        dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
        dialog.set_title(self._('new_allocation'))
        if dialog.run() == gtk.RESPONSE_YES:
            dialog.destroy()
            # case is valid
            return True
        dialog.destroy()
        # case is not valid
        return False

    def end_trial(self):
        # ask if user wants to extend the sample
        msg = self._('extend_sample').format(len(self.allocations))
        dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
        dialog.set_title(self._('trial_finished'))
        if dialog.run() == gtk.RESPONSE_YES:
            dialog.destroy()
            # if yes, then ask how much to extend and save the change in sample size
            return self.set_extra_sample_size()
        dialog.destroy()

    def set_extra_sample_size(self):
        # manage extra sample size
        # extra sample defaults to 0
        extra_sample = 0
        # this function prompts the user to enter an extra sample size
        extra_sample = functions.simple_spin_dialog(self._('extra_sample'), self.window)
        # if it zero return
        if extra_sample == 0: return False
        # total sample size
        ss = len(self.allocations)+int(extra_sample)
        # set the new total sample size
        self.trial_sample_size_spin.set_value(ss)
        # build extra UIs. Pass the list of extra UIs to the method for format it
        self.build_ui_pool(range(len(self.allocations), ss))
        # saving changes. Set the save_sample_size flag to save the sample size
        self.save_trial_changes(save_sample_size=True)
        return True

    def refresh_freq_table(self):
        # refresh the frequency table
        # create a Model object and setting it parameters
        model = Model()
        model.groups = range(len(self.group_liststore))
        model.variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
        model.variables_weight = [self.variable_liststore[row][1] for row in range(len(self.variable_liststore))]
        model.allocation_ratio = [self.group_liststore[row][1] for row in range(len(self.group_liststore))]
        model.allocations = self.allocations
        # create a Minim object based on the supplied Model and random
        m = Minim(random=self.random, model=model)
        # rebuild the frequency table
        m.build_freq_table()
        # if an initial table add to it
        if self.initial_freq_table:
            self.add_to_initial(m.freq_table)
        # no subject
        if not len(m.freq_table):
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_no_allocation'))
            return False
        # refreshin. First delete the frequency table cols
        n = len(self.freq_table_treeview.get_columns())
        while n:
            n = self.freq_table_treeview.remove_column(self.freq_table_treeview.get_column(n-1))
        # then build a list containing names of varable levels
        # first an empty list
        column_names = []
        # extend it for levels of each variable
        for variable in self.variable_liststore:
            column_names.extend([level for level in map(str.strip, variable[2].split(','))])
        # prepend a col for group names and append another col for row total
        column_names = [self._('general_group')] + column_names + [self._('general_total')]
        # how many cols this table has
        cols = 0
        for var in m.freq_table[0]:
            cols += len(var)
        # types of cols. first one is for group names, others are numeric
        col_types = [str] + [int] * (cols + 1)
        # create the liststore
        liststore = gtk.ListStore(*col_types)
        # create the columns
        for n in range(len(column_names)):
            tvcolumn = gtk.TreeViewColumn(column_names[n])
            self.freq_table_treeview.append_column(tvcolumn)
            cell = gtk.CellRendererText()
            tvcolumn.pack_start(cell, True)
            tvcolumn.add_attribute(cell, 'text', n)
            tvcolumn.set_resizable(True)
            tvcolumn.set_expand(True)
        # set the model of treeview
        self.freq_table_treeview.set_model(liststore)
        # adding data to the model
        for row, group in enumerate(m.freq_table):
            liststore.append()
            # first col is group names
            liststore[row][0] = self.group_liststore[row][0]
            col = 1
            # other cols are for levels of variables
            for variable in group:
                for level in variable:
                    liststore[row][col] = level
                    col += 1
            # last col is row total
            liststore[row][col] = sum(variable)
        # finally addan extra row for col totals
        liststore.append()
        liststore[len(m.freq_table)][0] = self._('general_total')
        # calculating col totals
        total = 0
        for c in range(1, col):
            col_total = sum([liststore[row][c] for row in range(len(m.freq_table))])
            # calculating grand total too
            total += col_total
            # setting col total
            liststore[len(m.freq_table)][c] = col_total
        # since grand total have need calculated many times (each for one variable,
        # so we have to divide the sum by the number of variables
        liststore[len(m.freq_table)][c+1] = total / len(self.variable_liststore)
        # set editable property to true, if the button label is ...
        if self.freq_table_enable_edit_button.get_label() == gtk.STOCK_SAVE_AS_INITIAL_TABLE:
            self.freq_table_enable_edit()

    def notebook_switch_page(self, page_num):
        # function to manage notebook page switch
        # display a status bar message specific to each page
        self.statusbar.pop(self.sb_context_id)
        self.statusbar.push(self.sb_context_id, self.notbook_tabs[page_num])
        # nothing for 4 pages
        if page_num < 4: return
        # if trial data are not valid do not rebuild the frequency table
        if not self.trial_is_valid(show_msg=False, table_edit=True): return
        # it table is still editable, do not change it
        if self.freq_table_enable_edit_button.get_label() == gtk.STOCK_SAVE_AS_INITIAL_TABLE: return
        # refresh the table
        self.refresh_freq_table()
        # and the balance table
        self.balance_table_refresh()

    def notebook_switch_page_event(self, notebook, page, page_num, data=None):
        if page_num == 6: # help
            self.window.set_focus(self.about_text)
        # event function for switch page event
        # only for table and balance pages
        if not page_num in (4, 5): return
        self.waiting_function(self.notebook_switch_page, (page_num,))

    def trial_properties_cell_edited(self, cell, row, new_text, col):
        # event function for cell edit event
        self.trial_properties_liststore[row][col] = new_text

    def case_properties_cell_edited(self, cell, row, new_text, col):
        # event function for cell edit event
        self.case_properties_liststore[row][col] = new_text

    def trial_properties_add_button(self, widget, data=None):
        # event function for add trial property event
        self.trial_properties_liststore.append((self._('property_name'), self._('property_value')))

    def case_properties_add_button(self, widget, data=None):
        # event function for add trial property event
        self.case_properties_liststore.append((self._('property_name'), self._('property_value')))

    def trial_properties_date_button(self, widget, data=None):
        # event function for add date property event
        self.trial_properties_liststore.append((self._('started_on'), time.ctime()))

    def case_properties_date_button(self, widget, data=None):
        # event function for add date property event
        self.case_properties_liststore.append((self._('enrolled_on'), time.ctime()))

    def trial_properties_delete_button(self, widget, data=None):
        # event function for delete property event
        if self.network_sync_dict['sync'] and self.trial_file_name:
            # with network trials, deleting trial properties after saving the trials may be too complicated.
            return False
        if self.trial_properties_treeview.get_cursor()[0]:
            row = self.trial_properties_treeview.get_cursor()[0][0]
            self.trial_properties_liststore.remove(self.trial_properties_liststore.get_iter(row))

    def case_properties_delete_button(self, widget, data=None):
        # event function for delete property event
        if self.case_properties_treeview.get_cursor()[0]:
            row = self.case_properties_treeview.get_cursor()[0][0]
            self.case_properties_liststore.remove(self.case_properties_liststore.get_iter(row))

    def show_info_message(self, widget, event, message, tooltip):
        # a general porpuse function for displaying extended info about an item
        dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK, message_format = message)
        dialog.set_title(tooltip)
        dialog.run()
        dialog.destroy()

    def create_image_info(self, parent, tooltip, message=""):
        # a function for creating tootip and clickable extended help
        eb = gtk.EventBox()
        img = gtk.Image()
        image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'b_info.png')
        img.set_from_file(image_file)
        eb.add(img)
        if len(message):
            eb.connect("button-press-event", self.show_info_message, message, tooltip)
            tooltip += self._("click_to_see_more")
        img.set_tooltip_text(tooltip)
        img.set_has_tooltip(True)
        parent.pack_start(eb, False, False)

    def network_sync_ssl_server_trust_prompt(self, trust_dict):
        # function for providing ssl certificate, if necessary
        return True, 3, True

    def network_sync_get_login(self, realm, username, may_save):
        # function for providing account info for network trial, if necessary
        self.get_repo_login()
        return self.network_sync_dict['auth'], self.network_sync_user, self.network_sync_pw, True

    def network_sync_chk_toggled(self, chk, data=None):
        # network sync checkbox toggled
        # if it goes active, display the network sync dialog
        if not chk.get_active():
            self.network_sync_dict['sync'] = False
            return
        # building the dialog
        dlg = gtk.Dialog(title= self._('network_sync'),
                                 parent=self.window,
                                 flags=gtk.DIALOG_MODAL,
                                 buttons=(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
        dlg.set_default_response(gtk.RESPONSE_APPLY)
        dlg.set_has_separator(True)
        lbl = gtk.Label(self._('enter_base_url'))
        lbl.set_line_wrap(True)
        dlg.vbox.pack_start(lbl)
        sep = gtk.HSeparator()
        dlg.vbox.pack_start(sep)
        hb = gtk.HBox(False)
        lbl = gtk.Label(self._('repository_url'))
        hb.pack_start(lbl, False, False)
        # base usrl of the repository for network sync
        url = gtk.Entry()
        if self.network_sync_dict.has_key('url'):
            url.set_text(self.network_sync_dict['url'])
        hb.pack_start(url, True, True)
        dlg.vbox.pack_start(hb)
        auth = gtk.CheckButton(self._('requires_authentication'))
        auth.set_active(True)
        dlg.vbox.show_all()
        controls = url, auth, chk
        # event function for different dialog responses
        dlg.connect('response', self.network_sync_dialog_respnse, controls)
        dlg.run()

    def network_sync_dialog_respnse(self, dialog, response_id, controls):
        # if cancel ot close, unset the network sync checkbox
        if response_id in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
            controls[-1].set_active(False)
            dialog.hide()
            return
        # an apply response
        url, auth, chk = controls
        # url can not be empty
        if url.get_text() == '':
            dialog.set_focus(url)
            return
        # setting the sync dict
        self.network_sync_dict['sync'] = True
        # trailing slashes abort the program suddenly and print
        # "svn_path_is_canonical(path, pool)" to the sdout
        # so this is to resolve this problem
        self.network_sync_dict['url'] = url.get_text().strip('/')
        self.network_sync_dict['auth'] = auth.get_active()
        dialog.hide()

    def get_repo_login(self):
        # return if not authentication required
        if not self.network_sync_dict['auth']: return False
        # building the dialog for entering user and pw
        dlg = gtk.Dialog(title= self._('network_login'),
                                 parent=self.window,
                                 flags=gtk.DIALOG_MODAL,
                                 buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
        dlg.set_default_response(gtk.RESPONSE_OK)
        dlg.set_has_separator(True)
        lbl = gtk.Label(self._('enter_user_pw').format(self.network_sync_dict['url']))
        dlg.vbox.pack_start(lbl)
        hb = gtk.HBox(False)
        lbl = gtk.Label(self._('username') + ': ')
        hb.pack_start(lbl, False, False)
        user = gtk.Entry()
        user.set_text(self.network_sync_user)
        hb.pack_start(user, True, True)
        dlg.vbox.pack_start(hb)
        hb = gtk.HBox(False)
        lbl = gtk.Label(self._('password') + ': ')
        hb.pack_start(lbl, False, False)
        pw = gtk.Entry()
        pw.set_visibility(False)
        pw.set_text(self.network_sync_pw)
        hb.pack_start(pw, True, True)
        dlg.vbox.pack_start(hb)
        dlg.vbox.show_all()
        controls = user, pw
        dlg.connect('response', self.get_repo_login_respnse, controls)
        controls = user, pw, dlg
        # either of two textboxes may be pressed by enter key
        user.connect('activate', self.user_pw_event, controls)
        pw.connect('activate', self.user_pw_event, controls)
        dlg.run()

    def user_pw_event(self, entry, controls):
        # event function for enter key press in user or pw textboxes
        user, pw, dialog = controls
        if user.get_text() == '':
            dialog.set_focus(user)
            return
        if pw.get_text() == '':
            dialog.set_focus(pw)
            return
        self.network_sync_user = user.get_text()
        self.network_sync_pw = pw.get_text()
        dialog.hide()

    def get_repo_login_respnse(self, dialog, response_id, controls):
        # event function for clicking login dialog button or closing it
        if response_id in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
            dialog.hide()
            self.network_sync_cancel_command = True
            return
        user, pw = controls
        if user.get_text() == '':
            dialog.set_focus(user)
            return
        if pw.get_text() == '':
            dialog.set_focus(pw)
            return
        self.network_sync_user = user.get_text()
        self.network_sync_pw = pw.get_text()
        dialog.hide()

    def variable_treeview_row_activated(self, treeview, path, view_column, data=None):
        # event function for editing a variable
        if self.variable_vbuttonbox.get_property('visible'):
            EditVariable(self, path[0])

    def filemenu_response(self, widget, data=None):
        # this correction is needed, because of different locale data
        dot_pos = data.index('.')
        data = data[dot_pos+1:]
        if data == "new":
            self.new_trial_clicked()
        elif data == "open":
            self.load_trial_clicked()
        elif data == "save":
            self.save_trial_clicked()
        elif data == "refresh":
            self.trial_refresh_button(None, None)
        elif data == "quit":
            self.delete_event(None, None)
        elif data == "add":
            pass
            #self.delete_event(None, None)

    def toolmenu_response(self, widget, data=None):
        # this correction is needed, because of different locale data
        dot_pos = data.index('.')
        data = data[dot_pos+1:]
        if data == "import":
            self.allocations_import_button()
        elif data == "export":
            self.allocations_export_button()
        elif data == "information":
            self.trial_info_button_clicked()
        elif data == "preferences":
            self.pref_clicked()

    def helpmenu_response(self, widget, data=None):
        # this correction is needed, because of different locale data
        dot_pos = data.index('.')
        data = data[dot_pos+1:]
        if data == "help":
            self.notebook.set_current_page(6)
        elif data == "about":
            dialog = gtk.AboutDialog()
            dialog.set_name("MinimPy Program")
            dialog.set_version("0.3")
            dialog.set_copyright("Copyright (c) 2010-2011 Mahmoud Saghaei")
            dialog.set_license("Distributed under the GNU GPL v3.\nFor full terms refer to http://www.gnu.org/copyleft/gpl.html.")
            dialog.set_website("http://minimpy.sourceforge.net")
            dialog.set_authors(["Mahmoud Saghaei"])
            dialog.set_logo(self.pixbuf)
            dialog.run()
            dialog.destroy()
            return False

    def addmenu_response(self, widget, data=None):
        # this correction is needed, because of different locale data
        dot_pos = data.index('.')
        data = data[dot_pos+1:]
        if data == "group":
            self.notebook.set_current_page(1)
            if self.group_vbuttonbox.get_property("visible"):
                self.group_add_button(None, None)
                self.window.set_focus(self.group_treeview)
        elif data == "variable":
            self.notebook.set_current_page(2)
            if self.variable_vbuttonbox.get_property("visible"):
                self.variable_add_button(None, None)
                self.window.set_focus(self.variable_treeview)
        elif data == "allocation":
            self.notebook.set_current_page(3)
            self.allocations_add_button(None, None)
        elif data == "trial_property":
            self.notebook.set_current_page(0)
            self.trial_properties_add_button(None, None)
            self.window.set_focus(self.trial_properties_treeview)

    def __init__(self):
        # restart only after locale change
        self.restart = False
        # reading local configuration
        self.config = Config()
        self.first_run = self.config.first_run
        # loading locale specific translatable strings into a dict
        fp = open(os.path.join(os.path.dirname(sys.argv[0]), 'locale', self.config.get('interface', 'locale'), 'locale.dat'), 'rb')
        self.tr_dict = pickle.load(fp)
        fp.close()
        # addin some stock items
        Stock_Class(self)
        # a list of temp files and folders used by this application. To be used on exit
        self.used_temp_files = []
        # persisting the working directory
        self.file_chooser_current_folder = os.getcwd()
        # if this become true, the network_sync_cancel function will terminate the current connecting attempt
        self.network_sync_cancel_command = False
        # the default random number generator. This can be chnaged in the preferences
        self.random = functions.get_app_random(self.config)
        # setting the trial file name, based on the program configuration, to either the last one or to None
        if self.config.getboolean('project', 'load_recent'):
            self.trial_file_name = self.config.get('project', 'recent_trial')
        else:
            self.trial_file_name = None
        # setting info for each tab. Switching the pages will display this in the statusbar
        self.notbook_tabs = []
        # unique identifier of each allocation from this pool
        self.ui_pool = []
        # optional preloading of trial with an already allocated sample. The default is an empty table
        self.initial_freq_table = False
        # empy list of allocations
        self.allocations = []
        # sync = true: use network syncing, url is the repository url, auth = true: authentication required
        self.network_sync_dict = dict(sync=False, url='', auth=False)
        # user and pw of the repository when auth = true
        self.network_sync_user = ''
        self.network_sync_pw = ''
        # gtk window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event", self.delete_event)
        self.window.set_border_width(2)
        # window size will ne near maximal depending on the screen resolution. No maximize (problem in some Linuxs)
        self.window.set_size_request(int(0.99 * gtk.gdk.screen_width()), int(0.85 * gtk.gdk.screen_height()))
        # required modlues: most are installed by default. Exceptions may be: pygtk, gtk, gobject, pysvn
        module_list = ['os', 'sys', 'pickle', 'tempfile', 'ConfigParser', 'shutil', 'time', 'math', 'random', 'pygtk', 'gtk', 'gobject', 'pickle', 'pysvn']
        # a function to check the dependency and displaying an error dialog if missing. This may be useless if 
        # the program can not display the dialog due to lack of gtk ad related. May be it is better to use 
        # python's intrinsic GUI classes and functions (tkinter) for this purpose
        ret = functions.check_dependencies(module_list)
        if ret:
            msg = self._('required_module_msq').format('\t'.join(ret))
            functions.error_dialog(self.window, msg, self._('module_not_found'))
            self.window.destroy()
            gtk.main_quit()
        # a dialog to display when syncing
        label = gtk.Label("")
        label.show()
        dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        dialog.set_title("")
        dialog.vbox.pack_end(label)
        self.network_sync_dialog = dialog
        self.network_sync_dialog_label = label
        self.variable_combos_dialog = self.build_variable_combos_dialog()
        # interface notebook
        self.accel_group = gtk.AccelGroup()
        self.window.add_accel_group(self.accel_group)
        menu_items = ("New:<Control>N", "Open:<Control>O", "-", "Save:<Control>S", "-", "Refresh:F5", "-", "Quit:<Control>Q")
        file_item = functions.create_menu(self._("_file"), menu_items, self.accel_group, self.filemenu_response)
        menu_items = ("Import:<Control>M", "Export:<Control>E", "-", "Information:<Control>I", "-", "Preferences:<Control>R")
        tool_item = functions.create_menu(self._("_tools"), menu_items, self.accel_group, self.toolmenu_response)
        menu_items = ("Help:F1", "-", "_About")
        help_item = functions.create_menu(self._("_help"), menu_items, self.accel_group, self.helpmenu_response)
        menu_bar = gtk.MenuBar()
        menu_bar.append(file_item)
        menu_bar.append(tool_item)
        menu_bar.append(help_item)
        self.top_menu_bar_hbox = gtk.HBox(False, 2)
        self.top_menu_bar_hbox.pack_start(menu_bar, True, True)

        toolbar = gtk.Toolbar()
        tool_button = functions.add_tool_button(toolbar, self._("add"), gtk.STOCK_ADD, self.filemenu_response, "file.add")
        self.top_menu_bar_hbox.pack_start(toolbar, True, True)
        menu_items = ("Allocation:<Control>A", "Group:<Control>G", "Variable:<Control>V", "Trial Property:<Control>T")
        add_item = functions.create_menu(self._("_add"), menu_items, self.accel_group, self.addmenu_response)
        submenu = add_item.get_submenu()
        add_item.remove_submenu()
        tool_button.set_menu(submenu)
        tool_button.connect('clicked', self.allocations_add_button)

        self.notebook = gtk.Notebook()
        # tab position preference
        self.notebook.set_tab_pos(self.config.getint('interface', 'tab_pos'))
        # right clicking and displaying a manu composed of tabs
        self.notebook.popup_enable()
        # switching the pages bring something depend on the page
        self.notebook.connect("switch-page", self.notebook_switch_page_event)
        # program logo
        img = gtk.Image()
        image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'logo.png')
        img.set_from_file(image_file)
        img.show()
        self.pixbuf = img.get_pixbuf()
        # main container for notebook and statusbar
        win_vbox = gtk.VBox(False)
        win_vbox.pack_start(self.top_menu_bar_hbox, False, False)
        win_vbox.pack_start(self.notebook, True, True)
        # a container for statusbar and network sync icon
        hb = gtk.HBox(False)
        self.statusbar = gtk.Statusbar()
        hb.pack_start(self.statusbar, True, True)
        # progressbar showing the progress of trial
        self.allocations_progressbar = gtk.ProgressBar()
        if self.config.get('interface', 'layout_dir') == 'rtl':
            self.allocations_progressbar.set_orientation(gtk.PROGRESS_RIGHT_TO_LEFT)
        elif self.config.get('interface', 'layout_dir') == 'ltr':
            self.allocations_progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
        hb.pack_start(self.allocations_progressbar, True, True)
        # container for network syncing
        icon_box = gtk.HBox(False)
        self.network_sync_icon = gtk.Image()
        self.network_sync_icon.set_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_SMALL_TOOLBAR)
        self.network_sync_icon.set_tooltip_text(self._('network_sync_enabled'))
        icon_box.pack_start(self.network_sync_icon, False, False)
        hb.pack_start(icon_box, False, False)
        win_vbox.pack_start(hb, False, False, 0)
        # setting the statusbar context id. This will be used when displaying text on statusbar
        self.sb_context_id = self.statusbar.get_context_id("Statusbar")
        # container for trial title and sample size
        nb_vbx = gtk.VBox(False)
        hbx1 = gtk.HBox(False)

        label = gtk.Label(self._("trial_title") + ": ")
        hbx1.pack_start(label, False, False)
        # a compact function to set an informative icon for tooltip and further help
        self.create_image_info(hbx1, self._("trial_title"), self._("trial_title_info"))
        # textbox for trial title
        self.trial_title_entry = gtk.Entry()
        hbx1.pack_start(self.trial_title_entry, True, True)
        # label and spin button for sample size
        label = gtk.Label(self._("sample_size") + ": ")
        hbx1.pack_start(label, False, False)

        self.create_image_info(hbx1, self._("sample_size"), self._("sample_size_info"))
        # an adjustment object for sample size spin button
        adj = gtk.Adjustment(value=30, lower=5, upper=1000000, step_incr=1, page_incr=10)
        self.trial_sample_size_spin = gtk.SpinButton(adj)
        hbx1.pack_start(self.trial_sample_size_spin, False, False)
        nb_vbx.pack_start(hbx1, False, False)
        # next row is the trial discription
        hbx2 = gtk.HBox(False)
        label = gtk.Label(self._("description") + ": ")
        hbx2.pack_start(label, False, False)

        self.create_image_info(hbx2, self._("trial_description"), self._("trial_description_info"))

        nb_vbx.pack_start(hbx2, False, False)
        # horizontal separator line
        sep = gtk.HSeparator()
        nb_vbx.pack_start(sep, False, False)
        hbx3 = gtk.HBox(False)
        sep = gtk.VSeparator()
        hbx3.pack_start(sep, False, False)
        self.trial_description_text = gtk.TextView()
        hbx3.pack_start(self.trial_description_text, True, True)
        sep = gtk.VSeparator()
        hbx3.pack_start(sep, False, False)
        nb_vbx.pack_start(hbx3, True, True)
        sep = gtk.HSeparator()
        nb_vbx.pack_start(sep, False, False)
        # setting the probability method radios
        hbx4 = gtk.HBox(False)
        nb_vbx.pack_start(hbx4, True, True)
        label = gtk.Label(self._("probability_method") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(label, False, False)

        self.create_image_info(hb, self._("probability_method"), self._("probability_method_info"))
        # biased coin
        vbox_prob = gtk.VBox(False)
        vbox_prob.pack_start(hb, False, False)
        radio = gtk.RadioButton(None, label= self._("biased_coin_minimization"))
        vbox_prob.pack_start(radio, False, False)
        # naive
        radio = gtk.RadioButton(radio, label= self._("naive_minimization"))
        vbox_prob.pack_start(radio, False, False)
        # this method returns the radios in revese order
        self.prob_method_radios = radio.get_group()
        # so we need to invert the returned list
        self.prob_method_radios.reverse()
        # the value of high probability for the group with the least allocation ratio
        hb = gtk.HBox(False)
        lbl = gtk.Label(self._("high_probability") + ": ")
        hb.pack_start(lbl, False, False)

        self.create_image_info(hb, self._("high_probability_tip"), self._("high_probability_info"))
        # adjustment object for the high probabilty spin button
        adj = gtk.Adjustment(value=0.7, lower=0.1, upper=1.0, step_incr=0.01, page_incr=0.1)
        self.high_prob_spin = gtk.SpinButton(adj, digits=2)
        hb.pack_start(self.high_prob_spin, False, False)
        vbox_prob.pack_start(hb, False, False)
        hbx4.pack_start(vbox_prob, False, False)
        sep = gtk.VSeparator()
        hbx4.pack_start(sep, False, False)
        # distance measure
        label = gtk.Label(self._("distance_measure") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(label, False, False)

        self.create_image_info(hb, self._("distance_measure_tip"))

        vbox = gtk.VBox(False)
        vbox.pack_start(hb, False, False)
        # marginal balance
        radio = gtk.RadioButton(None, label= self._("marginal_balance") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(radio, False, False)
        self.create_image_info(hb, self._("marginal_balance"), self._("marginal_balance_info"))
        
        vbox.pack_start(hb, False, False)
        # range
        radio = gtk.RadioButton(radio, label= self._("range") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(radio, False, False)
        vbox.pack_start(hb, False, False)
        self.create_image_info(hb, self._("range"), self._("range_info"))
        # SD
        radio = gtk.RadioButton(radio, label= self._("standard_deviation") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(radio, False, False)
        vbox.pack_start(hb, False, False)
        self.create_image_info(hb, self._("standard_deviation"), self._("standard_deviation_info"))
        # variance
        radio = gtk.RadioButton(radio, label= self._("variance") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(radio, False, False)
        vbox.pack_start(hb, False, False)
        self.create_image_info(hb, self._("variance"), self._("variance_info"))

        hbx4.pack_start(vbox, False, False)
        self.distance_measure_radios = radio.get_group()
        self.distance_measure_radios.reverse()
        sep = gtk.VSeparator()
        hbx4.pack_start(sep, False, False)
        # miscelaneous trial properties
        vbox = gtk.VBox(False)
        lbl = gtk.Label(self._("trial_properties") + ": ")
        hb = gtk.HBox(False)
        hb.pack_start(lbl, False, False)
        vbox.pack_start(hb, False, False)
        self.create_image_info(hb, self._("trial_properties"), self._("trial_properties_info"))

        hb = gtk.HBox(False)
        self.trial_properties_liststore, self.trial_properties_treeview = functions.make_treeview(
        (str, str), [self._('name'), self._('value')],
        editable=True, edit_handler=self.trial_properties_cell_edited)
        functions.make_scrolling(self.trial_properties_treeview, hb)
        vbuttonbox = gtk.VButtonBox()
        vbuttonbox.set_layout(gtk.BUTTONBOX_START)
        button = gtk.Button(None, gtk.STOCK_ADD)
        button.connect("clicked", self.trial_properties_add_button)
        vbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DELETE)
        button.connect("clicked", self.trial_properties_delete_button)
        vbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DATE)
        button.connect("clicked", self.trial_properties_date_button)
        vbuttonbox.pack_start(button, False, False)
        hb.pack_start(vbuttonbox, False, False)
        vbox.pack_start(hb, False, False)

        hbx4.pack_start(vbox, True, True)
        sep = gtk.VSeparator()
        hbx4.pack_start(sep, False, False)

        sep = gtk.HSeparator()
        nb_vbx.pack_start(sep, False, False)
        # container for buttons in the lower edge of the first notebook page
        hbuttonbox = gtk.HButtonBox()
        hbuttonbox.set_layout(gtk.BUTTONBOX_START)
        self.network_sync_chk = gtk.CheckButton(self._('network_sync'))
        self.network_sync_chk.set_sensitive(False)
        self.network_sync_chk_event_id = self.network_sync_chk.connect("toggled", self.network_sync_chk_toggled)
        hbx1.pack_start(self.network_sync_chk, False, False)
        # pysvn module is needed for syncing
        self.network_sync_chk.set_sensitive(True)

        # till here was the settings
        lbl = gtk.Label(self._("settings_tab"))
        self.notbook_tabs.append(self._("settings_tab_info"))
        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw.add_with_viewport(nb_vbx)
        self.notebook.append_page(sw, lbl)
        # next tab is to manage trial groups
        hbox = gtk.HBox(False)
        # each group has a name and an allocation ration
        # table listing showing the group info is editable
        column_types = (gobject.TYPE_STRING, gobject.TYPE_INT)
        column_names = (self._('group_name'), self._('allocation_ratio'))
        liststore = gtk.ListStore(*column_types)
        treeview = gtk.TreeView(liststore)
        treeview.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
        for n in range(len(column_names)):
            if n == 0:
                cell = gtk.CellRendererText()
            elif n == 1:
                cell = gtk.CellRendererSpin()
                adj = gtk.Adjustment(value=1, lower=1, upper=100, step_incr=1, page_incr=2)
                cell.set_property('adjustment', adj)
            cell.set_property('editable', True)
            cell.connect("edited", self.group_cell_edited, n)
            tvcolumn = gtk.TreeViewColumn(column_names[n], cell, text=n)
            treeview.append_column(tvcolumn)
            tvcolumn.set_resizable(True)
            tvcolumn.set_expand(True)

        self.group_liststore = liststore
        self.group_treeview = treeview
        vb = gtk.VBox(False)
        self.create_image_info(vb, self._('group_table'), self._('group_table_info'))
        functions.make_scrolling(self.group_treeview, vb)
        hbox.pack_start(vb, True, True)
        # add and delete buttons
        vbuttonbox = gtk.VButtonBox()
        vbuttonbox.set_layout(gtk.BUTTONBOX_START)
        button = gtk.Button(None, gtk.STOCK_ADD)
        button.connect("clicked", self.group_add_button)
        vbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DELETE)
        button.connect("clicked", self.group_delete_button)
        vbuttonbox.pack_start(button, False, False)
        hbox.pack_start(vbuttonbox, False, False)
        lbl = gtk.Label(self._('groups_tab'))
        self.notbook_tabs.append(self._("groups_tab_info"))
        self.group_vbuttonbox = vbuttonbox
        self.notebook.append_page(hbox, lbl)
        # next tab is trial variables tab (prognostic factors)
        hbox = gtk.HBox(False)
        # list is editable. each variable has a name, a weight and some levels
        self.variable_liststore, self.variable_treeview = functions.make_treeview(
        (str, float, str), [self._('variable_name'), self._('weight'), self._('levels')],
        editable=False)
        self.variable_treeview.connect('row-activated', self.variable_treeview_row_activated)
        # make the third col uneditable. So the edit is only via EditVariable class
        vb = gtk.VBox(False)
        self.create_image_info(vb, self._("variable_table"), self._("variable_table_info"))
        functions.make_scrolling(self.variable_treeview, vb)
        hbox.pack_start(vb, True, True)
        # buttons for add and delete variables
        vbuttonbox = gtk.VButtonBox()
        vbuttonbox.set_layout(gtk.BUTTONBOX_START)
        button = gtk.Button(None, gtk.STOCK_ADD)
        button.connect("clicked", self.variable_add_button)
        vbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DELETE)
        button.connect("clicked", self.variable_delete_button)
        vbuttonbox.pack_start(button, False, False)
        hbox.pack_start(vbuttonbox, False, False)
        lbl = gtk.Label(self._('variables_tab'))
        self.notbook_tabs.append(self._("variables_tab_info"))
        self.variable_vbuttonbox = vbuttonbox
        self.notebook.append_page(hbox, lbl)

        hbox = gtk.HBox(False)
        vbox = gtk.VBox(False)
        # next tab is to display allocation management. Minimization perform here
        vb = gtk.VBox(False)
        self.create_image_info(vb, self._("allocations_table"), self._("allocations_table_info"))

        hb_button_box = gtk.HBox()
        # button for bacth allocation (research uses): Add all, random case and clear the list
        self.hbuttonbox_batch_mode = gtk.HButtonBox()
        self.hbuttonbox_batch_mode.set_layout(gtk.BUTTONBOX_START)
        button = gtk.Button(None, gtk.STOCK_ADD_ALL)
        button.connect("clicked", self.allocations_add_all_button)
        self.hbuttonbox_batch_mode.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_RANDOM_CASE)
        button.connect("clicked", self.random_case_button)
        self.hbuttonbox_batch_mode.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_CLEAR)
        button.connect("clicked", self.allocations_clear_button)
        self.hbuttonbox_batch_mode.pack_start(button, False, False)

        hb_button_box.pack_start(self.hbuttonbox_batch_mode, True, True)
        # normal button for adding and deleting subjects
        hbuttonbox = gtk.HButtonBox()
        hbuttonbox.set_layout(gtk.BUTTONBOX_START)
        button = gtk.Button(None, gtk.STOCK_ADD)
        button.connect("clicked", self.allocations_add_button)
        hbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_DELETE)
        button.connect("clicked", self.allocations_delete_button)
        hbuttonbox.pack_start(button, False, False)
        button = gtk.Button(None, gtk.STOCK_REFRESH)
        button.connect("clicked", self.trial_refresh_button)
        hbuttonbox.pack_start(button, False, False)
        hb_button_box.pack_start(hbuttonbox, True, True)

        vb.pack_start(hb_button_box, False, False)
        # allocation list is editable, in case some error occured
        self.allocations_treeview = gtk.TreeView()
        self.allocations_treeview.connect('row-activated', self.allocations_edit_event)
        functions.make_scrolling(self.allocations_treeview, vb)
        hbox.pack_start(vb, True, True)

        #self.combo_vbox = gtk.VBox(False)
        #vbox.pack_start(self.combo_vbox, False, False)
        hbox.pack_start(vbox, False, False)

        lbl = gtk.Label(self._('allocations_tab'))
        self.notbook_tabs.append(self._('allocations_tab_info'))
        self.notebook.append_page(hbox, lbl)
        # next tab is the subjects frequency table
        vbox = gtk.VBox(False)
        self.create_image_info(vbox, self._("frequency_table"), self._("frequency_table_info"))
        self.freq_table_treeview = gtk.TreeView()
        functions.make_scrolling(self.freq_table_treeview, vbox)
        self.initial_table_hbox = gtk.HBox(False)
        # buttons for editing and setting the initial frequency table (preloading the allocation)
        self.freq_table_enable_edit_button = gtk.Button(None, gtk.STOCK_START_EDIT)
        self.freq_table_enable_edit_button.connect("clicked", self.freq_table_start_edit_clicked)
        self.initial_table_hbox.pack_start(self.freq_table_enable_edit_button, False, False)
        button = gtk.Button(None, gtk.STOCK_CLEAR_REFRESH)
        button.connect("clicked", self.freq_table_delete_initial_clicked)
        self.initial_table_hbox.pack_start(button, False, False)

        vbox.pack_start(self.initial_table_hbox, False, False)
        lbl = gtk.Label(self._('table_tab'))
        self.notbook_tabs.append(self._("table_tab_info"))
        self.notebook.append_page(vbox, lbl)
        # next tab is the balance tab, showing the trial balance in different scales for different trial items
        hbox = gtk.HBox(False)
        vb = gtk.VBox(False)
        self.create_image_info(vb, self._("balance_table"), self._("balance_table_info"))
        treestore = gtk.TreeStore(str, float, float, float, float)
        self.balance_table_treeview = gtk.TreeView(treestore)
        col_names = [self._('variable_level'), self._('marginal_balance'), self._('range'), self._('variance'), 'SD']
        for i in range(5):
            cell = gtk.CellRendererText()
            column = gtk.TreeViewColumn(col_names[i], cell, text=i)
            self.balance_table_treeview.append_column(column)
        functions.make_scrolling(self.balance_table_treeview, vb)
        hbox.pack_start(vb, True, True)
        lbl = gtk.Label(self._('balance_tab'))
        self.notbook_tabs.append(self._("balance_tab_info"))
        self.notebook.append_page(hbox, lbl)
        # next is the help and about tab
        hbox = gtk.HBox(True)
        self.about_text = gtk.TextView()
        self.about_text.set_wrap_mode(gtk.WRAP_WORD)
        self.about_text.set_editable(False)
        self.about_text.set_cursor_visible(False)
        self.about_text.set_left_margin(20)
        self.about_text.set_right_margin(20)
        about_text = self._('about_text')
        functions.set_text_buffer(self.about_text, about_text)
        functions.make_scrolling(self.about_text, hbox)
        self.add_quick_help_content()
        self.notbook_tabs.append(self._("help_tab_info"))
        lbl = gtk.Label(self._('help_tab'))
        self.notebook.append_page(hbox, lbl)
        vb = gtk.VBox(True, spacing=5)
        self.notebook.set_show_tabs(True)
        self.window.add(win_vbox)
        self.window.show_all()
        # hide the research tools if not indicated in the config
        if not self.config.getboolean('interface', 'batch_allocation'):
            self.hbuttonbox_batch_mode.hide()
        if self.first_run:
            # if this is the first run setup the preferences
            PrefWin(self)
        else:
            # if there is a previous trial to load
            if self.trial_file_name:
                # loading the last trial
                self.waiting_function(self.load_trial, (self.trial_file_name,))
                if not self.trial_file_name:
                    # usuallay load error will handel in the loading function. This is as a last backup
                    functions.error_dialog(self.window, self._('load_error_msg'))
                    # so start a new trial
                    self.set_new_trial()
            else:
                # no previous trial, or not according to configuration
                self.set_new_trial()

    def add_quick_help_content(self):
        # this function adds content to the help text view
        # address of help file
        file_name = os.path.join('doc', 'index.info')
        # a general function for adding texts and images to text views
        functions.textview_from_file(file_name, self.about_text)

    def allocations_edit_event(self, tw, path, col, data=None):
        # a function for editing allocations. Main indications are when
        # a subject enrolled but received a different treatment (by error) than the one
        # determined by minimization. Another is when the incorrect subjects data has been entered
        # first determinign the UI of the selected subject.
        model = self.allocations_treeview.get_model()
        row = path[0]
        ui = int(model[row][1])
        if self.network_sync_dict['sync'] and self.trial_file_name:
            # if network sync, first check out a have an updated local copy
            save_path = self.update_network_trial()
        else:
            save_path = self.trial_file_name
        model = self.allocations_treeview.get_model()
        # this updated model may be different from the one before update
        if not model or len(model) == 0:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_no_subject_allocated"))
            return False
        # another user may have deleted the selcted subject
        for case in self.allocations:
            if case['UI'] == ui:
                break
        else:
            functions.error_dialog(self.window, self._('non_updated_data'), self._('data_not_updated'))            
            return False
        # Edit the subject
        model.set_sort_column_id(0, gtk.SORT_ASCENDING)
        EditAllocation(self, ui, save_path)

    def allocations_import(self):
        # importing a file containing previously allocated subject (by any method)
        if self.network_sync_dict['sync'] and self.trial_file_name:
            # have an update
            repo_path = self.update_network_trial()
        # updated model
        model = self.allocations_treeview.get_model()
        # empty model
        if not model:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_groups_prognostic_factors_must_be_defined"))
            return False
        # trial ended or not initialized
        if not self.ui_pool:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._('statusbar_trial_finished_or_not_saved'))
            return False
        # import file
        file_name = self.select_file(self._("select_file"), gtk.FILE_CHOOSER_ACTION_OPEN)
        if not file_name:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_import_canceled"))
            return False
        # lines
        rows = open(file_name).readlines()
        # empty file
        if not rows:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_empty_file"))
            return False
        # working of each line
        for cnt, row in enumerate(rows):
            # work till the end of ui pool
            if len(self.ui_pool) == 0:
                # give the final success message and go for save
                msg = '{0} record{1} imported'.format(cnt, ('', 's')[cnt>0])
                dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO,
                    buttons=gtk.BUTTONS_OK, message_format = msg)
                dialog.set_title(self._("finished_importing"))
                dialog.run()
                dialog.destroy()
                break
            try:
                # each line is a record of fields separated by commas
                row = map(str.strip, row.split(','))[2:]
                # first field is the group. It must be numeric
                group = row[0]
                if not group.isdigit():
                    raise Exception, self._('bad_file_format')
                group = int(group)
                row = row[1:]
                # number of remaining fields must be the same as number of variables
                if len(row) != len(self.variable_combos):
                    raise Exception, self._('bad_file_format')
                # all must be digits
                if not all(map(str.isdigit, row)):
                    raise Exception, self._('bad_file_format')
                # capturing remaining fields
                for idx, level in enumerate(row):
                    cbo = self.variable_combos[idx]
                    cbo.set_active(int(level))
                model.append()
                # consume one ui for each record
                ui = self.ui_pool.pop()
                # building the new case to add to allocations
                new_case = {'levels': [], 'allocation': -1, 'UI': ui}
                row = len(model)-1
                # building the model. sequence and ui of the record
                model[row][0] = row
                UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
                model[row][1] = str(ui).zfill(UI_len)
                # adding variable levels to the model and new case
                for col, cbo in enumerate(self.variable_combos):
                    model[row][col+3] = cbo.get_active_text()
                    new_case['levels'].append(cbo.get_active())
                # setting the group of modle and new case
                new_case['allocation'] = group
                model[row][2] = self.group_liststore[group][0]
                # appending the new case to the allocations
                self.allocations.append(new_case)
            except Exception as err:
                # any error will be captured here. Mainly bad file format
                msg = self._('error_in_import') + str(err) + self._('original_data_will_resotre')
                dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO,
                    buttons=gtk.BUTTONS_OK, message_format = msg)
                dialog.set_title(self._("import_failed"))
                dialog.run()
                dialog.destroy()
                # restoring the original trial if any
                if self.trial_file_name:
                    self.load_trial(self.trial_file_name)
                    if not self.trial_file_name:
                        functions.error_dialog(self.window, self._('critical_error_restoring_trial'), self._('trial_restore_failed'))
                        self.set_new_trial()
                else:
                    # otherwise start a new one
                    self.set_new_trial()
                return
        # commiting the changes
        if self.network_sync_dict['sync']:
            path = repo_path
        else:
            path = self.trial_file_name
        self.save_trial(path)

    def allocations_import_button(self):
        # event function for importing data
        self.waiting_function(self.allocations_import, ())

    def allocations_export(self):
        # function for export data
        # updating
        if self.network_sync_dict['sync'] and self.trial_file_name:
            repo_path = self.update_network_trial()
            self.remove_folder(repo_path)
        if not self.trial_file_name:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_save_trial_first"))
            return False
        # export class
        Export(self)

    def allocations_export_button(self):
        # event function for export
        self.waiting_function(self.allocations_export, ())

    def trial_info_button_clicked(self):
        # getting details and saving into a file
        det_file_name = self.save_trial_details_temp()
        # view the file in a generic viewer
        Viewer(parent=self, file_name=det_file_name)

    def pref_clicked(self):
        # event function for preferences
        # start the PrefWin class
        PrefWin(self)

    def new_trial_clicked(self):
        # we have unsaved data?
        if not self.query_trial_dismis():
            return False
        # start a new trial
        self.set_new_trial()

    def set_new_trial(self):
        # trial name set to empty, clear title, set the sample size to 30, clear the description,
        # clear trial properties table, set the high property to 0.7, clear groups,
        # variables and allocations, clear frequency and initial frequency table, clear the UI pool,
        # clear the network sync parameters, unlock the trial, goto the first (settings) tab
        self.trial_file_name = None
        self.trial_title_entry.set_text('')
        self.trial_sample_size_spin.set_value(30)
        functions.set_text_buffer(self.trial_description_text, '')
        self.trial_properties_liststore.clear()
        self.high_prob_spin.set_value(0.7)
        self.prob_method_radios[0].set_active(True)
        self.distance_measure_radios[0].set_active(True)
        self.group_liststore.clear()
        self.variable_liststore.clear()
        self.allocations_treeview.set_model()
        self.allocations = []
        self.freq_table_treeview.set_model()
        self.initial_freq_table = False
        self.freq_table_treeview.set_model()
        self.update_interface()
        self.lock_trial(unlock=True)
        self.ui_pool = []
        self.network_sync_chk.set_active(False)
        self.network_sync_dict = dict(sync=False, url='', auth=False)
        self.window.set_title(self._('window_untitled'))
        self.notebook.set_current_page(0)
        self.set_progressbar_status()
        self.freq_table_enable_edit_button.set_label(gtk.STOCK_START_EDIT)

    def balance_table_refresh(self):
        # refreshing the balance table
        # update
        if self.network_sync_dict['sync'] and self.trial_file_name:
            repo_path = self.update_network_trial()
            # only update is required, no need for a working copy
            self.remove_folder(repo_path)
        # getting the frequency data model
        liststore = self.freq_table_treeview.get_model()
        if not liststore:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_no_allocation"))
            return False
        # start with an empty table
        table = []
        for row in range(len(liststore)-1):
            # for each group append one row to the table,
            # last row in the model is the col totals, so we do not use it
            table.append([])
            for col in range(1, len(liststore[0])-1):
                # each col in the model represent successive levels of veriables
                # last col is the row totals, so we do not use it
                table[row].append(liststore[row][col])
        # populating the table with the balance data
        balance = self.get_trial_balances(table)
        # first clear the balance table model
        treestore = self.balance_table_treeview.get_model()
        treestore.clear()
        # a list of level lists each for one variable
        variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
        row = 0
        # correcting balances for variable weights
        for idx, variable in enumerate(variables):
            wt = self.variable_liststore[idx][1]
            var_total = [0] * 4
            level_rows = []
            for level in variable:
                for i in range(4):
                    # here I applied the var weights to the final balance.
                    # may be a better way to do this
                    balance[row][i] *= float(wt)
                    var_total[i] += balance[row][i]
                level_rows.append(balance[row])
                row += 1
            # appending total of balances to the balances, one for each variable
            var_total = [self.variable_liststore[idx][0]] + [var_total[i] / len(variable) for i in range(4)]
            # populating the model with balance data, begining with total variable balance data
            variable_node = treestore.append(None, var_total)
            level_names = map(str.strip, self.variable_liststore[idx][2].split(','))
            # adding balances for each level under each variable
            for level, level_row in enumerate(level_rows):
                treestore.append(variable_node, [level_names[level]] + level_row)
        # last row is the mean and max
        last_row = row
        rows = len(balance)-2
        for col in range(4):
             balance[rows].append(1.0 * sum([balance[row][col] for row in range(rows)]) / rows)
             balance[rows+1].append(max([balance[row][col] for row in range(rows)]))
        treestore.append(None, [self._('mean')] + balance[last_row])
        treestore.append(None, [self._('max')] + balance[last_row+1])

    def get_trial_balances(self, table):
        # a general dispatching function for obtaining balance for each type of balance measure
        # table: input is the counts of different levels in each group
        # a Model object for passing to Minim object
        model = Model()
        # a Minim object for calculating different balances
        m = Minim(random=self.random, model=model)
        # an emapy list for each level
        levels = [[] for col in table[0]]
        # two extra list for mean and max
        balances = [[] for col in table[0]] + [[], []]
        # populating the levels list with count data
        for row in table:
            for col, value in enumerate(row):
                levels[col].append(value)
        # a list of allocation ratios
        allocation_ratio = [self.group_liststore[r][1] for r in range(len(self.group_liststore))]
        for row, level_count in enumerate(levels):
            # obtaining adjuted count for each level based on the allocation ratios
            adj_count = [(1.0 * level_count[i]) / allocation_ratio[i] for i in range(len(level_count))]
            # calculating marignal balance
            balances[row].append(m.get_marginal_balance(adj_count))
            # range
            balances[row].append(max(adj_count) - min(adj_count))
            # variance
            balances[row].append(m.get_variance(adj_count))
            # SD
            balances[row].append(m.get_standard_deviation(adj_count))
        return balances

    def freq_table_disable_edit(self):
        # disabling frequency table edit
        functions.treeview_disable_edit(self.freq_table_treeview)

    def freq_table_enable_edit(self):
        # enabling frequency table edit
        functions.treeview_enable_edit(self.freq_table_treeview, self.freq_table_treeview_edit_handler)

    def freq_table_start_edit_clicked(self, button, data=False):
        # enable of disable frequency table edit
        # frequency model
        initial_freq_model = self.freq_table_treeview.get_model()
        # empty model, groups and variables have not been defined yet
        if not initial_freq_model:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_trial_not_initialized"))
            return False
        if not len(initial_freq_model):
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_trial_not_initialized"))
            return False
        # disable or enable, check the button label, then change the button label
        if button.get_label() == gtk.STOCK_START_EDIT:
            self.freq_table_enable_edit()
            button.set_label(gtk.STOCK_SAVE_AS_INITIAL_TABLE)
        else:
            # if the label is gtk.STOCK_SAVE_AS_INITIAL_TABLE, first check for inconsistencies in
            # rows and cols totals. A value of -1 means inconsistency
            if initial_freq_model[-1][-1] == -1:
                functions.error_dialog(self.window, self._('initial_frequency_table_error'), self._('frequency_table_error'))
                return False
            # group list
            groups = range(len(self.group_liststore))
            # list of level lists
            variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
            # initializing a table to hold the frequency data
            table = [[[0 for l in v] for v in variables] for g in groups]
            for row, group in enumerate(table):
                col = 1
                for v, variable in enumerate(group):
                    for l, level in enumerate(variable):
                        table[row][v][l] = initial_freq_model[row][col]
                        col += 1
            # setting the table as the initial frequency table
            self.initial_freq_table = table
            # changing the button
            button.set_label(gtk.STOCK_START_EDIT)
            # disabling the edit
            self.freq_table_disable_edit()

    def freq_table_treeview_edit_handler(self, cell, row, new_text, col):
        # an event handler for editing cells of fequency table
        # the model
        model = self.freq_table_treeview.get_model()
        # some cells can not be edited
        if (col == 0) or (int(row) == (len(model) - 1)) or (col == (len(model[0]) - 1)):
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_cell_can_not-be_changed"))
            return False
        # non digit values entered
        if not new_text.isdigit():
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_only_interger_values"))
            return False
        # the value is OK, so set the cell to the value
        model[row][col] = int(new_text)
        # calculating rows and cols total
        col_sum = 0
        for r in range(len(model)-1):
            col_sum += model[r][col]
        model[-1][col] = col_sum
        # list of level list
        variables = [range(len(self.variable_liststore[r][2].split(','))) for r in range(len(self.variable_liststore) )]
        # level list initited to zeros
        table_row = [[0 for L in v] for v in variables]
        cum_cols = 0
        for v, variable in enumerate(table_row):
            # cols are successive, so add up to find the current col
            cum_cols += len(variable)
            # if we reach to the edited col
            # if yes, return to the start col of the varable whose cell is edited
            if cum_cols >= col:
                # cols of this variable
                sel_cols = range(cum_cols - len(variable) + 1, cum_cols + 1)
                break
        # calculating row sum for all cols of this variable (the variable which one of its cols is edited) 
        row_sum = 0
        for c in sel_cols:
            row_sum += model[row][c]
        # a flag to signal discrepancies in row or col totals
        err_sum = False
        cum_cols = 0
        # all row sums must be equal, otherwise ther is an error in entering values
        for v, variable in enumerate(table_row):
            # stacking up cols to get into the range of cols for each variable
            cum_cols += len(variable)
            # list of cols for each variable
            sel_cols = range(cum_cols - len(variable) + 1, cum_cols + 1)
            # row sum for this cols
            row_sum_ext = 0
            for c in sel_cols:
                row_sum_ext += model[row][c]
            # row sums must be equal
            if row_sum_ext != row_sum: err_sum = True
        # no error! set the total
        if not err_sum:
            model[row][-1] = row_sum
        else:
            # error: set the value to -1, to be checkable
            model[row][-1] = -1
        # total of totals
        total = 0
        for r in range(len(model)-1):
            total += model[r][-1]

        # if not error: set the total of totals
        if not err_sum:
            model[-1][-1] = total
        else:
            # error: set value to -1
            model[-1][-1] = -1

    def freq_table_delete_initial_clicked(self, button, data=None):
        # delete and refresh the frequency table. useful to apply changes in group and variable settings
        # ofcours manually entered frequency data will be lost
        initial_freq_model = self.freq_table_treeview.get_model()
        # no group and variable has been defined
        if not initial_freq_model:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_trial_not_initialized"))
            return False
        # warn against data loss
        msg = self._("warning_initial_frequency_table_delete")
        dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
        dialog.set_title(self._("initial_table_delete_refresh"))
        if dialog.run() == gtk.RESPONSE_NO:
            dialog.destroy()
            return False
        dialog.destroy()
        # refresh the table
        self.refresh_freq_table()
        # negating initial trial preload
        self.initial_freq_table = False
        # disabling edit
        self.freq_table_disable_edit()
        # stting the button label
        self.freq_table_enable_edit_button.set_label(gtk.STOCK_START_EDIT)

    def load_trial_clicked(self):
        # event function for trial load
        # first check if we have unsaved data
        if not self.query_trial_dismis():
            return False
        # get loading file name
        file_name = self.select_file(self._("enter_file_name"), gtk.FILE_CHOOSER_ACTION_OPEN)
        # cancel button
        if not file_name:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_trial_save_canceled"))
            return False
        # loading the trial
        self.waiting_function(self.load_trial, (file_name,))

    def try_network_info_file(self, file_name):
        # this function checks whether a file is a valid network trial info file
        # network trial info file contains required data for loading the trial over the network
        try:
            # first open it, any error here means file is not accessible or no accesible content
            fp = open(file_name, 'rb')
            data = pickle.load(fp)
            fp.close()
        except:
            # file is invalid
            return -1
        # then checking individual keyword elements
        if data.has_key('network_sync') and data.has_key('trial_name'):
            # if has two elementary network sync keywords, try to load the trial
            self.trial_file_name = file_name
            if self.update_network_trial():
                # successful, lock the trial
                self.lock_trial()
                # file is valid and trial loaded
                # return success
                return 1
            else:
                # load failed, nothing can be done except starting a new trial
                self.set_new_trial()
                # file is valid but trial not loaded
                # return failure, perhaps the file is invalid
                return 0
        else:
            # necessary keyword are missing, so start a new trial and retrun -1, means lack of keywords
            self.set_new_trial()
            # file is invalid
            return -1

    def save_trial_changes(self, save_sample_size=False):
        # this function saves minor changes in trial settings (title, description, properties)
        # first having a copy of the trial title, description, properties and 
        # variable combos setting, to set them again after update. Then we can safely save changes
        trial_title = self.trial_title_entry.get_text()
        trial_description = functions.get_text_buffer(self.trial_description_text)
        # saving this UI pool is necessary when changing sample size
        sample_size = self.trial_sample_size_spin.get_value()
        ui_pool = self.ui_pool
        # this list hold the states of cbos
        cbo_selects = []
        for cbo in self.variable_combos:
            cbo_selects.append(cbo.get_active())
        # getting trial properties
        trial_properties = self.get_trial_properties()
        # only if network sync, restore the saved values
        if self.network_sync_dict['sync'] and self.trial_file_name:
            # updating the trial, this will reset all variable combos, but we have a backup of them
            repo_path = self.update_network_trial()
            # restoring values to make then ready for save changes
            self.trial_title_entry.set_text(trial_title)
            functions.set_text_buffer(self.trial_description_text, trial_description)
            # only of changing sample size, restore these two values before the update
            if save_sample_size:
                self.trial_sample_size_spin.set_value(sample_size)
                self.ui_pool = ui_pool
            for i, cbo in enumerate(self.variable_combos):
                cbo.set_active(cbo_selects[i])
            self.set_trial_properties(trial_properties)
        # finally save changes
        if self.network_sync_dict['sync']:
            path = repo_path
        else:
            path = self.trial_file_name
        self.save_trial(path)

    def save_trial_event(self):
        # is this an update or save
        if self.trial_file_name:
            # so save the changes only
            self.save_trial_changes()
            return False
        if not self.trial_is_valid():
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("trial_not_ready_to_save"))
            return False
        # asking for the file name
        file_name = self.select_file(self._("enter_file_name"), gtk.FILE_CHOOSER_ACTION_SAVE)
        # cancel
        if not file_name:
            self.statusbar.pop(self.sb_context_id)
            self.statusbar.push(self.sb_context_id, self._("statusbar_trial_save_canceled"))
            return False
        # build the UI pool
        self.build_ui_pool()
        # actual save
        self.trial_file_name = self.save_trial(file_name, initial=True)

    def save_trial_clicked(self):
        # event function for saving trial
        self.waiting_function(self.save_trial_event, ())

    def set_groups_data(self, groups):
        # gathering group liststore data
        self.group_liststore.clear()
        for group in groups:
            self.group_liststore.append((group['name'], group['allocation_ratio']))

    def set_variables_data(self, variables):
        # setting variable liststore from the supplied data
        self.variable_liststore.clear()
        for variable in variables:
            self.variable_liststore.append((variable['name'], variable['weight'], variable['levels']))

    def build_ui_pool(self, lst=None):
        # building the UI pool
        # if this is an original save, build a new pool
        if not lst:
            # it's a new save, so build a list containing range of numbers from zero to
            # the sample size minus one
            ss = self.trial_sample_size_spin.get_value_as_int()
            lst = range(ss)
        # if this is an increase in sample size, work on the supplied list
        # shuffle the list
        self.random.shuffle(lst)
        # set the final UI pool.
        self.ui_pool = lst

    def get_trial_properties(self):
        # getting trial properties
        table = [['', ''] for row in range(len(self.trial_properties_liststore))]
        for row in range(len(table)):
            for col in range(len(table[0])):
                table[row][col] = self.trial_properties_liststore[row][col]
        return table

    def get_case_properties(self):
        # getting case properties
        table = [['', ''] for row in range(len(self.case_properties_liststore))]
        for row in range(len(table)):
            for col in range(len(table[0])):
                table[row][col] = self.case_properties_liststore[row][col]
        return table

    def set_trial_properties(self, table):
        # setting the trial propeties liststore from the supplied table
        self.trial_properties_liststore.clear()
        for row in range(len(table)):
            self.trial_properties_liststore.append(table[row])

    def trial_is_valid(self, show_msg=True, ret_code=None, table_edit=False):
        # checking whether the trial has required data and the data are valid
        # trial title
        if not self.trial_title_entry.get_text() and not table_edit:
            if show_msg:
                functions.error_dialog(self.window, self._("trial_title_first"), self._("trial_title"))
                self.notebook.set_current_page(0)
                self.window.set_focus(self.trial_title_entry)
            return False
        # in case of network sync check if any invalid character in title
        if self.trial_title_entry.get_text():
            if self.network_sync_dict['sync']:
                title = '_'.join(self.trial_title_entry.get_text().split())[:10]
                for char in title:
                    if char in self.invalid_chars:
                        if show_msg:
                            functions.error_dialog(self.window, self._("invalid_character").format(char), self._("trial_title"))
                        return False
        # descript is required, except when editing a table
        if not functions.get_text_buffer(self.trial_description_text) and not table_edit:
            if show_msg:
                functions.error_dialog(self.window, self._("enter_trial_description"), self._("trial_description"))
                self.notebook.set_current_page(0)
                self.window.set_focus(self.trial_description_text)
            return False
        # at least two groups are required
        if len(self.group_liststore) < 2:
            if show_msg:
                functions.error_dialog(self.window, self._("two_groups_needed"), self._("trial_groups"))
                self.notebook.set_current_page(1)
                self.window.set_focus(self.group_treeview)
            return False
        # at least one variable is required
        if len(self.variable_liststore) < 1:
            if show_msg:
                functions.error_dialog(self.window, self._("prognostic_factor_required"), self._("trial_variables"))
                self.notebook.set_current_page(2)
                self.window.set_focus(self.variable_treeview)
            return False
        # check if there is unsaved initial freq table
        if self.freq_table_enable_edit_button.get_label() == gtk.STOCK_SAVE_AS_INITIAL_TABLE:
            if show_msg:
                functions.error_dialog(
                self.window, self._("initial_frequency_table_not_saved"), self._("frequency_table"))
                self.notebook.set_current_page(4)
                self.window.set_focus(self.freq_table_treeview)
            return False
        # final asking to save the rial
        if not show_msg: return True
        # display trial details and asking confirmation for save
        return self.display_trial_details_response()

    def save_trial_details_temp(self):
        # save a temp file containg trial detains, to be used later in dialogs
        details = self._('trial_details') + '\n' + self.get_trial_info()
        det_file_name = tempfile.mkstemp(suffix='.info')[1]
        self.used_temp_files.append(det_file_name)
        fp = open(det_file_name, 'w')
        fp.write(details)
        fp.flush()
        fp.close()
        # return the file name
        return det_file_name

    def display_trial_details_response(self):
        # function for displaying trial details and asking for confirmation
        msg = self._("want_save_trial")
        dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
        dialog.set_title(self._("trial_save"))
        det_file_name = self.save_trial_details_temp()
        hbb = gtk.HButtonBox()
        hbb.show()
        # addin a button to display trial details
        button =  gtk.Button(self._("trial_details"))
        button.connect('clicked', self.save_dialog_button_clicked, det_file_name)
        button.show()
        hbb.pack_start(button)
        dialog.vbox.pack_start(hbb)
        if dialog.run() == gtk.RESPONSE_YES:
            # remove temp file
            dialog.destroy()
            # save the trial
            return True
        dialog.destroy()
        # don't save
        return False

    def save_dialog_button_clicked(self, button, file_name):
        # event function for dialog button to display trial details
        Viewer(parent=self, file_name=file_name)

    def remove_temp_file(self, path):
        if not os.path.exists(path): return
        if os.path.isdir(path):
            items = os.listdir(path)
            if len(items) == 0:
                os.rmdir(path)
            else:
                for item in items:
                    self.remove_temp_file(item)
        else:
            os.remove(path)

    def want_trial_unlock(self, prompt=True):
        if prompt:
            msg = self._("want_unlock_trial")
            dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
            dialog.set_title(self._("unlock_trial"))
            if dialog.run() == gtk.RESPONSE_NO:
                dialog.destroy()
                return False
            dialog.destroy()
        self.lock_trial(unlock=True)
        self.ui_pool = []
        self.trial_file_name = None

    def lock_trial(self, unlock=False):
        self.network_sync_chk.set_property("sensitive", unlock)
        self.trial_sample_size_spin.set_property("sensitive", unlock)
        for radio in self.prob_method_radios:
            radio.set_property("sensitive", unlock)
        self.high_prob_spin.set_property("sensitive", unlock)
        for radio in self.distance_measure_radios:
            radio.set_property("sensitive", unlock)
        self.group_vbuttonbox.set_property("visible", unlock)
        if unlock:
            functions.treeview_enable_edit(self.group_treeview)
        else:
            functions.treeview_disable_edit(self.group_treeview)
        self.variable_vbuttonbox.set_property("visible", unlock)
        self.initial_table_hbox.set_property("visible", unlock)
        self.statusbar.pop(self.sb_context_id)
        self.statusbar.push(self.sb_context_id, (self._("trial_locked"), self._("trial_unlocked"))[unlock])

    def get_trial_info(self):
        ret = []
        ret.append(self._("title") + ": " + self.trial_title_entry.get_text())
        ret.append(self._("sample_size") + ": " + str(self.trial_sample_size_spin.get_value_as_int()))
        if self.network_sync_dict['sync'] and self.network_sync_dict['url']:
            ret.append(self._('repository_url') + ' = {0}'.format(self.network_sync_dict['url']))
            ret.append(self._('trial_info_file') + ' = {0}'.format(self.trial_file_name))
        else:
            ret.append(self._('local_trial_file_name') + ' = {0}'.format(self.trial_file_name))
        ret.append(self._("description") + ": " + functions.get_text_buffer(self.trial_description_text))
        ret.append(self._("probability_method") + ": " + self.get_prob_method_name())
        ret.append(self._("distance_measure") + ": " + self.get_distance_measure_name())
        ret.append(self._("high_probability") + ": " + str(self.high_prob_spin.get_value()))
        ret.append(self._("groups") + ":\n" + str(self.get_groups_info()))
        ret.append(self._("variables") + ":\n" + str(self.get_variables_info()))
        return '\n'.join(ret)

    def load_trial_from_file(self, file_name):
        fp = open(file_name, 'rb')
        data = pickle.load(fp)
        fp.close()
        self.ui_pool = data['ui_pool']
        self.trial_title_entry.set_text(data['trial_title'])
        if len(data['trial_title']) > 60:
            trial_title = data['trial_title'][:57] + '...'
        else:
            trial_title = data['trial_title']
        win_title = self._('main_window_title').format(trial_title)
        self.window.set_title(win_title)
        functions.set_text_buffer(self.trial_description_text, data['trial_description'])
        self.set_trial_properties(data['trial_properties'])
        self.allocations = data['allocations']
        self.trial_sample_size_spin.set_value(data['sample_size'])
        self.high_prob_spin.set_value(data['high_prob'])
        self.initial_freq_table = data['initial_freq_table']
        self.prob_method_radios[data['prob_method']].set_active(True)
        self.distance_measure_radios[data['distance_measure']].set_active(True)
        self.set_groups_data(data['groups'])
        self.set_variables_data(data['variables'])
        self.update_interface()
        self.set_progressbar_status()
        if data.has_key('network_sync'):
            # previous versions of data files may not have this field
            self.network_sync_dict = data['network_sync']
            self.network_sync_chk.handler_block(self.network_sync_chk_event_id)
            self.network_sync_chk.set_active(self.network_sync_dict['sync'])
            self.network_sync_chk.handler_unblock(self.network_sync_chk_event_id)

    def waiting_function(self, func, args):
        gdk_cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
        win = gtk.gdk.get_default_root_window()
        win.set_cursor(gdk_cursor)
        gobject.idle_add(func, *args)
        gobject.idle_add(self.exit_waiting, win)
        self.network_sync_dialog.show()

    def exit_waiting(self, win):
        gdk_cursor = gtk.gdk.Cursor(gtk.gdk.ARROW)
        win.set_cursor(gdk_cursor)
        self.network_sync_dialog.hide()

    def load_trial(self, file_name):
        # checking the file if this is a network sync info file. If yes, then we checkout and 
        # load the trial from the checkout
        self.network_sync_dialog_label.set_text(self._('please_wait').format(self.network_sync_dict['url']))
        ret = self.try_network_info_file(file_name)
        self.file_chooser_current_folder = os.path.dirname(file_name)
        if ret > 0:
            self.network_sync_dialog_label.set_text(self._('network_syncing_wait').format(self.network_sync_dict['url']))
            self.config.set('project', 'recent_trial', file_name)
            self.notebook.set_current_page(3)
            self.config.write_config()
            return
        if ret == 0: return
        try:
            self.load_trial_from_file(file_name)
            self.lock_trial()
            self.trial_file_name = file_name
            self.notebook.set_current_page(3)
            self.config.set('project', 'recent_trial', file_name)
            self.notebook.set_current_page(3)
            self.config.write_config()
        except Exception as ex:
            functions.error_dialog(self.window, self._("trial_load_failed").format(file_name) + '\n' + str(ex), self._("error_loading_file"))
            self.lock_trial(unlock=True)
            self.set_new_trial()
            self.trial_file_name = False

    def get_svn_client(self):
        self.network_sync_cancel_command = False
        client = pysvn.Client()
        client.callback_cancel = self.network_sync_cancel
        client.callback_get_login = self.network_sync_get_login
        client.callback_ssl_server_trust_prompt = self.network_sync_ssl_server_trust_prompt
        client.callback_notify = self.network_sync_notify
        client.set_auth_cache(self.config.getboolean('operations', 'cach_cred'))
        client.set_store_passwords(self.config.getboolean('operations', 'cach_cred'))
        client.exception_style = 1
        return client

    def network_sync_notify(self, event_dict):
        return

    def save_trial_to_file(self, file_name):
        data = {}
        data['ui_pool'] = self.ui_pool
        data['trial_title'] = self.trial_title_entry.get_text()
        data['sample_size'] = self.trial_sample_size_spin.get_value_as_int()
        data['trial_description'] = functions.get_text_buffer(self.trial_description_text)
        data['trial_properties'] = self.get_trial_properties()
        data['high_prob'] = self.high_prob_spin.get_value()
        data['initial_freq_table'] = self.initial_freq_table
        data['prob_method'] = self.get_prob_method()
        data['distance_measure'] = self.get_distance_measure()
        data['allocations'] = self.allocations
        data['groups'] = self.get_groups_data()
        data['variables'] = self.get_variables_data()
        data['network_sync'] = self.network_sync_dict
        fp = open(file_name, 'wb')
        pickle.dump(data, fp)
        fp.flush()
        fp.close()
        if len(data['trial_title']) > 60:
            trial_title = data['trial_title'][:57] + '...'
        else:
            trial_title = data['trial_title']
        win_title = self._('main_window_title').format(trial_title)
        self.window.set_title(win_title)
        self.set_progressbar_status()
        if self.network_sync_dict['sync']:
            if self.config.getboolean('operations', 'backup_network'):
                backup_folder_name = self.config.get('operations', 'backup_network_path')
                if backup_folder_name:
                    back_file_name = os.path.join(backup_folder_name, os.path.basename(file_name))
                    # turning sync off to enable offline opening of the backup file
                    data['network_sync'] = dict(sync=False, url='', auth=False)
                    fp = open(back_file_name, 'wb')
                    pickle.dump(data, fp)
                    fp.flush()
                    fp.close()
        
    def save_trial_local(self, file_name):
        try:
            self.save_trial_to_file(file_name)
            self.config.set('project', 'recent_trial', file_name)
            self.config.write_config()
            return file_name
        except Exception as ex:
            functions.error_dialog(self.window, self._("trial_save_failed_no_permission").format(file_name, repr(ex)), self._("statusbar_trial_not_saved"))
            return False

    def load_network_trial_info(self):
        fp = open(self.trial_file_name, 'rb')
        data = pickle.load(fp)
        fp.close()
        try:
            if data.has_key('network_sync'):
                self.network_sync_dict = data['network_sync']
            else:
                raise Exception, self._("trial_info_file_not_valid")
            if data.has_key('trial_name'):
                trial_name = data['trial_name']
            else:
                raise Exception, self._("trial_info_file_not_valid")
            return trial_name
        except Exception as ex:
            functions.error_dialog(self.window, self._("network_trial_info_file_problem") + repr(ex), self._("trial_info_file"))
            return False

    def update_network_trial(self):
        # this method checkout the repo, load the trial from it, and then return the local path
        if not self.trial_file_name: 
            self.set_new_trial()
            return False
        trial_name = self.load_network_trial_info()
        if not trial_name:
            self.set_new_trial()
            return False
        try:
            client = self.get_svn_client()
            url = self.network_sync_dict['url'] + '/' + trial_name
            tempfolder = tempfile.mkdtemp()
            self.used_temp_files.append(tempfolder)
            rev = False
            while True:
                rev = client.checkout(url, tempfolder)
                if rev:
                    if type(rev) == type(pysvn.Revision(pysvn.opt_revision_kind.head)): break
            temp_file_name = os.path.join(tempfolder, trial_name)
            self.load_trial_from_file(temp_file_name)
            return tempfolder
        except Exception as ex:
            functions.error_dialog(self.window, self._("unknown_error_network_sync") + repr(ex), self._("network_sync_error"))
            return False

    def checkin_trial(self, path):
        if not self.trial_file_name:
            self.set_new_trial()
            return False
        trial_name = self.load_network_trial_info()
        if not trial_name:
            self.set_new_trial()
            return False
        url = self.network_sync_dict['url'] + '/' + trial_name
        file_name = os.path.join(path, trial_name)
        self.save_trial_to_file(file_name)
        client = self.get_svn_client()
        try:
            rev = False
            while True:
                rev = client.checkin(path, time.ctime())
                if rev:
                    if type(rev) == type(pysvn.Revision(pysvn.opt_revision_kind.head)): break
                stats = client.status(path)
                for stat in stats:
                    if stat.repos_text_status == pysvn.wc_status_kind.modified:
                        break
                else:
                    break
            self.config.set('project', 'recent_trial', self.trial_file_name)
            self.config.write_config()
            self.remove_folder(path)
        except pysvn.ClientError, e:
            for message, code in e.args[1]:
                if code == 160024 or 'Conflict' in message:
                    msg = self._("network_sync_conflict")
                    dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
                    dialog.set_title(self._("trial_conflict"))
                    if dialog.run() == gtk.RESPONSE_YES:
                        dialog.destroy()
                        self.update_network_trial()
                    dialog.destroy()
                    break
            else:
                functions.error_dialog(self.window, self._("unknown_error_network_sync") + str(e.args[0]), self._("network_sync_error"))
            if os.path.exists(path):
                self.remove_folder(path)
            return False
        except Exception as ex:
            functions.error_dialog(self.window, self._("unknown_error_network_sync") + repr(ex), self._("network_sync_error"))
            if os.path.exists(path):
                self.remove_folder(path)
            return False

    def set_progressbar_status(self):
        fraction = 1.0 * len(self.allocations) / self.trial_sample_size_spin.get_value_as_int()
        self.allocations_progressbar.set_fraction(fraction)
        self.allocations_progressbar.set_text('{0} / {1}'.format(
        len(self.allocations), self.trial_sample_size_spin.get_value_as_int()))

    def import_trial(self, file_name):
        trial_name = '_'.join(self.trial_title_entry.get_text().split())[:10] + str.partition(str(time.time()), '.')[0]
        temp_dir = tempfile.mkdtemp(prefix=trial_name)
        self.used_temp_files.append(temp_dir)
        temp_file = os.path.join(temp_dir, trial_name)
        self.save_trial_to_file(temp_file)
        try:
            client = self.get_svn_client()
            url = self.network_sync_dict['url'] + '/' + trial_name
            rev = False
            while True:
                rev = client.import_(temp_dir, url, self._('minimization_initialized'))
                if rev:
                    if type(rev) == type(pysvn.Revision(pysvn.opt_revision_kind.head)): break
            self.set_progressbar_status()
            data = {}
            data['network_sync'] = self.network_sync_dict
            data['trial_name'] = trial_name
            fp = open(file_name, 'wb')
            pickle.dump(data, fp)
            fp.flush()
            fp.close()
            self.config.set('project', 'recent_trial', file_name)
            self.config.write_config()
            self.remove_folder(temp_dir)
            self.lock_trial()
            return file_name
        except Exception as ex:
            functions.error_dialog(self.window, self._("unknown_error_network_sync") + repr(ex), self._("network_sync_error"))
            if os.path.exists(temp_dir):
                self.remove_folder(temp_dir)
            return False

    def remove_folder(self, folder):
        try:
            shutil.rmtree(folder)
        except:
            pass

    def save_trial(self, file_name, initial=False):
        if self.network_sync_dict['sync']:
            if initial:
                # here file_name is the file containing trial info: rep url etc
                self.trial_file_name = self.import_trial(file_name)
            else:
                # here file name is the path. A temp folder  for checkin into the repo.
                self.checkin_trial(file_name)
            self.network_sync_icon.set_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_SMALL_TOOLBAR)
            self.network_sync_icon.set_tooltip_text(self._('network_sync_enabled'))
        else:
            self.trial_file_name = self.save_trial_local(file_name)
            self.network_sync_icon.set_from_stock(gtk.STOCK_DISCONNECT, gtk.ICON_SIZE_SMALL_TOOLBAR)
            self.network_sync_icon.set_tooltip_text(self._('network_sync_disabled'))
        if self.trial_file_name:
            self.lock_trial()
            return file_name
        else:
            functions.error_dialog(self.window, self._('trial_save_failed'), self._('statusbar_trial_not_saved'))
            return False

    def network_sync_cancel(self):
        return self.network_sync_cancel_command

    def get_distance_measure_name(self):
        for distance_measure_radio in self.distance_measure_radios:
            if distance_measure_radio.get_active():
                return distance_measure_radio.get_label()
        return self._("unknown")

    def get_distance_measure(self):
        for idx, distance_measure_radio in enumerate(self.distance_measure_radios):
            if distance_measure_radio.get_active():
                return idx
        return 0

    def get_prob_method_name(self):
        for prob_method_radio in self.prob_method_radios:
            if prob_method_radio.get_active():
                return prob_method_radio.get_label()
        return self._("unknown")

    def get_prob_method(self):
        for idx, prob_method_radio in enumerate(self.prob_method_radios):
            if prob_method_radio.get_active():
                return idx
        return 0

    def get_variables_info(self):
        variables = []
        n = 0
        for row in self.variable_liststore:
            n += 1
            variable = self._("weight_levels").format(n, *row)
            variables.append(variable)
        return '\n'.join(variables)

    def get_variables_data(self):
        variables = []
        for row in self.variable_liststore:
            variable = {}
            variable['name'] = row[0]
            variable['weight'] = row[1]
            variable['levels'] = row[2]
            variables.append(variable)
        return variables

    def get_groups_info(self):
        groups = []
        n = 0
        for row in self.group_liststore:
            n += 1
            group = self._("allocation_ratio_format").format(n, *list(row))
            groups.append(group)
        return '\n'.join(groups)

    def get_groups_data(self):
        groups = []
        for row in self.group_liststore:
            group = {}
            group['name'] = row[0]
            group['allocation_ratio'] = row[1]
            groups.append(group)
        return groups

    def select_file(self, title, action):
        """
        A generic method returning file name
        """
        stock = {
            gtk.FILE_CHOOSER_ACTION_OPEN: gtk.STOCK_OPEN,
            gtk.FILE_CHOOSER_ACTION_SAVE: gtk.STOCK_SAVE,
            gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER: gtk.STOCK_SAVE}
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, stock[action], gtk.RESPONSE_OK)
        fdialog = gtk.FileChooserDialog(title, self.window, action, buttons)
        if action == gtk.FILE_CHOOSER_ACTION_SAVE:
            fdialog.set_do_overwrite_confirmation(True)
        fdialog.set_default_response(gtk.RESPONSE_OK)
        fdialog.set_current_folder(self.file_chooser_current_folder)
        response = fdialog.run()
        if response == gtk.RESPONSE_OK:
            file_name = fdialog.get_filename()
            self.file_chooser_current_folder = os.path.dirname(file_name)
        else:
            file_name = None
        fdialog.destroy()
        return file_name

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    m = ModelInteface()
    ret = main()
    while m.restart:
        m = ModelInteface()
        ret = main()

