/*
proto-prospects.js
By: Prospects PB v0.2
Required: Prototype version 1.6 or up
Optional: Script.aculo.us 1.8.0 for Effect
*/
Date.parseJSON = function(iso8601String) {
	var parts = null;
	if (iso8601String)
		parts = /^(?:(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(.\d+)?)?((?:[+-](\d{2}):(\d{2}))|Z)?)?$/.exec(iso8601String);
	var result = null;
	if(parts) {
		parts.shift();
		if(parts[1]){parts[1]--;} //zero-based months
		if(parts[6]){parts[6] *= 1000;} // Javascript Date expects fractional seconds as milliseconds

		result = new Date(parts[0]||1970, parts[1]||0, parts[2]||1, parts[3]||0, parts[4]||0, parts[5]||0, parts[6]||0);

		var offset = 0;
		var zoneSign = parts[7] && parts[7].charAt(0);
		if(zoneSign != 'Z'){
			offset = ((parts[8] || 0) * 60) + (Number(parts[9]) || 0);
			if(zoneSign != '-'){ offset *= -1; }
		}
		if(zoneSign){
			offset -= result.getTimezoneOffset();
		}
		if(offset){
			result.setTime(result.getTime() + offset * 60000);
		}
	}
	return result; // Date or null
}
function performAjaxRequest(url, params, waitingElem, waitingMsg, onSuccessHandler, onFailureHandler)
{
	if (waitingMsg && waitingMsg != null)
		Dialog.info(waitingMsg, { maxWidth:350, className: 'prospects_window', showEffect:Element.show, hideEffect:Element.hide });
	onFailureHandler = (onFailureHandler ? onFailureHandler : Prototype.emptyFunction);
	stopCloseInfo = false;
	var req = new Ajax.Request(url, {
		method:'post',
		encoding:'UTF-8',
		parameters: params,
		onSuccess: function(transport, xjson) {
			var json = transport.responseJSON;
			//if not completed successfully
			var withError = false;
			if (withError = (json['status'] && json['status']['errorCode'] != 0))
				alert('[Code '+json['status']['errorCode']+'] '+json['status']['errorMsg']);
			else if (withError = (json['status'] && json['status']['changed'] == 0))
				alert('[Code '+json['status']['errorCode']+'] '+json['status']['errorMsg']);
			stopCloseInfo = onSuccessHandler(transport, json, withError);
		},
		onFailure: function(transport, xjson) {
			onFailureHandler(transport, transport.responseJSON);
		},
		onException: function(req, e) {
			alert(e.name+': '+e.message+(e.number?'\n'+e.number:'')+(e.fileName?'\n'+e.fileName+' (Line: '+e.lineNumber+')':''));
		},
		onComplete: function(transport, xjson) {
			if (!stopCloseInfo)
			  Dialog.closeInfo();
		}
	});
}
function performAjaxUpdate(elemToUpdate, url, params, waitingElem, waitingMsg, onFailureHandler)
{
	if (waitingMsg && waitingMsg != null)
		Dialog.info(waitingMsg, { maxWidth:350, className: 'prospects_window', showEffect:Element.show, hideEffect:Element.hide }); //WaitControl.show(waitingMsg);
	onFailureHandler = (onFailureHandler ? onFailureHandler : Prototype.emptyFunction);
	var req = new Ajax.Updater(elemToUpdate, url, {
		method:'post',
		encoding:'UTF-8',
		parameters: params,
		evalScripts: true,
		onFailure: function(transport, xjson) {
			onFailureHandler(transport, transport.responseJSON);
		},
		onException: function(req, e) {
			alert(e.name+': '+e.message+(e.number?'\nError number:'+e.number:'')+(e.fileName?'\n'+e.fileName+' (Line: '+e.lineNumber+')':''));
		},
		onComplete: function(transport, xjson) {
			Dialog.closeInfo();
		}
	});
}
if(typeof Autocompleter != 'undefined')
{
/***********  a customized autocomplete *****************/
Autocompleter.Custom = Class.create(Autocompleter.Base, {
  initialize: function(element, update, array, options) {
    this.baseInitialize(element, update, options);
    this.options = Object.extend({ajaxParams: {}}, this.options);
    this.options.array = array;
    this.oriArray = this.options.array;
    this.loadingChoices = false;
    this.loaded=false;
  },
  onObserverEvent: function() {
    this.changed = false;   
    this.tokenBounds = null;
    var token = this.getToken();
    var isLastToken = this.tokenBounds != null && this.tokenBounds[1]==this.element.value.length;
    if(isLastToken && token.length>=this.options.minChars && !this.loaded) {
      this.loaded=true;
      this.getAjaxUpdatedChoices(token);
    } else if(isLastToken && token.length>this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.options.array = this.oriArray;
      this.loaded = false;
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },
  getAjaxUpdatedChoices: function(token) {
    this.loadingChoices = true;
    performAjaxRequest(this.options.ajaxUrl, Object.extend(this.options.ajaxParams,{ entry:token }), null, null, 
		function(transport, json) { 
		  this.options.array = json['valueList'];
		  this.loadingChoices=false;
		  this.activate();
		}.bind(this), 
		function(transport, json) { 
		  this.options.array = this.oriArray;
		  this.loadingChoices=false;
		  this.activate(); 
		}.bind(this)
	);
  },
  getUpdatedChoices: function() {
  	if (!this.loadingChoices)
      this.updateChoices(this.options.selector(this));
  },
  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 2,
      ignoreCase: true,
      fullSearch: false,
      partsFormater: function(elem, startIndex, endIndex) {
        var formated = '';
        var index = 0;
        var parts = elem.split("|");
        for(var i=0, len = parts.length; i < len; i++)
        {
          if (startIndex >= parts[i].length || endIndex <= index)
          	formated = (formated.length > 0?' ':'') + formated + parts[i];
          else if ((startIndex >= index) && (endIndex <= index + parts[i].length))
            formated = (formated.length > 0?' ':'') + formated + parts[i].substr(index, startIndex-index) + "<strong>" +
                  parts[i].substr(startIndex-index, endIndex-index) + "</strong>" + parts[i].substr(endIndex-index)
           index = index + parts[i].length + 1;//+1 for pipe
        }
        return formated;
      },
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;

        for (var i = 0, arrLen = instance.options.array.length; i < arrLen &&  
          ret.length < instance.options.choices ; i++) { 

          var elem = instance.options.array[i];
          var foundPos = instance.options.ignoreCase ? 
            elem.toLowerCase().indexOf(entry.toLowerCase()) : 
            elem.indexOf(entry);
          
          while (foundPos != -1) {//match found anywhere in piped elem
            if (foundPos == 0 && elem.length != entry.length) {
             	ret.push("<li>" + instance.options.partsFormater(elem, 0, entry.length) + "</li>");
              break;
            } else if (entry.length >= instance.options.partialChars && 
              instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s|\\|/.test(elem.substr(foundPos-1,1))) {
                partial.push("<li>" + instance.options.partsFormater(elem, foundPos, foundPos+entry.length) + "</li>");
                break;
              }
            }

            foundPos = instance.options.ignoreCase ? 
              elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
              elem.indexOf(entry, foundPos + 1);
          }
        }
        if (partial.length)
          ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || { });
  },
  
  onBlur: function(event) {
  	// needed to make click events working 
    // Because of scrollbar, dont hide the div when "blur" happens when the user on "div" clicks 
 
    // check if the click is in the menu or outside the menu
    if((event.x - parseInt(this.update.style.left)) > parseInt(this.update.style.width) 
    	| event.x < parseInt(this.update.style.left)
    	| (event.y - parseInt(this.update.style.top)) > 250 // 250 est la taille du menu (definie dans prospects_popup.css)
    	| event.y < parseInt(this.update.style.top) ) 
    {
       setTimeout(this.hide.bind(this), 250); 
       this.hasFocus = false; 
       this.active = false;
    }
  }  
});
/***********  a customized autocomplete finish*****************/
}
/**
 * @author Ryan Johnson <http://saucytiger.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/control/tabs
 * @require prototype.js 
 * Identifical to their version except doesn't require livepipe and 'beforeChange' implementation differs(return 
 * false not $break to stop tab switch)  --PB20081008 
 */
if(typeof(Control) == 'undefined')
	Control = {};
Control.Tabs = Class.create({
	initialize: function(tab_list_container,options){
		if(!$(tab_list_container))
			throw "Control.Tabs could not find the element: " + tab_list_container;
		this.activeContainer = false;
		this.activeLink = false;
		this.containers = $H({});
		this.links = [];
		Control.Tabs.instances.push(this);
		this.options = {
			beforeChange: Prototype.emptyFunction,
			afterChange: Prototype.emptyFunction,
			hover: false,
			linkSelector: 'li a',
			setClassOnContainer: false,
			activeClassName: 'active',
			defaultTab: 'first',
			autoLinkExternal: true,
			targetRegExp: /#(.+)$/,
			showFunction: Element.show,
			hideFunction: Element.hide
		};
		Object.extend(this.options,options || {});
		(typeof(this.options.linkSelector == 'string')
			? $(tab_list_container).select(this.options.linkSelector)
			: this.options.linkSelector($(tab_list_container))
		).findAll(function(link){
			//return (/^#/).exec((Prototype.Browser.WebKit ? decodeURIComponent(link.href) : link.href).replace(window.location.href.split('#')[0],''));                    // original code
			return (/^#/).exec(link.href.replace(window.location.href.split('#')[0],''));                   // always use link.href because in Safari Prototype.Browser.WebKit is true and the value in decodeURIComponent(link.href) is not correct  
		}).each(function(link){
			this.addTab(link);
		}.bind(this));
		this.containers.values().each(Element.hide);
		if(this.options.defaultTab == 'first')
			this.setActiveTab(this.links.first());
		else if(this.options.defaultTab == 'last')
			this.setActiveTab(this.links.last());
		else
			this.setActiveTab(this.options.defaultTab);
		var targets = this.options.targetRegExp.exec(window.location);
		if(targets && targets[1]){
			targets[1].split(',').each(function(target){
				this.setActiveTab(this.links.find(function(link){
					return link.key == target;
				}));
			}.bind(this));
		}
		if(this.options.autoLinkExternal){
			$A(document.getElementsByTagName('a')).each(function(a){
				if(!this.links.include(a)){
					var clean_href = a.href.replace(window.location.href.split('#')[0],'');
					if(clean_href.substring(0,1) == '#'){
						if(this.containers.keys().include(clean_href.substring(1))){
							$(a).observe('click',function(event,clean_href){
								this.setActiveTab(clean_href.substring(1));
							}.bindAsEventListener(this,clean_href));
						}
					}
				}
			}.bind(this));
		}
	},
	addTab: function(link){
		this.links.push(link);
		link.key = link.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
		var container = $(link.key);
		if(!container)
			throw "Control.Tabs: #" + link.key + " was not found on the page."
		this.containers.set(link.key,container);
		link[this.options.hover ? 'onmouseover' : 'onclick'] = function(link){
			if(window.event)
				Event.stop(window.event);
			this.setActiveTab(link);
			return false;
		}.bind(this,link);
	},
	setActiveTab: function(link){
		if(!link && typeof(link) == 'undefined')
			return;
		if(typeof(link) == 'string'){
			this.setActiveTab(this.links.find(function(_link){
				return _link.key == link;
			}));
		}else if(typeof(link) == 'number'){
			this.setActiveTab(this.links[link]);
		}else{
			if(this.options.beforeChange(this.activeContainer,this.containers.get(link.key)) === false) //PB20081008
				return;
			if(this.activeContainer)
				this.options.hideFunction(this.activeContainer);
			this.links.each(function(item){
				(this.options.setClassOnContainer ? $(item.parentNode) : item).removeClassName(this.options.activeClassName);
			}.bind(this));
			(this.options.setClassOnContainer ? $(link.parentNode) : link).addClassName(this.options.activeClassName);
			this.activeContainer = this.containers.get(link.key);
			this.activeLink = link;
			this.options.showFunction(this.containers.get(link.key));
			this.options.afterChange(this.containers.get(link.key)); //PB20081008
		}
	},
	next: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i + 1]){
				this.setActiveTab(this.links[i + 1]);
				throw $break;
			}
		}.bind(this));
	},
	previous: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i - 1]){
				this.setActiveTab(this.links[i - 1]);
				throw $break;
			}
		}.bind(this));
	},
	first: function(){
		this.setActiveTab(this.links.first());
	},
	last: function(){
		this.setActiveTab(this.links.last());
	}
});
Object.extend(Control.Tabs,{
	instances: [],
	findByTabId: function(id){
		return Control.Tabs.instances.find(function(tab){
			return tab.links.find(function(link){
				return link.key == id;
			});
		});
	}
});

/**
 * Converter of a UL-LI list of objects into a multi-select pseudo-object created
 * with DIVs and hidden input:checkboxes.
 * Prerequisite: <ul name="checkboxName"><li value="checkboxValue" [checked="true"]></li></ul> 
 */

MultiSelect = Class.create({

	initialize: function(tab_list_container,options){
		if(!$(tab_list_container))
			alert( "MultiSelect could not find the element: " + tab_list_container );

		tab_list_container.addClassName('outerSelectDiv');
		
		var innerDiv = $(document.createElement('DIV'));
		innerDiv.addClassName('innerSelectDiv');
		tab_list_container.appendChild(innerDiv);
		
		tab_list_container.select('ul')
		 .each( function(theselect){
		 	theselect.select('li')		 	
		 	 .each( function(theinput,theindex) {		 	 
			 	var thelabel = document.createElement('LABEL');
			 	thelabel.unselectable='on';
			 	thelabel.className='chkboxSelect';
			 	thelabel.htmlFor=theselect.readAttribute('name')+'_'+theindex ;
			 	
				innerDiv.appendChild(thelabel);

				var tmpInput = new Element('INPUT', {type:'checkbox',name:theselect.readAttribute('name'), className:'selectCheckbox',value:theinput.readAttribute('value'), id:theselect.readAttribute('name')+'_'+theindex });
				thelabel.appendChild(tmpInput);
				
				if(theinput.readAttribute('checked'))
				{
					tmpInput.writeAttribute('checked',theinput.readAttribute('checked'));
					$(thelabel).addClassName('selectCheckboxSel');
				}
				
				tmpInput.observe('click',function(e) {
			   		if (this.checked)
						$(this.parentNode).addClassName('selectCheckboxSel');
					else
						$(this.parentNode).removeClassName('selectCheckboxSel');
				}.bindAsEventListener(tmpInput,false));
				
				thelabel.appendChild(document.createTextNode(theinput.innerHTML));		
			} ); 
			
			Element.remove(theselect);
		});
		
	},

	first: function(){
		this.setActiveTab(this.links.first());
	},
	last: function(){
		this.setActiveTab(this.links.last());
	}
});
if(typeof Calendar != 'undefined')
{
	PopupCalendar = Class.create({});
	PopupCalendar.CALENDAR = null;
	PopupCalendar.show = function(input,rangeDe,rangeA,dateFormat,firstDayOfWeek) {
		if (PopupCalendar.CALENDAR != null)// we already have some calendar created 
			PopupCalendar.CALENDAR.hide();
		else
		{
			var cal = new Calendar(firstDayOfWeek || 0, null, selected, PopupCalendar.close);
		    cal.weekNumbers = false;
		    cal.showsOtherMonths = false; 
	 
		    if(rangeDe == null)
		        rangeDe = 1980;
		    if(rangeA == null)
		        rangeA = (new Date()).getYear();   
		    cal.setRange(rangeDe, rangeA);// min/max year allowed.
		    cal.yearStep = 3;
		    PopupCalendar.CALENDAR = cal;
		    cal.create();
		}
		
		// set the specified date format
		if(dateFormat == null)    
			PopupCalendar.CALENDAR.setDateFormat('%d-%m-%Y');    
		else
			PopupCalendar.CALENDAR.setDateFormat(dateFormat)         
		
		PopupCalendar.CALENDAR.parseDate(input.value);
		PopupCalendar.CALENDAR.sel = input;//inform it what input field we use
		PopupCalendar.CALENDAR.showAtElement(input, 'BR');
		return false;
	}
	PopupCalendar.close = function(cal) {
		cal.hide();
//		PopupCalendar.CALENDAR=null;
	}
}
/*
Usage: (For available options see this.options in initialize method)
var popmenu = new Proto_Popmenu(activatorElement, listElement, options);
//To clean affected elements
popmenu.destroy(); popmenu = null;
Ex:
new Popmenu($('languelink'), $('languechoices'), {
   	alignLeft:true, alignTop:false, delayOut:700, showEffect:Effect.blindDown
});
*/
var Popmenu = Class.create({
 hasEffectLib:(typeof Effect != 'undefined'),
 hideTimer:null,
 initialize: function(elem, listElemParam, options)
 {
    this.options = Object.extend({
    	activateByClick:true, //activator:'click', // 'click', 'mouseover', 'keypress'?
		itemClassName: 'li.popmenuitem', //for selectable items
		itemHoverClassName: 'popmenuitem_hover',
		showEffect:(this.hasEffectLib ? Effect.Appear : Element.show),
		hideEffect:(this.hasEffectLib ? Effect.Fade : Element.hide),
		showEffectOptions:{},
		hideEffectOptions:{},
		delayOut:1000,
		alignLeft:false,
		alignTop:true,
		offsetLeft:0,
		offsetTop:0,
		maxHeight:0,//default 0 = ignore
		getIndex: function() { return 0; },
		displayMenu: function() { return true; },
		onSelectItem: function(popmenu, item) { popmenu.hidePopmenu(); }
    }, options || {});

	this.elem = $(elem);
	if (this.options.activateByClick)
	    this.elem.observe('click',this._click.bindAsEventListener(this));
	this.elem.observe('mouseover',this._mouseover.bindAsEventListener(this));
    this.elem.observe('mouseout',this._mouseout.bindAsEventListener(this));
    
    this.listElem = [];
   	if (!Object.isArray(listElemParam)) listElemParam = [listElemParam];
	for (var i = 0, len = listElemParam.length; i < len; i++)
	{	
		this.listElem[i] = $(listElemParam[i]);
	    this.listElem[i].observe('mouseover',this._mouseover.bindAsEventListener(this));
	    this.listElem[i].observe('mouseout',this._mouseout.bindAsEventListener(this));
	    this.listElem[i].observe('click',this._clickList.bindAsEventListener(this));
	    if (!this.listElem[i].itemsInitialized)
	    	this.itemsChanged(i);
    }
    this.indexShown = -1;
 },
 _setHideTimer: function() {
	if (this.hideTimer == null)
		this.hideTimer = setTimeout(function() {this.hidePopmenu()}.bind(this), this.options.delayOut);
 },
 _clearHideTimer: function() {
	if (this.hideTimer)
	{
		clearTimeout(this.hideTimer);
		this.hideTimer = null;
	}
 },
 _setPosition:function(index) {
  var elemDim = this.elem.getDimensions();
  var listDim = this.listElem[index].getDimensions();
  var vpDim = document.viewport.getDimensions();
  
  var offset = [this.options.offsetLeft,this.options.offsetTop];
  var height = (this.options.maxHeight > 0 && listDim.height > this.options.maxHeight ? this.options.maxHeight : 
  		(listDim.height > vpDim.height ? vpDim.height : 0));
  if (height > 0) {
    listDim.height = height;
	this.listElem[index].setStyle({height: listDim.height+'px', overflowY: 'auto'});
  }
  if (!this.options.alignLeft) offset[0]=offset[0]+elemDim.width;
  if (!this.options.alignTop) offset[1]=offset[1]+elemDim.height;

  this.listElem[index].clonePosition(this.elem, {
    setWidth:false, setHeight:false, offsetLeft:offset[0], offsetTop:offset[1]
  });
 },
 _click: function(e) {
	this._clearHideTimer();
	var index = this.options.getIndex();
	var show = this.indexShown != index;
	this.hidePopmenu();
	if (show && this.options.displayMenu())
		this.showPopmenu(index);
 },
 _mouseover: function(e) {
 	this._clearHideTimer();
 	var index = this.options.getIndex();
 	if (!this.options.activateByClick && this.indexShown != index)
		this.showPopmenu(this.options.getIndex());
 },
 _mouseout: function(e) {
  	this._setHideTimer();
 },
 _clickList: function(e) {
 	if (this.indexShown != -1)
 	{
	 	var item = Event.findElement(e, 'LI');
	 	if (item)//if valid clicked, not space in between
 			this.options.onSelectItem(this, item);
 	}
 },
// _keypress: function(e) {
// },
 _mouseoverItem: function(e) {
 	this._clearHideTimer();
 	this.highlightItem(Event.element(e), true);
 },
 _mouseoutItem: function(e) {
 	this.highlightItem(Event.element(e), false);
 },
 showPopmenu: function(index) {
	if (this.indexShown >= 0 )
	{	
		return;
	}
	this.indexShown = index || 0;
	
	this.listElem[this.indexShown].popmenu = this;
	this._setPosition(this.indexShown);
	this.options.showEffect(this.listElem[this.indexShown], this.options.showEffectOptions);
 },
 hidePopmenu: function() {
 	if (this.indexShown < 0)
 		return;
 	var thisindexShown = this.indexShown;
 	this.indexShown = -1;
 	if (this.listElem[thisindexShown].popmenu!=this)
		return;
 	this.listElem[thisindexShown].popmenu = null;
	this.options.hideEffect(this.listElem[thisindexShown], this.options.hideEffectOptions);
	
 },
 highlightItem: function(elem, on) {
 	if (on)
		elem.addClassName(this.options.itemHoverClassName);
 	else
		elem.removeClassName(this.options.itemHoverClassName);
 },
 itemsChanged: function(index) {
 	var i = index || 0;
    this.listElem[i].select(this.options.itemClassName).each(function(iter){
    	iter.observe('mouseover',this._mouseoverItem.bindAsEventListener(this));
    	iter.observe('mouseout',this._mouseoutItem.bindAsEventListener(this));
    }.bind(this));
    this.listElem[i].itemsInitialized = true;
 }
});

//Lorsqu'on click sur une ligne dans une list pour afficher le sommaire (summary.jsp)
var currentShownSummary = 0;
function listClick(rowId,newDispatch)
{
   	if (typeof currentShownSummary == 'undefined' || currentShownSummary != rowId  )
   	{
		new Ajax.Updater('summaryTD', document.getElementById('mainForm').action, {
			method:'get',
			encoding:'UTF-8',
			evalScripts:true, 
			onSuccess: function(transport) { currentShownSummary = rowId; },
		 	parameters: { 
		 		dispatch: (newDispatch?newDispatch:'singleSommaire'),
		 		viewId:rowId 
		 	} 
		 });
	}
  	return false;
}