/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 
 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
 
(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/_media/img/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);;jQuery.fn.selecteSizer=function(C,E){var D={floatIndex:777,width:"auto",position:{type:"absolute",topOffset:0,leftOffset:0},callback:null};if(C){jQuery.extend(D,C)}var A=this;var B=0;this.each(function(){jQueryChild=jQuery(this);if(jQueryChild.attr("style")){jQueryChild.attr("ostyle",jQueryChild.attr("style"))}else{jQueryChild.attr("ostyle"," ")}jQueryChild.focus(function(){var G=jQuery(this).offset().top;var I=jQuery(this).offset().left;if(F(this)){G=jQuery(this).position().top;I=jQuery(this).position().left}var H=jQuery(this).css("margin");if(H){H="margin:"+H}else{H=""}jQuery(this).after("<select id='selectGhost' class='"+jQuery(this).attr("class")+"' style='"+H+";"+jQuery(this).attr("ostyle")+"; width:"+(jQuery(this).outerWidth())+"px;visibility:hidden'><option>&nbsp;</option></select>");jQuery(this).change();jQuery(this).css({width:D.width,position:D.position.type,top:G+D.position.topOffset,left:I+D.position.leftOffset,zIndex:D.floatIndex});if(jQuery(this).next("#selectGhost:first").width()>jQuery(this).width()){jQuery(this).attr("style",jQuery(this).attr("ostyle"));jQuery(this).next("#selectGhost:first").remove()}jQuery(this).trigger("mousedown")});jQueryChild.blur(function(){jQuery(this).next("#selectGhost:first").remove();jQuery(this).attr("style",jQuery(this).attr("ostyle"))});function F(G){var H=G;while(H.parentNode){if(jQuery(H).css("position")=="relative"||jQuery(H).css("position")=="absolute"){return true;break}H=H.parentNode}return false}if(D.callback!=null){D.callback(this)}B++});if(E!=null){E(A)}return jQuery(this)};if(console==undefined){var console={log:function(A){alert(A)}}};;/*
 * jQuery UI Datepicker 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.7.1" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false // True to show button panel, false to not show it
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))
			return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText)
			input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.trigger.remove();
			$target.siblings('.' + this._appendClass).remove().end().
				removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = false;
			inst.trigger.filter("button").
			each(function() { this.disabled = false; }).end().
				filter("img").
				css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = true;
			inst.trigger.filter("button").
			each(function() { this.disabled = true; }).end().
				filter("img").
				css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_optionDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		var inst = this._getInst(target);
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			extendRemove(inst.settings, settings);
			var date = new Date();
			extendRemove(inst, {rangeStart: null, // start of range
				endDay: null, endMonth: null, endYear: null, // end of range
				selectedDay: date.getDate(), selectedMonth: date.getMonth(),
				selectedYear: date.getFullYear(), // starting point
				currentDay: date.getDate(), currentMonth: date.getMonth(),
				currentYear: date.getFullYear(), // current selection
				drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px'});
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var dims = {width: inst.dpDiv.width() + 4,
			height: inst.dpDiv.height() + 4};
		var self = this;
		inst.dpDiv.empty().append(this._generateHTML(inst))
			.find('iframe.ui-datepicker-cover').
				css({width: dims.width, height: dims.height})
			.end()
			.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1) {
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		} else {
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		}
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
		var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
		offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val() : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			date = defaultDate;
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '') + // highlight selected day
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, monthNames, monthNamesShort) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-year" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				'>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.1";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;

})(jQuery);
;/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood@iprimus.com.au) and St�phane Nahmani (sholby@sholby.net). */

jQuery(function($){
	$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
		closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
		prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
		nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
		currentText: 'Courant', currentStatus: 'Voir le mois courant',
		monthNames: ['janvier','février','mars','avril','mai','juin',
		'juillet','août','septembre','octobre','novembre','décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
		weekHeader: 'Sm', weekStatus: '',
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
		dateFormat: 'dd/mm/yy', firstDay: 0, 
		initStatus: 'Choisir la date', isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});

;/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(3($){$.31.1o({12:3(b,d){5 c=Y b=="1w";d=$.1o({},$.D.1L,{11:c?b:14,w:c?14:b,1D:c?$.D.1L.1D:10,Z:d&&!d.1x?10:3U},d);d.1t=d.1t||3(a){6 a};d.1q=d.1q||d.1K;6 I.K(3(){1E $.D(I,d)})},M:3(a){6 I.X("M",a)},1y:3(a){6 I.15("1y",[a])},20:3(){6 I.15("20")},1Y:3(a){6 I.15("1Y",[a])},1X:3(){6 I.15("1X")}});$.D=3(o,r){5 t={2N:38,2I:40,2D:46,2x:9,2v:13,2q:27,2d:3x,2j:33,2o:34,2e:8};5 u=$(o).3f("12","3c").P(r.24);5 p;5 m="";5 n=$.D.2W(r);5 s=0;5 k;5 h={1z:B};5 l=$.D.2Q(r,o,1U,h);5 j;$.1T.2L&&$(o.2K).X("3S.12",3(){4(j){j=B;6 B}});u.X(($.1T.2L?"3Q":"3N")+".12",3(a){k=a.2F;3L(a.2F){Q t.2N:a.1d();4(l.L()){l.2y()}A{W(0,C)}N;Q t.2I:a.1d();4(l.L()){l.2u()}A{W(0,C)}N;Q t.2j:a.1d();4(l.L()){l.2t()}A{W(0,C)}N;Q t.2o:a.1d();4(l.L()){l.2s()}A{W(0,C)}N;Q r.19&&$.1p(r.R)==","&&t.2d:Q t.2x:Q t.2v:4(1U()){a.1d();j=C;6 B}N;Q t.2q:l.U();N;3A:1I(p);p=1H(W,r.1D);N}}).1G(3(){s++}).3v(3(){s=0;4(!h.1z){2k()}}).2i(3(){4(s++>1&&!l.L()){W(0,C)}}).X("1y",3(){5 c=(1n.7>1)?1n[1]:14;3 23(q,a){5 b;4(a&&a.7){16(5 i=0;i<a.7;i++){4(a[i].M.O()==q.O()){b=a[i];N}}}4(Y c=="3")c(b);A u.15("M",b&&[b.w,b.H])}$.K(1g(u.J()),3(i,a){1R(a,23,23)})}).X("20",3(){n.18()}).X("1Y",3(){$.1o(r,1n[1]);4("w"2G 1n[1])n.1f()}).X("1X",3(){l.1u();u.1u();$(o.2K).1u(".12")});3 1U(){5 b=l.26();4(!b)6 B;5 v=b.M;m=v;4(r.19){5 a=1g(u.J());4(a.7>1){v=a.17(0,a.7-1).2Z(r.R)+r.R+v}v+=r.R}u.J(v);1l();u.15("M",[b.w,b.H]);6 C}3 W(b,c){4(k==t.2D){l.U();6}5 a=u.J();4(!c&&a==m)6;m=a;a=1k(a);4(a.7>=r.22){u.P(r.21);4(!r.1C)a=a.O();1R(a,2V,1l)}A{1B();l.U()}};3 1g(b){4(!b){6[""]}5 d=b.1Z(r.R);5 c=[];$.K(d,3(i,a){4($.1p(a))c[i]=$.1p(a)});6 c}3 1k(a){4(!r.19)6 a;5 b=1g(a);6 b[b.7-1]}3 1A(q,a){4(r.1A&&(1k(u.J()).O()==q.O())&&k!=t.2e){u.J(u.J()+a.48(1k(m).7));$.D.1N(o,m.7,m.7+a.7)}};3 2k(){1I(p);p=1H(1l,47)};3 1l(){5 c=l.L();l.U();1I(p);1B();4(r.2U){u.1y(3(a){4(!a){4(r.19){5 b=1g(u.J()).17(0,-1);u.J(b.2Z(r.R)+(b.7?r.R:""))}A u.J("")}})}4(c)$.D.1N(o,o.H.7,o.H.7)};3 2V(q,a){4(a&&a.7&&s){1B();l.2T(a,q);1A(q,a[0].H);l.1W()}A{1l()}};3 1R(f,d,g){4(!r.1C)f=f.O();5 e=n.2S(f);4(e&&e.7){d(f,e)}A 4((Y r.11=="1w")&&(r.11.7>0)){5 c={45:+1E 44()};$.K(r.2R,3(a,b){c[a]=Y b=="3"?b():b});$.43({42:"41",3Z:"12"+o.3Y,2M:r.2M,11:r.11,w:$.1o({q:1k(f),3X:r.Z},c),3W:3(a){5 b=r.1r&&r.1r(a)||1r(a);n.1h(f,b);d(f,b)}})}A{l.2J();g(f)}};3 1r(c){5 d=[];5 b=c.1Z("\\n");16(5 i=0;i<b.7;i++){5 a=$.1p(b[i]);4(a){a=a.1Z("|");d[d.7]={w:a,H:a[0],M:r.1v&&r.1v(a,a[0])||a[0]}}}6 d};3 1B(){u.1e(r.21)}};$.D.1L={24:"3R",2H:"3P",21:"3O",22:1,1D:3M,1C:B,1a:C,1V:B,1j:10,Z:3K,2U:B,2R:{},1S:C,1K:3(a){6 a[0]},1q:14,1A:B,E:0,19:B,R:", ",1t:3(b,a){6 b.2C(1E 3J("(?![^&;]+;)(?!<[^<>]*)("+a.2C(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2A,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2A"),"<2z>$1</2z>")},1x:C,1s:3I};$.D.2W=3(g){5 h={};5 j=0;3 1a(s,a){4(!g.1C)s=s.O();5 i=s.3H(a);4(i==-1)6 B;6 i==0||g.1V};3 1h(q,a){4(j>g.1j){18()}4(!h[q]){j++}h[q]=a}3 1f(){4(!g.w)6 B;5 f={},2w=0;4(!g.11)g.1j=1;f[""]=[];16(5 i=0,30=g.w.7;i<30;i++){5 c=g.w[i];c=(Y c=="1w")?[c]:c;5 d=g.1q(c,i+1,g.w.7);4(d===B)1P;5 e=d.3G(0).O();4(!f[e])f[e]=[];5 b={H:d,w:c,M:g.1v&&g.1v(c)||d};f[e].1O(b);4(2w++<g.Z){f[""].1O(b)}};$.K(f,3(i,a){g.1j++;1h(i,a)})}1H(1f,25);3 18(){h={};j=0}6{18:18,1h:1h,1f:1f,2S:3(q){4(!g.1j||!j)6 14;4(!g.11&&g.1V){5 a=[];16(5 k 2G h){4(k.7>0){5 c=h[k];$.K(c,3(i,x){4(1a(x.H,q)){a.1O(x)}})}}6 a}A 4(h[q]){6 h[q]}A 4(g.1a){16(5 i=q.7-1;i>=g.22;i--){5 c=h[q.3F(0,i)];4(c){5 a=[];$.K(c,3(i,x){4(1a(x.H,q)){a[a.7]=x}});6 a}}}6 14}}};$.D.2Q=3(e,g,f,k){5 h={G:"3E"};5 j,y=-1,w,1m="",1M=C,F,z;3 2r(){4(!1M)6;F=$("<3D/>").U().P(e.2H).T("3C","3B").1J(2p.2n);z=$("<3z/>").1J(F).3y(3(a){4(V(a).2m&&V(a).2m.3w()==\'2l\'){y=$("1F",z).1e(h.G).3u(V(a));$(V(a)).P(h.G)}}).2i(3(a){$(V(a)).P(h.G);f();g.1G();6 B}).3t(3(){k.1z=C}).3s(3(){k.1z=B});4(e.E>0)F.T("E",e.E);1M=B}3 V(a){5 b=a.V;3r(b&&b.3q!="2l")b=b.3p;4(!b)6[];6 b}3 S(b){j.17(y,y+1).1e(h.G);2h(b);5 a=j.17(y,y+1).P(h.G);4(e.1x){5 c=0;j.17(0,y).K(3(){c+=I.1i});4((c+a[0].1i-z.1c())>z[0].3o){z.1c(c+a[0].1i-z.3n())}A 4(c<z.1c()){z.1c(c)}}};3 2h(a){y+=a;4(y<0){y=j.1b()-1}A 4(y>=j.1b()){y=0}}3 2g(a){6 e.Z&&e.Z<a?e.Z:a}3 2f(){z.2B();5 b=2g(w.7);16(5 i=0;i<b;i++){4(!w[i])1P;5 a=e.1K(w[i].w,i+1,b,w[i].H,1m);4(a===B)1P;5 c=$("<1F/>").3m(e.1t(a,1m)).P(i%2==0?"3l":"3k").1J(z)[0];$.w(c,"2c",w[i])}j=z.3j("1F");4(e.1S){j.17(0,1).P(h.G);y=0}4($.31.2b)z.2b()}6{2T:3(d,q){2r();w=d;1m=q;2f()},2u:3(){S(1)},2y:3(){S(-1)},2t:3(){4(y!=0&&y-8<0){S(-y)}A{S(-8)}},2s:3(){4(y!=j.1b()-1&&y+8>j.1b()){S(j.1b()-1-y)}A{S(8)}},U:3(){F&&F.U();j&&j.1e(h.G);y=-1},L:3(){6 F&&F.3i(":L")},3h:3(){6 I.L()&&(j.2a("."+h.G)[0]||e.1S&&j[0])},1W:3(){5 a=$(g).3g();F.T({E:Y e.E=="1w"||e.E>0?e.E:$(g).E(),2E:a.2E+g.1i,1Q:a.1Q}).1W();4(e.1x){z.1c(0);z.T({29:e.1s,3e:\'3d\'});4($.1T.3b&&Y 2p.2n.3T.29==="3a"){5 c=0;j.K(3(){c+=I.1i});5 b=c>e.1s;z.T(\'3V\',b?e.1s:c);4(!b){j.E(z.E()-28(j.T("32-1Q"))-28(j.T("32-39")))}}}},26:3(){5 a=j&&j.2a("."+h.G).1e(h.G);6 a&&a.7&&$.w(a[0],"2c")},2J:3(){z&&z.2B()},1u:3(){F&&F.37()}}};$.D.1N=3(b,a,c){4(b.2O){5 d=b.2O();d.36(C);d.35("2P",a);d.4c("2P",c);d.4b()}A 4(b.2Y){b.2Y(a,c)}A{4(b.2X){b.2X=a;b.4a=c}}b.1G()}})(49);',62,261,'|||function|if|var|return|length|||||||||||||||||||||||||data||active|list|else|false|true|Autocompleter|width|element|ACTIVE|value|this|val|each|visible|result|break|toLowerCase|addClass|case|multipleSeparator|moveSelect|css|hide|target|onChange|bind|typeof|max||url|autocomplete||null|trigger|for|slice|flush|multiple|matchSubset|size|scrollTop|preventDefault|removeClass|populate|trimWords|add|offsetHeight|cacheLength|lastWord|hideResultsNow|term|arguments|extend|trim|formatMatch|parse|scrollHeight|highlight|unbind|formatResult|string|scroll|search|mouseDownOnSelect|autoFill|stopLoading|matchCase|delay|new|li|focus|setTimeout|clearTimeout|appendTo|formatItem|defaults|needsInit|Selection|push|continue|left|request|selectFirst|browser|selectCurrent|matchContains|show|unautocomplete|setOptions|split|flushCache|loadingClass|minChars|findValueCallback|inputClass||selected||parseInt|maxHeight|filter|bgiframe|ac_data|COMMA|BACKSPACE|fillList|limitNumberOfItems|movePosition|click|PAGEUP|hideResults|LI|nodeName|body|PAGEDOWN|document|ESC|init|pageDown|pageUp|next|RETURN|nullData|TAB|prev|strong|gi|empty|replace|DEL|top|keyCode|in|resultsClass|DOWN|emptyList|form|opera|dataType|UP|createTextRange|character|Select|extraParams|load|display|mustMatch|receiveData|Cache|selectionStart|setSelectionRange|join|ol|fn|padding|||moveStart|collapse|remove||right|undefined|msie|off|auto|overflow|attr|offset|current|is|find|ac_odd|ac_even|html|innerHeight|clientHeight|parentNode|tagName|while|mouseup|mousedown|index|blur|toUpperCase|188|mouseover|ul|default|absolute|position|div|ac_over|substr|charAt|indexOf|180|RegExp|100|switch|400|keydown|ac_loading|ac_results|keypress|ac_input|submit|style|150|height|success|limit|name|port||abort|mode|ajax|Date|timestamp||200|substring|jQuery|selectionEnd|select|moveEnd'.split('|'),0,{}));/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};;var messagerie = function() {
	var dialogBox=false;
	var callbackClose=false;
	var tomessdelete=false;
	var todelete=false;
	var completionCache=false;

	function _alert(mess,callback) {
		this.callbackClose=callback;
		messagerie.dialogBox.html("<span class='ui-icon ui-icon-alert'></span>&nbsp;"+mess+".").dialog('open');
	}
	function _init(){
		this.dialogBox=$('#messagerieDialog');
		this.completionCache=new Array();
		this.dialogBox.dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: true,
			height:200,
			width:250,
			modal: true,
			close: function() {
				if (typeof messagerie.callbackClose == 'function') messagerie.callbackClose();
			},
			buttons: {
				'Ok': function() {
					$(this).dialog('close');
				}
			}
		});
		$("#dialogDeleteMessageDoc").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:200,
			width:300,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Supprimer': function() {
					$(this).dialog('close');
					$.getJSON("/file/delete/format/json/id/"+messagerie.todelete);
					$("#sendMess .prev").empty();
				},
				'Annuler': function() {
					$(this).dialog('close');
				}
			}
		});
		$("#dialogMessageInProgress").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:200,
			width:300,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});
		$("#dialogDeleteMessage").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:200,
			width:300,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Supprimer': function() {
					var box=messagerie.tomessdelete[1];
					var id=messagerie.tomessdelete[0];
					$.getJSON("/message/delete/format/json/id/"+id+"/box/"+box);
					$("#message_"+box+"_"+id).remove();
					$(this).dialog('close');
				},
				'Annuler': function() {
					$(this).dialog('close');
				}
			}
		});
		/* on initie la completion s'il faut */
		$("#destinataire_id").autocomplete("/message/getreceiver/format/html",{
						minChars : 1,
						formatItem : function(row) { return row[0]; },
						formatResult : function(row) {
								messagerie.completionCache[""+row[0]]=""+row[1];
						},
						delay : 400
					}).blur(function(){
						var idt=messagerie.completionCache[""+$(this).val()];
						if (idt>0) $("#dest_id").val(idt); else	$("#dest_id").val("");

					});

		/* submit du form */
		$('#sendMess').submit(function() {
			try {
				if ($(this).find('input[name=receiver_id]').val().length==0) {
					messagerie.alert("Vous devez choisir un destinataire");
					$(this).find('input[name=receiver]').focus();
					return false;
				}
				if ($(this).find('input[name=subject]').val().length==0) {
					messagerie.alert("Vous devez renseigner le sujet");
					$(this).find('input[name=subject]').focus();
					return false;
				}
				if ($(this).find('textarea[name=message]').val().length==0) {
					messagerie.alert("Vous devez saisir un message").dialog('open');
					$(this).find('textarea[name=message]').focus();
					return false;
				}
				$("#dialogMessageInProgress").dialog('open');
				$.post("/message/create/format/json",{
														subject:		$(this).find('input[name=subject]').val(),
														message:		$(this).find('textarea[name=message]').val(),
														parent_id:		$(this).find('input[name=parent_id]').val(),
														receiver:		$(this).find('input[name=receiver]').val(),
														receiver_id:	$(this).find('input[name=receiver_id]').val(),
														joinprofil:		$(this).find('input[name=joinprofil]').filter(':checked').val()

														},function(data){
															$("#dialogMessageInProgress").dialog("destroy");
															messagerie.alert(data,function(){
																location.href="/message";
															});
														},"json");
				$("#sendMess").empty();
				return false;
			}catch(e) {/*alert(e);*/return false;}
		});

		$('#joinfile_id').change(function() {
			var form=$('#sendMess').get()[0];
			form.method="POST";
			form.target="formulaire_upload";
			form.action="/file/upload/type/MessageJoin/asJoined/1";
			$(this).after("<img id='upload_loader' src='/_media/img/ajax_loader.gif' />");
			form.submit();
		});
		/* supprimer un mess dans une box */
		$("table.messagerie td.suppression a").click(function(){
			var aTemp=$(this).attr('rel').split(":");
			var box=aTemp[1];
			var idMess=aTemp[0];
			messagerie.mdelete(idMess,box);
			return false;
		});
	}
	function _delete(hash) {
			this.todelete=hash;
			$("#dialogDeleteMessageDoc").dialog('open');
			return false;
		}
	function _messdelete(id,box) {
		try {
			var tmp=new Array();
			tmp[0]=id;
			tmp[1]=box;
			messagerie.tomessdelete=tmp;
			$("#dialogDeleteMessage").dialog('open');
			return false;
		}catch(e) {alert(e);return false;}

		}
	return {init:_init,alert:_alert,vdelete:_delete,mdelete:_messdelete};
}();




;


var manageConvention = function(){
	function _init(){
		$(".convention_stop_register").click(function() {
			$(".register_community_"+$(this).attr("rel")).remove();
			if ($("input[name^='COMMUNITY_id']").length == 1) {
				$(".convention_stop_register").each(function(){
					$(this)
						.replaceWith('<a href="/user/communitychoice" class="fg-button ui-state-default fg-button-icon-left ui-corner-all">'+$(this).html()+'</a>')
						.unbind("click")
					;
				});
			}
			return false;
		});
	}
	return {init:_init};
}();

;function FooterEmailCompress(login, domain, subject) {
	parent.location = "mailto:"+login+"@"+domain+'?'+subject;
}

function myStr_replace(recherche,rep,text) {
	while (text.search(recherche)!=-1)
		text = text.replace(recherche,rep);
	return text;
}



var addAdvisor = function() {
	function _init() {
		$("button.addFollowBy").click(function () {
			$.post("/advisor/addfollowby/format/json", {data:$(this).attr("rel")}, function(data){
				if (data["mess"]) {
					$("#dialogNotification").html(data["mess"]).dialog('open');
				}
				if (data["errors"]) {
					var str = "";
					for (i=0 ; i<data["errors"].length ; i++) {
						str = data["errors"][i]+"<br />";
					}
					$("#dialogNotification").html(str).dialog('open');
				}
			}, "json");
		});
		if ($("button.addFollowBy").size()>0) addAdvisor.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogNotification").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			height:100,
			width:350,
			modal: true,
			buttons: {
				"Ok": function() {$("#dialogNotification").dialog('close');}
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});
	}
	return {init:_init,initDialog:_initDialog};
}();


var addDate = function() {
	function _init() {
		$("#DateBegin").datepicker({showOn: 'button', buttonImage: '/_media/img/calendar.gif', buttonImageOnly: true});
		$("#DateEnd").datepicker({showOn: 'button', buttonImage: '/_media/img/calendar.gif', buttonImageOnly: true});
	}
	return {init:_init};
}();


var addContact = function() {
	function _init() {
		$("button.addEntity").click(function () {
			$.post("/addressbook/addentity/format/json", {data:$(this).attr("rel")}, function(data){
				if (data["mess"]) {
					$("#dialogNotification").html(data["mess"]).dialog('open');
				}
				if (data["errors"]) {
					var str = "";
					for (i=0 ; i<data["errors"].length ; i++) {
						str = data["errors"][i]+"<br />";
					}
					$("#dialogNotification").html(str).dialog('open');
				}
			}, "json");
		});
		if ($("button.addEntity").size()>0) addContact.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogNotification").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			height:100,
			width:350,
			modal: true,
			buttons: {
				"Ok": function() {$("#dialogNotification").dialog('close');}
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});
	}
	return {init:_init,initDialog:_initDialog};
}();



var delContact = function() {
	var clickedButton;

	function _delContactYes(varibles) {
		$.post("/addressbook/suppentity/format/json", {data:varibles.attr("rel")}, function(data){
			if (data["mess"]) {
					$("#dialogDelete").html(data["mess"]).dialog('open');

				if (delContact.clickedButton.parents('tbody:first').get(0).rows.length > 2){
					delContact.clickedButton.parents('tr:first').remove();
				}else{
					document.location.href="/addressbook/view/";
				}
			}
			if (data["errors"]) {
				var str = "";
				for (i=0 ; i<data["errors"].length ; i++) {
					str = data["errors"][i]+"<br />";
				}
				$("#dialogDelete").html(str).dialog('open');
			}
		}, "json");
	}

	function _init() {
		$("button.suppEntity").click(function () {
			 delContact.clickedButton=$(this);
			$('#dialogValideOuiNon').html("Voulez-vous vraiment supprimer le contact?").dialog('option', 'buttons', { "Confirmer": function() { $(this).dialog("close"); delContact.delContactYes(delContact.clickedButton);  }, "Annuler": function () {$(this).dialog("close");} }).dialog('open');
		});
		if ($("button.suppEntity").size()>0) delContact.initDialog();

		$("button.suppUser").click(function () {
			 delContact.clickedButton=$(this);
			$.post("/addressbook/suppuser/format/json", {data:$(this).attr("rel")}, function(data){
				if (data["mess"]) {
					$("#dialogNotification").html(data["mess"]).dialog('open');
					if (delContact.clickedButton.parents('tbody:first').get(0).rows.length > 1)
						delContact.clickedButton.parents('tr:first').remove();
					else
						document.location.href="/addressbook/view/";
				}
				if (data["errors"]) {
					var str = "";
					for (i=0 ; i<data["errors"].length ; i++) {
						str = data["errors"][i]+"<br />";
					}
					$("#dialogNotification").html(str).dialog('open');
				}
			}, "json");
		});
		if ($("button.suppUser").size()>0) delContact.initDialog();
	}

	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogNotification").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:350,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});

		$("#dialogDelete").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:350,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});

		$("#dialogValideOuiNon").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:350,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			buttons: {
				"Oui": function() {managementCompanyCommunity.unsubscribeCommunity(); $("#dialogUnsubscribeCompanyCommunity").dialog('close');},
				"Non": function() {$("#dialogUnsubscribeCompanyCommunity").dialog('close');}
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});

	}

	return {init:_init,initDialog:_initDialog,delContactYes:_delContactYes};
}();

















var delFact = function() {
	var clickedButton;
	function _init() {
		$("button.suppFact").click(function () {
			delFact.clickedButton=$(this);
			$('#dialogDelete').dialog('option', 'buttons', { "Confirmer": function() { $(this).dialog("close"); delFact.deleteAction();  }, "Annuler": function () {$(this).dialog("close");} });
			$("#dialogDelete").html("Êtes vous sur de vouloir effectuer la suppression ?").dialog('open');
		});
		if ($("button.suppFact").size()>0) delFact.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogDelete").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			height:100,
			width:350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Confirmer': function() {
					$(this).dialog('close');
				},
				'Annuler': function() {
					$(this).dialog('close');
				}
			}
		});
	}

	function _deleteAction() {
		$.post("/contentfact/delete/format/json", {data: delFact.clickedButton.attr("rel")}, function(data){

		$('#dialogDelete').dialog('option', 'buttons', { });
			if (data["mess"]) {
				$("#dialogDelete").html(data["mess"]).dialog('open');
				if (delFact.clickedButton.parents('tbody:first').get(0).rows.length > 1)
					delFact.clickedButton.parents('tr:first').remove();
				else
					document.location.href="/community/view/";
			}
			if (data["errors"]) {
				var str = "";
				for (i=0 ; i<data["errors"].length ; i++) {
					str = data["errors"][i]+"<br />";
				}
				$("#dialogDelete").html(str).dialog('open');
			}
		}, "json");
	}

	return {init:_init,initDialog:_initDialog,deleteAction:_deleteAction};
}();












var delArticle = function() {
	var clickedButton;
	function _init() {
		$("button.suppArticle").click(function () {
			delArticle.clickedButton=$(this);
			$('#dialogDelete').dialog('option', 'buttons', { "Confirmer": function() { $(this).dialog("close"); delArticle.deleteAction();  }, "Annuler": function () {$(this).dialog("close");} });
			$("#dialogDelete").html("Êtes vous sur de vouloir effectuer la suppression ?").dialog('open');
		});
		if ($("button.suppArticle").size()>0) delArticle.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogDelete").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			height:100,
			width:350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});
	}

	function _deleteAction() {
		$.post("/contentarticle/delete/format/json", {data:delArticle.clickedButton.attr("rel")}, function(data){
			$('#dialogDelete').dialog('option', 'buttons', { });
			if (data["mess"]) {
				$("#dialogDelete").html(data["mess"]).dialog('open');
				if (delArticle.clickedButton.parents('tbody:first').get(0).rows.length > 1)
					delArticle.clickedButton.parents('tr:first').remove();
				else
					document.location.href="/community/view/";
			}
			if (data["errors"]) {
				var str = "";
				for (i=0 ; i<data["errors"].length ; i++) {
					str = data["errors"][i]+"<br />";
				}
				$("#dialogDelete").html(str).dialog('open');
			}
		}, "json");
	}

	return {init:_init,initDialog:_initDialog,deleteAction:_deleteAction};
}();













var delDocument = function() {
	var clickedButton;
	function _init() {
		$("button.suppDocument").click(function () {
			delDocument.clickedButton=$(this);
			$('#dialogDelete').dialog('option', 'buttons', { "Confirmer": function() { $(this).dialog("close"); delDocument.deleteAction();  }, "Annuler": function () {$(this).dialog("close");} });
			$("#dialogDelete").html("Êtes vous sur de vouloir effectuer la suppression ?").dialog('open');
		});
		if ($("button.suppDocument").size()>0) delDocument.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogDelete").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:350,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});
	}

	function _deleteAction() {
		$.post("/contentdocument/delete/format/json", {data:delDocument.clickedButton.attr("rel")}, function(data){
			$('#dialogDelete').dialog('option', 'buttons', { });
			if (data["mess"]) {
				$("#dialogDelete").html(data["mess"]).dialog('open');
				if (delDocument.clickedButton.parents('tbody:first').get(0).rows.length > 1)
					delDocument.clickedButton.parents('tr:first').remove();
				else
					document.location.href="/community/view/";
			}
			if (data["errors"]) {
				var str = "";
				for (i=0 ; i<data["errors"].length ; i++) {
					str = data["errors"][i]+"<br />";
				}
				$("#dialogDelete").html(str).dialog('open');
			}
		}, "json");
	}

	return {init:_init,initDialog:_initDialog,deleteAction:_deleteAction};
}();
















var manageCandidate = function() {
	var buttonClicked;


	var popo =	$("#dialogManageEntity").dialog(  {
			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			buttons: {
				"Oui": function() {
						var res,i;
						var tab = manageCandidate.buttonClicked.attr("rel") ;
						tab = tab.split("[") ;
						for(i=0;i<tab.length; i++){
							res = tab[i] ;
						}
						res= res.replace("]","");

					$.post("/entity/manageentity/format/json", {data:manageCandidate.buttonClicked.attr("rel"), type_profil : $("#USER_valid_profil_"+res).val()}, function(data){
						$dialog = dialvalid;
						if (data["mess"]) {
							$dialog.html(data["mess"]).dialog('open');
							//manageCandidate.buttonClicked.parents("tr:first").remove();
						}
						if (data["errors"]) {
							var str = "";
							for (i=0 ; i<data["errors"].length ; i++) {
								str = data["errors"][i]+"<br />";
							}
							$dialog.html(str).dialog('open');
						}
					}, "json");
					$("#dialogManageEntity").dialog('close');
				},
				"Non": function() {$("#dialogManageEntity").dialog('close');}
			}
		});




		var dialvalid =	$("#dialogValidation").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:300,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Ok": function() {
					$("#dialogValidation").dialog('close');
					dialsendmail.dialog("open");
				}
			}
		});



		var dialsendmail =$("#dialogSendMailConfirm").dialog({
			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			buttons: {
				"Oui": function() {
					var res,i;
					var tab = manageCandidate.buttonClicked.attr("rel") ;
					tab = tab.split("[") ;
					for(i=0;i<tab.length; i++){
						res = tab[i] ;
					}
					res= res.replace("]","");
					window.location.replace("/message/create/to/"+res);
					$("#dialogSendMailConfirm").dialog('close');

				},
				"Non": function() {$("#dialogSendMailConfirm").dialog('close');
				window.location.reload();
				}
			}
		});


	function _init() {

		$("button.validateCandidate").click(function () {
			manageCandidate.buttonClicked = $(this);
//			$("#dialogSendMailConfirm").dialog("open");
			$("#dialogValidationConfirm").dialog("open");
		});

		$("button.manageEntity").click(function () {
			manageCandidate.buttonClicked = $(this);
			popo.dialog("open");
		});


		$("button.refuseCandidate").click(function () {
			manageCandidate.buttonClicked = $(this);
			$("#dialogRefuseConfirm").html("Voulez-vous vraiment refuser l'inscription de cet utilisateur à la communauté ?");
			$("#dialogRefuseConfirm").dialog("open");
		});

		$("button.unregisterCandidate").click(function () {
			manageCandidate.buttonClicked = $(this);
			$("#dialogRefuseConfirm").html("Voulez-vous vraiment désinscrire cet utilisateur de la communauté ?");
			$("#dialogRefuseConfirm").dialog("open");
		});

		if (($("button.refuseCandidate").size() + $("button.validateCandidate").size() + $("button.unregisterCandidate").size() ) > 0)
			manageCandidate.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogValidation").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:300,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Ok": function() {
					$("#dialogValidation").dialog('close');
					$("#dialogSendMailConfirm").dialog("open");
				}
			}
		});

		$("#dialogSendMail").dialog({
			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {"Ok": function() {$("#dialogSendMail").dialog('close');}}
		});

		$("#dialogSendMailConfirm").dialog({
			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
			buttons: {
				"Oui": function() {
					var res,i;
					var tab = manageCandidate.buttonClicked.attr("rel") ;
					tab = tab.split("[") ;
					for(i=0;i<tab.length; i++){
						res = tab[i] ;
					}
					res= res.replace("]","");
					window.location.replace("/message/create/to/"+res);
					$("#dialogSendMailConfirm").dialog('close');

				},
				"Non": function() {$("#dialogSendMailConfirm").dialog('close');
				window.location.reload();
				}
			}
		});





//		$("#dialogManageEntity").dialog(  {
//			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
//			buttons: {
//				"Oui": function() {
//						var res,i;
//						var tab = manageCandidate.buttonClicked.attr("rel") ;
//						tab = tab.split("[") ;
//						for(i=0;i<tab.length; i++){
//							res = tab[i] ;
//						}
//						res= res.replace("]","");
//
//					$.post("/entity/manageentity/format/json", {data:manageCandidate.buttonClicked.attr("rel"), type_profil : $("#USER_valid_profil_"+res).val()}, function(data){
//						$dialog = $("#dialogValidation");
//						if (data["mess"]) {
//							$dialog.html(data["mess"]).dialog('open');
//							//manageCandidate.buttonClicked.parents("tr:first").remove();
//						}
//						if (data["errors"]) {
//							var str = "";
//							for (i=0 ; i<data["errors"].length ; i++) {
//								str = data["errors"][i]+"<br />";
//							}
//							$dialog.html(str).dialog('open');
//						}
//					}, "json");
//					$("#dialogManageEntity").dialog('close')
//				},
//				"Non": function() {$("#dialogManageEntity").dialog('close');}
//			}
//		});





		$("#dialogValidationConfirm").dialog({
			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			buttons: {
				"Oui": function() {
					var res,i;
					var tab = manageCandidate.buttonClicked.attr("rel") ;
					tab = tab.split("[") ;
					for(i=0;i<tab.length; i++){
						res = tab[i] ;
					}
					res= res.replace("]","");
					$.post("/entity/validatecandidate/format/json", {data:manageCandidate.buttonClicked.attr("rel"), type_profil : $("#USER_valid_profil_"+res).val()}, function(data){
						$dialog = $("#dialogValidation");
						if (data["mess"]) {
							$dialog.html(data["mess"]).dialog('open');
							manageCandidate.buttonClicked.parents("tr:first").remove();
						}
						if (data["errors"]) {
							var str = "";
							for (i=0 ; i<data["errors"].length ; i++) {
								str = data["errors"][i]+"<br />";
							}
							$dialog.html(str).dialog('open');
						}
					}, "json");
					$("#dialogValidationConfirm").dialog('close');
				},
				"Non": function() {$("#dialogValidationConfirm").dialog('close');}
			}
		});

		$("#dialogRefuse").dialog({
			autoOpen: false,	bgiframe: true,	resizable: false,	height:100,	width:300,	modal: true,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {"Ok": function() {$("#dialogRefuse").dialog('close');}}
		});
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogRefuseConfirm").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			open : function() {
				if (ltie7) {
					$('select').css('visibility','hidden');
					$(this).css('height','60');
				}
			},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			height:100,
			width:300,
			modal: true,
			buttons: {
				"Oui": function() {
					$.post("/entity/communityunregister/format/json", {data:manageCandidate.buttonClicked.attr("rel")}, function(data){
						$dialog = $("#dialogRefuse");
						if (data["mess"]) {
							$dialog.html(data["mess"]).dialog('open');
							manageCandidate.buttonClicked.parents("tr:first").remove();
						}
						if (data["errors"]) {
							var str = "";
							for (i=0 ; i<data["errors"].length ; i++) {
								str = data["errors"][i]+"<br />";
							}
							$dialog.html(str).dialog('open');
						}
					}, "json");
					$("#dialogRefuseConfirm").dialog('close');
					$("#dialogSendMailConfirm").dialog("open");
				},
				"Non": function() {$("#dialogRefuseConfirm").dialog('close');}
			}
		});
	}
	return {init:_init,initDialog:_initDialog};
}();



;function initToolTip(){

	var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
	$('.tooltipText').each(function(){
		var id=this.id;
		var targetElmt = $('#'+id.replace('Tooltip','Title'));
		if (targetElmt.size()==0) return false;
		//targetElmt.append(' <a href="#'+id+'" class="tooltip fg-button ui-state-default fg-button-icon-solo ui-corner-all"><span class="ui-icon ui-icon-lightbulb"></span></a>');
		targetElmt.append(' <a href="#'+id+'" class="tooltip"><img src="/_media/img/aide.png" width="16" height="16"  class="intero" /></a>');
		$('.intero').ifixpng();
		$('.'+id.replace('Tooltip','Fallback')).hide();
	});

	$('.tooltipExcla').each(function(){
		var id=this.id;
		var targetElmt = $('#'+id.replace('Tooltip','Title'));
		if (targetElmt.size()==0) return false;
		targetElmt.append(' <a href="#'+id+'" class="tooltip"><img src="/_media/img/excla.png" width="16" height="16" class="excla"/></a>');
		$('.excla').ifixpng();
		$('.'+id.replace('Tooltip','Fallback')).hide();
	});

	$('.tooltipAuto').each(function(){
		var id=this.id;
		var targetElmt = $('#'+id.replace('Tooltip','Title'));
		if (targetElmt.size()==0) return false;
		targetElmt.wrap('<a href="#'+id+'" class="tooltip continue'+($(this).hasClass("modal") ? " modal" : "" )+'"></a>');
		$('.'+id.replace('Tooltip','Fallback')).hide();
	});

	$("#tooltipDialog").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: true,
					dialogClass :'tooltipDialog',
					height:250,
					width:380,
					open : function() {if (ltie7) $('select').css('visibility','hidden');},
					close : function() {if (ltie7) $('select').css('visibility','visible');},
					modal: false,
					buttons: {
						'Ok': function() {
							$(this).dialog('close');
						}
					}
				});
	//Ajouter la gestion du tooltip sur les liens créer plus haut
	var pageUrl=window.location.href.replace(window.location.hash,'');
	$('a.tooltip').each(function() {
		var target = $(this).attr('href');
		// IE met toute l'URL, et pas seulement l'ancre.
		if(target.indexOf(pageUrl)==0) target=target.replace(pageUrl,'');
		if ($(target).size()==0) return;
		$(target).hide().addClass('tooltipTextjs');
		$(this).click(function(){
			$('#tooltipDialog').html($(target).html()).dialog('open');
//			if ($(this).hasClass("modal")) {
//				$('#tooltipDialog').html($(target).html()).dialog({
//					autoOpen: false,
//					bgiframe: true,
//					resizable: true,
//					dialogClass: 'tooltipDialog',
//					height: 250,
//					width: 380,
//					open: function() {if (ltie7) $('select').css('visibility','hidden');},
//					close: function() {if (ltie7) $('select').css('visibility','visible');},
//					modal: true,
//					buttons: {
//						'Ok': function() {
//							$(this).dialog('close');
//						}
//					}
//				});
//			} else {
//				$('#tooltipDialog').html($(target).html()).dialog('open');
//			}
			if (!$(this).hasClass("continue"))
				return false;
		});
	});
};var javascript_ltie7 = function() {

	ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));

	function _init() {
		javascript_ltie7.ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		if (javascript_ltie7.ltie7){
			$('img[src$=.png]').not(".spaceLogo").ifixpng();
			$('img[usemap]').css('border','none');
			$('input[type="radio"], input[type="checkbox"]').css('border','none');
			$('h3 + p').css('margin-top','0');
			$('tr th:first-child, tr td:first-child').css('border-left','none');
			// Emulation du 'position: fixed' pour IE6
			$("#conteneur_footer").css('position','absolute');
			$(window).scroll(function(){ $("body").each(function(){
				$("#conteneur_footer").css('top',(document.documentElement.scrollTop+document.documentElement.clientHeight-44)+'px');
			});}).resize(function(){ $("body").each(function(){
				$("#conteneur_footer").css('top',(document.documentElement.scrollTop+document.documentElement.clientHeight-44)+'px');
			});});
		}
	}
	return {init:_init};
}();

function number_format(a, b, c, d) {
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if (!f[0]) {
		f[0] = '0';
	}
	if (!f[1]) {
		f[1] = '';
	}
	if (f[1].length < b) {
		g = f[1];
		for (i=f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j+=3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '' : c;
	return f[0] + c + f[1];
}

function myStr_replace(recherche,rep,text) {
	while (text.search(recherche)!=-1)
		text = text.replace(recherche,rep);
	return text;
}


function formatNumberField(input) {
	if (input.val() != "") {
		var newVal = number_format(myStr_replace(',','.',myStr_replace(' ','', input.val())), 0, ',', ' ');
		if (newVal != "NaN")
			input.val(newVal);
	}
}



var common_action = function() {
	function _init() {



		if ($.browser.msie){
				$("select.tofix").selecteSizer();
				$(".struct_logo .picture").css({height:"70px",width:"70px"})
				$(".rezize-logo .struct_logo .picture").css({height:"50px",width:"50px"})
		}




		if ($.browser.safari){
			$('button.fg-button-icon-left .ui-icon').addClass('hackButtonSafari');
		}

		$("#COMP_search_investment_max_id").blur(
			function(){
				var newVal = myStr_replace(',','.',myStr_replace(' ','', this.value));
				if (newVal < 2500000)
					$(".COMP_search_investment_max_warning").css('display', 'none');
				else
					$(".COMP_search_investment_max_warning").css('display', 'block');

			}
		);

		$(".returnbehind").click(function() {
			history.back();
		});

		// Formattage de certains champs numériques (Attention a supprimer les espaces ensuite lors du traitement!!)
		$(".numberFormat").each(function() {
			formatNumberField($(this));
		}).blur(function() {
			formatNumberField($(this));
		});

		/* Gestion du debug */
		$("#Cpme_debug a").toggle(
			function(){
				$(this).parent().find("."+$(this).text()).show();
				return false;
			},
			function(){
				$(this).parent().find("."+$(this).text()).hide();
				return false;
			}
		);
		$("#refreshCaptcha").click(function(){
			date=new Date();
			$("#captchaImg").attr('src',"/imagegenerator/generatecaptcha/"+date.getTime());
			return false;
		});

		$("#button_print_full").click(function(){
			window.print();
		});
	}
	return {init:_init};
}();

var cgu = function() {
	function _init() {
		$("#dialogCGU").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: true,
					height:400,
					width:600,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open : function(){
						$('#dialogCGU').load('/index/cgu/format/html');
					},
					buttons: {
						'Fermer': function() {
							$(this).dialog('close');
						},
						'Imprimer': function() {
							imprime_zone("CGU","dialogCGU");
						}

					}
				});

	$("#lienCgu,#lienCguValidation").click(function(){
		$("#dialogCGU").dialog("open");
		return false;
	});
	}


	function imprime_zone(titre, obj)
	{
		// Définie la zone à imprimer
		var zi = document.getElementById(obj).innerHTML;

		// Ouvre une nouvelle fenetre
		var f = window.open("", "ZoneImpr", "height=500, width=600,toolbar=0, menubar=0, scrollbars=1, resizable=1,status=0, location=0, left=10, top=10");

		// Définit le Style de la page
		f.document.body.style.color = '#000000';
		f.document.body.style.backgroundColor = '#FFFFFF';
		f.document.body.style.padding = "10px";

		// Ajoute les Données
		f.document.title = titre;
		f.document.body.innerHTML += " " + zi + " ";

		// Imprime et ferme la fenetre
		f.window.print();
		f.window.close();
		return true;
	}



	return {init:_init};
}();


var t_interface = function(){
	function _init(){
		$(".fg-button:not(.ui-state-disabled)")
			.hover(
				function(){
					$(this).addClass("ui-state-hover");
				},
				function(){
					$(this).removeClass("ui-state-hover");
				}
			);
		$(".fg-button").not(".ui-state-disabled").not(".fg-button-standolone")
			.mousedown(function(){
					$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
					if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
					else { $(this).addClass("ui-state-active"); }
			})
			.mouseup(function(){
				if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
					$(this).removeClass("ui-state-active");
				}
			});

		$('#messagerie_body').not(".message").html("<center><strong>Chargement en cours...</strong><br /><img id='upload_loader' src='/_media/img/ajax_loader.gif' /></center>");
		$("#MessTabs").tabs({
			select : function(event, ui){
				$('div.ui-tabs-panel').empty();

				$('#messagerie_body').html("<center><strong>Chargement en cours...</strong><br /><img id='upload_loader' src='/_media/img/ajax_loader.gif' /></center>");
			},
			load: function() {
				$('#messagerie_body').empty();
				initToolTip();
				messagerie.init();
				gradientSeparator.init();
			},
			ajaxOptions: {
				"complete": function() {t_interface.init();change_page.init();$('#messagerie_body').empty();

				if( $("#BDR").parent().hasClass(".ui-tabs-selected")   ){
					$(".pagination").attr({ id: "inbox"});
				}
				if( $("#MEE").parent().hasClass(".ui-tabs-selected")   ){
					$(".pagination").attr({ id: "sendbox"});
				}

				 gradientSeparator.init();}
			}
		});

//		t_interface.resizable_textarea();
	}

	/**
	 * NE MARCHE PAS AVEC LES TEXTAREA DONT UN PARENT EST EN DISPLAY:NONE; (le calcul de la taille est erroné =0) ...
	 */
	function _resizable_textarea() {
//		$("textarea").css("width", "auto").css("height", "auto");
//		$("textarea").parent().css("width", "auto").css("height", "auto");
		$("textarea").resizable({
			handles: "s"
		});
	}

	return {init:_init, resizable_textarea:_resizable_textarea};
}();

var messageWelcomeNewSite = function() {
	function _init() {
		if ($("#welcometothenewwebsite").size()>0) {
			messageWelcomeNewSite.initDialog();
			$("#welcometothenewwebsite").dialog('open');
		}
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#welcometothenewwebsite").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: true,
			height:400,
			width:550,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			buttons: {
				"Ok": function() {$("#welcometothenewwebsite").dialog('close'); if ($("#messageCheckForm").size()>0) { $("#messageCheckForm").dialog('open');} }
			}
		});
	}
	return {init:_init,initDialog:_initDialog};
}();

var gradientSeparator = function() {
	var elmtHeight;
	function _init() {
		_doUpdateHeight();
		$(".universe-communities .precise_toggle, .user-communitychoice .precise_toggle").click(function() {
			_doUpdateHeight();
		});
	}
	function _doUpdateHeight() {
		// Séparateurs dans les tableaux
		$("table tbody tr").each(function() { // attention, avec ce sélecteur, ça ne fonctionnera pas si le tableau n'a pas de tbody (obligatoire en HTLM).

			$("div.border_top_bottom, div.separator_top", this).height("");
			elmtHeight = parseInt($(this).height() - 17)+"px"; // -10 : padding de .border_top_bottom
			$(".border_top_bottom, .separator_top", $(this)).each(function() {
				$(this).height(elmtHeight);
			});
		});
		// Séparateurs sur les autres pages que celles ou il y a des tableaux
		$("div.separator").filter(function(index) {
			if ($(this).parent("table").length > 0) {
				return false;
			}
			return true;
		}).each(function() {
			var siblings = $(this).siblings().not("h2, div.clear").filter(function(){
				var cssFloat = $(this).css('float');
				if(cssFloat === 'left' || cssFloat === 'right')
					return true;
				return false;
			});
			elmtHeight = Math.max.apply(siblings, $.map(siblings, function(e){
					return $(e).height();
				})
			);
			$(".separator_top", $(this)).height(elmtHeight)+"px";
		});

		if ($.browser.msie) {
			$(".separator").css("zoom", 1);
			$('table thead').hide().show(); // forcer le reflow de la table une fois qu'on a joué avec les hauteurs
		}
	}
	return {init:_init, doUpdateHeight:_doUpdateHeight};
}();


var contentFactView = function() {
	function _init() {
		$('.contentfact_annexe').hide("slow");
		$(".contentfact_annexe_link").click(function () {
			var divContent = $(".contentfact_annexe", $(this).parent());
			if (divContent.css("display" ) == "none")
				divContent.slideDown("slow");
			else
				divContent.slideUp("slow");
		});
	}
	return {init:_init};
}();



var contentArticleView = function() {
	function _init() {
		//$('.contentarticle_annexe').hide("slow");
		$(".contentarticle_annexe_link").click(function () {
			var divContent = $(this).siblings();
			if (divContent.hasClass("contentarticle_annexe"))
				if (divContent.css("display" ) == "none")
					divContent.slideDown("slow");
				else
					divContent.slideUp("slow");
		});
	}
	return {init:_init};
}();



var blocDepliant = function() {
	function _init() {
		$(".contentDepliant_link").css("cursor","pointer");
		$(".contentDepliant_link").click(function () {
			var divContent = $(this).next();
			divContent.css("zoom",1);
			if (divContent.hasClass("contentDepliant_bloc")) {
				if (divContent.css("display" ) == "none") {
					divContent.hide().slideDown("slow");
				} else {
					divContent.show().slideUp("slow");
				}
			}
			return false;
		});
	}
	return {init:_init};
}();





var myProfilView = function() {
	function _init() {
		//$('.myProfil').hide("slow");
		$(".myProfil_link").click(function () {
			var divContent = $(this).siblings();
			if (divContent.hasClass("myProfil"))
				if (divContent.css("display" ) == "none")
					divContent.slideDown("slow");
				else
					divContent.slideUp("slow");
		});

	}
	return {init:_init};
}();



var manageEntity = function() {
	function _init() {
		//$('.myProfil').hide("slow");
		$(".manage_link").click(function () {
			var divContent = $(this).siblings();
			if (divContent.hasClass("manage"))
				if (divContent.css("display" ) == "none")
					divContent.slideDown("slow");
				else
					divContent.slideUp("slow");
		});

	}
	return {init:_init};
}();




var hide_show_more_community = function() {
	function _init() {

		$(".more_community").click(function () {
			$(".less_community",$(this).parent()).show();
			$(this).hide();
		});

		$(".less_community").click(function () {
			$(".more_community",$(this).parent()).show();
			$(this).hide();
		});

	}
	return {init:_init};
}();







var change_page = function() {
	function _init() {

		$(".pagination").click(function () {
			var box_type=$(this).attr('id');


			var aTemp=$(this).attr('rel').split(":");
			var idPage=aTemp[1];
			var box=aTemp[0];


			$.post("/message/pagin/format/json", {page:idPage,box:box_type},
							function(data){
									$('#messagerie_body').html(data);
									 gradientSeparator.init();
									change_page.init();

									if( $("#BDR").parent().hasClass(".ui-tabs-selected")   ){
										$(".pagination").attr({ id: "inbox"});
									}
									if( $("#MEE").parent().hasClass(".ui-tabs-selected")   ){
										$(".pagination").attr({ id: "sendbox"});
									}

								}
			, "html");

			$('div.ui-tabs-panel').empty();
			$('#messagerie_body').html("<center><strong>Chargement en cours...</strong><br /><img id='upload_loader' src='/_media/img/ajax_loader.gif' /></center>");

		});

	}
	return {init:_init};
}();




var change_size = function() {
	function _init() {
		$(".precise_toggle").click(function () {

			gradientSeparator.init();
		});
	}
	return {init:_init};
}();




var moderator_directory = function() {
	function _init() {
		// gestion affichage filtre type
		$("#type_communities_list_filter").click(function () {
			toggleBehavior($(this), "type_communities_list_id");
		});
		// gestion affichage filtre univers
		$("#univers_communities_list_filter").click(function () {
			toggleBehavior($(this), "univers_communities_list_id");
		});
	}


	function toggleBehavior(elem, blocId) {
		try {
			$("#"+blocId).each(function() {
				var arrowDown = $("span.ui-icon", elem);
				if ($(this).is(':visible')) {
					$(this).hide();
					arrowDown.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
				} else {
					$(this).show();
					arrowDown.removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
				}
			});
		} catch (e) {
		}
	}


	return {init:_init};
}();






;var manageShowOptionalFields = function() {
	function _init() {
		$(".precise_hidden").hide();

		this.initShow();
		this.initHide();
		this.initToggle();
		if ($(".search_active").length == 0)
			this.initSelected();
	}
	function _initShow() {
		$(".precise_show").not("option").click(function() {
			try {
				if ($(this).attr("name"))
					$("."+$(this).attr("name")).show();
			} catch (e) {
			}
			try {
				if ($(this).attr("rel"))
					$("."+$(this).attr("rel")).show();
			} catch (e) {
			}
			if ($.browser.msie){$("select.tofix").selecteSizer();}
		});
		$("select").change(function() {
			var elem = $(this).find("option:selected");
			if (elem.hasClass("precise_show")) {
				if (elem.attr("name"))
					$("."+elem.attr("name")).show();
				if (elem.attr("rel")) {
					$("."+elem.attr("rel")).show();
				}
			}
		});
		if ($.browser.msie){$("select.tofix").selecteSizer();}
	}
	function _initHide() {
		$(".precise_hide").not("option").click(function() {
			try {
				if ($(this).attr("name"))
					$("."+$(this).attr("name")).hide();
			} catch (e) {
			}
			try {
				if ($(this).attr("rel"))
					$("."+$(this).attr("rel")).hide();
			} catch (e) {
			}
		});
		$("select").change(function() {
			var elem = $(this).find("option:selected");
			if (elem.hasClass("precise_hide")) {
				if (elem.attr("name"))
					$("."+elem.attr("name")).hide();
				if (elem.attr("rel")) {
					$("."+elem.attr("rel")).hide();
					parentElt = $("."+elem.attr("rel")).parent();
					if (parentElt.hasClass("me_contacter")) {
						differentOptions = parentElt.find("option:visible");
						if (differentOptions.length > 0)
							parentElt.find("option:visible").get(0).selected = "selected";
					}
				}
			}
		});
	}
	function _initToggle() {
		$(".precise_toggle").click(function() {
			manageShowOptionalFields.toggleBehavior($(this));
		});
	}

	function _toggleBehavior(elem) {
		try {
			var elemsName	= elem.attr("name") ? $("."+elem.attr("name")) : null;
			if (elemsName)	elemsName.each(function() {$(this).is(':visible') ? $(this).hide() : $(this).show();});
		} catch (e) {
		}
		try {
			var elemsRel	= elem.attr("rel") ? $("."+elem.attr("rel")) : null;
			if (elemsRel)	elemsRel.each(function() {$(this).css("display" ) != "none" ? $(this).hide() : $(this).show();});
		} catch (e) {
		}
	}
	function _initSelected() {
		$(".precise_show:checked,.precise_show:selected,.precise_toggle:checked").each(function (){
			try {
				if ($(this).attr("name"))
					$("."+$(this).attr("name")).show();
			} catch (e) {
			}
			try {
				if ($(this).attr("rel"))
					$("."+$(this).attr("rel")).show();
			} catch (e) {
			}
		});
		if ($.browser.msie){$("select.tofix").selecteSizer();}
	}
	return {init:_init,initShow:_initShow,initHide:_initHide,initToggle:_initToggle,toggleBehavior:_toggleBehavior,initSelected:_initSelected};
}();


/*
 * Gestion des comportements caché/visible spécifiques
 */
var optionalFieldsSpecificBehaviour = function () {
	function _init() {
		_manageConfidentiality();
		_manageFieldPseudo();
		_manageFieldPseudoHide();
		_manageSectorTitles();
		_manageToggleArrows();
		_manageAutoSubmit();
	}
		// Déselection de la valeur du choix du mode de contact
	function _manageConfidentiality() {
		$("#confidentiality .precise_hide").change(function() {
			$("."+$(this).attr("rel")).parent().val('');
		});
	}

		// Affichage ou non du champs Pseudo
	function _manageFieldPseudo() {
		$("select[name^='USER_COMMUNITY_visibility']").change(function () {
			if ($(this).val() == 1) {
				$("#USER_nickname").show();
			} else {
				optionalFieldsSpecificBehaviour.manageFieldPseudoHide();
			}
		});
	}
	function _manageFieldPseudoHide() {
		var showPseudo = false;
		var list = $("select[name^='USER_COMMUNITY_visibility']").each(function () {
			if ($(this).val() == 1) {
				showPseudo = true;
			}
		});
		if (showPseudo==false) {
			$("#USER_nickname").hide();
			$("#USER_nickname").val('');
		}
	}

		// Permet d'éviter de lancer 2 fois l'évènement si clique sur le label avec IE
	function _manageSectorTitles() {
		if ($.browser.msie || $.browser.safari) {
			$(".techno_sectors label.title,.tradi_sectors label.title").click(function() {
				return false;
			});
		}
	}

		// Gestion des flêches sur les toggle
	function _manageToggleArrows() {
		$(".precise_toggle").click(function (){
			$(".ui-icon", this).toggleClass("ui-icon-triangle-1-s").toggleClass("ui-icon-triangle-1-e");
		});
	}

		// Gestion des autoSubmit
	function _manageAutoSubmit() {
		$("select.form_auto_submit").change(function (){
			$(this).parents("form").submit();
		});
		$(".form_auto_submit_click").click(function (){
			if (javascript_ltie7.ltie7) {
				$("button[type='submit']", $(this).parents("form")).remove();
			}
			$(this).parents("form").submit();
		});
	}

	return {
			init:_init,
			manageConfidentiality:_manageConfidentiality,
			manageFieldPseudo:_manageFieldPseudo,
			manageFieldPseudoHide:_manageFieldPseudoHide,
			manageToggleArrows:_manageToggleArrows,
			manageSectorTitles:_manageSectorTitles,
			manageAutoSubmit:_manageAutoSubmit
	};
}();


var manageTableHisto = function () {
	function _init() {
		this.initDelete();
		this.initAdd();
	}
	function _initDelete() {
		$("#table_histo input[name^='delHisto']").click(function() {
			if ($(this).parents("tr").siblings().length > 2) {
				$(this).parents("tr").remove();
			} else {
				$(this).parents("tr").find("input").val('');
				$(this).parents("tr").find("select").val('');
			}
			if ($.browser.msie){$("select.tofix").selecteSizer();}
			return false;
		});
	}
	function _initAdd() {
		$("#table_histo input[name='addHisto']").click(function() {
				// Ajout de la nouvelle ligne
			var elemTr = $(this).parents("tr").prev("tr");
			elemTr.after('<tr>'+elemTr.html()+'</tr>');
			elemTr.next("tr").find("input").val('');
			elemTr.next("tr").find("select").val('');
				// rechargement de la gestion des delete
			manageTableHisto.initDelete();
			if ($.browser.msie){$("select.tofix").selecteSizer();}
			return false;
		});
	}
	return {init:_init,initDelete:_initDelete,initAdd:_initAdd};
}();

	/**
	Gestion affichage secteurs
	*/


var manageTechnoSectors = function() {
	function _init() {
		$("ul.sectorList li input:not(:checked)").siblings("ul").hide();
		$("ul.sectorList li input:checked").siblings(".sector_precise").show();

		$("ul.sectorList li input").click(function() {
			if($(this).is(':checked')) {
				$(this).siblings("ul").show();
			} else {
				$(this).siblings("ul").hide();
			}
		});
//		$("#TECHNO_sectors_id").click(function() {
//			if ($(this).is(":not(:checked)")) {
//				$(".sectorList input").attr('checked', '');
//			}
//		});
	}
	return {init:_init};
}();


var manageTradiSectors = function() {
	function _init() {
		this.updateTradiSectors();
	}
	// TODO : dé-dupliquer le code
	function _updateTradiSectors() {
		$("select[name='TraditionalSector[1][1]']").change(function() {
			var parent = $(this).parents("div.TRADI_sectors");
			parent.load("/"+parent.attr("rel")+"/gettradisectors/format/html/priority/1/TRADI_id_1/"+$(this).val(), null, function() {
				manageTradiSectors.init();
			});
		});
		$("select[name='TraditionalSector[1][2]']").change(function() {
			var tradi_1 = $("select[name='TraditionalSector[1][1]']").val();
			var parent = $(this).parents("div.TRADI_sectors");
			parent.load("/"+parent.attr("rel")+"/gettradisectors/format/html/priority/1/TRADI_id_1/"+tradi_1+"/TRADI_id_2/"+$(this).val(), null, function() {
				manageTradiSectors.init();
			});
		});
		$("select[name='TraditionalSector[2][1]']").change(function() {
			var parent = $(this).parents("div.TRADI_sectors");
			parent.load("/"+parent.attr("rel")+"/gettradisectors/format/html/priority/2/TRADI_id_1/"+$(this).val(), null, function() {
				manageTradiSectors.init();
			});
		});
		$("select[name='TraditionalSector[2][2]']").change(function() {
			var tradi_1 = $("select[name='TraditionalSector[2][1]']").val();
			var parent = $(this).parents("div.TRADI_sectors");
			parent.load("/"+parent.attr("rel")+"/gettradisectors/format/html/priority/2/TRADI_id_1/"+tradi_1+"/TRADI_id_2/"+$(this).val(), null, function() {
				manageTradiSectors.init();
			});
		});
	}
	return {init:_init, updateTradiSectors:_updateTradiSectors};
}();

var autoCompleteTechnoSector= function() {
	function _init() {
		$("li.sector_precise > input").each(function(){
			$(this).autocomplete("/company/getdynamictechnosectors/format/html/idinput/"+$(this).attr('id'),{
				minChars : 1,
				delay : 400
			});
		});
	}
	return {init:_init};
}();

	/**
	Gestion confidentialité
	*/


var managementUserCommunity = function() {

	var buttonData = "";

	function _init() {
		$("button.unsubscribeUserCommunity").click(function () {
			buttonData = $(this).attr("rel");
			$("#ui-dialog-title-dialogUnsubscribeUserCommunity").html($(".popupTitle", $(this)).length>0 ? $(".popupTitle", $(this)).html() : "Désabonnement de la communauté");
			$("#dialogUnsubscribeUserCommunity").html($(".popupTexte", $(this)).length>0 ? $(".popupTexte", $(this)).html() : "Voulez-vous vraiment vous désinscrire de la communauté");
			$("#dialogUnsubscribeUserCommunity").dialog('open');
			return false;
		});
		$("button.activateUserCommunity").click(function () {
			$.post("/user/unsubscribecommunity/format/json", {data:$(this).attr("rel")}, function(data){
				if (data["mess"]) {
					$("#dialogUnsubscribeUserCommunity").html(data["mess"]).dialog('open');
					var tmpStr = "li_community_"+data["id"];
					var obj = document.getElementById(tmpStr);
					managementUserCommunity.updatedivconfidentialite();
				}
				if (data["errors"]) {
					var str = "";
					for (i=0 ; i<data["errors"].length ; i++) {
						str = data["errors"][i]+"<br />";
					}
					$("#dialogUnsubscribeUserCommunity").html(str).dialog('open');
				}
			}, "json");
			return false;
		});
		if ($("button.unsubscribeUserCommunity").size()>0) managementUserCommunity.initDialog();
	}

	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogUnsubscribeUserCommunity").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: true,
			height:150,
			width:300,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			buttons: {
				"Oui": function() {managementUserCommunity.unsubscribeCommunity(); $("#dialogUnsubscribeUserCommunity").dialog('close');},
				"Non": function() {$("#dialogUnsubscribeUserCommunity").dialog('close');}
			}
		});
	}

	function _unsubscribeCommunity() {
		$.post("/user/unsubscribecommunity/format/json", {data:buttonData}, function(data){
			if (data["mess"]) {
				$("#dialogNotification").html(data["mess"]).dialog('open');
				var tmpStr = "li_community_"+data["id"];
				var obj = document.getElementById(tmpStr);
				managementUserCommunity.updatedivconfidentialite();
			}
			if (data["errors"]) {
				var str = "";
				for (i=0 ; i<data["errors"].length ; i++) {
					str = data["errors"][i]+"<br />";
				}
				$("#dialogNotification").html(str).dialog('open');
			}
		}, "json");
	}

	function _updatedivconfidentialite() {
		$("#confidentialite").load("/user/displayprivacy/format/html", null, _resetJsUsed);
	}

	function _resetJsUsed() {
		managementUserCommunity.init();
		manageShowOptionalFields.init();
		optionalFieldsSpecificBehaviour.init();
	}

	return {init:_init,initDialog:_initDialog,unsubscribeCommunity:_unsubscribeCommunity,updatedivconfidentialite:_updatedivconfidentialite,resetJsUsed:_resetJsUsed};
}();


var managementCompanyCommunity = function() {

	var buttonData = "";

	function _init() {
		$("button.unsubscribeCompanyCommunity").click(function () {
			buttonData = $(this).attr("rel");
			$("#ui-dialog-title-dialogUnsubscribeCompanyCommunity").html($(".popupTitle", $(this)).length>0 ? $(".popupTitle", $(this)).html() : "Désabonnement de la communauté");
			$("#dialogUnsubscribeCompanyCommunity").html($(".popupTexte", $(this)).length>0 ? $(".popupTexte", $(this)).html() : "Voulez-vous vraiment vous désinscrire de la communauté");
			$("#dialogUnsubscribeCompanyCommunity").dialog('open');
			return false;
		});
		$("button.activateCompanyCommunity").click(function () {
			$.post("/company/unsubscribecommunity/format/json", {data:$(this).attr("rel")}, function(data){
				if (data["mess"]) {
					$("#dialogUnsubscribeCompanyCommunity").html(data["mess"]).dialog('open');
					var tmpStr = "li_community_"+data["id"];
					var obj = document.getElementById(tmpStr);
					managementCompanyCommunity.updatedivconfidentialite();
				}
				if (data["errors"]) {
					var str = "";
					for (i=0 ; i<data["errors"].length ; i++) {
						str = data["errors"][i]+"<br />";
					}
					$("#dialogUnsubscribeCompanyCommunity").html(str).dialog('open');
				}
			}, "json");
			return false;
		});
		if ($("button.unsubscribeCompanyCommunity").size()>0) managementCompanyCommunity.initDialog();
	}
	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		$("#dialogUnsubscribeCompanyCommunity").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: true,
			height:150,
			width:300,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			buttons: {
				"Oui": function() {managementCompanyCommunity.unsubscribeCommunity(); $("#dialogUnsubscribeCompanyCommunity").dialog('close');},
				"Non": function() {$("#dialogUnsubscribeCompanyCommunity").dialog('close');}
			}
		});
	}
	function _unsubscribeCommunity() {
		$.post("/company/unsubscribecommunity/format/json", {data:buttonData}, function(data){
			if (data["mess"]) {
				$("#dialogNotification").html(data["mess"]).dialog('open');
				managementCompanyCommunity.updatedivconfidentialite();
			}
			if (data["errors"]) {
				var str = "";
				for (i=0 ; i<data["errors"].length ; i++) {
					str = data["errors"][i]+"<br />";
				}
				$("#dialogNotification").html(str).dialog('open');
			}
		}, "json");
	}

	function _updatedivconfidentialite() {
		$("#confidentialite").load("/company/displayprivacy/format/html", null, managementCompanyCommunity.resetjsused());
	}

	function _resetjsused() {
		managementCompanyCommunity.init();
		manageShowOptionalFields.init();
		optionalFieldsSpecificBehaviour.init();
	}

	return {init:_init,initDialog:_initDialog,unsubscribeCommunity:_unsubscribeCommunity,updatedivconfidentialite:_updatedivconfidentialite,resetjsused:_resetjsused};
}();


var temoignages = function() {
//	var message="";
	function _init() {

		$('.voir_temoignage').click(function() {
			$(this).siblings(".temoignage").show();
			$(this).siblings(".cacher_temoignage").show();
			$(this).hide();
			return false;
		});
		$('.cacher_temoignage').click(function() {
			$(this).siblings(".temoignage").hide();
			$(this).siblings(".voir_temoignage").show();
			$(this).hide();
			return false;
		});

	}

	return {init:_init};
}();

var subscribeAccordion = function() {
	function _init() {
		jQuery("#accordionSubscribe").accordion({header: "h2", active: false, collapsible : true, autoHeight: false});
		if ($('#accordionSubscribe')) {
			$('#accordionSubscribe').show("slow");
		}
	}
	return {init:_init};
}();

var messageCheckForm = function() {
	function _init() {
		if ($("#messageCheckForm").size()>0) {
			messageCheckForm.initDialog($("#messageCheckForm").attr('rel'));
			if ($("#welcometothenewwebsite").size() < 1)
				$("#messageCheckForm").dialog('open');
		}
	}
	function _initDialog(formid) {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		var form=$("#formProfil").get()[0];
		$("#messageCheckForm").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: true,
			height:200,
			width:350,
			open : function() {if (ltie7) $('select').css('visibility','hidden');},
			close : function() {if (ltie7) $('select').css('visibility','visible');},
			modal: true,
			buttons: {
				"Ok": function() {
					$("#messageCheckForm").dialog('close');
					if ($("#"+formid).size()>0) {
						$("#"+formid).submit();
					}
				}
			}
		});
	}
	return {init:_init,initDialog:_initDialog};
}();


var addAdvisor = function() {
	function _init() {
		$("button.addFollowBy").click(function () {
			$.post("/company/addadvisor/format/json", {data:$(this).attr("rel")}, function(data){
				if (data["mess"]) {
					$("#dialogNotification").html(data["mess"]).dialog('open');
				}
				if (data["errors"]) {
					var str = "";
					for (i=0 ; i<data["errors"].length ; i++) {
						str = data["errors"][i]+"<br />";
					}
					$("#dialogNotification").html(str).dialog('open');
				}
			}, "json");
		});
		if ($("button.addFollowBy").size()>0) addAdvisor.initDialog();
	}
	function _initDialog() {
		$("#dialogNotification").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:100,
			width:350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});
	}
	return {init:_init,initDialog:_initDialog};
}();


var userDelete = function() {
	function _init() {
		$(".userDelete").click(function() {
				$.post("/user/delete/format/json", {data:$(this).attr("rel")}, function delete_java(data){
					$("#dialogNotification").html(data).dialog('open');
					//alert(data);
				}, "json");
		});
	}
	return {init:_init};
}();



var advisorCreate = function() {
	function _init() {
		$("input[id^='development_state_16_']").click(function() {
			if ($(this).attr("checked")) {
				$("input[id^='development_state_16_']").attr("checked", true);
			} else {
				$("input[id^='development_state_16_']").attr("checked", false);
			}
		});
	}
	return {init:_init};
}();


var delCountryException = function (){
	function _init() {
		$(".Country_name_del_cross").click(function() {
			$("#Country_id_"+$(this).attr("rel")).remove();
		});
	}
	return {init:_init};
}();


var addCountryException = function (){
	function _init() {
		$("#ADD_country_exep_id").click(function() {
			$("#Country_id_"+$('#Country_id').val()).remove();
			$("#List_exeption_list").append("<div class='ui-state-default ui-corner-all country_add_box_element' id='Country_id_"+$('#Country_id').val()+"'><span class='Country_name_del'>"+$('#Country_id :selected').text()+"</span><span class='ui-icon ui-icon ui-icon-circle-close Country_name_del_cross' rel='"+$('#Country_id').val()+"'></span><input type='hidden' name='Country_exception_tab[]' value='"+$('#Country_id').val()+"' id='Country_exep_"+$('#Country_id').val()+"'/></div>");
				delCountryException.init();
		});
	}
	return {init:_init};
}();




var changeZone = function (){
	function _init() {
		$(".ZONE_choice").click(function() {
			var zone = $(this).val();
			$.post("/country/getcountrybyzone/format/json", {data:zone}, function test(data_back){
				var taille = data_back["ids"].length;

				if( zone == 1){
					$("#COMP_localisation_partnership").hide();
					$("#List_exeption_list").empty();
				}else{
					$("#COMP_localisation_partnership").show();
					$("#Country_id").empty();
					$("#List_exeption_list").empty();
					for(var i=0; i<taille ;i++){
						$("#Country_id").append("<option value='"+data_back["ids"][i]+"'>"+data_back["values"][i]+"</option>");
					}
				}
			}, "json");
		});
	}
	return {init:_init};
}();




/**
 * Système d'auto-validation des formulaires sur le changement d'onglets (fiche société)
 */
var naviCompany = function() {

	function _init() {
		$(".user-edit .fiche_onglet a, .company-edit .fiche_onglet a, .company-funds .fiche_onglet a, .company-techno .fiche_onglet a").click(function() {
			var form = $("form.navi_autosubmit");
			if (form) {
				form.append("<input type='hidden' name='redirect' value='"+$(this).attr("href")+"' />");
				form.submit();
				return false;
			}
		});
	}

	return {init:_init};
}();


/**
 * Gestion en JS des ancres sur la fiche société pour ne pas encombrer l'historique du navigateur et pouvoir faire back sans passer par toutes les ancres
 */
var naviCompanyView = function() {

	// Fonctionnement avec les ancres
//	function _init() {
//		$(".company-view .fiche_onglet a").click(function() {
//			var elem = document.getElementById($(this).attr("href").substr(1));
//			elem.scrollIntoView(true);
//			return false;
//		});
//	}

	// Fonctionnement en cachant les 2 autres blocs
	function _init() {
		$(".company-view .fiche_onglet .onglet_bg a, .company-preview .fiche_onglet .onglet_bg a").click(function() {
			naviCompanyView.showBloc($(this).attr("href"));
			return false;
		});
	}

	function _showBloc(elementId) {
		$(".company-view .fiche_onglet, .company-preview .fiche_onglet").filter(function() {
			var aMatches = $(elementId, this);
			aMatches.each(function() {
				$(this).parent(".fiche_onglet").show();
			});
			if (aMatches.length > 0)
				return false;
			return true;
		}).hide();
	}

	return {init:_init, showBloc:_showBloc};
}();






;

var manageInvitation = function() {
	var buttonClicked, optionalMessage;

	function _init() {

		$("button.inviteEntity").click(function () {
			manageInvitation.buttonClicked = $(this);
			// Maj de la liste (les intitulés peuvent changer)
			var i, vals=[];
			var tab = $(this).attr("rel").split("[");
			for(i=1;i<tab.length; i+=2){
				vals[((i-1)/2)] = tab[(i+1)].replace("]","");
			}
			$("#tooltipInvitationDialog").html(
				"<p>Inviter en tant que " + $("#ProfilListe_"+vals[2]).html() + "</p>" +
				"<p style='margin-bottom: 0;'>Message optionel à ajouter au courriel" +
				"<textarea cols='45' rows='3' id='invitationPersonalisation'></textarea></p>"
			);
			$("#tooltipInvitationDialog").dialog("open");
		});
		
		if ($("button.inviteEntity").size() > 0) {
			manageInvitation.initDialogs();
		}
	}

	function _getMessage() {
		return $("#invitationPersonalisation").val();
	}

	function _getSelectedStatus() {
		return $("#tooltipInvitationDialog select option:selected").val();
	}

	function _initDialogs() {
//		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
		
		$("#conteneur_footer").after('<div class="jqueryUiDialog" id="tooltipInvitationDialog"></div>');
		$("#conteneur_footer").after('<div class="jqueryUiDialog" id="tooltipInvitationSendMessage"></div>');

		$("#tooltipInvitationDialog").attr("title", "Inviter cet utilisateur sur la communauté?");
		$("#tooltipInvitationDialog").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height: 196,
			width: 300,
			modal: true,
			buttons: {
				"Oui": function() {
					var i, vars=[], vals=[];
					var tab = manageInvitation.buttonClicked.attr("rel").split("[");
					for(i=1;i<tab.length; i+=2){
						vars[((i-1)/2)] = tab[i].replace("]","");
						vals[((i-1)/2)] = tab[(i+1)].replace("]","");
					}
					$.post("/community/invitefrommoderator/id/"+vals[2]+"/format/json", {userId:vals[1], entityId:vals[0], entityType:vars[0], communityId:vals[2], invitedProfil:manageInvitation.getSelectedStatus(), optionalMessage:manageInvitation.getMessage()}, function(data){
						if (data["message"]) {
							$dialog = $("#tooltipInvitationSendMessage");
							$dialog.html(data["message"]).dialog('open');
						}
						if (data["error"]) {
							$dialog = $("#dialogNotification");
							$("#ui-dialog-title-dialogNotification").html("Invitation");
							$dialog.html(data["error"]).dialog('open');
						}
					}, "json");
					$("#tooltipInvitationDialog").dialog('close');
				},
				"Non": function() {$("#tooltipInvitationDialog").dialog('close');}
			}
		});

		$("#tooltipInvitationSendMessage").attr("title", "Envoyer un message");
		$("#tooltipInvitationSendMessage").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:150,
			width:300,
			modal: true,
			buttons: {
				"Oui": function() {
					var i, vars=[], vals=[];
					var tab = manageInvitation.buttonClicked.attr("rel").split("[");
					for(i=1;i<tab.length; i+=2){
						vars[((i-1)/2)] = tab[i].replace("]","");
						vals[((i-1)/2)] = tab[(i+1)].replace("]","");
					}
					window.location.replace("/message/create/to/"+vals[1]);
					$("#tooltipInvitationSendMessage").dialog('close');
				},
				"Non": function() {$("#tooltipInvitationSendMessage").dialog('close');}
			}
		});

	}
	
	return {init:_init, initDialogs:_initDialogs, getMessage:_getMessage, getSelectedStatus:_getSelectedStatus};
}();

;var userProfilPhoto = function(){
	function _init(){
		$('#USER_picture_id input[type=file]').change(function(){
			var form=$("#formProfil").get()[0];
			form.target="formulaire_upload";
			form.action="/file/upload/type/UserProfil";
//			$("#form_valid_button_id").val('Téléchargement en cours...');
			//$("#form_valid_button_id .texte").html('Téléchargement en cours...');
			$(this).after("<img id='upload_loader' src='/_media/img/ajax_loader.gif' />");
			form.submit();
		});
		if ($('#USER_picture_id input[type=file]').size()>0) {
			this.initDelete();
			this.initDialog();
		}
	}
	function _initDialog() {
				$("#dialogDeletePhotoProfil").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: false,
					height:200,
					width:350,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open: function() {
						$('select').css('visibility','hidden');
					},
					close : function() {
						$('select').css('visibility','visible');
					},
					buttons: {
						'Supprimer': function() {
							$(this).dialog('close');
//							$.getJSON("/file/delete/format/json/id/"+$("#USER_picture_id .preview>img").attr('rel'));
							$.getJSON("/file/delete/format/json/id/"+$("#USER_picture_id .preview img.document").attr('rel'));
							$("#USER_picture_id .preview").empty();
							$("#USER_picture_id .delete").hide();
						},
						'Annuler': function() {
							$(this).dialog('close');
						}
					}
				});
	}
	function _initDelete() {
		$("#USER_picture_id .delete").click(function(){
			$("#dialogDeletePhotoProfil").dialog('open');
			return false;
		});
	}
	return {init:_init,initDelete:_initDelete,initDialog:_initDialog};
}();

var structureLogo = function(){
	function _init(){
		$('#STRUCT_picture_id input[type=file]').change(function(){
			var form=$("#entityForm").get()[0];
			form.target="formulaire_upload";
			form.action="/file/upload/type/StructureLogo";
//			$("#form_valid_button_id").val('Téléchargement en cours...');
			//$("#form_valid_button_id .texte").html('Téléchargement en cours...');
			$(this).after("<img id='upload_loader' src='/_media/img/ajax_loader.gif' />");
			form.submit();
		});
		if ($('#STRUCT_picture_id input[type=file]').size()>0) {
			this.initDelete();
			this.initDialog();
		}
	}
	function _initDialog() {
				$("#dialogDeleteLogoStructure").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: false,
					height:200,
					width:350,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open: function() {
						$('select').css('visibility','hidden');
					},
					close : function() {
						$('select').css('visibility','visible');
					},
					buttons: {
						'Supprimer': function() {
							$(this).dialog('close');
							$.getJSON("/file/delete/format/json/id/"+$("#STRUCT_picture_id .preview img").attr('rel'));
							$("#STRUCT_picture_id .preview").empty();
							$("#STRUCT_picture_id .delete").hide();
						},
						'Annuler': function() {
							$(this).dialog('close');
						}
					}
				});
	}
	function _initDelete() {
		$("#STRUCT_picture_id .delete").click(function(){
			$("#dialogDeleteLogoStructure").dialog('open');
			return false;
		});
	}
	return {init:_init,initDelete:_initDelete,initDialog:_initDialog};
}();

var structureVideo = function(){
	var todelete="";
	function _init(){
		$('#STRUCT_video_id input[type=file]').change(function(){
			var form=$("#entityForm").get()[0];
			form.target="formulaire_upload";
			form.action="/file/upload/type/StructureVideo";
//			$("#form_valid_button_id").val('Téléchargement en cours...');
			//$("#form_valid_button_id .texte").html('Téléchargement en cours...');
			$(this).after("<div id='upload_loader'><img src='/_media/img/ajax_loader.gif' /><br />Le téléchargement de vidéos peut prendre plusieurs minutes.</div>");
			form.submit();
		});
		if ($('#STRUCT_video_id input[type=file]').size()>0) this.initDialog();
	}
	function _initDialog() {
				$("#dialogDeleteVideoStructure").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: false,
					height:200,
					width:350,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open: function() {
						$('select').css('visibility','hidden');
					},
					close : function() {
						$('select').css('visibility','visible');
					},
					buttons: {
						'Supprimer': function() {
							$(this).dialog('close');
							$.getJSON("/file/delete/format/json/id/"+structureVideo.todelete);
							$("#STRUCT_video_id .preview").empty();
						},
						'Annuler': function() {
							$(this).dialog('close');
						}
					}
				});
	}
	function _delete(hash) {
		this.todelete=hash;
		$("#dialogDeleteVideoStructure").dialog('open');
		return false;
	}
	return {init:_init,vdelete:_delete,initDialog:_initDialog};
}();

var structureDoc = function(){
	var todelete="";
	function _init(){
		$('#STRUCT_documents_id input[type=file]').change(function(){
			var form=$("#entityForm").get()[0];
			form.target="formulaire_upload";
			form.action="/file/upload/type/StructureDocs";
//			$("#form_valid_button_id").val('Téléchargement en cours...');
			//$("#form_valid_button_id .texte").html('Téléchargement en cours...');
			$(this).after("<img id='upload_loader' src='/_media/img/ajax_loader.gif' />");
			form.submit();
		});
		if ($('#STRUCT_documents_id input[type=file]').size()>0) this.initDialog();
	}
	function _initDialog() {
				$("#dialogDeleteDocsStructure").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: false,
					height:200,
					width:350,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open: function() {
						$('select').css('visibility','hidden');
					},
					close : function() {
						$('select').css('visibility','visible');
					},
					buttons: {
						'Supprimer': function() {
							$(this).dialog('close');
							$.getJSON("/file/delete/format/json/id/"+structureDoc.todelete);
							$("#STRUCT_documents_id .preview #doc_"+structureDoc.todelete).remove();
						},
						'Annuler': function() {
							$(this).dialog('close');
						}
					}
				});
	}
	function _delete(hash) {
		this.todelete=hash;
		$("#dialogDeleteDocsStructure").dialog('open');
		return false;
	}
	return {init:_init,vdelete:_delete,initDialog:_initDialog};
}();


var blocDocumentFile = function(){
	function _init(){
		$('#DOCUMENT_file_id input[type=file]').change(function(){
			var form=$("#documentForm").get()[0];
			var id=$("#documentId").get()[0].value;
			form.target="formulaire_upload";
			form.action="/file/upload/type/Document/id/"+id;
//			$("#form_valid_button_id").val('Téléchargement en cours...');
			//$("#form_valid_button_id .texte").html('Téléchargement en cours...');
			$(this).after("<img id='upload_loader' src='/_media/img/ajax_loader.gif' />");
			form.submit();
		});
		if ($('#DOCUMENT_file_id input[type=file]').size()>0) {
			this.initDelete();
			this.initDialog();
		}
	}
	function _initDialog() {
				$("#dialogDeleteDocumentFile").dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: false,
					height:200,
					width:350,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open: function() {
						$('select').css('visibility','hidden');
					},
					close : function() {
						$('select').css('visibility','visible');
					},
					buttons: {
						'Supprimer': function() {
							$(this).dialog('close');
//							$.getJSON("/file/delete/format/json/id/"+$("#USER_picture_id .preview>img").attr('rel'));
							$.getJSON("/file/delete/format/json/id/"+$("#DOCUMENT_file_id .preview div.document").attr('rel'));
							$("#DOCUMENT_file_id .preview").empty();
							$("#DOCUMENT_file_id .delete").hide();
						},
						'Annuler': function() {
							$(this).dialog('close');
						}
					}
				});
	}
	function _initDelete() {
		$("#DOCUMENT_file_id .delete").click(function(){
			$("#dialogDeleteDocumentFile").dialog('open');
			return false;
		});
	}
	return {init:_init,initDelete:_initDelete,initDialog:_initDialog};
}();

var communityLogoActions = function(){
	function _init(){
		$('#COMMUNITY_LOGO_24x24_fid input[type=file], #COMMUNITY_LOGO_50x50_fid input[type=file],#COMMUNITY_LOGO_70x70_fid input[type=file],#COMMUNITY_LOGO_100x100_fid input[type=file],#COMMUNITY_Convention_fid input[type=file]').change(function(){
			var form=$("#communityimages").get()[0];
			form.target="formulaire_upload";
			form.action="/file/upload/type/"+$(this).attr('name');
			$(this).after("<img id='upload_loader' src='/_media/img/ajax_loader.gif' class='clear'/>");
			form.submit();
		});
	}
	return {init:_init};
}();;
var search = function() {

	function _checkSiblings(rootElem, bCheck) {
		rootElem.siblings("ul").find("li input").attr("checked", bCheck ? "checked" : "");
	}

	function _checkParents(rootElem, bCheck) {
		rootElem.parents("li").find("input:first").attr("checked", bCheck ? "checked" : "");

	}

	function _init(){
			// Gestion des cases à cocher pour les régions


//			if($("input#SEARCH_geo_all_id").attr("checked")){
//				$("#region_div_id").hide();
//				$("#region_div_id :checkbox").attr("checked","");
//			}else{
//				$("#region_div_id").show();
//				$("#region_div_id :checkbox").attr("checked","");
//			}


			if($("input#SEARCH_geo_all_id").attr("checked")){
				$("#region_div_id").hide();
			}else{
				$("#region_div_id").show();
			}


		$(".SEARCH_geo input").click(

			function() {
				var isCheck = $(this).attr("checked");
				search.checkSiblings($(this), isCheck);
				if (!isCheck)
					search.checkParents($(this).parents("ul:first"), false);

			}
		);
		$("input#SEARCH_geo_all_id").click(
			function() {

				var isCheck = $(this).attr("checked");
				search.checkSiblings($(this).parent(), isCheck);
				if (!isCheck){
					search.checkParents($(this).parent().parents("ul:first"), false);
				}

					if (!isCheck){
						$("#region_div_id").show();
						$("#region_div_id :checkbox").attr("checked","");

					}else{
						$("#region_div_id").hide();
						$("#region_div_id :checkbox").attr("checked","");

					}

			}



		);
		$(".SEARCH_geo ul ul input").click(
			function() {
				if ($(this).attr("checked")) {
					$(this).siblings("ul:first").show();
				} else {
					$(this).siblings("ul:first").hide();
				}
			}
		);
			// Comportements particuliers pour IE et Safari
		if ($.browser.msie || $.browser.safari) {
			$("div.header.precise_toggle label.title").click(function () {
				$(this).parent("div.header").click();
				return false;
			});
			$("#secteur_activite .search_block div.precise_toggle label.title").click(function (){
				$(this).parent("div:first").click();
				return false;
			});
		}

			// Gestion de l'affichage des blocs un seul bloc actif en meme temps sur certaines pages
		$("form.search_active .header.precise_toggle").click(function (){
			$(".header.precise_toggle").not(this).each(function() {
				var arrowDown = $("span.ui-icon-triangle-1-s", this);
				if (arrowDown.length > 0) {
					arrowDown.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
					manageShowOptionalFields.toggleBehavior($(this));
				}
			});
			return false;
		});




		// Gestion de l'encart pour filtre communautés dans les resultats de la recherche
		// l'affichage est géré par une autre fonction, d'où l'emploi de la fonction 'one'.
		$(".precise_toggle.in_search_result").one('click',function() {
			var elemsName	= $(this).attr("name") ? $("."+$(this).attr("name")) : null;
			var elemsRel	= $(this).attr("rel") ? $("."+$(this).attr("rel")) : null;
			var elmt = elemsName ? elemsName : elemsRel;

			var conteneur = $(this).parent("th:first");
			var positionConteneur = conteneur.offset();
			var positionElmt = elmt.offset();
//			if (javascript_ltie7.ltie7)
				elmtTop = parseInt(positionConteneur.top - positionElmt.top + conteneur.height() + 50)+"px";
//			else
//				elmtTop = parseInt(positionConteneur.top - positionElmt.top + conteneur.height())+"px";
			elmtLeft = parseInt(positionConteneur.left - positionElmt.left)+"px";
			elmt.css("top", elmtTop);
			elmt.css("left", elmtLeft);
		});


		// Gestion de la popin de preload recherche

		$("#dialogSearchInProgress").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			closeOnEscape: false,
			height:100,
			width:300,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
		});





		$("input.rechercher, button.rechercher").click(function () {

			var tmpform = $(this).parent("form:first");

			$("#dialogSearchInProgress").dialog('open');
			if ($.browser.msie) {
				$("#progressBar").remove();
				$("#progressMessage").append('<div id="progressBar"><img class="progressBarImg" src="/_media/img/ajax_loader.gif" /></div>');
			}
			$(".ui-dialog-titlebar-close").remove();
			tmpform.submit();
		});

		$("a.rechercher_prec").click(function () {
			$("#dialogSearchInProgress").dialog('open');
			if ($.browser.msie) {
				$("#progressBar").remove();
				$("#progressMessage").append('<div id="progressBar"><img class="progressBarImg" src="/_media/img/ajax_loader.gif" /></div>');
			}
			$(".ui-dialog-titlebar-close").remove();
		});

		$("a.rechercher_suiv").click(function () {
			$("#dialogSearchInProgress").dialog('open');
			if ($.browser.msie) {
				$("#progressBar").remove();
				$("#progressMessage").append('<div id="progressBar"><img class="progressBarImg" src="/_media/img/ajax_loader.gif" /></div>');
			}
			$(".ui-dialog-titlebar-close").remove();
		});

		manageFilterBlocks();
	}


	function manageFilterBlocks() {
		// Gestion bloc sur moteur company
		$(".search_category_title input.precise_toggle").click(function() {
			if ($(this).is(":checked")) {
				$(this).parent(".search_category_title").addClass("active");
				$(this).parent().siblings(".search_category_details").show();
			} else {
				$(this).parent(".search_category_title").removeClass("active");
				$(this).parent().siblings(".search_category_details").hide();
			}

			$(".search_active .search_category_title input.precise_toggle, .search_active .search_category_title[rel='company_bloc_identity'] .title").not($(this)).each(function() {
				if ($(this).parent().siblings(".search_category_details").is(":visible")) {
					$(this).parent().siblings(".search_category_details").hide();
					var arrow = $("span.ui-icon", $(this).parent());
					if (arrow.hasClass("ui-icon-triangle-1-s") > 0) {
						arrow.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
					} else {
						arrow.removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
					}
				}
			});
			return true;
		});
		$(".search_active .search_category_title[rel='company_bloc_identity']").click(function() {
			$(".SEARCH_funds, .SEARCH_partner").hide();
			return true;
		});
	}

	return {init:_init, checkSiblings:_checkSiblings, checkParents:_checkParents};
}();

var savedSearch = function(){
	var todelete="";
	function _init(){
		$("#notification_savedsearch p.select button").click(function(){
			savedSearch.vdelete($(this));
		});
		if ($("#notification_savedsearch p.select button").size()>0) this.initDialog();
	}
	function _initDialog() {
		$("#dialogDeleteAlerte").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:200,
			width:350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Supprimer': function() {
					$(this).dialog('close');
					$.post("/savedsearch/delete/id/"+savedSearch.todelete.attr('rel'));
					savedSearch.todelete.parents("p.select:first").remove();
				},
				'Annuler': function() {
					$(this).dialog('close');
				}
			}
		});
	}
	function _delete(obj) {
		this.todelete=obj;
		$("#dialogDeleteAlerte").dialog('open');
		return false;
	}
	return {init:_init,vdelete:_delete,initDialog:_initDialog};
}();

var coinsArrondisIE = function() {
	function init(){
		if (!$.browser.msie) return;

		$('.bloc').hover(function(){
			$(this).toggleClass('bloc_hover');
		}, function(){
			$(this).toggleClass('bloc_hover');
		});
	}
	return {init:init};
}();

var buttonFilterIE = function() {
	function init(){
		if (!$.browser.msie) return;
		$('#filter_button').click(function(){
			$("#search_button button").remove();
		});
	}
	return {init:init};
}();



;/*=DEGRAD VERSION CONSEIL RESEARCH= ( a ne pas supp )
var manageAdvisors = function() {
	var _xwindow;
	var _xbutton;
	var _xbuttondelete;
	var _searchparams = new Array();
	function _init() {
		// init
		manageAdvisors.xwindow = $("#dialogEditCompanyAdvisorSearch");
		manageAdvisors.xbutton = $("#EditCompanyAdvisorSearch");
		manageAdvisors.xbuttondelete = $("#EditCompanyAdvisorSearchDelete");

		if (manageAdvisors.xwindow.size()>0) {
			manageAdvisors.xwindow.dialog({
				autoOpen: false,
				bgiframe: true,
				resizable: true,
				height:500,
				width:750,
				modal: true,
				close : function(){$('select').show();},
				open: function(){ $('select').hide(); manageAdvisors.xwindow.html('<center><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><strong>Recherche en cours...</strong><br /><img class="progressBarImg" src="/_media/img/ajax_loader.gif" /></center>');},
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				}
			});
		}
		manageAdvisors.xbutton.click(function(){
			manageAdvisors.searchparams['ENTITY_TYPE_id'] = $("#ENTITY_TYPE_id_id").val();
			manageAdvisors.searchparams['REGION_id'] = $("#REGION_id_id").val();
			manageAdvisors.xwindow.dialog("open").load(
						"/company/searchadvisor/format/html/",{
																'ENTITY_TYPE_id':manageAdvisors.searchparams['ENTITY_TYPE_id'],
																'REGION_id':manageAdvisors.searchparams['REGION_id']
															  },
						function(){manageAdvisors.initEventXwindow();});
		});

		$("#showInvitConseil").toggle(function(){$("#InvitConseilBlock").slideDown();},function(){$("#InvitConseilBlock").slideUp();});

		manageAdvisors.xbuttondelete.click(function(){
			$('#advisorConseil').empty();
			$('#ConseillerIdId').val(0);
			manageAdvisors.xbuttondelete.hide();
			$('#advisorConseilSearchActive').show();

		});

	}
	function _initEventXwindow() {
		manageAdvisors.xwindow.find('.resultList tr').click(function(){
			var a = $(this).find('a:first');
			var id = a.attr('rel');
			var html = a.parent().html()+"<br /><br /><br /><br />";
			$('#advisorConseil').html(html).show();
			$('#advisorConseil a').each(function(){
				var temp=$(this).html();
				$(this).after("<strong>"+temp+"</strong>");
				$(this).remove();
			});
			$('#ConseillerIdId').val(id);
			manageAdvisors.xbuttondelete.show();
			$('#advisorConseilSearchActive').hide();
			manageAdvisors.xwindow.dialog('close');
			return false;
		});
	}

	return {init:_init,xwindow:_xwindow,xbutton:_xbutton,searchparams:_searchparams,initEventXwindow:_initEventXwindow,xbuttondelete:_xbuttondelete}
}();
*/












var manageAdvisors = function() {
	var _xbuttondelete;
	var _searchparams = new Array();
	function _init() {



		// init
		manageAdvisors.xbuttondelete = $("#EditCompanyAdvisorSearchDelete");
		$("#ENTITY_TYPE_id_id").change(function(){

		  if($("#ENTITY_TYPE_id_id").val() !=""){
			if($("#ENTITY_TYPE_id_id").val() ==1){
				//cas expert comptable
				$('#advisorConseil').empty();
				$('#ConseillerIdId').val(0);
				manageAdvisors.xbuttondelete.hide();
				$("#advisorListFind").empty();
				$('#advisorConseilSearchActive').show();


				//ajouter le bouton pour chercher un expert comptable
				$("#advisorListFind").html("<button type='button' class='fg-button ui-state-default fg-button-icon-left ui-corner-all float_right hide' id='id_ad_advisor' style='display: inline;'><span class='ui-icon ui-icon-search'></span>Rechercher Votre Expert-Comptable</button>");
				manageExpertComptable.init();
				$("#advisorListFind").show();
				$(".relation_advisor").hide();
				$("#invite_advisor_id").hide();

			}else{
				manageAdvisors.searchparams['ENTITY_TYPE_id'] = $("#ENTITY_TYPE_id_id").val();
				$(".relation_advisor").show();
				$("#invite_advisor_id").show();
				$("#advisorListFind").show();
				$("#advisorListFind").load(
							"/company/searchadvisor/format/html/",{
																	'ENTITY_TYPE_id':manageAdvisors.searchparams['ENTITY_TYPE_id']

																  },
							function(){manageAdvisors.xbuttondelete.show();});


			}

		  }else{
		  	$("#advisorListFind").empty();
		  }
		});





		$("#showInvitConseil").toggle(function(){$("#InvitConseilBlock").slideDown();},function(){$("#InvitConseilBlock").slideUp();});

		manageAdvisors.xbuttondelete.click(function(){
			$('#advisorConseil').empty();
			$('#ConseillerIdId').val(0);
			manageAdvisors.xbuttondelete.hide();
			$("#advisorListFind").empty();
			$('#advisorConseilSearchActive').show();
		});

	}

	return {init:_init,searchparams:_searchparams,xbuttondelete:_xbuttondelete};
}();


var manageExpertComptable = function() {
	function _init() {
		$("#id_ad_advisor").click(function () {
			$(".search_expert_comptable_global").hide();
			$(".paginationControl").hide();
			manageExpertComptable.initDialog();
			$("#dialogExpertComptable").dialog('open');
			$("#search_expert_comptable_departement_id").css('visibility', 'visible');
			$("#search_expert_comptable_departement_id").animate({ opacity: "show" }, "slow");
			getFocus();
		});
	}

	function _initDialog() {
		var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));
			$("#dialogExpertComptable").dialog({
				autoOpen: false,
				bgiframe: true,
				resizable: false,
				open : function() {if (ltie7) $('select').css('visibility','hidden');},
				close : function() {if (ltie7) $('select').css('visibility','visible');},
				height:150,
				width:670,

				position: ["top",100],
				draggable: false,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				}
			});
	}

	function getFocus() {
	    $('#search_expert_comptable_id').keypress(function(e) {
	        if(e.which == 13) {
	          	 $("#id_search_export_comptable").click();
	        }
	    });
	}
	return {init:_init,initDialog:_initDialog};
}();




var searchExpertComptable = function() {
	function _init() {

		$("#id_search_expert_comptable").click(function () {
			$("#id_expert_comptable_result").html("<img id='upload_loader_expert' src='/_media/img/ajax_loader.gif' />");
			$.post("/advisor/searchexpertcomptable/format/json",
				   {search_expert_comptable:$("#search_expert_comptable_id").val(),search_expert_comptable_departement:$("#search_expert_comptable_departement_id").val()},
				    function(data){
				    	$("#id_expert_comptable_result").hide();
						$("#id_expert_comptable_result").html(data);
						$("#id_expert_comptable_result").fadeIn("fast");
						addExpertComptable.init();
						changePageExpertComptable.init();

						$("#search_expert_comptable_departement_id").show();
						$("#dialogExpertComptable").css("height","450px");
						gradientSeparator.init();

					}, "html");
		});
	}
	return {init:_init};
}();



var changePageExpertComptable = function(){
	function _init() {
		$(".pagination_expert").click(function () {
			$("#id_expert_comptable_result").html("<img id='upload_loader_expert' src='/_media/img/ajax_loader.gif' />");
			var aTemp=$(this).attr('rel').split(":");
			var idPage=aTemp[1];
			$.post("/advisor/searchexpertcomptable/format/json",
				   {search_expert_comptable:$("#search_expert_comptable_id").val(), page:idPage ,search_expert_comptable_departement:$("#search_expert_comptable_departement_id").val()},
				    function(data){
				    	$("#id_expert_comptable_result").hide();
						$("#id_expert_comptable_result").html(data);
						$("#id_expert_comptable_result").fadeIn("fast");
						addExpertComptable.init();
						changePageExpertComptable.init();
						gradientSeparator.init();
						$("#search_expert_comptable_departement_id").show();
					}, "html");
		});
	}
	return {init:_init};
}();




var addExpertComptable = function(){
	function _init() {
		$(".addexpert").click(function () {
			var aTemp=$(this).attr('id').split("_");
			var idUser=aTemp[1];
			var idEntity=aTemp[2];
			var mailExist=aTemp[3];
			var firstName=aTemp[4];
			var lastName=aTemp[5];
			var civility=aTemp[6];
			if(mailExist==0){
				$("#invite_advisor_text").html("Votre conseil financier n'a pas de compte sur la plateforme, néanmoins vous pouvez l'inviter.").css("color","red");
				$("#invite_advisor_id").show();
				$("#InvitConseilBlock").show();
				$("#ADVISOR_last_name_id").val(lastName);
				$("#ADVISOR_first_name_id").val(firstName);
				$("#ADVISOR_civility_id").val(civility);
				$("#ADVISOR_old_id").val(idUser+"_"+idEntity);
				$('html,body').animate({scrollTop: $(".CONTACT_suivi").offset().top},'slow');
			}else{
				$("#invite_advisor_id").hide();
				$("#InvitConseilBlock").hide();
				$("#ADVISOR_last_name_id").val("");
				$("#ADVISOR_first_name_id").val("");
				$("#ADVISOR_civility_id").val("");
				$("#advisorListFind").html("<input type='hidden' value='"+idEntity+"' name='ADVISOR_id'>");
				$("#entityForm").attr('action', $("#entityForm").attr('action')+'#fnFrm');
				$("#entityForm").submit();
			}
			$("#dialogExpertComptable").dialog('close');
		});
	}
	return {init:_init};
}();







;


var manageCa = function() {

	function _init() {
		$("#change_visu input[name='visu']").click(function () {
			$(this).parents("form").submit();
		});
	}

	
	return {init:_init};
}();


;


var sso = function() {

	function _init() {
		init_logoutMonOseo();
	}

	function init_logoutMonOseo() {
		$("#logout_id").click(function(){
			logout = new Image();
			logout.src="http://www.mon.oseo.fr/logout.php";
			logout.src="http://monoseo.novactive.fr/logout.php";
			logout.src="http://monoseo.novactive.com/logout.php";
			$.cookie('MonSSOseo','invalid',{path: '/', domain: '.oseo.fr'});
			$.cookie('MonSSOseo','invalid',{path: '/', domain: '.novactive.fr'});
			$.cookie('MonSSOseo','invalid',{path: '/', domain: '.novactive.com'});
		});
	}

	return {init:_init};
}();
;$(function() {

/* test svn */

	javascript_ltie7.init();
	common_action.init();
	t_interface.init();
	initToolTip();
	cgu.init();

	userProfilPhoto.init();
	structureDoc.init();
	structureLogo.init();
	structureVideo.init();
	blocDocumentFile.init();
	contentFactView.init();
	contentArticleView.init();
	blocDepliant.init();
	myProfilView.init();
	manageEntity.init();

	manageShowOptionalFields.init();
	optionalFieldsSpecificBehaviour.init();
	manageTableHisto.init();
	manageTradiSectors.init();
	manageTechnoSectors.init();
	manageAdvisors.init();
	manageExpertComptable.init();
	searchExpertComptable.init();
	autoCompleteTechnoSector.init();
	search.init();
	savedSearch.init();
	buttonFilterIE.init();
//	displayListFilter.init();
	addContact.init();
	addDate.init();
	delContact.init();
	delFact.init();
	delArticle.init();
	delDocument.init();

	addAdvisor.init();
	advisorCreate.init();
	userDelete.init();
	manageCandidate.init();
	manageConvention.init();
	manageInvitation.init();
	manageCa.init();

	moderator_directory.init();	// common.js

	hide_show_more_community.init();
	change_page.init();
	change_size.init();
	changeZone.init();
	communityLogoActions.init();

	if (
			($('#MessTabs').size()>0) 		||
			($('#messagerie_body').size()>0)
		) messagerie.init();



	managementCompanyCommunity.init();
	managementUserCommunity.init();

	temoignages.init();
	subscribeAccordion.init();

	addCountryException.init();
	delCountryException.init();

	naviCompany.init();
	naviCompanyView.init();

	messageWelcomeNewSite.init();
	messageCheckForm.init();
	gradientSeparator.init(); // Common.js

	coinsArrondisIE.init(); // search.js


	sso.init();

});


;