// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var regions = new Array()
regions['France'] = new Array("Alsace", "Aquitaine", "Auvergne", "Basse-Normandie", "Bourgogne", "Bretagne", 
                            "Centre", "Champagne-Ardenne", "Corse", "Franche-Comté", "Guadeloupe", "Guyane",
                            "Haute-Normandie", "Île-de-France", "La Réunion", "Languedoc-Roussillon", "Limousin",
                            "Lorraine", "Martinique", "Midi-Pyrénées", "Nord-Pas-de-Calais", "Pays de la Loire",
                            "Picardie", "Poitou-Charentes", "Provence-Alpes-Côte d'Azur", "Rhône-Alpes");

regions['United States'] = new Array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", 
                            "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", 
                            "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", 
                            "Massachusetts", "Michigan", "Minnesota", "Mississipi", "Missouri", "Montana", 
                            "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", 
                            "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", 
                            "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", 
                            "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming");

function display_regions(select, selected, layer_id)
{
	for (i = $('regions').length; i > 1; i--)
		$('regions').options[i-1] = null
	
	if ($F(select) == "France" || $F(select) == "United States") {
	  	for (i = 0; i < regions[$F(select)].length; i++) {
			region = (regions[$F(select)])[i]
	  		$('regions').options[i + 1] = new Option(region, region)
			if (region == selected) {
	  			$('regions').options[i + 1].selected = true;
	  		}
	  	}
		$(layer_id).className = 'required';
		$(layer_id).getElementsByTagName('label')[0].getElementsByTagName('sup')[0].update('*');
	} else {
		$(layer_id).className = 'optional';
		$(layer_id).getElementsByTagName('label')[0].getElementsByTagName('sup')[0].update('');
	}
}


function find_index(id, value)
{
	index = null
	for (i=0; i<$(id).options.length;i++) {
		if ( $(id).options[i].value == value ) {
			index = i
			break;
		}
	}
	return index
}

function hide_flash_message()
{
  if ( $('flash_success') ) {
    $('flash_success').hide();
  }
  if ( $('flash_warning') ) {
    $('flash_warning').hide();
  }
  if ( $('flash_error') ) {
    $('flash_error').hide();
  }  
}


function change_current01_tab_to(id)
{
  $('current01').id = '';
  $(id).getElementsByTagName('a')[0].id = 'current01';  
  Element.hide('current01_content');
  Element.show('current01_in_progress');
  return true;
}

function current01_content_display()
{
  hide_flash_message();
  Element.hide('current01_in_progress');
  Element.show('current01_content');
}

function change_current02_tab_to(id)
{
  $('current02').id = '';
  $(id).getElementsByTagName('a')[0].id = 'current02';
  $('current02_content').hide();
  $('current02_in_progress').show();
  return true;
}

function current02_content_display()
{
  hide_flash_message();
  $('current02_in_progress').hide();
  $('current02_content').show();
}

function load_wysiwyg(ids)
{
	buttons = ['bold','italic','underline', 'left', 'center', 'right', 'ol', 'ul', 'link' ]
	icons   = '/images/nicEditorIcons.gif'
	ids.each(function(s) {
		new nicEditor({xhtml: true,buttonList : buttons,iconsPath : icons }).panelInstance(s);
	})
}

var Dashboard = Class.create(
//Dashboard.prototype = {
{	initialize: function(element, options){
		this.options = Object.extend({
			picture: 'dashboard_arrow',
			width: 426,
			height: 426,
			open: '/images/deco/dashboard_open.gif',
			close: '/images/deco/dashboard_close.gif',
			pictureW: 26,
			pictureH: 26,
			unfolded: false,
			cookie_name: 'dashboard_contributor_opened'
		}, options || {});
		this.element = $(element);
		this.picture = $(this.options.picture)
		this.width  = this.options.width;
		this.height = this.options.height;
		if (this.options.unfolded) {
			this.set_unfold_coordinates();
			this.set_open_picture();
		}	else {
			this.set_fold_coordinates();
			this.set_close_picture();
		}
		this.element.setStyle({width: this.width + 'px', height: this.height + 'px', left:this.x + 'px',top:this.y + 'px'})
		Event.observe(window, 'scroll', this.move.bind(this));
		this.element.show();
	},
	move: function() {
		scrollOffsets = document.viewport.getScrollOffsets(); 
		new Effect.Move(this.element, {mode: 'absolute',y: (this.y + scrollOffsets.top), x: (this.x + scrollOffsets.left)});		
	},
	fold: function() {
		if ( this.folded() ) return;
		scrollOffsets = document.viewport.getScrollOffsets(); 
		this.set_fold_coordinates()
		new Effect.Move(this.element, {x: this.x, y: this.y, afterFinish: this.do_closed.bind(this) })
		
	},
	unfold: function() {
		if ( !this.folded() )	return;
		scrollOffsets = document.viewport.getScrollOffsets();
		this.set_unfold_coordinates()
		new Effect.Move(this.element, {x: (this.width - this.options.pictureW), y: (this.height - this.options.pictureH), afterFinish: this.do_opened.bind(this)});
	},
	folded: function () {
		return this.x < 0
	},
	fold_or_unfold: function() {
		if ( this.folded() ) this.unfold() 
		else this.fold();
	},
	set_fold_coordinates: function() {
		this.x = -this.width  + this.options.pictureW;
		this.y = -this.height + this.options.pictureH;
	},
	set_unfold_coordinates: function() {
		this.x = 0;
		this.y = 0;
	},
	set_close_picture: function() {
		this.picture.src = this.options.close;
	},
	set_open_picture: function() {
		this.picture.src = this.options.open;
	},
	do_closed: function() {
		this.set_close_picture();
		SetCookie(this.options.cookie_name, false, 3650)
	},
	do_opened: function() {
		this.set_open_picture();		
		SetCookie(this.options.cookie_name, true, 3650)
	}
});

function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
 	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName + '=' + escape(cookieValue) + '; path=/; expires=' + expire.toGMTString();
}

function myScrollTo(container, element){
	container = $(container);
	element = $(element);
	// get element top left xy
	var tlx = element.x ? element.x : element.offsetLeft;
	var tly = element.y ? element.y : element.offsetTop;
	// get element  bottom right xy
	var elementwh = Element.getDimensions(element)
	var brx = tlx + elementwh['width'];
	var bry = tly + elementwh['height'];
	// get top and bottom values for currently viewable area of container
	var containerwh = Element.getDimensions(container)
	var top = container.scrollTop
	var bottom = containerwh['height'] + container.scrollTop
	// Image falls below bottom
	if(bry > bottom) container.scrollTop= top + (bry - bottom) +10 ;
	// if image is above top
	if(tly < top) container.scrollTop= top - (top - tly) -10 ;
	return element;
}

function check_all(form, name) {
	$(form).getInputs('checkbox', name).each(function(input){ input.checked = true; });
}

function uncheck_all(form, name) {
	$(form).getInputs('checkbox', name).each(function(input){ input.checked = false; });	
}

function one_checked(form, name) {
	inputs = $(form).getInputs('checkbox', name)
	checked = false;
	for (i = 0; i < inputs.length; i++) {
		if ( inputs[i].checked ) {
			checked = true;
			break;			
		}
  }
	return checked;
}

var FacebookLike = Class.create(
{
	initialize: function(element, options){
		this.options = Object.extend({
			className: 'bit',
			separator: ',',
			maxelements: 20
		}, options || {});
    this.element = $(element);
    this.holder = new Element('ul', {
      'class': 'holder'
    });
    this.element.insert({'before':this.holder});
		this.values = new Hash();		
		this.count = 0;
		this.update_counter();
	},
  createBox: function(text, options) {
    var li = new Element('li', options).addClassName(this.options.className + '-box').update(text);
    var a = new Element('a', {
      'href': '#',
      'class': 'closebutton'
      }
    );
    a.observe('click',function(e) {
          e.stop();
          this.dispose(li);
    }.bind(this));
    li.insert(a);
		return li;
  },	
  add: function(text, value) {
		real_value = value.split('|')[1]
		if ( value.blank() || !real_value || real_value.blank() || ( !real_value.include('@') && real_value.match("[^0-9]")) || this.exists(value) ) return false;
		if ( this.values.size() >= this.options.maxelements ) { return false; }
		if ( text.blank() ) text = value;
		var id = this.options.className + '-' + this.count++;
		var el = this.createBox(text, {'id': id});
		this.holder.insert({'bottom':el});
		this.values.set(id, new Hash({'label': text, 'value':value}));
		this.update_counter();
		return true;
  },
  update: function() {
		what = new Array();
		this.values.each(function(pair) { what.push(pair.value.get('value'))});
    this.element.value = what.join(this.options.separator);
    return this;
  },
	empty_list:	function() {
		this.values.keys().each(function(el){this.dispose($(el))}.bind(this))
	},
  dispose: function(el) {
		this.values.unset(el.id);
    el.remove();
		this.update_counter();    
    return this;
  },
	exists: function(value) {
		found = false;
		this.values.each(function(pair) {
			if (pair.value.get('value') == value) {
	  		found = true;
	  		throw $break;
	  	}
		});
		return found;
	},
	update_counter: function() {
		if ($('nb_contacts')) {
			if ( this.values.size() >= this.options.maxelements )
				$('nb_contacts').setStyle({'color':'red','font-weight':'bold'});
			else
				$('nb_contacts').setStyle({'color':'#069','font-weight':'bold'});
			$('nb_contacts').update(this.values.size() + ' / ' + this.options.maxelements)
		}		
	}	
});

var CharsCountdown = Class.create(
{
	initialize: function(element, options) {
		this.options = Object.extend({
			maxlength: 100
		}, options || {});
    this.element = $(element);
		if ( !$('counter_' + this.element.id) ) this.element.insert({before: '<div id="counter_' + this.element.id + '">' + $F(this.element).length + ' / ' + this.options.maxlength + '</div>'})
		this.element.observe('keyup', function() { this.do_countdown() }.bind(this))
		this.element.observe('keydownup', function() { this.do_countdown() }.bind(this))
  },
	do_countdown: function() {
		if ( $F(this.element).length >= this.options.maxlength ) {
			$('counter_' + this.element.id).setStyle({'color': 'red','font-weight': 'bold'});
			$(this.element).value = $F(this.element).substring(0, this.options.maxlength)
		} else {
			$('counter_' + this.element.id).setStyle({'color': '#069','font-weight': 'normal'});
		}
		$('counter_' + this.element.id).update($F(this.element).length + ' / ' + this.options.maxlength)
	}
});

var FlickrMenu = Class.create(
{
	initialize: function(element, options) {
		this.active = null;
		that = this
		document.observe("dom:loaded", function() {
			$$("span.head_menu").invoke("observe", "click", function(e) {
				//div.sub_menu
				headMenu = this;
				submenu  = e.findElement('li').down(3);
				arrow    = this.childElements().last();

				if ( submenu.getStyle('display')=='block' ) {
					if ( that.active != headMenu ) headMenu.removeClassName("active");
					if ( that.active ) that.active.addClassName('active');
					submenu.hide();
					arrow.writeAttribute('src','/images/deco/arrow_hover.png');
				} else {
					headMenu.addClassName("active");
					submenu.appear({duration: 0.2});
					arrow.writeAttribute('src','/images/deco/arrow_select.png');
				}
		
				$$("div.sub_menu:visible").each(function(e){ if ( e != submenu ) { e.setStyle({'display': 'none'}); } });
								
				$$("div.sub_menu").each(function(e){
					$A(e.getElementsByTagName('a')).invoke("observe", "click", function(e){
		  			if ( that.active ) that.active.removeClassName('active');
						that.active = headMenu;
						headMenu.addClassName('active');
		  		});
				});
		
				$$("#nicemenu img.arrow").each(function(e) { if ( e != headMenu ) { e.writeAttribute('src','/images/deco/arrow.png'); } });		
		
				$$("#nicemenu span.head_menu").each(function(e) {	if(e != headMenu && e != that.active ) { e.removeClassName('active'); } });
		
			});
		
			$$("#nicemenu span.head_menu").invoke("observe", "mouseover", function() { this.addClassName('over'); });
		
			$$("#nicemenu span.head_menu").invoke("observe", "mouseout", function() {	this.removeClassName('over'); });
			
			document.observe("click", function(e) {
				var elt = e.findElement('#nicemenu');
				if (elt == undefined){
				 $$("#nicemenu span.head_menu").invoke('removeClassName','active');
				 if ( that.active ) that.active.addClassName('active')
				 $$("#nicemenu div.sub_menu").invoke('hide');
				 $$("#nicemenu img.arrow").invoke('writeAttribute','src','/images/deco/arrow.png');
				}
			});
		});
		this.setActive($$("#nicemenu span.head_menu.active").first());
	},
	hide: function() {
	 $$("#nicemenu span.head_menu").invoke('removeClassName','active');
	 if ( this.active ) this.active.addClassName('active')
	 $$("#nicemenu div.sub_menu").invoke('hide');
	 $$("#nicemenu img.arrow").invoke('writeAttribute','src','/images/deco/arrow.png');
	},
	setActive: function(elt) {
		this.active = elt;
		elt.addClassName('active');
	}
})

function moveOptions(from, to) {
	$A($(from).options).each(function(e) {
		if ( !e.selected || e.disabled || optionExists(to, e) ) return;
		addOption(to, e.text, e.value);
		e.selected = false;
		e.writeAttribute('disabled');
	});
}

function optionExists(select, option) {
	element = null;
	$A($(select).options).each(function(e){
		if ( e.text == option.text && e.value == option.value ) {
			element = e;
			throw $break;
		}
	});
	return element;
}

function addOption(to, text, value) {
	option = new Option(text, value);
	if ( optionExists(to, option) ) return;
	$(to).options[$(to).options.length] = option;
}

function removeOptions(from, to) {
	for (i=$(from).length-1; i >= 0; i-- ) {
		opt = $(from).options[i];
		if (opt.selected) {
			$(from).remove(i);
			if ($(to) && (option = optionExists(to, opt))) 
				option.disabled = false;
		}
	}
}

function addUser(text, li) {
	addOption($('members_select'), $F(text), li.id.gsub('user_', ''));
	$(text).value = '';
}

function disableOptions(for_select, according_to_select) {
	$A($(for_select).options).each(function(e){
		if ( optionExists(according_to_select, e) ) {
			e.disabled = true;
		}
	});
}

function switch_image(id){
	if($('edition_proposition_img_show_'+id).visible()){
		Element.show('edition_proposition_img_hide_'+id);
		Element.hide('edition_proposition_img_show_'+id);
	}else{
		Element.show('edition_proposition_img_show_'+id);
		Element.hide('edition_proposition_img_hide_'+id);
	}
}
