/**
 * flex forms
 *
 */
/**
 * array of controls and their properties
 */
var sections = ['elements'];

var cp = new Array();
cp['text']      = new Array('title','size');
cp['paragraph'] = new Array('title');
cp['website']   = new Array('title');
cp['email']     = new Array('title');
cp['number']    = new Array('title','units');
cp['date']      = new Array('title');
cp['money']     = new Array('title','currency');
cp['image']     = new Array('title');
cp['selection'] = new Array('title');



/*
 *array of months used by the date control
 */
months = ['select','january','february','march','april','may','june','july','august','september','october','november','december'];

var frm_id ;
var frm_name;
var frm_description;
var frm_icon;
/*
 * HTML specific settings
 */

function frms(){
                //$("settings").style.display = "none";
                $("preview").style.display = "";
}
function settings(){
                $("props").style.display = "block";
                $("preview").style.display = "none";
}

function set_header(value) {
             (value == 'preview') ?  $('form_edit').update("Edit existing fields or add new fields from the drop down list provided below.") : $('form_edit').update("Edit layer properties by providing name, description and icon for your layer");
}

/**
 *save the form and commit changes
 */
function save(){
    getGroupOrder();
    displ = encodeURIComponent(jd.getDisplay());
    fields = encodeURIComponent(jd.make());
    params = 'display='+ displ + '&fields='+fields + '&form='+frm_id+ getFormProperties();
    new Ajax.Request('/form/build',{parameters:params,onSuccess:function(){window.location ='/main';}});
//    new Ajax.Request('/form/build',{onSuccess:function(){window.location = '/form/list';},parameters:params});
}

function preview() {
    getGroupOrder();
    displ = jd.getDisplay();
    txt = "Preview of " + this.frm_name + " layer";
    Element.update('preview_title', txt);
    Element.update('elements_preview', displ);
    Element.show('field_preview');
}

/*
 * form settings
 */
function updateSettings(obj,val){
	switch(obj){
		case "set_name":
			this.frm_name = val;
			$('form_name').innerHTML = val.strip();;
			break;
		case "set_description":
			this.frm_description = val;
			$('form_description').innerHTML = val.strip();
			break;
                case "set_icon":
                        this.frm_icon = val;
                        break;
	}
}
function getFormProperties(){return '&template[name]=' + this.frm_name + '&template[description]=' + this.frm_description + '&template[icon]=' + this.frm_icon;}
function createID (){ c_id++; return c_id;}
function showList(){ window.location = '/form/list';}
/**
 * is it an array?
 */
function isArray(obj) {
  return !( !obj || (!obj.length || obj.length == 0) || typeof obj !== 'object' || !obj.constructor || obj.nodeType || obj.item );
}
/*
 * this is called when the control is loaded at the time of editing
 */
function loadProperties(f_properties){
   this.frm_name = $('form_name').innerHTML ;
   this.frm_description = $('form_description').innerHTML;
   this.frm_icon = $('form_icon').innerHTML;
   //f_props =  eval("(" + f_properties + ")");
   f_props = f_properties;
   if (f_props.length == 0) { Element.show('nofields'); }
   jd = new Db();
   f_props.each(
        function(e){
            id = e.dom_id;
            if(c_id < id) { c_id  = id; }
            type = e.dom_type;
            control = new Control(id);
            jd.iField(type,id,control);
            $H(e.props).each(
                function(prop){
                    jd.set(id,prop.key,prop.value);
                }
            );
            jd.set(id,'object',control);
            control.display();
            bindFieldEvents(control);
        }
   );
   if( f_props.length > 0){
     id = jd.firstID();
     selectControl();
   }
}
var Flex = {
    /*
     * when the user clicks on the control to create a new one
     */
    loadControl: function(c_name){
      Element.hide('nofields');
      if (c_name){
        ctl = this.initControl(c_name);
        this.displayControl(ctl);
        bindFieldEvents(ctl);
        id  = ctl.id;
        $('props_' + id).scrollIntoView(true);
        selectControl();      
      }else{
        alert("no control specified");
      }
    },
    /*
     * initialize the control
     */ 
    initControl :function(name){
        id = createID();
        control = new Control(id);
        jd.iField(name,id,control);
        jd.set(id,'object',control);
        return control;
    },
   /*
    * display the control
    */
    displayControl : function(ctl){
        ctl.display();
    }
}
/*
 * temp store of the values
 * this is the JSON-DB acts as store for manipulation and retrieval of control properties
 */
var Db = Class.create();
    Db.prototype = {
        initialize: function(){ 
       		this.data	=	{'fields':[]};
        },
        iField:function(type,id,ctrl){
      		this.data['fields'].push({
			'title'		:   'enter label for ' + type,
			'type'		:   type,
			'object'	:   ctrl,
			'id'		:   id,
			'size'          :   'small',
			'mandatory'     :   false,
			'units'         :   '',
			'currency'      :   '',
                        'dom_order'     :   id,
			'choice'        :   [{"option" : "enter choice1 ", 'id':0},
			                     {"option" : "enter choice2 ", 'id':1},
                                             {"option" : "enter choice3 ", 'id':2}]

    		});
        },
        firstID : function(){
              return this.data['fields'][0].id;
        },
        get : function(id, name) {
	       	fld = this.data['fields'].detect(function(num){return num.id == id;}); if(fld){return fld[name];}
    	},
    	set : function(id,name,value){
    	   this.data['fields'].each( function(num,index){ if (num.id == id)num[name]=value;});
    	},
        setDomOrder: function(id, order) {
    	   this.data['fields'].each( function(num,index){ if (num.id == id)num['dom_order']=order;});
        },
        getByDomOrder: function(dom_order) {
           fld = this.data['fields'].detect(function(num, index){return num.dom_order == dom_order;}); if(fld){return fld['object'];}
        },
	getChoice : function(id, pos){
	   var el = "";
	   this.data['fields'].each(function(num, index){ 
		if(num.id == id) {
		   num.choice.detect(function(num1, index1){if(num1.id == pos)el=num1.option;}); 
		}
	   });
	   return el;
        },
	//Selection contains an array of options. Set the value of the option here.
	setChoice : function(id, value, pos){
	   this.data['fields'].each(function(num, index){ 
	       if(num.id == id) { 
	          num.choice.each(function(num1, index1){if(num1.id == pos) num1.option = value;}); 
	       }
   	   });
        },
	getChoiceIndex: function(id, pos) {
	   var idx;
	   this.data['fields'].each(function(num, index){ 
		if(num.id == id) {
		  num.choice.detect(function(num1,index1){if(num1.id == pos)idx = index1; });
		}
	   });
	   return idx;
	},
    	removeField :function(id){
	       idx = this.getIndex(id);if(idx != undefined){this.data['fields'].splice(idx,1);}
    	},
	getIndex :function(id){
		this.data['fields'].detect(function(num,index){if(num.id == id)idx = index; });return idx;
	},
    	make :function(){
                saveFields = new Array();
                this.data['fields'].each(function(num, index){
                        saveFields.push(num.object);
                        num.object = '';
                });
                ret = JSONstring.make(this.data);
                this.data['fields'].each(function(num, index){
                        num.object = saveFields[index];
                });
                return ret;
    	},
	exists :function(id,fld,prop){
		el = this.data['fields'].detect(function(num,index){return num[fld] == prop && num.id != id;});
		return el ? true : false;
	},
	existsChoice :function(id,prop,pos){
	        var el = false;
	        this.data['fields'].each(function(num, index){ 
			if(num.id == id) {
			   num.choice.each(function(num1, index1){if(num1.id != pos && num1.option == prop)el=true;}); 
			}
		});
		return el ? true : false;
	},
    	getDisplay :function(){
    	      displ = "";
              dom_order = this.data['fields'].pluck('dom_order').sort();
              dom_order.each(function(num, index) {
                  obj = jd.getByDomOrder(num);
                  fld = "<div id=\"" + obj.div.id + "\" style=\"padding: 5px 2px 0pt; display: block;\">"; 
    	          displ += fld + obj.domdiv.innerHTML + "</div>";
              });
    	      return displ;
    	}
};

/*
 * controls are defined here
 * you can add more controls by defining them below
 *
 */
var Control = Class.create();
Control.prototype = {
    id : 0,
    div:0,
    domdiv:null,
    propdiv:null,
    //additional:null,
    initialize: function(id){this.id = id;},
    closeProps: function(){p.close();},
    display :function(){
        this.div = Builder.node('div', {id:this.id, className:'element'});
        $('elements').appendChild(this.div);
	this.domdiv = Builder.node('div', {style:'display:none;'},[this.label(),this.units(),this.mandatory(), this.lineBreak(), this[jd.get(this.id, 'type')]()]);
        if (jd.get(this.id, 'type') == 'selection') {
          this.propdiv = Builder.node('div',{style:'display:inline;'},[props.get(this.id), this.move(), this.remove(), this.lineBreak(), props.selection(), props.mandatory(this.id)]);
    }
        else {
           this.propdiv = Builder.node('div',{style:'display:inline;'},[props.get(this.id), this.move(), this.remove(), this.lineBreak(), props.mandatory(this.id)]);
        }
        this.div.appendChild(this.domdiv);
        this.div.appendChild(this.propdiv);
        $('label_'+this.id).innerHTML = jd.get(this.id, 'title');
        if (jd.get(this.id, 'type') == 'money') selectCurrency(this.id);
    //    $('controls').options[0].selected = "selected";
    },
    loading :function(){
    	return "<div id=loading_div>loading.....</div>";
    },
    getID: function(name){return id = name ? name +"_" +this.id:id;},
    lineBreak :function(){return Builder.node('br');},
    mandatory: function(){
        name = "mandatory"; man = Builder.node('label',{id: this.getID(name)}); man.innerHTML =  jd.get(this.id,'mandatory') ? "*": ""; return man;
    },
    units :function(){
        name = "units"; unt = Builder.node('label',{id: this.getID(name)}); unt.innerHTML =  jd.get(this.id,'units') ; return unt;
    },
    remove :function(){
        name = 'delete'; rm = Builder.node('span',{id:this.getID(name),style:'padding-bottom:2px ;text-align:left;font-size:10px;'}); rm.innerHTML = "<img src='/images/remove.png' onClick=\"if (confirm('Are you sure you want to delete this field')) { removeControl(" + this.id + "); }\">&nbsp;";return rm;
    },
    move :function(){
        name = 'move'; rm = Builder.node('span',{id:this.getID(name),style:'padding-bottom:2px ;text-align:left;font-size:10px;'}); rm.innerHTML = "<img src='/images/move.png' onmousedown=activateMove() onmouseup=deactivateMove() title='drag and drop to move'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";return rm;
    },
    saveButton: function() {
        name = 'text' ;save = Builder.node('span',{className:'large_button'}, [Builder.node('a', {href:'#', onClick:"Element.show('save_msg');"}, 'save')]);return save;
    },
    label: function(){
       name = 'label'; label =  Builder.node(name,{id:this.getID(name)});  label.innerHTML = jd.get(this.id, 'title'); return label;

      //  name = 'label'; label =  Builder.node(name,{id:this.getID(name), onClick:'props.edit($(this.id), "title")'});  label.innerHTML = jd.get(this.id, 'title'); return label;
    },
    text: function (){
        name = 'text' ;return Builder.node('input',{type:name,name:'form['+this.getID(name) +']', readonly:'readonly', id:this.getID(name), className:jd.get(this.id,'size') });
    },
    paragraph: function(){
        name = 'paragraph';return Builder.node('textarea',{readonly:'readonly',name:'form['+ this.getID(name) +']',id:this.getID(name),className:'medium', style: 'margin-right:20px'});
    },
    email :function(){
        name = 'email'; 
        jd.set(this.id,'title',name); 
        return Builder.node('input',{type:'text',name:'form['+this.getID(name) +']', readonly:'readonly', id:this.getID(name), className:'medium', style:'margin-right:20px;' });
    },
    website :function(){
        name = 'website';jd.set(this.id,'title',name);return Builder.node('input',{type:'text',name:'form['+this.getID(name) +']', readonly:'readonly', id:this.getID(name), className:'large', style: 'margin-right:20px;' });
    },
    number :function(){
        name = 'number'; return Builder.node('input',{type:'text',name:'form['+this.getID(name) +']', readonly:'readonly', id:this.getID(name), className:'small' });
    },
    date :function(){
        name='date';
        default_option = Builder.node('option', {value:'', disabled:true, selected:true}, 'select');
        o_day = [Builder.node('option', {value:'', disabled:true, selected:true}, 'select')];
	o_month=[]; 
	o_year = [ Builder.node('option', {value:'', disabled:true, selected:true}, 'select')];
        for(i = 1; i <=31; i++){o_day[i] = Builder.node('option', {value:i,disabled:true},   i);}
        months.each(function(num,index){o_month[index] = Builder.node('option', {value:num,disabled:true},   num);});
	o_month[0].value = ''; o_month[0].selected = true;
        for(i = 1900; i <=2020; i++){o_year[i] = Builder.node('option', {value:i,disabled:true},   i);}
        sel_day = Builder.node('select',{id:this.getID(name)+'[1]',name:'form['+this.getID(name)+'][1]', style:'margin-right:10px' }, o_day);
        sel_month = Builder.node('select',{id:this.getID(name)+'[2]',name:'form['+this.getID(name)+'][2]', style:'margin-right:10px'}, o_month);
        sel_year = Builder.node('select',{id:this.getID(name)+'[3]',name:'form['+this.getID(name)+'][3]', style:'margin-right:20px' }, o_year);
        return[sel_day,sel_month,sel_year];
    },
    money :function(){
       name = 'money';return Builder.node('input',{type:'text',name:'form['+this.getID(name) +']', readonly:'readonly', id:this.getID(name), className:'small' });
        
    },
    image :function(){
      name = 'image';jd.set(this.id,'title','upload image');return Builder.node('input',{type:'file',name:'form['+this.getID(name) +']', disabled:true, id:this.getID(name), className:'small', style:'margin-right:20px;' });
  },
    selection: function(){
      name = 'selection';
      select = Builder.node('select', {name:'form['+this.getID(name) + ']', readonly:'readonly', style: 'margin-right:20px', id:this.getID(name)});
      choices = jd.get(this.id, 'choice');
      dom_id = this.id;
      container = Builder.node('div');
      default_option = Builder.node('option', {value:'', disabled:true, selected:true}, 'select');
      select.appendChild(default_option);
      choices.each(function(item,index){
          option = Builder.node('option', {value:jd.getChoice(dom_id,item.id), disabled:true, id: 'option_' + dom_id + '_' +item.id}, jd.getChoice(dom_id, item.id));
          select.appendChild(option);
	
      });
      return select;
    }
}

/*
 *Properties for the controls
 *Properties for each control is defined in the array at the top, they will be called when control is invoked
 */
var Properties = Class.create();
    Properties.prototype = {
        id : null,
        initialize: function(){},
        show :function(id){
          _id = id;
       //   if (id == this.id){return;}this.hide(); _id = id; 
       //   $('properties').innerHTML = this.get(id).innerHTML;
	 // if (jd.get(id, 'type') == 'selection') {
	//	  bindPropertyEvents(id);
	 // }
        },
        close :function(){ if(this.id){this.hide()}; },
        hide :function(){
            current_props = $(this.fieldID('properties'));
            if(!current_props)return;
            current_props.style.display = "none";
            current_props = null ;
        },

        get :function(id){
            this.id = id;
	    type = jd.get(id,'type');
            parr = new Array();
            for(x = 0; x < cp[type].length; x++){
	       parr[x] =  this.list(this[cp[type][x]]());
            }
            return Builder.node('ul',{className:"props",style:"display:inline;",id:this.fieldID('props')},parr);            
        },
        fieldID: function(field_name){
            return field_name + "_" + this.id;
        },
        lineBreak :function(){return Builder.node('br');},
        label :function(label_name){
            label = Builder.node('label',{style:"margin-right:4px;"}); label.innerHTML = label_name; return label;
        },
        text: function(field){
            return  Builder.node('input',{name: field, type:'text', id:this.fieldID(field), style:"width:70%;", onkeyup:'a.updateProps(this.name, this.value)'});  
	},
	choice_text: function(field, pos){
            return  Builder.node('input',{name: field, type:'text', id:this.fieldID(field) + "_" + pos, value:jd.getChoice(this.id,pos), className:'medium', onkeyup:'a.updateProps(this.name, this.value,' + pos + ')',  onchange:'a.checkChoiceUniqness(this.id,this.value, ' + pos + ')'});
        },
        list :function(children){
            return Builder.node('li', {style:"display:inline;padding: 8px;"},children);
        },
        title :function(){
            //$("label_"+this.id ).innerHTML = jd.get(this.id,'title');
            return Builder.node('input',{type:'text',value: jd.get(this.id,'title'), name:"title",id:"title", className:'small', onkeyup:'a.updateProps(this.name,this.value)',onchange:'a.checkUniqness(this.id,this.value)'});
	},
        size :function(){
            lbl = this.label('size:');
            options = new Array();
            sizes = ['small','medium','large'];
            sel_size = jd.get(this.id,'size');
            sizes.each(function(num,index){options[index] = Builder.node('option', {value:sizes[index]}, sizes[index]) });
            options.each(function(num,index){
                    if(options[index].value == sel_size){
                        options[index] = Builder.node('option', {value:sizes[index],selected:'yes'}, sizes[index]);
                    }
            });
            return [lbl,Builder.node('select',{name:"size",onchange:'a.updateProps(this.name,this.options[this.options.selectedIndex].value)'}, options)];
        },
        mandatory : function(id){
            lbl = this.label(' mandatory');
            if(jd.get(id,'mandatory')){
                return [Builder.node('input', {name:'mandatory',type:'checkbox',checked:'true', style:'margin-left:5px;',onClick:'_id='+id+';a.updateProps(this.name,this.checked)'}), lbl];                
            }else{
                return [Builder.node('input', {name:'mandatory',type:'checkbox',style:'margin-left:5px', onClick:'_id='+id+';a.updateProps(this.name,this.checked)'}), lbl];
            }
            
        },
        units :function(){
            lbl = this.label("units");
            return [lbl,Builder.node('input',{name:'units',id:'units',type:'text',className:'small',value:jd.get(this.id,'units'),onkeyup:'a.updateProps(this.name,this.value)'})];
        },
        currency :function(){
            lbl = this.label('currency');
            cu = ['Indian Rupee (INR),(Rs.)','US Dollar (USD),($)','GB Pound (GBP),(#)'];
            currencies = [];
            c_selected = jd.get(this.id,'currency');
            if(jd.get(this.id, 'units') == "") { jd.set(this.id,'units','(Rs.)'); }
            cu.each(function(item,index){
                parts = item.split(",");
                if(c_selected == parts[1]){
                    currencies[index] = Builder.node('option', {value:parts[1],selected:'selected'},  parts[0]);
                }else{
                    currencies[index] = Builder.node('option', {value:parts[1]},  parts[0]);
                }
            });
            return [lbl,Builder.node('select',{id:"currency_"+this.id,name:"currency",onchange:'a.updateProps(this.name,this.options[this.options.selectedIndex].value)'}, currencies)];
            
        },
        edit: function(field, name, pos) {
            action = (name == 'title') ? 'a.checkUniqness(event,this.id,this.value)' : 'a.checkChoiceUniqness(event,this.id,this.value, ' + pos + ')'; 
            Element.hide(field);
            inp = Builder.node('input',{name: name, type:'text', id:"edit_" + field.id, className:"medium", onchange:action, onkeyup:'a.updateProps1(event,this.name, this.value,' + pos + ')', onblur:'props.hideEdit("' + field.id + '");', value: field.innerHTML});  
            fld = Builder.node('div', {id: "editor_"+field.id}, [inp]);
            new Insertion.After(field, fld.innerHTML);
            $('edit_'+field.id).select();
        },
        hideEdit: function(id) {
            Element.hide('edit_' + id);
            Element.show(id);
        },
        addChoiceLink :function(){
            name = 'add'; add = Builder.node('div',{style:'display:block;padding-bottom:2px;margin-top:10px;padding:2px;padding-right:30px;font-size:11px;text-align:right;'}); add.innerHTML = "<a href='#' onClick='addChoice("+ this.id +"); '>add more choices</a>";return add;
        },
        removeChoiceLink :function(pos){
            name = 'remove'; 
            remove = Builder.node('span',{id: 'remove_choice_' + this.id + '_' + pos, style:'margin-left:100px;font-size:10px;'}); remove.innerHTML = "<a href='#' onClick=\"if (confirm('Are you sure you want to delete this field')) { removeChoice("+ this.id +"," + pos + "); }\"><img src='/images/remove.png' /></a>";
            return Builder.node('div', {style:'border:0px solid green;float:right;margin:0px 70px 0px 0px;'}, remove);
        },
	selection :function(){
	    var choices = [];
	    dom_id = this.id;
	    lbl = this.label('selection');
	    var choices = jd.get(this.id, 'choice');
	    var container = Builder.node('div', {id: 'selection_container_' + this.id});
	    var elements = Builder.node('div', {id: 'choice_elements_' + this.id});
	    for(var i=0;i<choices.length;i++){
	       choice_element = Builder.node('div', {id: 'choice_element_' + this.id + "_" + choices[i].id, className: '', width:'550px',style:'height:20px;border:0px solid yellow;padding:5px 2px 0pt'});
	       choice_element.appendChild(this.removeChoiceLink(choices[i].id));
	       choice_element.appendChild(this.choice_text('choice', choices[i].id));
	       elements.appendChild(choice_element);
	    }
	    container.appendChild(elements);
	    container.appendChild(this.addChoiceLink());
	    return container;
        }
        
    }
 /*
  * invoked when the property of the control is changed
  */
var Actions = Class.create();
    Actions.prototype = {
        initialize :function(){},
        updateProps1 :function(e,field,value,pos){
            this[field](e,_id,value,pos);
        },
        updateProps :function(field,value,pos){
            this[field](_id,value,pos);
        },
	checkUniqness :function(id,value){
	    if(jd.exists(_id,'title',value)){alert(value + " is already assigned to another field"); $(id).value = "untitled"; this['title'](_id,"untitled"); }
	},
	checkChoiceUniqness :function(id,value,pos){
	    if(jd.existsChoice(_id,value, pos)){alert(value + " is already assigned to another choice field"); this['choice'](_id,"untitled",pos); }

	},
        //title :function(e, id,value,pos){$("label_"+id).innerHTML = value;jd.set(id,'title',value);if(e.keyCode == 13) {props.hideEdit('label_' + id);}},
        title :function(id,value,pos){$("label_"+id).innerHTML = value;jd.set(id,'title',value);},
        units :function(id,value,pos){$("units_"+id).innerHTML = "(" + value +")";jd.set(id,'units',value);},
        currency :function(id,value,pos){$("units_"+id).innerHTML =  value ;jd.set(id,'units',value);},
        size : function(id,value,pos){$("text_"+id).className = value; jd.set(id,'size',value);},
        choice  :function(id,value,pos){$("option_"+id+"_"+pos).value=value;$("option_"+id+"_"+pos).innerHTML =  value;$("choice_"+id+"_"+pos).value=value;jd.setChoice(id,value,pos);},
        mandatory : function(id,value,pos){jd.set(id,'mandatory',value);$('mandatory_'+id).innerHTML = jd.get(id,'mandatory') ? "*": ""; }
   }    
 
   /*
    * binds events to the controls
    */
   function bindFieldEvents(ctl){
    	Event.observe(ctl.div, 'click', selectControl.bind(ctl) , false);
   }

   function bindPropertyEvents(ctl){
	 choices = jd.get(ctl, 'choice');
	 for (var i=0;i<choices.length;i++) {
	   element = $('choice_element_' + ctl + '_' + choices[i].id);
    	   Event.observe(element, 'click', selectProperty.bind(element), false);
	 }

   }

   function selectProperty() {
	   if(selected_choice != undefined ) {
		sel_ctl = $(selected_choice);
		if(sel_ctl) {
		   sel_ctl.className = '';
		   sel_ctl_ids = sel_ctl.id.split('_');
		   Element.hide('remove_choice_' + sel_ctl_ids[2] + '_' + sel_ctl_ids[3]);
		}
	   }
	   ids =  this.id.split('_');
	   this.addClassName = 'selected';
	   Element.show('remove_choice_' + ids[2] + '_' + ids[3]);
	   selected_choice = this.id;
   }

   /*
    * control selected usually through click
    */
   function selectControl(){
        if(selected  > 0){
            ctl = jd.get(selected,'object');
		if(ctl){
                      Element.removeClassName(ctl.div, "selected");
	    	}
        }
        ctl = jd.get(this.id,'object');
        Element.addClassName(ctl.div, "selected");
        selected = this.id;
        _id = this.id;
        props.show(this.id);
        type = jd.get(this.id, 'type');
        setControlType(type);
   }

   function setControlType(type) {
     switch(type) {
       case 'text': $('controls').options[1].selected = "selected"; break;
       case 'paragraph': $('controls').options[2].selected = "selected";break;
       case 'number': $('controls').options[3].selected = "selected";break;
       case 'date': $('controls').options[4].selected = "selected";break;
       case 'weblink': $('controls').options[5].selected = "selected";break;
       case 'email': $('controls').options[6].selected = "selected";break;
       case 'money': $('controls').options[7].selected = "selected";break;
       case 'image': $('controls').options[8].selected = "selected";break;
       case 'selection': $('controls').options[9].selected = "selected";break;
     }
   }

   function selectCurrency(id) {
     c_selected = jd.get(id,'units');
     opts = $('currency_'+id).options;
     for(var i=0;i<opts.length;i++) {
         if (opts[i].value == c_selected) {
           opts[i].selected = true;
           return;
         } 
     }
   }

   
   /**
    * removes the control 
    */
 	
   function removeControl(ctl_id){
        ctl = jd.get(ctl_id,'object');
        Element.remove(ctl.div);
     //   Element.remove(ctl.additional);
        jd.removeField(ctl_id);
	selected = 0;
   }

   /**
    * Activates the drag and drop control
    */
   function activateMove(){
       Sortable.create('elements',{tag:'div',dropOnEmpty: true, containment: sections,only:'element',format:/^(.*)$/});  
       ctl.div.style.cursor="move";
   }

   /**
    * Deactivates the drag and drop control
    */
   function deactivateMove() {
   //  window.setTimeout("disable_now()", 1000);
     ctl.div.style.cursor="pointer";
   }
  
   function disable_now() {
     Sortable.destroy('elements');return false;
   }

   /*
    * Add an input field to the Properties
    * Add an option to the current selection control
    * Add an entry with required data to the Json Database 
    */
   function addChoice(ctl_id){
	ctl = jd.get(ctl_id, 'choice');
	var next_index = ctl.length;
	var pos = ctl[ctl.length - 1].id + 1;
	lbl = props.label((pos+1) + ". ");
	jd.get(ctl_id,'choice').splice((pos),0,{'option':"enter choice" + (pos+1),'id':pos});
	value = jd.getChoice(ctl_id, pos);
	$('selection_' + ctl_id).appendChild(Builder.node('option', {value:value, disabled:true, id: 'option_' + ctl_id + '_' + pos}, value));
	choice_element = Builder.node('div', {id: 'choice_element_' + ctl_id + "_" + pos, style:'padding:5px 2px 0pt'});
	choice_element.appendChild(props.removeChoiceLink(pos));
	choice_element.appendChild(props.choice_text('choice', pos));
	$('choice_elements_' + ctl_id).appendChild(choice_element);
	selected_choice = choice_element.id;
   }

   /*
    * Remove input field from Properties
    * Remove the corresponding option from the current selection control
    * Remove the corresponding entry from the Json Database 
    */
   function removeChoice(ctl_id, pos){
     Element.remove("choice_element_" + ctl_id + "_" + pos);
     idx = jd.getChoiceIndex(ctl_id, pos);
     jd.get(ctl_id,'choice').splice(idx,1);
     Element.remove('option_' + ctl_id + "_" + pos);
   }

   /*
    *  Debug Functions for checking the group and item order
    **/
   function getGroupOrder() {
       Sortable.create('elements',{tag:'div',dropOnEmpty: true, containment: sections,only:'element',format:/^(.*)$/});  
       var sequence = Sortable.sequence('elements');
        sequence.each(function(num, index) {
          jd.setDomOrder(num, (index+1));
       });
   }



var props = new Properties();
var a = new Actions();
var jd = new Db();
var _field = null;
var _id = null;
var c_id = 0;
var selected = 0;
var selected_choice;
