var Application = {
	
	start: function() {
		if ($('available_items') && $('nav_elements')) Navigation.init();
		if ($('donations_form')) Donations.init();
		if ($('waiting_layer')) Waitings.init();
		if ($('dialog_layer')) Dialogs.init();
		if ($('scroller')) window.setTimeout('AutoScroll()', 15000);
		if ($('map') && $$('#map .draggables')) {
		 	Map.init(); 		
		}
	}
}
Event.observe(window, 'load', function() { Application.start() }, false);

var Dialogs = {
	in_waiting : {},
	dialog_layer : 'dialog_layer',
	dialog_table : 'dialog_table',
	dialog_table_content: 'dialog_table_content',
	
	init: function () {
	//	Event.observe(document,'scroll',function(e){
//			Dialogs.layer_set_position();
		//});
	},
	
	send_message: function(url) {
		new Ajax.Updater(this.dialog_table_content, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait(); Dialogs.show_dialog()}});
		Waitings.wait();
	},
	
	show_dialog: function(do_update) {
		if (do_update) $('dialog_table_content').update($(do_update).innerHTML);
		Dialogs.hide_selects();
		Dialogs.show_selects('dialog_table_content');
		$(this.dialog_layer).show();
		$(this.dialog_table).show();
		//window.setTimeout("Dialogs.show()", 600);
		Dialogs.layer_set_position();
	},
	
	show: function() {
		$(this.dialog_table).show();
	},
	
	sending: function() {
		$(this.dialog_layer).hide();
		$(this.dialog_table).hide();
	},
	
	show_message: function(do_update) {
		if (do_update) $('dialog_table_content').update($(do_update).innerHTML);
		this.show_dialog();
		window.setTimeout("Dialogs.cancel()", 5000);
	},
	
	message_sent: function() {
		
	},

	cancel: function() {
		//new Effect.Fade(this.dialog_layer);
		//new Effect.Fade(this.dialog_table);
		$(this.dialog_layer).hide();
		$(this.dialog_table).hide();	
		Dialogs.show_selects();
	},
	
	hide_selects: function() {
		var selects = $$('select');
		for (var i=0; i<selects.length; i++) {
			selects[i].hide();
		}
	},
	
	show_selects: function(container) {
		var selects = [];
		if (container) {
			selects = $$('#'+container+' select');
		} else {
			selects = $$('select');
		}
		for (var i=0; i<selects.length; i++) {
			selects[i].show();
		}
	},
	
	layer_set_position: function() {
		if (!this.dialog_layer) this.dialog_layer = 'dialog_layer';
		if (!this.dialog_table) this.dialog_table = 'dialog_table';
		if ($(this.dialog_layer)) {
			$(this.dialog_layer).style.height = document.body.scrollHeight+'px';
		}
	}

};

var Waitings = {
	in_waiting : {},
	waiting_layer : 'waiting_layer',
	waiting_table : 'waiting_table',
	waiting_timer: '',
	
	init: function () {
		Event.observe(document,'scroll',function(e){
			Waitings.layer_set_position();
			//if(wait_bar) wait_bar.togglePause();
		});
	},
	
	button_wait: function(button_id) {
		if (button_id && $(button_id) && $('waiting_button')) {
			this.in_waiting[button_id] = $(button_id).innerHTML;
			$(button_id).update($('waiting_button').innerHTML);
		}
	},
	
	success_wait: function (button_id) {
		if (button_id && this.in_waiting[button_id]) {
			$(button_id).update(this.in_waiting[button_id]);
		}
	},
	
	failure_wait: function (button_id) {
		alert('An error occuped. Please try again.');
		if (button_id && this.in_waiting[button_id]) {
			$(button_id).update(this.in_waiting[button_id]);
		}
	},
	
	wait: function (wlayer,wtable) {
		if (wlayer) this.waiting_layer = wlayer;
		if (wtable) this.waiting_table = wtable;
		Waitings.hide_selects();
		if ($(this.waiting_layer)) $(this.waiting_layer).show();
		if ($(this.waiting_table)) $(this.waiting_table).show();
		this.layer_set_position();
		//if(wait_bar) wait_bar.togglePause();
	},
	
	hide_selects: function() {
		var selects = $$('select');
		for (i=0; i<selects.length; i++) {
			selects[i].hide();
		}
	},
	
	show_selects: function() {
		var selects = $$('select');
		for (var i=0; i<selects.length; i++) {
			selects[i].show();
		}
	},
	
	stop_wait: function (wlayer,wtable,error) {
		if (wlayer) this.waiting_layer = wlayer;
		if (wtable) this.waiting_table = wtable;
		if (error) alert('An error occuped. Please try again.');
		if ($(this.waiting_layer)) $(this.waiting_layer).hide();
		if ($(this.waiting_table))$(this.waiting_table).hide();
		Waitings.show_selects();
	},
	
	layer_set_position: function() {
		if (!this.waiting_layer) this.waiting_layer = 'waiting_layer';
		if (!this.waiting_table) this.waiting_table = 'waiting_table';
		var y = window.scrollY?window.scrollY:document.body.scrollTop;
		if ($(this.waiting_layer)) $(this.waiting_layer).style.top = y+'px';
		if ($(this.waiting_table)) $(this.waiting_table).style.top = y+'px';
	},
	
	start_waiting: function(error_delay) {
		this.wait();
		if (error_delay) this.waiting_timer = window.setTimeout('waiting_timeout()',error_delay*1000);
		
	},
	
	stop_waiting: function() {
		clearTimeout(this.waiting_timer);
		this.stop_wait();
	}
	
}

function waiting_timeout() {
	alert('Error: server not answer.');
	Waitings.stop_waiting();
}


function FormAJAXsubmit(formObj) {
    if (typeof(formObj)=='string') formObj = $(formObj);
    if (typeof(formObj)!='object') return false;
    if (typeof(tinyMCE)!='undefined') {
	    var tareas = $A(formObj.getElementsByTagName('textarea'));
	    tareas.each(function(elem) {
	       var inst = tinyMCE.getInstanceById(elem.name);
	       if (typeof(inst)=='object') {
	           elem.value = inst.getHTML();
	       }
	    });
    }
    url = formObj.action?formObj.action:document.location.href;
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formObj), onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
    Waitings.wait();
}


function updateSelect(element, options, selected_value) {
	if (!element) return false;
	if (typeof(element)=='string') element = $(element);
	if (typeof(options)=='string') {
		options = options.split('</option>');
	    for (var i=0; i<options.length; i++) {
	    	options[i] = options[i].replace(/<option/g,'');
	    	options[i] = options[i].replace(/\s+value=\'?\"?/g,''); //"'
	    	options[i] = options[i].replace(/(\"|\')/g,''); // '"
	    	options[i] = options[i].split('>');
	    }
	}
	element.options.length = 0;
	for (i=0; i<options.length; i++) {
		if (typeof(options[i][1])=='undefined') continue;
		element.options[element.options.length] = new Option(options[i][1], options[i][0], false, false);
	}
	FieldSetValue(element, selected_value);
}

function FieldSetValue(field, val) {
	if (typeof(field)=='string') field = $(field);
    if (typeof(val)!='undefined') {
        field.value = val; 
    }    
}

function readToggleInput(element, status) {
	if (typeof(element)=='string') element = $(element);
	element.setAttribute('readOnly', typeof(status)!='undefined'?status:true);
	if (typeof(status)=='undefined' || status) {
		element.addClassName('readonly');
	} else {
		element.removeClassName('readonly');
	}
}

function ToggleField(field_id, turn_on) {
    if (!$(field_id)) return;
    $(field_id).disabled=turn_on?false:true; 
    $(field_id).style.background=turn_on?'#fff':'#eee';
}

function reportError(request) {
	alert('Sorry. There was an error.');
}

function openPopupWindow(url, options) {
    window.open (url, "", options); 
}

function searchQuery(element, entry) {
    var queryString = new Array();
    params = element.readAttribute("extraparams")
    if(!params) return entry;
    params.split(',').each(
        function(e){
            e = $(e)
//            alert(e.name + ":" + e.value)
//            if(e.value != "") {
                queryString.push(encodeURIComponent(e.name) + '=' + encodeURIComponent(e.value));
  //          }
        });
    return queryString.join('&');
}

function Autocomplete_size_position(element, update) { 
	if(!update.style.position || update.style.position=='absolute') {
    	update.style.position = 'absolute';
        Position.clone($('searchmodel'), update, {setHeight: false, offsetTop: element.offsetHeight});
    }
    Effect.Appear(update,{duration:0.15});
}


function show_help(srcEl) {
	if (typeof(srcEl)=='undefined') return false;
	help_note = $('help_note');
	var help_note_close = $('help_note_close');
	help_note.show();
	help_note_close.show();
	
	Position.clone(srcEl, help_note, {setHeight: false, offsetTop:srcEl.getHeight()});
	Position.clone(help_note, help_note_close, {setHeight: false, setWidth:false, offsetLeft:help_note.getWidth()-help_note_close.getWidth()});
	return true;
}

function help_close() {
	$('help_note').hide();
	$('help_note_close').hide();
}

var Categories = {
	add_edit_flag: 0,
	
	update: function(id, url) {
		if (!Categories.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
				Categories.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!Categories.add_edit_flag) {
			var s = '<tr id="list_item_0"></tr>';
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
			Categories.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
		}
		Categories.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
	}
}


var Rgroups = {
	add_edit_flag: 0,
	
	update: function(id, url) {
		if (!this.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
				this.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!this.add_edit_flag) {
			var s = '<tr id="list_item_0"></tr>';
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
			this.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
		}
		this.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
	}
}


var Users = {
	add_edit_flag: 0,
	
	update: function(id, url) {
		if (!Users.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
				Users.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!Users.add_edit_flag) {
			var s = '<tr id="list_item_0"></tr>';
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
			Users.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
		}
		Users.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
	}
	
}


var Articles = {
	add_edit_flag: 0,
	
	update: function(id, url) {
		if (!Articles.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
				Articles.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!Articles.add_edit_flag) {
			var s = '<tr id="list_item_0"></tr>';
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
			Articles.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
		}
		Articles.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
	}
}


var Navigation = {
	ActEls: [],
	changed: false,
	
	init: function() {
		this.register_draggables();
		Event.observe(document,'mousemove',function(e){
			if (Drag_Drop.keptElement ) {
				fillActiveAreas();
			}
			if (Drag_Drop.draggedElement ) {
				var areaIds = findTargetArea(Event.pointerX(e), Event.pointerY(e), true);
				Navigation.remove_selection();
				if (areaIds && areaIds.length) {
					areaIds.each(function(el){
						if ($(el) &&  el!=Drag_Drop.draggedElement.id ) {
							$(el).addClassName('selected');
							Navigation.ActEls.push(el);
						}
					});
				}
			}
		});
		
	},
	
	clearOldMenu: function() {
		draggables = $$('#nav_elements .draggable');
		draggables.each( function(draggable) {
			Drag_Drop.ClearMovableObjectsData(draggable);
			ClearActiveArea(draggable.id);
			draggable.remove();
		});
	},
	
	initMenu: function() {
		draggables = $$('#nav_elements .draggable');
		draggables.each( function(draggable) {
			Drag_Drop.RegisterMovableObject(draggable, {'ghosting':false, 'onDrop':'navigation_drop_item'});
		});
		this.register_active_areas();
	},
	
	remove_selection: function() {
		while (this.ActEls.length) {
			ael = this.ActEls.pop();
			if($(ael)) $(ael).removeClassName('selected');
		}
	},
	
	register_draggables: function() {
		draggables = $$('#available_items .draggable');
		draggables.each( function(draggable) {
			Drag_Drop.RegisterMovableObject(draggable, {'ghosting':true, 'onDrop':'navigation_drop_item'});
		});
		this.initMenu();
	},
	
	unregister_draggables: function() {
		Drag_Drop.ClearMovableObjectsData();
		ClearActiveAreas();
	},
	
	register_active_areas: function() {
		items = $$('#nav_elements .draggable');
		RegisterActiveArea('nav_elements');
		if (items.length) {
			items.each( function(item) {
				RegisterActiveArea(item.id);
			});
		}
	},
	
	drop_item: function(el) {
		if (Drag_Drop.draggedElement) {
			//set_status(Drag_Drop.draggedElement.id);
			idparts = Drag_Drop.draggedElement.id.split('_');
			if (idparts[0]=='navelement') {
				if (this.ActEls.length) {
					for(i=0; i<this.ActEls.length; i++) {
						if (this.ActEls[i].indexOf('navelement')>=0) {
							this.move_element(Drag_Drop.draggedElement,this.ActEls[i]);
							//add_status('<br /> move '+Drag_Drop.draggedElement.id+' before element '+this.ActEls[i]);
							this.element_added = 1;
						}
					}
					if (!this.element_added) {
						for(i=0; i<this.ActEls.length; i++) {
							if (this.ActEls[i].indexOf('nav_elements')>=0) {
								this.move_element(Drag_Drop.draggedElement);
								//add_status('<br /> move '+Drag_Drop.draggedElement.id+' to the end of the list ');
								this.element_added = 1;
							}
						}
					}
				} else {
					this.remove_element(Drag_Drop.draggedElement);
					//add_status('<br /> remove '+Drag_Drop.draggedElement.id+' from list');
					Drag_Drop.item_drag_handler.hide();
				}
			}
			this.element_added = false;
			if (idparts[0]!='navelement') {
				if (this.ActEls.length) {
					for(i=0; i<this.ActEls.length; i++) {
						if (this.ActEls[i].indexOf('navelement')>=0) {
							//add_status('<br /> add '+Drag_Drop.draggedElement.id+' before element '+this.ActEls[i]);
							if (this.add_element(Drag_Drop.draggedElement.id, Drag_Drop.item_drag_handler.innerHTML, this.ActEls[i])) {
								//add_status(' added ');
							} else {
								//add_status(' error ');
							}
							this.element_added = 1;
						}
					}
					if (!this.element_added) {
						for(i=0; i<this.ActEls.length; i++) {
							if (this.ActEls[i].indexOf('nav_elements')>=0) {
								//add_status('<br /> add '+Drag_Drop.draggedElement.id+' at the end of the list ');
								if (this.add_element(Drag_Drop.draggedElement.id, Drag_Drop.item_drag_handler.innerHTML)) {
									//add_status(' added ');
								} else {
									//add_status(' error ');
								}
								this.element_added = 1;
							}
						}	
					}
				}
				Drag_Drop.item_drag_handler.hide();
			}
		}
		this.element_added = false;
		Navigation.remove_selection();
	},
	
	add_element: function(el_id, element_html, before_element) {
		if (!el_id || !element_html) return false;
		num = navelements.length;
		position = navelements.length;
		el_parts = el_id.split('_');
		el_num = el_parts[1];
		if (before_element) {
			el_parts = before_element.split('_');
			bel_num = el_parts[1];
			position = navelements[bel_num].position;
			this.shiftPositionDown(navelements[bel_num].position);
		}
		navelements[num] = {}
		for (prop in avelements[el_num]) {
			if (typeof(avelements[el_num][prop])=='object' || typeof(avelements[el_num][prop])=='function') continue;
			navelements[num][prop] = avelements[el_num][prop];
		}
		navelements[num]['position'] = position;
		element_html = element_html.replace (/id="[^\"]+"/g, 'id="navelement_'+num+'"');
		if (before_element && $(before_element)) {
			new Insertion.Before(before_element, element_html);
		} else {
			new Insertion.Bottom($('nav_elements'), element_html);
		}
		Drag_Drop.RegisterMovableObject($('navelement_'+num), {'ghosting':false, 'onDrop':'navigation_drop_item'});
		RegisterActiveArea('navelement_'+num);
		this.changed = true;
		return true;
	},
	
	move_element: function(element, before_element) {
		position = navelements.length-1;
		el_parts = element.id.split('_');
		el_num = el_parts[1];
		el_position = navelements[el_num].position;
		
		if (before_element) {
			el_parts = before_element.split('_');
			bel_num = el_parts[1];
			position = navelements[bel_num].position-1;
		}
		
		if (el_position<position) { // move element down
			for (i=0; i<navelements.length; i++) {
				if (navelements[i] && navelements[i].position>el_position && navelements[i].position<=position) {
					navelements[i].position--;
				}
			}
			navelements[el_num].position = position;
		} else if (el_position>position) { // move element up
			position++;
			for (i=0; i<navelements.length; i++) {
				if (navelements[i] && navelements[i].position>=position && navelements[i].position<el_position) {
					navelements[i].position++;
				}
			}
			navelements[el_num].position = position;
		}
		element_html = element.parentNode.innerHTML;
		Drag_Drop.ClearMovableObjectsData(element);
		ClearActiveArea(element.id);
		element.parentNode.update('');
		if (before_element && $(before_element)) {
			new Insertion.Before(before_element, element_html);
		} else {
			new Insertion.Bottom($('nav_elements'), element_html);
		}
		Drag_Drop.RegisterMovableObject($('navelement_'+el_num), {'ghosting':false, 'onDrop':'navigation_drop_item'});
		RegisterActiveArea('navelement_'+el_num);
		this.changed = true;
	},
	
	remove_element: function(element) {
		if (!element || !element.id) return false;
		el_parts = element.id.split('_');
		el_num = el_parts[1];
		el_position = navelements[el_num].position;
		navelements[el_num] = '';
		this.shiftPositionUp(el_position);
		this.changed = true;
		Drag_Drop.ClearMovableObjectsData(element);
		ClearActiveArea(element.id);
	},
	
	shiftPositionDown: function(position) {
		for (i=0; i<navelements.length; i++ ) {
			if (navelements[i] && navelements[i].position>=position) navelements[i].position++;
		}
	},
	
	shiftPositionUp: function(position) {
		for (i=0; i<navelements.length; i++ ) {
			if (navelements[i] && navelements[i].position>=position) navelements[i].position--;
		}
	},
	
	add: function(url) {
		if ($('navigation_name').value!='') {
			navname = $('navigation_name').value;
			new Ajax.Updater('data_layer', url, {asynchronous:true, evalScripts:true, parameters: {'name': navname}});
		}
	},
	
	save: function(formObj) {
		// set_status(this.pack(navelements));
		$('navigation_structure').value = this.pack(navelements);
		new Ajax.Updater('data_layer', formObj.action, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formObj), onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
		Waitings.wait();
		this.changed = false;
	},
	
	loadNavList: function(formObj) {
		if (this.changed) {
			if (confirm('Data was changed. Save?')) {
				$('navigation_structure').value = this.pack(navelements);
			} else {
				$('navigation_structure').value = '';
			}
		} else {
			$('navigation_structure').value = '';
		}
		new Ajax.Updater('data_layer', $('load_path').value, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formObj), onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
		Waitings.wait();
	},
	
	loadNavElements: function(navels) {
		navelements = null;
		navelements = navels;
	},
	
	pack: function(arr) {
		return pack(arr);
	}
}

function pack(arr) {
	var str='';
	if (typeof(arr)=='object') {
		for (var i in arr) {
			if (arr[i]==='') continue;
			if (typeof(arr[i])=='object') {
				str+=i+'=>'+this.pack(arr[i])+',';
			} else if(typeof(arr[i])!='function') {
				if (typeof(arr[i])=='string') {
					s = arr[i].replace(/\[/,'&lblock;');
					s = s.replace(/\]/,'&rblock');
					s = s.replace(/\,/,'&comma;');
				} else {
					s = arr[i];
				}
				str+=i+'=>'+s+',';
			}
		}
		str = str.replace(/\,$/,'');
		str = '['+str+']';
	} else {
		str = arr;
	}
	return str;
}

function navigation_drop_item(el) {
	Navigation.drop_item(el);
}


function url_convert(url) {
	url = url.replace(/^\s*/,'');
	url = url.replace(/\s*$/,'');
	var res_url = escape(url.toLowerCase());
	if (res_url!=url) {
		var pattern = /(\%(u[a-zA-Z0-9]{4}|\S{2})|\.)/g;
		res_url = res_url.replace(pattern,'-');
//		alert(res_url);
	}
	return res_url;
}

var Inquirers = {
	add_edit_flag: 0,
	tr_open : '<tr id="list_item_[id]">',
	tr_close: '</tr>',
	
	update: function(id, url) {
		if (!this.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
				this.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!this.add_edit_flag) {
			var s = this.tr_open.replace('[id]',0)+this.tr_close;
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
			this.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
		}
		this.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
	},
	
	set_position: function(item_num, after) {
		if ($('list_item_'+item_num) && $('list_item_'+after)) {
			item = $('list_item_'+item_num).remove();
			var s = this.tr_open.replace('[id]',item_num)+item.innerHTML+this.tr_close;
			new Insertion.After($('list_item_'+after), s);
		}
	},
	
	question_move: function(item_num,url) {
		if ($('list_item_'+item_num)) {
			Waitings.wait();
			this.add_edit_flag = 1;
			new Ajax.Updater('temp', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
		}
	}
}


var Testimonials = {
	add_edit_flag: 0,
	
	update: function(id, url) {
		if (!this.add_edit_flag) {
			if ($('list_item_'+id) && url) {
				new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
				this.add_edit_flag = 1;
			}
		}
	},
	
	create: function (url) {
		if (!this.add_edit_flag) {
			var s = '<tr id="list_item_0"></tr>';
			var el = $('table_list').descendants();
			new Insertion.After(el[1], s);
			new Ajax.Updater('list_item_0', url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
			this.add_edit_flag = 1;
		}
	},
	
	cancel: function(id, url) {
		if (typeof(id)=='undefined' || !id || url=='') {
			if ($('list_item_0')) $('list_item_0').remove();
		} else {
			new Ajax.Updater('list_item_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
			Waitings.wait();
		}
		this.add_edit_flag = 0;
	},
	
	oncreate: function(id) {
		if ($('list_item_0') && id) $('list_item_0').id = 'list_item_'+id;
	}
}

var Polls = {
	
	view: function(id, url) {
		if (!$('list_item_info_'+id)) {
			if ($('list_item_'+id) && url) {
				var s = '<tr id="list_item_info_'+id+'"></tr>';
				new Insertion.After('list_item_'+id, s);
				new Ajax.Updater('list_item_info_'+id, url, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
				Waitings.wait();
			}
		} else {
			$('list_item_info_'+id).show();
		}
	},
	
	close_view: function(id) {
		if ($('list_item_info_'+id)) $('list_item_info_'+id).hide();
	},
	
	poll_delete: function (id) {
		Waitings.success_wait('buttons_'+id);
 	    if ($('list_item_'+id)) $('list_item_'+id).hide();
		if ($('list_item_info_'+id)) $('list_item_info_'+id).hide();
	}
	
}


var Questions = {
  vlist: [],
  current_edition: 0,
  
  countLength: function (field, max) {
	countLength(field, max);
  },

  changeFormFields: function(prop_type) {
    if (typeof(form_types[prop_type])!='undefined') {
        /*  $('additional_fields').update('');
            $('additional_fields').update($('values_'+form_types[prop_type]).innerHTML);
        */
        $('values_'+form_type).hide();
        $('values_'+form_types[prop_type]).show();
        form_type = form_types[prop_type];
    }
  },
  
  get_max_pos: function() {
  	var maxPos = 0;
  	for(i in this.vlist) {
  		if (this.vlist[i].position > maxPos) {
  			maxPos = this.vlist[i].position;
  		}
  	}
  },
  
  value_add_new: function() {
    if ($('values_new_value').value=='') {
        alert("Field 'Add/Edit value' must be filled.");
        return;
    }
    this.vlist[this.vlist.length] = {
    	'key' : '',
    	'value': $('values_new_value').value,
    	'label': $('values_new_label').value?$('values_new_label').value:$('values_new_value').value
    }
    $('values_new_value').value=$('values_new_label').value='';
    this.refresh_select_boxes();
  },
  
  value_apply: function() {
      if (this.current_edition=='' || $('values_new_value').value=='') {
         alert("Field 'Add/Edit value' must be filled.");
         return;
      }
      this.vlist[this.current_edition].value = $('values_new_value').value;
      this.vlist[this.current_edition].label = $('values_new_label').value?$('values_new_label').value:$('values_new_value').value;
      this.refresh_select_boxes();
      this.cancel_edition();
  },
  
  value_delete: function() {
      if ($('values_list').value=='') {
        alert("Nothing selected to delete.");
        return;
      }
      var reg = $('values_list').value;
      for (i=reg; i<this.vlist.length; i++) {
      	this.vlist[i] = this.vlist[i+1];
      }
      this.vlist.length --;
      this.refresh_select_boxes();
  },
  
  cancel_edition: function() {
    $('apply_value').hide();
    $('add_value').show();
    $('cancel').hide();
    $('values_new_value').value = $('values_new_label').value = '';
    this.current_edition = 0;
  },
  
  value_edit: function() {
    if ($('values_list').value!='') {
        this.current_edition = $('values_list').value;
        $('values_new_value').value = this.vlist[this.current_edition].value
        $('values_new_label').value = this.vlist[this.current_edition].label;
        $('add_value').hide();
        $('apply_value').show();
        $('cancel').show();
    }
  },
  
  value_move: function(step) {
    if ($('values_list').value=='') {
        alert("Nothing selected to move.");
        return;
    }
    var moving_value = $('values_list').value;
    if (this.vlist[moving_value]) {
    	var nxt = 1*step+1*moving_value;
        if (this.vlist[nxt]) {
			temp = this.vlist[moving_value];
			this.vlist[moving_value] = this.vlist[nxt];
			this.vlist[nxt] = temp;
            moving_value = nxt
        }
	}
    this.refresh_select_boxes();
    $('values_list').value=moving_value;
  },
  
  refresh_select_boxes: function() {
    var options='<option value=""></option>';
    var options_def='<option value=""></option>';
    
    for (i=0; i<this.vlist.length; i++) {
        if (typeof(this.vlist[i])!='object') continue;
        options+='<option value="'+i+'">'+this.vlist[i].label+'</option>';
        options_def+='<option value="'+i+'">'+this.vlist[i].label+'</option>';
    }
    updateSelect('question2_default_value', options_def);
    updateSelect('values_list', options);
  },
  
  fill_vlist: function(new_values) {
	   this.vlist = new_values;
  },
  
  prepare_form: function() {
  	   if ($('question2_values')) {
	  	   $('question2_values').value = pack(this.vlist);
  	   }
  	   //confirm($('question2_values').value+' ?')
  	   return true;
  }
}

function countLength(field, max) {
	var warning = false;
	if (typeof(field)=='object' && typeof(field.value)!='undefined') {
		if (field.id!='' && $(field.id+'_counter')) {
			if (max && field.value.length>max) {warning = true}
			var str = 'Length: '+ (warning?'<span class="warning">':'') + field.value.length + (warning?'</span>':'') + ' chr.';
			$(field.id+'_counter').update(str);
		}
	}
}


var Map = {
	ActEl: 0,
	CurrEl: 0,
	draggedElement: '',
	found: false,
	find_timer: 0,
	
	init: function() {
		this.unregister_draggables();
		this.register_draggables();
		ActEl = 0;
		CurrEl = 0;
		draggedElement: '';
		found: false;
		Event.observe(document,'mousemove',function(e){
			if (Drag_Drop.keptElement ) {
				fillActiveAreas();
			}
			if (Drag_Drop.draggedElement) {
				var areaIds = findTargetArea(Event.pointerX(e), Event.pointerY(e), true);
//				areaIds = [];
				if (areaIds && areaIds.length) {
					Map.found=false;
					areaIds.each(function(el){
						if (Drag_Drop.keptElement && Map.CurrEl!=el && el!=Drag_Drop.keptElement.id && $(el)) {
							Map.CurrEl = el;
							clearTimeout(Map.find_timer);
							Map.find_timer = setTimeout('Map.findActEl()',500);
						} else {
							Map.found=true;
						}
					});
					if (!Map.find_timer && !Map.found) {
						if ($(Map.ActEl)) $(Map.ActEl).removeClassName('act');
						Map.ActEl = '';
					}
				}
			}
		});
		
	},
	
	findActEl: function() {
		if (this.checkParent(this.CurrEl, Drag_Drop.keptElement.id)) {
			if ($(this.ActEl)) $(this.ActEl).removeClassName('act');
			this.ActEl = this.CurrEl;
			if ($(this.ActEl)) $(this.ActEl).addClassName('act');
			this.found=true;
		} else {
			if ($(this.ActEl)) $(this.ActEl).removeClassName('act');
			this.ActEl = '';
		}
	},
	
	checkParent: function(TargetEl, DraggedEl) {
		TargetEl = $(TargetEl);
		DraggedEl = $(DraggedEl);
		if (!TargetEl || !DraggedEl) return false;

		if (DraggedEl.parentNode && DraggedEl.parentNode.id) {
			target_id = TargetEl.id;
			t_id = this.decode_id_from_name(target_id);
			dp_id = this.decode_id_from_name(DraggedEl.parentNode.id);
			if (t_id==dp_id) {
				return false;
			}
		}
		if (TargetEl.parentNode && TargetEl.parentNode.id) {
			t_parent_id = TargetEl.parentNode.id;
			t_id = this.decode_id_from_name(t_parent_id);
			d_id = this.decode_id_from_name(DraggedEl.id);
			if (t_id==d_id) {
				return false;
			}
		}
		return true;
	},
	
	decode_id_from_name: function(name) {
		if (!name) return 0;
		
		parts = name.toString().split('_');
		return parts[1];
	},
	
	register_draggables: function() {
		draggables = $$('#map .draggable');
		draggables.each( function(draggable) {
			Drag_Drop.RegisterMovableObject(draggable, {'ghosting':true, 'onDrop':'map_drop_item'});
		});
		this.register_active_areas();
	},
	
	register_active_areas: function() {
		items = $$('#map .draggable');
		
		if (items.length) {
			items.each( function(item) {
				RegisterActiveArea(item.id);
			});
		}
	},
	
	unregister_draggables: function() {
		Drag_Drop.ClearMovableObjectsData();
		ClearActiveAreas();
	},
	
	drop_item: function(el) {
		// this.draggedElement = null;
		Drag_Drop.item_drag_handler.hide();
		if (!this.ActEl) {
			this.ActEl = 'tree_0';
		}
		if (Drag_Drop.draggedElement && this.ActEl) {
			this.draggedElement = Drag_Drop.container.firstChild;
			if (this.draggedElement.id!='' && this.ActEl!='') {
				if ($(this.ActEl)) $(this.ActEl).removeClassName('act');
				if ($(this.ActEl)) {
					if (!confirm("Do you really want move page "+this.draggedElement.innerHTML.stripTags()+'" into "'+$(this.ActEl).innerHTML.stripTags()+'"?')) return false;
				} else {
					if (!confirm('Do you really want move page "'+this.draggedElement.innerHTML.stripTags()+'" into root ?')) return false;
				}
				el_id = this.decode_id_from_name(this.draggedElement.id);
				newparent_id = this.decode_id_from_name(this.ActEl);
				if (el_id && newparent_id ) this.save(el_id,newparent_id);
			}
		}
	},
	
	save: function(el, newparent) {
		if (!save_url || !el || !newparent) return false;
		
		new Ajax.Updater('temp', save_url+'?id='+el+'&pid='+newparent, {asynchronous:true, evalScripts:true, onFailure:function(request){Waitings.stop_wait('','',true);}, onSuccess:function(request){Waitings.stop_wait();}});
		Waitings.wait();
	}
	
}

function map_drop_item(el) {
	Map.drop_item(el);
}

function refresh_captcha(num) {
	$('captcha_img'+num).src = $('captcha_img'+num).src.replace(/id=.*/,'id='+Math.random());
}

