AppState = {
	page: 1,
	ipp: 25,
	show: 'all',
	q: ''
}

function init()
{
	
  btn = MakeGlButton({
  	caption: 'Default',
	onclick:function(){
		if (confirm('Are you sure you want to reset all fields to defaults?'))
		{
			removeChildNodes(neo('gsom-fields-list'));
			BuildForm({arr:def_form});
		}	
	},
	width: 90
  });
  
  if (btn)
  	neo('gsom-ddbutton-restore').appendChild(btn);
	
  btn = new MakeDDGlButton({
		caption: 'Add Field',
		id: 'gsom-dropdown-add-field',
		items: [{caption:'Text Field',
				 onclick: function(){FormAddEditTextField()}},
				{caption:'Checkbox',
				 onclick:function(){FormAddEditCheckboxField()}},
				{caption:'Radio Group',
				 onclick:function(){FormAddEditRadioGroupField()}}				 
			   ],
		width: 90
	});
	
  if (btn.ibtn)
  	neo('gsom-ddbutton-placeholder').appendChild(btn.ibtn);
	
  
  Event.observe(document.body,'click',function(event){
	var element = Event.element(event);
	var p = neo(element).up('ul.glbuttonddlist');
	if (p) return;
	
	p = neo(element).up('div#gsom-dropdown-add-field');
	if (p) return;

	if (this.lst) 		
	{
		if (neo(this.lst).visible())
			this.lst.hide();
	}
  }.bindAsEventListener(btn))

}

//Event.observe(window, 'load', init, false);

//gsom-ddbutton-placeholder

//TODO: Manage Actions through AppState object

function initManager(args)
{
	var tbl = neo('gsom-mgr-subscribers');
	if (tbl)
	{
		var mainCheckBox = neo(tbl.tHead.rows[0].cells[0]).down('input');
		if (mainCheckBox)
		{
			Event.observe(mainCheckBox,'click',function(){
				MarkAll(this.checked);
			}.bindAsEventListener(mainCheckBox));
		}
	}
	
	var btn = neo('gsom-btn-unsubscribe');
	if (btn)
		Event.observe(btn,'click',Unsubscribe);		
		
		
	btn = neo('gsom-btn-delete');
	if (btn)
		Event.observe(btn,'click',DeleteSubscribers);
		
		
	btn = neo('gsom-search-btn');
	if (btn)
	{
		Event.observe(btn,'click',function(){
			var inp = neo('gsom-search-input');
			if (inp)
			{				
				var query = inp.value;
				AppState.q = query;
				
				//switching type button
				var list = neo('wpbody').down('ul.subsubsub');
				var links;
				if (list)
				{
					links = list.select('a');
					for(var i=0; i < links.length; i++)
					{
						if (neo(links[i]).hasClassName('current'))
							neo(links[i]).removeClassName('current');
					}		
				}
				btn = neo('gsom-mgr-stype-all');
				if (btn)								
					btn.addClassName('current');				
				//-
				getSubscribers();
			}
		});
	}
	
	btn = neo('gsom-search-input');
	if (btn)
	{
		Event.observe(btn,'keyup',function(e){
		    var edit = e.element();
		    if (edit) {
		        if (e.keyCode == 13) 
		            neo('gsom-search-btn').click();		        		        
		    }
		});
	}
	
	btn = neo('gsom-search-cancel-btn');
	if (btn)
	{
		Event.observe(btn,'click',function(){
			AppState.q = '';
			getSubscribers();
			var inp = neo('gsom-search-input');
			if (inp)
				inp.value = '';
		});
	}
		
	btn = neo('gsom-btn-export');
	if (btn)
	{
		MakeDDMenu({
			parent: btn,
			items: [{caption:'Comma Separated Value (.csv)',
					 onclick: function(){window.location = pathToScripts+'export.php?to=csv&type='+AppState.show+'&q='+AppState.q}},
					{caption:'Excel XML Spreadsheet (.xls)',
					 onclick:function(){window.location = pathToScripts+'export.php?to=xml&type='+AppState.show+'&q='+AppState.q}}
				   ]		
		});		
		
		  Event.observe(document.body,'click',function(event){
			var element = Event.element(event);
			var p = neo(element).up('ul.glbuttonddlist');
			if (p) return;
			
			if (neo(element).id == 'gsom-btn-export') return;
			
			var lst = neo(document.body).down('ul.glbuttonddlist');
		
			if (lst) 		
			{
				if (neo(lst).visible())
					lst.hide();
			}
		  }.bindAsEventListener(btn));		
		
		
	}
	
	
		
/*	'gsom-mgr-stype-all'
	'gsom-mgr-stype-confirmed'
	'gsom-mgr-stype-unconfirmed'
	'gsom-mgr-stype-unsubscribed'		*/
	
	btn = neo('gsom-mgr-stype-all');
	if (btn)
		Event.observe(btn,'click',function(){
			sub3LinkClick('all',this);
		}.bindAsEventListener(btn));
		
	btn = neo('gsom-mgr-stype-confirmed');
	if (btn)
		Event.observe(btn,'click',function(){
			sub3LinkClick('confirmed',this);
		}.bindAsEventListener(btn));
		
	btn = neo('gsom-mgr-stype-unconfirmed');
	if (btn)
		Event.observe(btn,'click',function(){
			sub3LinkClick('unconfirmed',this);
		}.bindAsEventListener(btn));
		
	btn = neo('gsom-mgr-stype-unsubscribed');
	if (btn)
		Event.observe(btn,'click',function(){			
			sub3LinkClick('unsubscribed',this);
		}.bindAsEventListener(btn));
	
	getSubscribers();
}

function RefreshSublinks(args)
{
    if (typeof args == 'undefined') 
        args = new Object();

	var all = typeof args.all != 'undefined' ? args.all : 0;
	var unconfirmed = typeof args.unconfirmed != 'undefined' ? args.unconfirmed : 0;
	var confirmed = typeof args.confirmed != 'undefined' ? args.confirmed : 0;
	var unsubscribed = typeof args.unsubscribed != 'undefined' ? args.unsubscribed : 0;
	var q = typeof args.q != 'undefined' ? args.q : false;
	
	btn = neo('gsom-mgr-stype-all');
	
	var list = neo(btn).up('ul');
	var lbl = neo('gsom-search-results-lbl');		
	if (lbl)
	{
		Element.remove(lbl);
		Element.remove(neo(list).down('br'));
	}	
	
	if (q)
	{		
		if (list)
		{					var oldItem = neo(btn).up('li');
			var newItem = Builder.node('li',{id:'gsom-search-results-lbl'},'Search results for "'+q+'":');
			list.insertBefore(newItem,oldItem);
			newItem = Builder.node('br');
			list.insertBefore(newItem,oldItem);
		}
	}
	
	if (btn)
	{
		if (all > 0)
			btn.innerHTML = 'All Subscribers ('+all+')';		
		else
			btn.innerHTML = 'All Subscribers';				
	}	

	btn = neo('gsom-mgr-stype-confirmed');
	if (btn)
	{
		if (confirmed > 0)
			btn.innerHTML = 'Confirmed ('+confirmed+')';		
		else
			btn.innerHTML = 'Confirmed';				
	}	
		
	btn = neo('gsom-mgr-stype-unconfirmed');
	if (btn)
	{
		if (unconfirmed > 0)
			btn.innerHTML = 'Unconfirmed ('+unconfirmed+')';		
		else
			btn.innerHTML = 'Unconfirmed';				
	}	
	
	btn = neo('gsom-mgr-stype-unsubscribed');
	if (btn)
	{
		if (unsubscribed > 0)
			btn.innerHTML = 'Unsubscribed ('+unsubscribed+')';		
		else
			btn.innerHTML = 'Unsubscribed';				
	}
	
}

function sub3LinkClick(go,el)
{
	if (typeof go == 'undefined') 
		var go = 'all';
	if (!el) return;

	var list = neo('wpbody').down('ul.subsubsub');
	var links;
	if (list)
	{
		links = list.select('a');
		for(var i=0; i < links.length; i++)
		{
			if (neo(links[i]).hasClassName('current'))
				neo(links[i]).removeClassName('current');
		}		
	}
	
	neo(el).addClassName('current');
	
	getSubscribers({
		show:go
	});		
}

function getSubscribers(args)
{
    if (typeof args == 'undefined') 
        args = new Object();

	var page = typeof args.page != 'undefined' ? args.page : 1;
	var ipp = typeof args.ipp != 'undefined' ? args.ipp : 25;
	var show = typeof args.show != 'undefined' ? args.show : 'all';
	var q = typeof AppState.q != 'undefined' ? AppState.q : '';
	
	AppState.page = page;
	AppState.ipp = ipp;
	AppState.show = show;
	
	if (q)
		neo('gsom-search-cancel-btn').show();
	else
		neo('gsom-search-cancel-btn').hide();
			

	
	

	/*  

	
	var tbl = neo('gsom-mgr-subscribers');
	//*/
	
//	return;
	
	tableLoadingIndicator('gsom-mgr-subscribers');

    new Ajax.Request(pathToScripts+'aj.getsubscribers.php', {
        method: 'post',
        parameters: {
            show: show,
			page: page,
			ipp: ipp,
			q: q
        },
        requestHeaders: {
            Accept: 'application/json'
        },
/*
		onComplete: function(transport){
			alert(transport.responseText);
		},
//*/				
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json.state == "true") 
			{
				var table = neo('gsom-mgr-subscribers');
				if(!table) return;
				var tblBody = table.tBodies[0];				
				if(!tblBody) return;
				
				RefreshSublinks({
					all : json.count.all,
					confirmed: json.count.confirmed,
					unconfirmed: json.count.unconfirmed,
					unsubscribed: json.count.unsubscribed,
					q: q
				});
				
				removeChildNodes(tblBody);
				
				for(var i = 0; i < json.rows.length; i++)
				{
					tblBody.appendChild(Builder.node('tr',{className:'alternate'},[
						Builder.node('th',{className:'check-column'},[
							Builder.node('input',{type:'checkbox', value:json.rows[i].id})
						]),
						Builder.node('td',json.rows[i].email),
						Builder.node('td',json.rows[i].time),
						Builder.node('td',json.rows[i].ip),
						Builder.node('td',StatusCodeToText(json.rows[i].status)),
						Builder.node('td',getCustomFieldList(json.rows[i].customData))
					]));
				}				
				if (json.rows.length == 0)
				{
					tableNoDataToDisplay(table);
				}
				
				
				if (json.pageCount > 1)
				{								
					var bars = neo('wpbody').select('div.tablenav-pages');
					if (bars)
					{					
						for (i=0; i < bars.length; i++)
						{
							removeChildNodes(bars[i]);
							CreatePagenationBar({
								bar: bars[i],
								pageCount: json.pageCount,
								selectedPage: page,
								ipp: ipp,
								onClick: getSubscribers													
							});
							bars[i].appendChild(Builder.node('br',{className:'clear'}));
						}
					}
				}
				else
				{
					var bars = neo('wpbody').select('div.tablenav-pages');
					if (bars)
						for (i=0; i < bars.length; i++)
							removeChildNodes(bars[i]);
				}
				
			}
        }
    });
}

function getCustomFieldList(jsonCustomFormData)
{
	var fd = jsonCustomFormData.evalJSON(true);
	var tbl = Builder.node('table',{className:'gsom_small_table'});
	for(var i = 0; i < fd.length; i++)
	{
		tbl.appendChild(Builder.node('tr',[
			Builder.node('td',fd[i].label),
			Builder.node('td',fd[i].value)
		]));
	}
	return tbl;
}


function StatusCodeToText(status)
{
	if (status)
	{
		switch (status)
		{
			case '0':
				return 'Unconfirmed';
			break;
			case '1':
				return 'Confirmed';
			break;
			case '2':
				return 'Unsubscribed';
			break;						
		}
	}
}

function CreatePagenationBar(args)
{
    if (typeof args == 'undefined') 
        args = new Object();
    
	var bar = typeof args.bar != 'undefined' ? args.bar : false;
    var pageCount = typeof args.pageCount != 'undefined' ? args.pageCount : 1;
    var selectedPage = typeof args.selectedPage != 'undefined' ? args.selectedPage : 1;
	var ipp = typeof args.ipp != 'undefined' ? args.ipp : 25;
	var style = typeof args.style != 'undefined' ? args.style : '';
	var onClick = typeof args.onClick != 'undefined' ? args.onClick : false;
	
	var bstyle = 'line-height: 26px; overflow:hidden; background: transparent url(/images/bform/thead_bg.png) repeat-x scroll 0 0; ' + style;
   
    if (bar === false)
		return;
    //var bar = Builder.node('div',{className:'tablenav-pages', style:bstyle});
    
    var btn;
    var from;
	
	if (ipp > 0)
	{			
		
//		bar.appendChild(Builder.node('span','Pages: '));
	    
	    if (selectedPage != 1)
		{
		    // add previous button
		    btn = Builder.node('a');  
			btn.innerHTML = '&laquo; Previous';		
	        btn.addClassName('prev page-numbers');
			btn.addClassName('gsom-flink');
			bar.appendChild(btn);    
			if (onClick !== false)
		    Event.observe(btn,'click',function(){				
				onClick({
					page: selectedPage - 1,
					ipp:ipp,
					show: AppState.show					
				});
		    });
		}
		
		//TODO: add event for number buttons    
	    
	    var centerStart = selectedPage - 1;
	    var centerEnd = selectedPage + 1;
	    var ta = false;
	    
	    for(var i = 1; i <= pageCount; i++)
	    {
	      if (i < 4)
	      {
	        if (i == selectedPage)
			{
			  btn = Builder.node('span',i);
			  bar.appendChild(btn);
	          btn.addClassName('current');        
			}
			else		
			{
			  btn = Builder.node('a',i);
  			  bar.appendChild(btn);			  
		  	  if (onClick !== false)
		      Event.observe(btn,'click',function(){
				  var pg = parseInt(this.innerHTML,10);
				  onClick({
					  page: pg,
					  ipp:ipp					
				  });
		      }.bindAsEventListener(btn));			  

			}
			btn.addClassName('page-numbers');
			btn.addClassName('gsom-flink');
	        ta = false;
	      } 
	      else if ((i >= centerStart) && (i <= centerEnd))
	      {
	        if (i == selectedPage)
			{
			  btn = Builder.node('span',i);
			  bar.appendChild(btn);
	          btn.addClassName('current');        
			}
			else		
			{
			  btn = Builder.node('a',i);
  			  bar.appendChild(btn);			  
		  	  if (onClick !== false)
		      Event.observe(btn,'click',function(){
				  var pg = parseInt(this.innerHTML,10);
				  onClick({
					  page: pg,
					  ipp:ipp					
				  });
		      }.bindAsEventListener(btn));			  

			}
			btn.addClassName('page-numbers');
			btn.addClassName('gsom-flink');
			  
	        ta = false;
	      }
	      else if (i > (pageCount - 3))
	      {
	        if (i == selectedPage)
			{
			  btn = Builder.node('span',i);
			  bar.appendChild(btn);
	          btn.addClassName('current');        
			}
			else		
			{
			  btn = Builder.node('a',i);
  			  bar.appendChild(btn);			  
		  	  if (onClick !== false)
		      Event.observe(btn,'click',function(){
				  var pg = parseInt(this.innerHTML,10);
				  onClick({
					  page: pg,
					  ipp:ipp					
				  });
		      }.bindAsEventListener(btn));			  

			}
			btn.addClassName('page-numbers');
			btn.addClassName('gsom-flink');
			  
	        ta = false;      
	      }
	      else
	      {
	        if (!ta)
	        {
				btn = Builder.node('span');
				btn.innerHTML = '&#8230;';
				bar.appendChild(btn);
		        btn.addClassName('prev');        
  				btn.addClassName('page-numbers');
  	            ta = true;
	        }
	      }   
	
	    }   
	    
	    if (selectedPage != pageCount)
		{
		    // add previous button
		    btn = Builder.node('a');  
			btn.innerHTML = 'Next &raquo;';		
	        btn.addClassName('next page-numbers');        
			btn.addClassName('gsom-flink');
			bar.appendChild(btn);    
			if (onClick !== false)
		    Event.observe(btn,'click',function(){
				onClick({
					page: selectedPage + 1,
					ipp:ipp					
				});
		    });
		} 
		
	}  
		
	var BuildSelect = function (selVal)
	{
		var slkt = Builder.node('select',[
			Builder.node('option',{value:15},'15'),
			Builder.node('option',{value:25},'25'),
			Builder.node('option',{value:50},'50'),
			Builder.node('option',{value:100},'100'),
			Builder.node('option',{value:0},'All')
		]);
		
		var done = false;
		
		for(var i=0; i< slkt.length; i++)
		{
			if (slkt.options[i].value == selVal)
			{
				slkt.selectedIndex = i;
				done = true;
				break;
			}			
		}
		if (!done)
		{				
			slkt.appendChild(Builder.node('option',{value:selVal},String(selVal)));
		}
		
	    Event.observe(slkt,'change',function(){          
		  var nipp = this.options[this.selectedIndex].value;
		  if (nipp)
		  {
			var obj = GetAppStateObj();
		  	obj.ipp = nipp;
	        var rs = obj.StateFunction;
      	    rs(obj);  
		  }
      	}.bindAsEventListener(slkt)); 		

		
		return slkt;			

	}
//		
//	bar.appendChild(Builder.node('div',{style:'float:right; text-decoration: none; background: none;'},[
//		Builder.node('span','Rows on page: '),
//		BuildSelect(ipp)
//	]));
//    
//    return bar;
}

function MarkAll(check)
{
  if (typeof check == 'undefined') 
        var check = true;
	
  var table = neo('gsom-mgr-subscribers');		
  if(!table) return;
  var cbx;
  var cbs = table.select('th.check-column');
  for(var i=0; i < cbs.length; i++)
  {
	cbx = neo(cbs[i]).down('input');
	if (cbx)
		cbx.checked = check;
  }  
}

function DeleteSubscribers()
{
  if (!confirm('Are you sure you want tot delete selected items?'))
  	return;

  var vals = [];
  var table = neo('gsom-mgr-subscribers');		
  if(!table) return;
  var cbx;
  var cbs = table.select('th.check-column');
  for(var i=0; i < cbs.length; i++)
  {
	cbx = neo(cbs[i]).down('input');
	if (cbx)
	{
		if ((cbx.checked) && (cbx.value != 'on'))
			vals[vals.length] = cbx.value;
	}
  }  
  
    new Ajax.Request(pathToScripts+'aj.delete.php', {
        method: 'post',
        parameters: {
            json: Object.toJSON(vals)
        },
        requestHeaders: {
            Accept: 'application/json'
        },
/*
		onComplete: function(transport) {
			alert(transport.responseText);
		},
/*/		
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json.state == "true") 
			{  
				  getSubscribers({
					page: AppState.page,
					ipp: AppState.ipp,
					show:AppState.show
				  });
			}
        }
    });  

  
  getSubscribers({
	page: AppState.page,
	ipp: AppState.ipp,
	show : AppState.show
  });
}

function Unsubscribe()
{
  var vals = [];
  var table = neo('gsom-mgr-subscribers');		
  if(!table) return;
  var cbx;
  var cbs = table.select('th.check-column');
  for(var i=0; i < cbs.length; i++)
  {
	cbx = neo(cbs[i]).down('input');
	if (cbx)
	{
		if ((cbx.checked) && (cbx.value != 'on'))
			vals[vals.length] = cbx.value;
	}
  }  
  
    new Ajax.Request(pathToScripts+'aj.unsubscribe.php', {
        method: 'post',
        parameters: {
            json: Object.toJSON(vals)
        },
        requestHeaders: {
            Accept: 'application/json'
        },
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json.state == "true") 
			{  
				  getSubscribers({
					page: AppState.page,
					ipp: AppState.ipp,
					show : AppState.show					
				  });
			}
        }
    });
}

function tableLoadingIndicator(tblId)
{
	var table = neo(tblId);
	if(!table) return;
	
	var mainCbx = neo('gsom-cbx-main');
	if (mainCbx) mainCbx.checked = false;
	
	var cols = table.tHead.rows[0].cells.length;
	var tblBody = table.tBodies[0];
	if (!tblBody) return;
	removeChildNodes(tblBody);
	tblBody.appendChild(Builder.node('tr',[
		Builder.node('td',{align:'center',colspan:cols},[
			Builder.node('div',{style:'overflow:hidden; width: 70px;'},[
				Builder.node('img',{style:'float:left;',src:'images/loading.gif'}),
				Builder.node('span',{style:'float:left; margin-left: 5px;'},'Loading')			
			])
		])
	]));
	
}

function tableNoDataToDisplay(tblId)
{
	var table = neo(tblId);
	if(!table) return;
	
	var mainCbx = neo('gsom-cbx-main');
	if (mainCbx) mainCbx.checked = false;
	
	var cols = table.tHead.rows[0].cells.length;
	var tblBody = table.tBodies[0];
	if (!tblBody) return;
	removeChildNodes(tblBody);
	tblBody.appendChild(Builder.node('tr',[
		Builder.node('td',{align:'center',colspan:cols},'< No Data To Display >')
	]));
	
}




function stripSymbols (str)
{
	return str.replace(/[\s]+/g,'_').replace(/[^A-Za-z0-9\_]+/g,'');
}


function MakeDDGlButton(args)
{

    if (typeof args == 'undefined') 
        args = new Object();
    var on = typeof args.on != 'undefined' ? args.on : false;
	var id = typeof args.id != 'undefined' ? args.id : '';
    var imgsrc = typeof args.imgsrc != 'undefined' ? args.imgsrc : false;
	var className = typeof args.className != 'undefined' ? args.className : '';
    var onclick = typeof args.onclick != 'undefined' ? args.onclick : false;
	var onfinally = typeof args.onfinally != 'undefined' ? args.onfinally : false;
	var width = typeof args.width != 'undefined' ? args.width : false;
    var caption = typeof args.caption != 'undefined' ? args.caption : 'Untitled';
	var style = typeof args.style != 'undefined' ? args.style : '';
	var sw = typeof args.sw != 'undefined' ? args.sw : false;
	
	this.listItems = typeof args.items != 'undefined' ? args.items : [];
	
	this.ibtn;
	
	this.lst;
	
	this.BuildList = function(args)
	{

	    if (typeof args == 'undefined') 
	        args = new Object();
	    var items = typeof args.items != 'undefined' ? args.items : false;
		var left = typeof args.left != 'undefined' ? args.left : 0;
		var top = typeof args.top != 'undefined' ? args.top : 0;

	    if (!items) 
			items = [
						{caption:'Item Number One'},
						{caption:'Item Number Two'}							
					];

		this.lst = Builder.node('ul',{style:'display:none; left:'+left+'px; '+'top: '+top+'px;',className:'glbuttonddlist'});
		for (var i = 0; i < items.length; i++)		
		{
			var xdiv;
			var d = new Date();
			var ddlirid = 'ddli'+d.getTime();
			xdiv = Builder.node('div',{id:ddlirid, className:'glbuttonddlistitem'}, items[i].caption);
			if (typeof items[i].onclick != 'undefined')
				Event.observe(xdiv,'click',items[i].onclick);
				
			Event.observe(xdiv,'click',function(){
				neo(this).hide();
			}.bindAsEventListener(this.lst));					
			this.lst.appendChild(Builder.node('li',[
				xdiv		
			]));
		}
		
		document.body.appendChild(this.lst);
		
		this.lst.show();
	}
	
	var el;
	
	if(width)	
		{
			if(width == 'def')
				var midblockstyle = 'width:50px;';
			else
				var midblockstyle = 'width:'+(width-10)+'px';
		}
	else
		var midblockstyle = '';

	if(imgsrc)
	{
	    el = Builder.node('img', {
			className: 'bbico',
	        src: imgsrc
	    });	    
	}
	
	if (!on)
		cname = 'glbutton'+' '+className;
	else
		cname = 'glbutton_on'+' '+className;
    
    this.ibtn = Builder.node('div', {className: cname, style: style,id:id},[
		Builder.node('div',{className:'bbleftside'}),
		Builder.node('div',{className:'bbmiddle', style:midblockstyle},[
			el,
			Builder.node('span',{style:'float:left;'},caption),
			Builder.node('img',{style:'margin-left:3px; margin-top: 11px; float:left;',src:gsomPluginPath+'img/darrow.gif'})
		]),
		Builder.node('div',{className:'bbrightside'}),
	]);
	if(onclick)
	    Event.observe(this.ibtn, 'click', onclick);
		
	if(onfinally)
		Event.observe(this.ibtn, 'click', onfinally);
		
	if (sw)
	{
		Event.observe(this.ibtn,'click',function(){
			if(neo(this).hasClassName('glbutton_on'))
			{
				neo(this).removeClassName('glbutton_on').addClassName('glbutton');
			}
			else
				neo(this).removeClassName('glbutton').addClassName('glbutton_on');
		}.bindAsEventListener(this.ibtn));
	}
	
	Event.observe(this.ibtn,'mouseover',function(){
		if(neo(this).hasClassName('glbutton'))
			{
				neo(this).removeClassName('glbutton').addClassName('glbutton_act');
			}
	}.bindAsEventListener(this.ibtn));

	
	Event.observe(this.ibtn,'mouseout',function(){
		if(neo(this).hasClassName('glbutton_act'))
			{
				neo(this).removeClassName('glbutton_act').addClassName('glbutton');
			}	
	});
	
	Event.observe(this.ibtn,'click',function(){
		if (this.lst)
		{
			if (neo(this.lst).visible())
				this.lst.hide();
			else	
				this.lst.show();
				
			return;
		}
		
		var el = this.ibtn;
		if(el)		
		{
			var offset = Element.positionedOffset(el);
			offset.top += Element.getHeight(el) + 1; 			
		}
		this.BuildList({items: this.listItems,left: offset.left,top:offset.top});
	}.bindAsEventListener(this));
	
	return this;
}


function MakeDDMenu(args)
{

    if (typeof args == 'undefined') 
        args = new Object();
		
	var parent = typeof args.parent != 'undefined' ? args.parent : false;
	
	this.listItems = typeof args.items != 'undefined' ? args.items : [];
	
	this.ibtn = neo(parent);
	
	this.lst;
	
	this.BuildList = function(args)
	{

	    if (typeof args == 'undefined') 
	        args = new Object();
	    var items = typeof args.items != 'undefined' ? args.items : false;
		var left = typeof args.left != 'undefined' ? args.left : 0;
		var top = typeof args.top != 'undefined' ? args.top : 0;

	    if (!items) 
			items = [
						{caption:'Item Number One'},
						{caption:'Item Number Two'}							
					];

		this.lst = Builder.node('ul',{style:'display:none; left:'+left+'px; '+'top: '+top+'px;',className:'glbuttonddlist'});
		for (var i = 0; i < items.length; i++)		
		{
			var xdiv;
			var d = new Date();
			var ddlirid = 'ddli'+d.getTime();
			xdiv = Builder.node('div',{id:ddlirid, className:'glbuttonddlistitem'}, items[i].caption);
			if (typeof items[i].onclick != 'undefined')
				Event.observe(xdiv,'click',items[i].onclick);
				
			Event.observe(xdiv,'click',function(){
				neo(this).hide();
			}.bindAsEventListener(this.lst));					
			this.lst.appendChild(Builder.node('li',[
				xdiv		
			]));
		}
		
		document.body.appendChild(this.lst);
		
		this.lst.show();
	}
	
	var el;
	
    	
	Event.observe(this.ibtn,'click',function(){
		if (this.lst)
		{
			if (neo(this.lst).visible())
				this.lst.hide();
			else	
				this.lst.show();
				
			return;
		}
		
		var el = this.ibtn;
		if(el)		
		{
			var offset = Element.positionedOffset(el);
			offset.top += Element.getHeight(el) + 1; 			
		}
		this.BuildList({items: this.listItems,left: offset.left,top:offset.top});
	}.bindAsEventListener(this));
	
	return this;
}

function FormEditSubscribeButton(args)
{
    if (typeof args == 'undefined') 
        args = new Object();    
    
    var fieldId = typeof args.fieldId != 'undefined' ? args.fieldId : '';	
	var type = (!fieldId) ? 'add' : 'edit';
	var oldItem = typeof args.oldItem != 'undefined' ? args.oldItem : false;	
	
	
	var flabel = '';
	var fvalue = '';
	
	if (oldItem)
	{
		type = 'edit';
		flabel = neo(oldItem).down('input').value;
		fvalue = '';
		//fvalue = neo(oldItem).down('input').value;
	}
	
	switch(type)
	{
		case 'add': 
			caption = 'Add Text Field';
		break;
		case 'edit':
			caption = 'Edit Subscribe Button';
		break;
	}
	
	var onSaveClick = typeof args.onSaveClick != 'undefined' ? args.onSaveClick : false;
	//var onCancelClick = typeof args.onCancelClick != 'undefined' ? args.onCancelClick : false;
	
	//--------
	
	var form = Builder.node('div',{className:'bform'});
	
	form.style.width = '325px';
	
	
	form.appendChild(Builder.node('div',{className:'handle'},[
	Builder.node('div',[
		Builder.node('div',{className:'bform-lt'},[
			Builder.node('div',{className:'bform-rt'},[
				Builder.node('div',{className:'bform-t'})
			])
		])
	]),	
	Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-header'},[
					Builder.node('div',{style:'float:left'},caption),
					Builder.node('div',{className:'bform-closebutton'}),
				])
			])
		])
	])
	]));
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-body'})
			])
		])
	]));	
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-lb'},[
			Builder.node('div',{className:'bform-rb'},[
				Builder.node('div',{className:'bform-b'})
			])
		])
	]));	
					
					
	/* creating content */					
	
	var innerframe = Builder.node('div',{style:'margin:20px 0px'},[
						Builder.node('ul',{className:'bform-list'},[
							Builder.node('li',[
								Builder.node('label','Label:'),
								Builder.node('input',{name:'flabel', type:'edit', value:flabel})
							]),							
							Builder.node('li',[								
								Builder.node('input',{name:'id', type:'hidden'}),
								Builder.node('div',{className:'btngroup',style:'overflow:hidden;'},[
									MakeGlButton({
										caption:'OK',
										onclick: function(){
											var inputs = form.select('input');
											var fvalue, flabel;
											var ftype = 'submit';
											for(var i=0; i< inputs.length; i++)
											{
												if (inputs[i].name == 'flabel')
													fvalue = inputs[i].value;													
											}

											var r = MakeFormFieldListItem({
												ul:'gsom-fields-list',
												oldItem: oldItem,
												label:flabel,
												type: ftype,
												value: fvalue,
												name: 'gsom-subscribe'
											});
											if (r)
											{
												var tkill = KillForm.bind(form);
												tkill();
												//Sortable.destroy('gsom-fields-list');
												Sortable.create('gsom-fields-list',{onUpdate:SerializeForm, markDropZone:true, dropOnEmpty: true});   
												//Sortable.create('gsom-fields-list',{onUpdate:SerializeForm});
												SerializeForm();
											}
										},
										width: 'def'
									}),
									MakeGlButton({
										caption:'Cancel',
										onclick: KillForm.bindAsEventListener(form),										
										width: 'def'
									})								
								])
							]),													
							
						])
					 ]);	
					 
	/*    adding box to the document*/	
					
					
					
	document.body.appendChild(form);
	
	neo(form).down('div.bform-body').appendChild(innerframe);		
	
	
	Event.observe(neo(form.down('div.bform-closebutton')),'click',KillForm.bindAsEventListener(form));
	
	var offleft = Math.round(document.viewport.getWidth() / 2) - Math.round(neo(form).getWidth() / 2);
	var offtop = document.viewport.getScrollOffsets().top + Math.round(document.viewport.getHeight() / 2) - Math.round(neo(form).getHeight() / 2);
	
	form.style.top = offtop+'px';
	form.style.left = offleft+'px';	
	
	
	new Draggable(form,{handle:'handle'});	
}


function FormAddEditTextField(args)
{
    if (typeof args == 'undefined') 
        args = new Object();    
    
    var fieldId = typeof args.fieldId != 'undefined' ? args.fieldId : '';	
	var type = (!fieldId) ? 'add' : 'edit';
	var oldItem = typeof args.oldItem != 'undefined' ? args.oldItem : false;	
	
	
	var flabel = '';
	var fvalue = '';
	
	if (oldItem)
	{
		type = 'edit';
		flabel = neo(oldItem).down('label').innerHTML;
		fvalue = neo(oldItem).down('input').value;
	}
	
	switch(type)
	{
		case 'add': 
			caption = 'Add Text Field';
		break;
		case 'edit':
			caption = 'Edit Text Field';
		break;
	}
	
	var onSaveClick = typeof args.onSaveClick != 'undefined' ? args.onSaveClick : false;
	//var onCancelClick = typeof args.onCancelClick != 'undefined' ? args.onCancelClick : false;
	
	//--------
	
	var form = Builder.node('div',{className:'bform'});
	
	form.style.width = '325px';
	
	
	form.appendChild(Builder.node('div',{className:'handle'},[
	Builder.node('div',[
		Builder.node('div',{className:'bform-lt'},[
			Builder.node('div',{className:'bform-rt'},[
				Builder.node('div',{className:'bform-t'})
			])
		])
	]),	
	Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-header'},[
					Builder.node('div',{style:'float:left'},caption),
					Builder.node('div',{className:'bform-closebutton'}),
				])
			])
		])
	])
	]));
	
//	form.appendChild(Builder.node('div',[
//		Builder.node('div',{className:'bform-lt'},[
//			Builder.node('div',{className:'bform-rt'},[
//				Builder.node('div',{className:'bform-t'})
//			])
//		])
//	]));
	
//	form.appendChild(Builder.node('div',[
//		Builder.node('div',{className:'bform-l'},[
//			Builder.node('div',{className:'bform-r'},[
//				Builder.node('div',{className:'bform-header'},[
//					Builder.node('div',{style:'float:left'},caption),
//					Builder.node('div',{className:'bform-closebutton'}),
//				])
//			])
//		])
//	]));	
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-body'})
			])
		])
	]));	
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-lb'},[
			Builder.node('div',{className:'bform-rb'},[
				Builder.node('div',{className:'bform-b'})
			])
		])
	]));	
					
					
	/* creating content */					
	
	var innerframe = Builder.node('div',{style:'margin:20px 0px'},[
						Builder.node('ul',{className:'bform-list'},[
//							Builder.node('li',[
//								Builder.node('label','Field Name:'),
//								Builder.node('input',{name:'fname', type:'edit'})
//							]),
							Builder.node('li',[
								Builder.node('label','Label:'),
								Builder.node('input',{name:'flabel', type:'edit', value:flabel})
							]),							
							Builder.node('li',[
								Builder.node('label','Default value:'),
								Builder.node('input',{name:'fvalue', type:'edit',value: fvalue})
							]),								
//							Builder.node('li',[
//								Builder.node('label','Field type:'),
//								Builder.node('div',[
//									Builder.node('div',[
//										Builder.node('input',{type:'radio', checked:'checked', name:'gsom-ftype', value:'text'}),
//										Builder.node('label','Text Input')										
//									]),
//									Builder.node('div',[
//										Builder.node('input',{type:'radio',name:'gsom-ftype', value:'checkbox'}),
//										Builder.node('label','Checkbox')										
//									]),
//									Builder.node('div',[
//										Builder.node('input',{type:'radio',name:'gsom-ftype', value:'radio'}),
//										Builder.node('label','Radio Button')									
//									])									
//								])
//							]),
							Builder.node('li',[								
								Builder.node('input',{name:'id', type:'hidden'}),
								Builder.node('div',{className:'btngroup',style:'overflow:hidden;'},[
									MakeGlButton({
										caption:'OK',
										onclick: function(){
											var inputs = form.select('input');
											var fvalue, flabel;
											var ftype = 'text';
											for(var i=0; i< inputs.length; i++)
											{
												if (inputs[i].name == 'flabel')
													flabel = inputs[i].value;
													
												if (inputs[i].name == 'fvalue')
													fvalue = inputs[i].value;
													
											}

											var r = MakeFormFieldListItem({
												ul:'gsom-fields-list',
												oldItem: oldItem,
												label:flabel,
												type: ftype,
												value: fvalue												
											});
											if (r)
											{
												var tkill = KillForm.bind(form);
												tkill();
												//Sortable.destroy('gsom-fields-list');
												Sortable.create('gsom-fields-list',{onUpdate:SerializeForm, markDropZone:true, dropOnEmpty: true});   
												//Sortable.create('gsom-fields-list',{onUpdate:SerializeForm});
												SerializeForm();
											}
										},
										width: 'def'
									}),
									MakeGlButton({
										caption:'Cancel',
										onclick: KillForm.bindAsEventListener(form),										
										width: 'def'
									})								
//									Builder.node('button',{className:'savebutton'}, 'Save'),
//									Builder.node('button',{className:'cancelbutton'} ,'Cancel')
								])
							]),													
							
						])
					 ]);	
					 
//	var cbtn = neo(innerframe).down('button.cancelbutton');
//	if(cbtn)
//		Event.observe(cbtn,'click',KillForm.bindAsEventListener(form));	
//
//	var sbtn = neo(innerframe).down('button.savebutton');
//	if(sbtn)
//		Event.observe(sbtn,'click',CampaignAddEditSaveButtonClick.bindAsEventListener(form));						 
					 
	/*    adding box to the document*/	
					
					
					
	document.body.appendChild(form);
	
//	neo(form).down('div.bform-body').appendChild(Builder.node('div',
//		{style:'float:left; z-index:9000; top: 10px; left: 10px; width: 30px; height:30px; backgroud: #ffffff;'}
//		));
		
	neo(form).down('div.bform-body').appendChild(innerframe);		
	
	
	Event.observe(neo(form.down('div.bform-closebutton')),'click',KillForm.bindAsEventListener(form));
	
	var offleft = Math.round(document.viewport.getWidth() / 2) - Math.round(neo(form).getWidth() / 2);
	var offtop = document.viewport.getScrollOffsets().top + Math.round(document.viewport.getHeight() / 2) - Math.round(neo(form).getHeight() / 2);
	
	form.style.top = offtop+'px';
	form.style.left = offleft+'px';	
	
	
	new Draggable(form,{handle:'handle'});	
}

function FormAddEditCheckboxField(args)
{
    if (typeof args == 'undefined') 
        args = new Object();    
    
    var fieldId = typeof args.fieldId != 'undefined' ? args.fieldId : '';	
	var type = (!fieldId) ? 'add' : 'edit';
	var oldItem = typeof args.oldItem != 'undefined' ? args.oldItem : false;	
	
	
	var flabel = '';
	var fchecked = false;
	var caption = '';
	
	if (oldItem)
	{
		type = 'edit';
		var oi = neo(oldItem);
		if (oi)
		{
			flabel = oi.down('label').innerHTML;
			fchecked = oi.down('input').checked;
		}
	}
	
	switch(type)
	{
		case 'add': 
			caption = 'Add Checkbox';
		break;
		case 'edit':
			caption = 'Edit Checkbox';
		break;
	}
	
	
	var onSaveClick = typeof args.onSaveClick != 'undefined' ? args.onSaveClick : false;
	//var onCancelClick = typeof args.onCancelClick != 'undefined' ? args.onCancelClick : false;
	
	//--------
	
	var form = Builder.node('div',{className:'bform'});
	
	form.style.width = '325px';
	
	form.appendChild(Builder.node('div',{className:'handle'},[
	Builder.node('div',[
		Builder.node('div',{className:'bform-lt'},[
			Builder.node('div',{className:'bform-rt'},[
				Builder.node('div',{className:'bform-t'})
			])
		])
	]),	
	Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-header'},[
					Builder.node('div',{style:'float:left'},caption),
					Builder.node('div',{className:'bform-closebutton'}),
				])
			])
		])
	])
	]));	
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-body'})
			])
		])
	]));	
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-lb'},[
			Builder.node('div',{className:'bform-rb'},[
				Builder.node('div',{className:'bform-b'})
			])
		])
	]));
	
	var cparams;	
	
	if(fchecked)
		cparams = {name:'fchecked', checked:'checked',type:'checkbox'};
	else
		cparams = {name:'fchecked', type:'checkbox'};
		
					
					
	/* creating content */					
	
	var innerframe = Builder.node('div',{style:'margin:20px 0px'},[
						Builder.node('ul',{className:'bform-list'},[
//							Builder.node('li',[
//								Builder.node('label','Field Name:'),
//								Builder.node('input',{name:'fname', type:'edit'})
//							]),
							Builder.node('li',[
								Builder.node('label','Label:'),
								Builder.node('input',{name:'flabel', type:'edit',value:flabel})
							]),							
							Builder.node('li',[
								Builder.node('label','Checked:'),
								Builder.node('input',cparams)
							]),
							Builder.node('li',[								
								Builder.node('input',{name:'id', type:'hidden'}),
								Builder.node('div',{className:'btngroup',style:'overflow:hidden;'},[
									MakeGlButton({
										caption:'OK',
										onclick: function(){
											var inputs = form.select('input');
											var fvalue, flabel,fchecked;
											var ftype = 'checkbox';
											for(var i=0; i< inputs.length; i++)
											{
												if (inputs[i].name == 'flabel')
													flabel = inputs[i].value;
													
												if (inputs[i].name == 'fchecked')
													fchecked = inputs[i].checked;													
											}

											var r = MakeFormFieldListItem({
												ul:'gsom-fields-list',
												oldItem: oldItem,
												label:flabel,
												type: ftype,
												checked: fchecked
											});
											if (r)
											{
												var tkill = KillForm.bind(form);
												tkill();
												//Sortable.destroy('gsom-fields-list');
												Sortable.create('gsom-fields-list',{onUpdate:SerializeForm, markDropZone:true, dropOnEmpty: true});   
												//Sortable.create('gsom-fields-list',{onUpdate:SerializeForm});
												SerializeForm();
											}
										},
										width: 'def'
									}),
									MakeGlButton({
										caption:'Cancel',
										onclick: KillForm.bindAsEventListener(form),										
										width: 'def'
									})								
//									Builder.node('button',{className:'savebutton'}, 'Save'),
//									Builder.node('button',{className:'cancelbutton'} ,'Cancel')
								])
							]),													
							
						])
					 ]);	
					 
	/*    adding box to the document*/	
	document.body.appendChild(form);
	
	neo(form).down('div.bform-body').appendChild(innerframe);		
	
	Event.observe(neo(form.down('div.bform-closebutton')),'click',KillForm.bindAsEventListener(form));
	
	var offleft = Math.round(document.viewport.getWidth() / 2) - Math.round(neo(form).getWidth() / 2);
	var offtop = document.viewport.getScrollOffsets().top + Math.round(document.viewport.getHeight() / 2) - Math.round(neo(form).getHeight() / 2);
	
	form.style.top = offtop+'px';
	form.style.left = offleft+'px';	
	
	
	new Draggable(form,{handle:'handle'});	
}

function AddRbListItem(args){
	    if (typeof args == 'undefined') 
	        args = new Object();    
	    
	    var parent = typeof args.parent != 'undefined' ? args.parent : '';	
		var flabel = typeof args.label != 'undefined' ? args.label : '';	
		var fchecked = typeof args.checked != 'undefined' ? args.checked : false;	
		
		var el, rbparams;
		
		if (fchecked)
			rbparams = {className: 'radio', checked:'checked', style:'float:left;',type:'radio', name:'gsom-temp-radio'};
		else
			rbparams = {className: 'radio', style:'float:left;',type:'radio', name:'gsom-temp-radio'};
		
		
		
		var rbrid = 'rbrid'+Math.floor(Math.random()*101);
		
		el = Builder.node('li',{id: rbrid, style:'clear:both; overflow:hidden;'},[
				Builder.node('input',rbparams),
				Builder.node('input',{className: 'lbl', style:'float:left;',type:'text',value:flabel}),
				makeLButton({
					imgsrc: gsomPluginPath+'img/delete.png',
					onclick: function(){ 
						if (confirm('Are you sure you want to delete this item?')) 
						{	
							var rel = neo(rbrid);
							Element.remove(rel);
						}
					}
				})
			]);
			
		if(parent)	
		{
			neo(parent).appendChild(el);
			return true;
		}
		else			
			return el;
		
	}	

function FormAddEditRadioGroupField(args)
{
    if (typeof args == 'undefined') 
        args = new Object();    
    
    var fieldId = typeof args.fieldId != 'undefined' ? args.fieldId : '';	
	var type = (!fieldId) ? 'add' : 'edit';
	var oldItem = typeof args.oldItem != 'undefined' ? args.oldItem : false;	
	
	
	
	var flabel = '';
	
	
	if (oldItem)
	{
		type = 'edit';		
		flabel = neo(oldItem).down('label').innerHTML;
	}
	
	switch(type)
	{
		case 'add': 
			caption = 'Add Radio Group';
		break;
		case 'edit':
			caption = 'Edit Radio Group';
		break;
	}
	
	var onSaveClick = typeof args.onSaveClick != 'undefined' ? args.onSaveClick : false;
	//var onCancelClick = typeof args.onCancelClick != 'undefined' ? args.onCancelClick : false;
	
	//--------
	
	var form = Builder.node('div',{className:'bform'});
	
	form.style.width = '345px';
	
	form.appendChild(Builder.node('div',{className:'handle'},[
		Builder.node('div',[
			Builder.node('div',{className:'bform-lt'},[
				Builder.node('div',{className:'bform-rt'},[
					Builder.node('div',{className:'bform-t'})
				])
			])
		]),	
		Builder.node('div',[
			Builder.node('div',{className:'bform-l'},[
				Builder.node('div',{className:'bform-r'},[
					Builder.node('div',{className:'bform-header'},[
						Builder.node('div',{style:'float:left'},caption),
						Builder.node('div',{className:'bform-closebutton'}),
					])
				])
			])
		])
	]));
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-l'},[
			Builder.node('div',{className:'bform-r'},[
				Builder.node('div',{className:'bform-body'})
			])
		])
	]));	
	
	form.appendChild(Builder.node('div',[
		Builder.node('div',{className:'bform-lb'},[
			Builder.node('div',{className:'bform-rb'},[
				Builder.node('div',{className:'bform-b'})
			])
		])
	]));	
	
	

					
					
	/* creating content */					
	
	var innerframe = Builder.node('div',{style:'margin:20px 0px 10px 0px;'},[
						Builder.node('ul',{className:'bform-list'},[
//							Builder.node('li',[
//								Builder.node('label','Field Name:'),
//								Builder.node('input',{name:'fname', type:'edit'})
//							]),
							Builder.node('li',[
								Builder.node('label','Label:'),
								Builder.node('input',{id:'flabel',name:'flabel', type:'edit',value:flabel})
							]),							
							Builder.node('li',{style:'overflow:hidden;'},[
								makeLButton({
									imgsrc:gsomPluginPath+'img/add.png',
									style:'float:left;',
									onclick: function(){										
										AddRbListItem({parent:neo(innerframe).down('ul.bform-rb-list')});	
									}									
								}),							
								Builder.node('label','Radio Buttons:'),
								Builder.node('ul',{className:'bform-rb-list'})
//								Builder.node('ul',{ className:'grid'},[
//									Builder.node('li',{style:'clear:both'},[
//										Builder.node('div',{className:'grid-hdr', style:'width:150px'},'Label'),
//										Builder.node('div',{className:'grid-hdr', style:'width:50px'},'Value'),
//									]),
//									Builder.node('li',{style:'clear:both'},[
//										Builder.node('div',{className:'grid-row', style:'width:150px'},'Subscribe'),
//										Builder.node('div',{className:'grid-row', style:'width:50px'},'Unsubscribe')
//									])									
//									
//								])
							]),
							Builder.node('li',{style:'margin-top:20px;'},[								
								Builder.node('input',{name:'id', type:'hidden'}),
								Builder.node('div',{className:'btngroup',style:'overflow:hidden;'},[
									MakeGlButton({
										caption:'OK',
										onclick: function(){
											var inputs = form.select('ul.bform-rb-list li');
											var rbArray = [];
											var flabel;
											var ftype = 'radio';
											
											flabel = neo('flabel').value;
											
											for(var i=0; i< inputs.length; i++)
											{
												rbArray[rbArray.length] = {
													label: inputs[i].down('input.lbl').value,
													checked: inputs[i].down('input.radio').checked
												}												
											}
												
											var r = MakeFormFieldListItem({
												ul:'gsom-fields-list',
												oldItem:oldItem,
												label:flabel,
												type: ftype,
												value: rbArray
											});
											if (r)
											{
												var tkill = KillForm.bind(form);
												tkill();
												//Sortable.destroy('gsom-fields-list');
												Sortable.create('gsom-fields-list',{onUpdate:SerializeForm, markDropZone:true, dropOnEmpty: true});   
												//Sortable.create('gsom-fields-list',{onUpdate:SerializeForm});
												SerializeForm();
											}
										},
										width: 'def'
									}),
									MakeGlButton({
										caption:'Cancel',
										onclick: KillForm.bindAsEventListener(form),										
										width: 'def'
									})								
//									Builder.node('button',{className:'savebutton'}, 'Save'),
//									Builder.node('button',{className:'cancelbutton'} ,'Cancel')
								])
							]),													
							
						])
					 ]);	
					 
					 
					 
	/*    adding box to the document*/	
	document.body.appendChild(form);
	neo(form).down('div.bform-body').appendChild(innerframe);		
	
	// ---------->>>>>>>s	
	var place = innerframe.down('ul.bform-rb-list');
	if (place)
	{
		if (oldItem)
		{
			var oiList = neo(oldItem).select('input');
			if(oiList)
			{
				for(var i=0; i < oiList.length; i++)
				{
					var chkd = oiList[i].checked;
					var lbl = Element.nextSiblings(oiList[i])[0].innerHTML;
					place.appendChild(AddRbListItem({
						label: lbl,
						checked: chkd
					}));
				}
			}			
		}							
		else
			place.appendChild(AddRbListItem());

	}
					 
	
	
	
	
	Event.observe(neo(form.down('div.bform-closebutton')),'click',KillForm.bindAsEventListener(form));
	
	var offleft = Math.round(document.viewport.getWidth() / 2) - Math.round(neo(form).getWidth() / 2);
	var offtop = document.viewport.getScrollOffsets().top + Math.round(document.viewport.getHeight() / 2) - Math.round(neo(form).getHeight() / 2);
	
	form.style.top = offtop+'px';
	form.style.left = offleft+'px';	
	
	
	new Draggable(form,{handle:'handle'});	
}


function SerializeForm()
{	
	var form = [];
	var inps, inp,lbl;
	var list = neo('gsom-fields-list');	
	if (list)
	{
		removeChildNodes(neo('gsom-confirm-mess-varlist'));
//		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoblog_name'));
//		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoblog_url'));
//		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neomanage_subscription_link'));
//		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoconfirmation_link'));
//		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoresend_confirmation_link'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoblog_name'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoblog_url'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neofrom_email'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neofrom_name'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neomanage_subscription_link'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoconfirmation_link'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoresend_confirmation_link'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neoencoded_email'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neodecoded_email'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neosubscription_time'));
		neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neosubscriber_ip'));
				
		var items = neo(list).select('li');
		if (items)
		{
			for (var i = 0; i < items.length; i++)
			{
				lbl = items[i].down('label');
				label = lbl ? lbl.innerHTML : '';				
				
				inps = items[i].select('input');
				if (inps.length > 1)
				{
					var options = [];
					for(var j = 0; j < inps.length; j++)
					{
						options[options.length] = {
							label: neo(inps[j]).nextSiblings()[0].innerHTML,
							checked: inps[j].checked
						}
					}
					form[form.length] = {
						label : label,
						name  : inps[0].name,
						value : options,
						type  : 'radio' 
					}					
					
					neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neo'+inps[0].name));
				}
				else
				{
					inp = inps[0];
					if (inp)
					{	
						var tp = inp.type;			
						if (inp.type.toLowerCase() == 'button')
							tp = 'submit';
					
						
					var nobj = {
							label : label,
							name  : inp.name,
							value : inp.value,
							type  : tp
						}					
					if (inp.type.toLowerCase() == 'checkbox')
						nobj.checked = inp.checked;
						
						form[form.length] = nobj;			
						
						if (inp.name != 'gsom-subscribe')								
							neo('gsom-confirm-mess-varlist').appendChild(Builder.node('p','neo'+inp.name));
						
					}
				}
				


			}
		}
	}
	var formOutput = neo('gsom-json-serialized-form');
	if (formOutput)
	{
		formOutput.value = Object(form).toJSON();
		// further code for debug only
		//neo('gsom_form').gsom_sform_footer.value = formOutput.value;
		//alert('done');
	}
	
}

function BuildForm(args)
{
    if (typeof args == 'undefined') 
        args = new Object();			

	var arr = typeof args.arr != 'undefined' ? args.arr : [];
	var place = typeof args.place != 'undefined' ? args.place : 'gsom-fields-list';
	var makeDivs = typeof args.makeDivs != 'undefined' ? args.makeDivs : false;
	var itemNodeName = makeDivs ? 'div' : 'li';
	if (typeof arr != 'undefined')
	{
		for(var i=0; i < arr.length; i++)
		{
			MakeFormFieldListItem({
				ul:place,
				label:arr[i].label,
				type: arr[i].type,
				value: arr[i].value,
				name: arr[i].name,
				checked: arr[i].checked,
				itemType: itemNodeName
			});
		}
		SerializeForm();
	}
}

function MakeFormFieldListItem(args)
{
    if (typeof args == 'undefined') 
        args = new Object();		
		
	var ul = typeof args.ul != 'undefined' ? args.ul : '';
	var oldItem = typeof args.oldItem != 'undefined' ? args.oldItem : false;
    var type = typeof args.type != 'undefined' ? args.type : 'text';
	var label = typeof args.label != 'undefined' ? args.label : '';
	var fname = typeof args.name != 'undefined' ? args.name : '';
	var fvalue = typeof args.value != 'undefined' ? args.value : '';
	var checked = typeof args.checked != 'undefined' ? args.checked : false;
	var itemType = typeof args.itemType != 'undefined' ? args.itemType : 'li';
	
	var list = neo(ul);
	
	var FieldExist = function(fieldName)
	{
		if (list)
		{
			var fl = neo(list).select('input');
			for (var i=0; i < fl.length; i++)
			{
				if (fl[i].name == fieldName)
					return true;
			}
		}
		return false;
	}
	
	if(fname == '')
	{
		var ctr = 1;
		do
		{
			fname = stripSymbols(label);
			fname += String(ctr);
			ctr++;
		} while (FieldExist(fname));
	}	

	
	//fvalue = fname;
	
	var lItem, tel, tdiv;
	
    var d = new Date();
//    var rid = 'newcamp' + d.getTime();	
	var lrid = 'sfi_' + d.getTime();
	
	var labelClass = '';
	var cbRbClass = '';
	
	if (typeof gsomAdminMenu == 'undefined')
		gsomAdminMenu = false;
	
	if (gsomAdminMenu)
	{
		cbRbClass = 'gsom-optin-radiogroup-admin';
	}
	else
	{
		cbRbClass = 'gsom-optin-radiogroup';
	}
	
	if ((type == 'text' ) && (itemType == 'div'))		
		labelClass = 'gsom-optin-div-label'
	else
		labelClass = 'gsom-optin-label';
	
	switch(type)
	{
		case 'text':
			var wrapper;
			lItem = Builder.node(itemType,{id:lrid});
			
			if (gsomAdminMenu)
			{
				wrapper = Builder.node('div',{className:'gsom-list-item-wrapper'});
				lItem.appendChild(wrapper);
				if (fname != 'gsom-email-field')
				{
					lItem.appendChild(Builder.node('div',{style:'float:left; overflow: hidden;'},[
						makeLButton({
							imgsrc: gsomPluginPath+'img/delete.png',
							onclick: deleteFormItem.bindAsEventListener(lItem)
						}),
						makeLButton({
							imgsrc: gsomPluginPath+'img/pencil.png',
							onclick: function(){
								var oid = neo(this).id;
								FormAddEditTextField({oldItem:oid});
							}.bindAsEventListener(lItem)
						})										
					]));
				}
				
			}
			else
				wrapper = lItem;		
			
			wrapper.appendChild(Builder.node('label',{className:labelClass},label));
			wrapper.appendChild(Builder.node('input',{type:'text', name:fname, value:fvalue}));

		break;
		case 'checkbox':
			var cparams;
			var wrapper;
			
			if (checked)
				cparams = {type:'checkbox', checked:'checked', name:fname, value:'1'};
			else	
				cparams = {type:'checkbox', name:fname, value:'1'};
				
			lItem = Builder.node(itemType,{id:lrid});					
				
			if (gsomAdminMenu)
			{
				wrapper = Builder.node('div',{className:'gsom-list-item-wrapper'});
				lItem.appendChild(wrapper);
				lItem.appendChild(Builder.node('div',{style:'float:left'},[
						makeLButton({
							imgsrc: gsomPluginPath+'img/delete.png',
							onclick: deleteFormItem.bindAsEventListener(lItem)
						}),
						makeLButton({
							imgsrc: gsomPluginPath+'img/pencil.png',
							onclick: function(){
								var oid = neo(this).id;
								FormAddEditCheckboxField({oldItem:oid});
							}.bindAsEventListener(lItem)
						})
					])
				);

			}				
			else	
				wrapper = lItem;
				
				
			wrapper.appendChild(Builder.node('div',{className:cbRbClass},[
					Builder.node('input',cparams),
					Builder.node('label',{className:labelClass},label)
				]));				
		break;
		case 'radio':
			var wrapper;
			lItem = Builder.node(itemType,{id:lrid});
			
			if (gsomAdminMenu)
			{
				wrapper = Builder.node('div',{className:'gsom-list-item-wrapper'});
				lItem.appendChild(wrapper);
				lItem.appendChild(Builder.node('div',{style:'float:left'},[
						makeLButton({
							imgsrc: gsomPluginPath+'img/delete.png',
							onclick: deleteFormItem.bindAsEventListener(lItem)
						}),
						makeLButton({
							imgsrc: gsomPluginPath+'img/pencil.png',
							onclick: function(){
								var oid = neo(this).id;
								FormAddEditRadioGroupField({oldItem:oid});
							}.bindAsEventListener(lItem)
						})
					]));
			}
			else
				wrapper = lItem;
			
			
			wrapper.appendChild(Builder.node('label',label));
			for(var i=0; i < fvalue.length; i++)
			{				
				tdiv = Builder.node('div',{className:cbRbClass});
				wrapper.appendChild(tdiv);
				
				tel = Builder.node('input',{type:'radio', name:fname, value:stripSymbols(fvalue[i].label)});
				if (fvalue[i].checked)
					tel.checked = true;				
				tdiv.appendChild(tel);
				
				tel = Builder.node('label',{className:labelClass},fvalue[i].label);
				tdiv.appendChild(tel);
				
			}			
		break;		
		case 'button':
		case 'submit':			
			if (gsomAdminMenu)
			{
				lItem = Builder.node(itemType,{id:lrid});
				wrapper = Builder.node('div',{className:'gsom-list-item-wrapper'});
				lItem.appendChild(wrapper);
				lItem.appendChild(Builder.node('div',{style:'float:left'},[
//						makeLButton({
//							imgsrc: gsomPluginPath+'img/delete.png',
//							onclick: deleteFormItem.bindAsEventListener(lItem)
//						}),
						makeLButton({
							imgsrc: gsomPluginPath+'img/pencil.png',
							onclick: function(){
								var oid = neo(this).id;
								FormEditSubscribeButton({oldItem:oid});
							}.bindAsEventListener(lItem)
						})
					]));
				
				wrapper.appendChild(Builder.node('div',{className:cbRbClass},[
							Builder.node('input',{type:'button', name:fname, value:fvalue})
						]));	
						
//				lItem = Builder.node(itemType,{id:lrid},[	
//					Builder.node('div',{className:'gsom-list-item-wrapper'},[
//						Builder.node('div',{className:cbRbClass},[
//							Builder.node('input',{type:'button', name:fname, value:fvalue})
//						])								
//					])
//				]);
			}
			else
			{
				lItem = Builder.node(itemType,{id:lrid},[	
					Builder.node('div',{className:cbRbClass},[
						Builder.node('input',{type:type, name:fname, value:fvalue})
					])			
				]);
			}
		break;		
		
	}	
	
	
	if (list)
	{
		if (oldItem)
		{
			var oi = neo(oldItem);
			if(oi)
				list.insertBefore(lItem,oi);
			Element.remove(oi);
		}
		else		
			list.appendChild(lItem);
  	// we need to use this 'cuz stupid Sortable.onUpdate event does not work
	//Event.observe(lItem,'mouseup',function(){SerializeForm();});		
		return true;
	}
	return false;
}


function deleteFormItem()
{
	var el = neo(this);
	if(el)
	{
		if (confirm('Are you sure you want to delete this item?')) 
		{	
			Element.remove(el);
			SerializeForm();
		}		
	}
		
}

function makeLButton(args)
{
    if (typeof args == 'undefined') 
        args = new Object();
    var imgsrc = typeof args.imgsrc != 'undefined' ? args.imgsrc : false;
	var className = typeof args.className != 'undefined' ? args.className : '';
    var onclick = typeof args.onclick != 'undefined' ? args.onclick : false;
	var style = typeof args.style != 'undefined' ? args.style : '';
	
	style += ' display:block; margin-top:2px; cursor: pointer;';

    var lbtn = Builder.node('img', {			
	        src: imgsrc,
			style:style
	    });	    
		
	if(onclick)
	    Event.observe(lbtn, 'click', onclick);
	return lbtn;
}

function MakeGlButton(args){

    if (typeof args == 'undefined') 
        args = new Object();
    var on = typeof args.on != 'undefined' ? args.on : false;
    var imgsrc = typeof args.imgsrc != 'undefined' ? args.imgsrc : false;
	var className = typeof args.className != 'undefined' ? args.className : '';
    var onclick = typeof args.onclick != 'undefined' ? args.onclick : false;
	var onfinally = typeof args.onfinally != 'undefined' ? args.onfinally : false;
	var width = typeof args.width != 'undefined' ? args.width : false;
    var caption = typeof args.caption != 'undefined' ? args.caption : 'Untitled';
	var style = typeof args.style != 'undefined' ? args.style : '';
	var sw = typeof args.sw != 'undefined' ? args.sw : false;
	
	var el;
	
	if(width)	
		{
			if(width == 'def')
				var midblockstyle = 'width:50px;';
			else
				var midblockstyle = 'width:'+(width-10)+'px';
		}
	else
		var midblockstyle = '';

	if(imgsrc)
	{
	    el = Builder.node('img', {
			className: 'bbico',
	        src: imgsrc
	    });	    
	}
	
	if (!on)
		cname = 'glbutton'+' '+className;
	else
		cname = 'glbutton_on'+' '+className;
    
    var ibtn = Builder.node('div', {className: cname, style: style},[
		Builder.node('div',{className:'bbleftside'}),
		Builder.node('div',{className:'bbmiddle', style:midblockstyle},[
			el,
			Builder.node('span',{style:"float:none; margin: 0; padding: 0; display:block;"},caption)
		]),
		Builder.node('div',{className:'bbrightside'}),
	]);
	if(onclick)
	    Event.observe(ibtn, 'click', onclick);
		
	if(onfinally)
		Event.observe(ibtn, 'click', onfinally);
		
	if (sw)
	{
		Event.observe(ibtn,'click',function(){
			if(neo(this).hasClassName('glbutton_on'))
			{
				neo(this).removeClassName('glbutton_on').addClassName('glbutton');
			}
			else
				neo(this).removeClassName('glbutton').addClassName('glbutton_on');
		}.bindAsEventListener(ibtn));
	}
	
	Event.observe(ibtn,'mouseover',function(){
		if(neo(this).hasClassName('glbutton'))
			{
				neo(this).removeClassName('glbutton').addClassName('glbutton_act');
			}
	}.bindAsEventListener(ibtn));

	
	Event.observe(ibtn,'mouseout',function(){
		if(neo(this).hasClassName('glbutton_act'))
			{
				neo(this).removeClassName('glbutton_act').addClassName('glbutton');
			}	
	});

    
	return ibtn;
}

function KillForm()
{
	var ilist = neo(this).select('input');
	if(ilist)
	{
		for(i=0;i<ilist.length;i++)
		{
			if(ilist[i].name == 'endDate' || ilist[i].name == 'startDate')
			{
				var dp = datePickers.get(ilist[i].id);
				if(dp)
					dp.close();
			}
			
		}
	}

	removeChildNodes(this);
	Element.remove(this);
}

function removeChildNodes(ctrl){
    while (ctrl.childNodes[0]) {
        ctrl.removeChild(ctrl.childNodes[0]);
    }
}

