/*
 * 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']);
});

;/**
 FCBKcomplete 2.7.5
 - Jquery version required: 1.2.x, 1.3.x, 1.4.x
 
 Based on TextboxList by Guillermo Rauch http://devthought.com/
 
 Changelog:
 - 2.00 new version of fcbkcomplete
 
 - 2.01 fixed bugs & added features
    fixed filter bug for preadded items
    focus on the input after selecting tag
    the element removed pressing backspace when the element is selected
    input tag in the control has a border in IE7
    added iterate over each match and apply the plugin separately
    set focus on the input after selecting tag
 
 - 2.02 fixed fist element selected bug
    fixed defaultfilter error bug
 
 - 2.5  removed selected="selected" attribute due ie bug
    element search algorithm changed
    better performance fix added
    fixed many small bugs
    onselect event added
    onremove event added
 
 - 2.6  ie6/7 support fix added
    added new public method addItem due request
    added new options "firstselected" that you can set true/false to select first element on dropdown list
    autoexpand input element added
    removeItem bug fixed
    and many more bug fixed
    fixed public method to use it $("elem").trigger("addItem",[{"title": "test", "value": "test"}]);
    
- 2.7   jquery 1.4 compability
    item lock possability added by adding locked class to preadded option <option value="value" class="selected locked">text</option>
    maximum item that can be added

- 2.7.1 bug fixed
    ajax delay added thanks to http://github.com/dolorian

- 2.7.2 some minor bug fixed
    minified version recompacted due some problems
    
- 2.7.3 event call fixed thanks to William Parry <williamparry!at!gmail.com>

- 2.7.4 standart event change call added on addItem, removeItem
    preSet also check if item have "selected" attribute
    addItem minor fix
    
- 2.7.5  event call removeItem fixed
         new public method destroy added needed to remove fcbkcomplete element from dome

 */
/* Coded by: emposha <admin@emposha.com> */
/* Copyright: Emposha.com <http://www.emposha.com> - Distributed under MIT - Keep this message! */

/**
 * json_url         - url to fetch json object
 * cache            - use cache
 * height           - maximum number of element shown before scroll will apear
 * newel            - show typed text like a element
 * firstselected    - automaticly select first element from dropdown
 * filter_case      - case sensitive filter
 * filter_selected  - filter selected items from list
 * complete_text    - text for complete page
 * maxshownitems    - maximum numbers that will be shown at dropdown list (less better performance)
 * onselect         - fire event on item select
 * onremove         - fire event on item remove
 * maxitimes        - maximum items that can be added
 * delay            - delay between ajax request (bigger delay, lower server time request)
 * addontab         - add first visible element on tab or enter hit
 * attachto         - after this element fcbkcomplete insert own elements
 */
 
jQuery(function($){$.fn.fcbkcomplete=function(opt){return this.each(function(){function init(){createFCBK();preSet();addInput(0)}function createFCBK(){element.hide();element.attr("multiple","multiple");if(element.attr("name").indexOf("[]")==-1){element.attr("name",element.attr("name")+"[]")}holder=$(document.createElement("ul"));holder.attr("class","holder");if(options.attachto){if(typeof(options.attachto)=="object"){options.attachto.append(holder)}else{$(options.attachto).append(holder)}}else{element.after(holder)}complete=$(document.createElement("div"));complete.addClass("facebook-auto");complete.append('<div class="default">'+options.complete_text+"</div>");complete.hover(function(){options.complete_hover=0},function(){options.complete_hover=1});feed=$(document.createElement("ul"));feed.attr("id",elemid+"_feed");complete.prepend(feed);holder.after(complete);feed.css("width",complete.width())}function preSet(){element.children("option").each(function(i,option){option=$(option);if(option.hasClass("selected")){addItem(option.text(),option.val(),true,option.hasClass("locked"));option.attr("selected","selected")}cache.push({key:option.text(),value:option.val()});search_string+=""+(cache.length-1)+":"+option.text()+";"})}$(this).bind("addItem",function(event,data){addItem(data.title,data.value,0,0,0)});$(this).bind("removeItem",function(event,data){var item=holder.children('li[rel='+data.value+']');if(item.length){removeItem(item)}});$(this).bind("destroy",function(event,data){holder.remove();complete.remove();element.show()});function addItem(title,value,preadded,locked,focusme){if(!maxItems()){return false}var li=document.createElement("li");var txt=document.createTextNode(title);var aclose=document.createElement("a");var liclass="bit-box"+(locked?" locked":"");$(li).attr({"class":liclass,"rel":value});$(li).prepend(txt);$(aclose).attr({"class":"closebutton","href":"#"});li.appendChild(aclose);holder.append(li);$(aclose).click(function(){removeItem($(this).parent("li"));return false});if(!preadded){$("#"+elemid+"_annoninput").remove();var _item;addInput(focusme);if(element.children("option[value="+value+"]").length){_item=element.children("option[value="+value+"]");_item.get(0).setAttribute("selected","selected");_item.attr("selected","selected");if(!_item.hasClass("selected")){_item.addClass("selected")}}else{var _item=$(document.createElement("option"));_item.attr("value",value).get(0).setAttribute("selected","selected");_item.attr("value",value).attr("selected","selected");_item.attr("value",value).addClass("selected");_item.text(title);element.append(_item)}if(options.onselect){funCall(options.onselect,_item)}element.change()}holder.children("li.bit-box.deleted").removeClass("deleted");feed.hide()}function removeItem(item){if(!item.hasClass('locked')){item.fadeOut("fast");if(options.onremove){var _item=element.children("option[value="+item.attr("rel")+"]");funCall(options.onremove,_item)}element.children('option[value="'+item.attr("rel")+'"]').removeAttr("selected").removeClass("selected");item.remove();element.change();deleting=0}}function addInput(focusme){var li=$(document.createElement("li"));var input=$(document.createElement("input"));var getBoxTimeout=0;li.attr({"class":"bit-input","id":elemid+"_annoninput"});input.attr({"type":"text","class":"maininput","size":"1"});holder.append(li.append(input));input.focus(function(){complete.fadeIn("fast")});input.blur(function(){if(options.complete_hover){complete.fadeOut("fast")}else{input.focus()}});holder.click(function(){input.focus();if(feed.length&&input.val().length){feed.show()}else{feed.hide();complete.children(".default").show()}});input.keypress(function(event){if(event.keyCode==13){return false}input.attr("size",input.val().length+1)});input.keydown(function(event){if(event.keyCode==191){event.preventDefault();return false}});input.keyup(function(event){var etext=xssPrevent(input.val());if(event.keyCode==8&&etext.length==0){feed.hide();if(!holder.children("li.bit-box:last").hasClass('locked')){if(holder.children("li.bit-box.deleted").length==0){holder.children("li.bit-box:last").addClass("deleted");return false}else{if(deleting){return}deleting=1;holder.children("li.bit-box.deleted").fadeOut("fast",function(){removeItem($(this));return false})}}}if(event.keyCode!=40&&event.keyCode!=38&&event.keyCode!=37&&event.keyCode!=39&&etext.length!=0){counter=0;if(options.json_url){if(options.cache&&json_cache){addMembers(etext);bindEvents()}else{getBoxTimeout++;var getBoxTimeoutValue=getBoxTimeout;setTimeout(function(){if(getBoxTimeoutValue!=getBoxTimeout)return;$.getJSON(options.json_url,{tag:etext},function(data){addMembers(etext,data);json_cache=true;bindEvents()})},options.delay)}}else{addMembers(etext);bindEvents()}complete.children(".default").hide();feed.show()}});if(focusme){setTimeout(function(){input.focus();complete.children(".default").show()},1)}}function addMembers(etext,data){feed.html('');if(!options.cache&&data!=null){cache=new Array();search_string=""}addTextItem(etext);if(data!=null&&data.length){$.each(data,function(i,val){cache.push({key:val.key,value:val.value});search_string+=""+(cache.length-1)+":"+val.key+";"})}var maximum=options.maxshownitems<cache.length?options.maxshownitems:cache.length;var filter="i";if(options.filter_case){filter=""}var myregexp,match;try{myregexp=eval('/(?:^|;)\\s*(\\d+)\\s*:[^;]*?'+etext+'[^;]*/g'+filter);match=myregexp.exec(search_string)}catch(ex){};var content='';while(match!=null&&maximum>0){var id=match[1];var object=cache[id];if(options.filter_selected&&element.children("option[value="+object.value+"]").hasClass("selected")){}else{content+='<li rel="'+object.value+'">'+itemIllumination(object.key,etext)+'</li>';counter++;maximum--}match=myregexp.exec(search_string)}feed.append(content);if(options.firstselected){focuson=feed.children("li:visible:first");focuson.addClass("auto-focus")}if(counter>options.height){feed.css({"height":(options.height*24)+"px","overflow":"auto"})}else{feed.css("height","auto")}}function itemIllumination(text,etext){if(options.filter_case){try{eval("var text = text.replace(/(.*)("+etext+")(.*)/gi,'$1<em>$2</em>$3');")}catch(ex){}}else{try{eval("var text = text.replace(/(.*)("+etext.toLowerCase()+")(.*)/gi,'$1<em>$2</em>$3');")}catch(ex){}}return text}function bindFeedEvent(){feed.children("li").mouseover(function(){feed.children("li").removeClass("auto-focus");$(this).addClass("auto-focus");focuson=$(this)});feed.children("li").mouseout(function(){$(this).removeClass("auto-focus");focuson=null})}function removeFeedEvent(){feed.children("li").unbind("mouseover");feed.children("li").unbind("mouseout");feed.mousemove(function(){bindFeedEvent();feed.unbind("mousemove")})}function bindEvents(){var maininput=$("#"+elemid+"_annoninput").children(".maininput");bindFeedEvent();feed.children("li").unbind("mousedown");feed.children("li").mousedown(function(){var option=$(this);addItem(option.text(),option.attr("rel"),0,0,1);feed.hide();complete.hide()});maininput.unbind("keydown");maininput.keydown(function(event){if(event.keyCode==191){event.preventDefault();return false}if(event.keyCode!=8){holder.children("li.bit-box.deleted").removeClass("deleted")}if((event.keyCode==13||event.keyCode==9)&&checkFocusOn()){var option=focuson;addItem(option.text(),option.attr("rel"),0,0,1);complete.hide();event.preventDefault();focuson=null;return false}if((event.keyCode==13||event.keyCode==9)&&!checkFocusOn()){if(options.newel){var value=xssPrevent($(this).val());addItem(value,value,0,0,1);complete.hide();event.preventDefault();focuson=null;return false}if(options.addontab){focuson=feed.children("li:visible:first");var option=focuson;addItem(option.text(),option.attr("rel"),0,0,1);complete.hide();event.preventDefault();focuson=null;return false}}if(event.keyCode==40){removeFeedEvent();if(focuson==null||focuson.length==0){focuson=feed.children("li:visible:first");feed.get(0).scrollTop=0}else{focuson.removeClass("auto-focus");focuson=focuson.nextAll("li:visible:first");var prev=parseInt(focuson.prevAll("li:visible").length,10);var next=parseInt(focuson.nextAll("li:visible").length,10);if((prev>Math.round(options.height/2)||next<=Math.round(options.height/2))&&typeof(focuson.get(0))!="undefined"){feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(prev-Math.round(options.height/2))}}feed.children("li").removeClass("auto-focus");focuson.addClass("auto-focus")}if(event.keyCode==38){removeFeedEvent();if(focuson==null||focuson.length==0){focuson=feed.children("li:visible:last");feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(parseInt(feed.children("li:visible").length,10)-Math.round(options.height/2))}else{focuson.removeClass("auto-focus");focuson=focuson.prevAll("li:visible:first");var prev=parseInt(focuson.prevAll("li:visible").length,10);var next=parseInt(focuson.nextAll("li:visible").length,10);if((next>Math.round(options.height/2)||prev<=Math.round(options.height/2))&&typeof(focuson.get(0))!="undefined"){feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(prev-Math.round(options.height/2))}}feed.children("li").removeClass("auto-focus");focuson.addClass("auto-focus")}})}function maxItems(){if(options.maxitems!=0){if(holder.children("li.bit-box").length<options.maxitems){return true}else{return false}}}function addTextItem(value){if(options.newel&&maxItems()){feed.children("li[fckb=1]").remove();if(value.length==0){return}var li=$(document.createElement("li"));li.attr({"rel":value,"fckb":"1"}).html(value);feed.prepend(li);counter++}else{return}}function funCall(func,item){var _object="";for(i=0;i<item.get(0).attributes.length;i++){if(item.get(0).attributes[i].nodeValue!=null){_object+="\"_"+item.get(0).attributes[i].nodeName+"\": \""+item.get(0).attributes[i].nodeValue+"\","}}_object="{"+_object+" notinuse: 0}";func.call(func,_object)}function checkFocusOn(){if(focuson==null){return false}if(focuson.length==0){return false}return true}function xssPrevent(string){string=string.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g,"\"\"");string=string.replace(/script(.*)/g,"");string=string.replace(/eval\((.*)\)/g,"");string=string.replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','');return string}var options=$.extend({json_url:null,cache:false,height:"10",newel:false,addontab:false,firstselected:false,filter_case:false,filter_selected:false,complete_text:"Start to type...",maxshownitems:30,maxitems:10,onselect:null,onremove:null,attachto:null,delay:350},opt);var holder=null;var feed=null;var complete=null;var counter=0;var cache=new Array();var json_cache=false;var search_string="";var focuson=null;var deleting=0;var complete_hover=1;var element=$(this);var elemid=element.attr("id");init();return this})}});;/*
 *
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: does not validate that the final text is a valid number
 * (that could be done by another script, or server-side)
 *
 * @name     numeric
 * @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
 * @param    allowPaste   let paste operations through
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(",");
 * @example  $(".numeric").numeric(null, false);
 *
 */
jQuery.fn.numeric = function(decimal, allowPaste)
{
	decimal = decimal || ".";
	allowPaste = typeof allowPaste == "boolean" ? allowPaste : true;
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste)
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45))
			{
				if(allowPaste) return true;
				else return false;
			}
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
				{
					allow = false;
				}
				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)
				{
					allow = true;
				}
			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	// allow/prevent pasting in IE
	.bind("paste", function(){return allowPaste});
	return this;
};/**
 * 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;
	var recipientDialog = 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.recipientDialog = $('#recipientListDialog');
		this.recipientDialog.dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:350,
			width:300,
			modal: true,
			draggable: false,
			close: function() {
				$(this).empty();
			}
		});

		this.dialogBox=$('#messagerieDialog');
		this.completionCache=new Array();
		this.dialogBox.dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: true,
			height:200,
			width:250,
			modal: true,
			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("");
//		});

		$("#destinataire_id").fcbkcomplete({
//			json_url: "/message/getreceiver/format/json",
//			cache: true,
//			filter_case: true,
//			filter_hide: true,
//			newel: true,
			addontab: true,
			height: 5,
			complete_text: _t_messagerie_complete_text
		});


		// 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();
//		});
		$('#joinfile_id').change(function() {
			$(this).after("<form id='tempForm' target='formulaire_upload' action='/file/upload/type/MessageJoin/asJoined/1' method='post' enctype='multipart/form-data'></form>");
			var form = $("#tempForm");
//			form.method="post";
//			form.target="formulaire_upload";
//			form.action="/file/upload/type/MessageJoin/asJoined/1";
			form.append($(this));
			$(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;
//		});

		$("#joinprofil_id").change(function(){
			if ($(this).attr("checked")) {
				$(".table_join_profil").show();
			} else {
				$(".table_join_profil").hide();
			}
		});

		$(".messages_actions button[name^='button_delete']").click(function(){
			$("body").append("<div title='"+_t_messagerie_confirm_delete_messages_title+"' id='confirm_delete'>"+_t_messagerie_confirm_delete_messages_message+"</div>");
			$("#form_messages_actions").append("<input type='hidden' name='"+$(this).attr("name")+"' />");
			$("#confirm_delete").dialog({
				autoOpen: true,
				buttons: {
					"Oui": function() {
						$("#form_messages_actions").submit();
						$(this).dialog("close");
					},
					"Annuler": function() {
						$(this).dialog("close");
					}
				},
				close: function() {
					$(this).remove();
				}
			});
			return false;
		});

		$(".messages_actions button[name='button_mark']").toggle(
			function(){
				$(".overlay_choice", $(this).parent()).show();
			}, function(){
				$(".overlay_choice", $(this).parent()).hide();
			}
		);

		$(".messages_actions button[name='button_direct_mark']").click(function() {
			$("#form_messages_actions").append("<input type='hidden' name='button_mark' />");
			$("#form_messages_actions").submit();
		});
		$(".messages_actions input[name='message_mark']").change(function() {
			$("#form_messages_actions").append("<input type='hidden' name='button_mark' />");
			$("#form_messages_actions").submit();
		});


		$(".message_select a").click(function() {
			var action = $(this).attr("rel");
			switch(action) {
				case "none" :
					$(".message_check").attr("checked", "");
					break;
				case "all" :
					$(".message_check").attr("checked", "checked");
					break;
				case "unread" :
					$(".message_check").attr("checked", "");
					$(".message_check.nonlu").attr("checked", "checked");
					break;
				case "read" :
					$(".message_check").attr("checked", "");
					$(".message_check.lu").attr("checked", "checked");
					$(".message_check.reply").attr("checked", "checked");
					break;
			}
			return false;
		});
		$("span.more_link").click(function() {
			$('#recipientListDialog').append($(this).siblings("ul").clone());
			$('#recipientListDialog').dialog('open');
		});

	}
	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 addressbook = function() {

	function _init(){

		$("#addressbook_body .addressbook_actions a.delete_contact").click(function(){
			var contact_id = $(this).attr('href');
			contact_id = contact_id.replace('#delete_', '');
			
			$("body").append("<div title='"+_t_adressebook_delete_contact+"' id='confirm_delete'>"+_t_adressebook_delete_contact+"</div>");
			$("#confirm_delete").dialog({
				autoOpen: true,
				buttons: {
					"Oui": function() {
						$('#form_addressbook_actions').append('<input type="hidden" name="button_delete['+contact_id+']" value="'+contact_id+'" />');
						$("#form_addressbook_actions").submit();
						$(this).dialog("close");
					},
					"Annuler": function() {
						$(this).dialog("close");
					}
				},
				close: function() {
					$(this).remove();
				}
			});
			return false;
		});
			
		$("#addressbook_body .addressbook_actions button[name^='button_message'], #addressbook_body .addressbook_actions input[name='button_message']").click(function(){
			if (!$(".contact_check:checked").length) {
				$("body").append("<div title='"+_t_adressebook_send_title+"' id='select_contacts_id'>"+_t_adressebook_send_message+"</div>");
				$("#select_contacts_id").dialog({
					autoOpen: true,
					buttons: {
						"Ok": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
				return false;
			}
		});


		$(".addressbook_actions button[name='button_addto_group']").toggle(
			function(){
				$(".overlay_choice", $(this).parent()).show();
			}, function(){
				$(".overlay_choice", $(this).parent()).hide();
			}
		);

		$(".contact_select a").click(function() {
			var action = $(this).attr("rel");
			$(".contact_check").attr("checked", "");
			switch(action) {
				case "none" :
					break;
				case "all" :
					$(".contact_check").attr("checked", "checked");
					break;
				default :
					$(".contact_check."+action).attr("checked", "checked");
					break;
			}
			return false;
		});

	}


	return {init:_init};
}();




;var addressbookgroup = function() {

	function _init(){

		$("#addressbookgroup_body .addressbook_actions a.delete_group").click(function(){
			var group_id = $(this).attr('href');
			group_id = group_id.replace('#delete_', '');
			
			$("body").append("<div title='"+_t_adressebookgroup_delete_title+"' id='confirm_delete_group'>"+_t_adressebookgroup_delete_message+"</div>");
			$("#confirm_delete_group").dialog({
				autoOpen: true,
				buttons: {
					"Oui": function() {
						$('#form_addressbook_actions').append('<input type="hidden" name="button_delete_group['+group_id+']" value="'+group_id+'" />');
						$("#form_addressbook_actions").submit();
						$(this).dialog("close");
					},
					"Annuler": function() {
						$(this).dialog("close");
					}
				},
				close: function() {
					$(this).remove();
				}
			});
			return false;
		});


		$("#addressbookgroup_body .addressbook_actions input[name='button_delete_group']").click(function(){
			var nameAttr = $(this).attr("name");
			var classname = $("#form_addressbook_actions").attr("class");
			var sElementCheck = classname == "list" ? "group_check" : "contact_check";
			var sElement = classname == "list" ? "groupe" : "membre";
			if (!$("."+sElementCheck+":checked").length) {
				$("body").append("<div title='"+_t_adressebookgroup_delete_once_title+""+sElement+"' id='select_groups_id'>"+_t_adressebookgroup_delete_once_message+""+sElement+"s</div>");
				$("#select_groups_id").dialog({
					autoOpen: true,
					buttons: {
						"Ok": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
			} else {
				$("body").append("<div title='"+_t_adressebookgroup_delete_once1_title+sElement+"(s)' id='confirm_delete'>"+_t_adressebookgroup_delete_once1_message+sElement+_t_adressebookgroup_delete_once1_selected+"</div>");
				$("#confirm_delete").dialog({
					autoOpen: true,
					buttons: {
						"Oui": function() {
//							$("#form_addressbook_actions").append("<input type='hidden' name='delete_selected_groups' />");
							$("#form_addressbook_actions").append("<input type='hidden' name='"+nameAttr+"' />");
							$("#form_addressbook_actions").submit();
							$(this).dialog("close");
						},
						"Annuler": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
			}
			return false;
		});


		$("#addressbookgroup_body .addressbook_actions button[name^='button_message'], #addressbookgroup_body .addressbook_actions input[name='button_message']").click(function(){
			var classname = $("#form_addressbook_actions").attr("class");
			var sElementCheck = classname == "list" ? "group_check" : "contact_check";
			var sElement = classname == "list" ? "groupe" : "membre";
			if (!$("."+sElementCheck+":checked").length) {
				$("body").append("<div title='"+_t_adressebookgroup_send_title+"' id='select_groups_id'>"+_t_adressebookgroup_delete_once_message+sElement+"s</div>");
				$("#select_groups_id").dialog({
					autoOpen: true,
					buttons: {
						"Ok": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
				return false;
			}
		});

		
		
		$("#addressbookgroup_body .addressbook_actions button[name^='button_message_user'], #addressbookgroup_body .addressbook_actions input[name='button_message_user']").click(function(){
			if (!$(".contact_check:checked").length) {
				$("body").append("<div title='"+_t_adressebookgroup_delete_once_message+"' id='select_groups_id'></div>");
				$("#select_groups_id").dialog({
					autoOpen: true,
					buttons: {
						"Ok": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
				return false;
			}
		});

		
		
		$("#addressbookgroup_body .addressbook_actions button[name^='button_message_group'], #addressbookgroup_body .addressbook_actions input[name='button_message_group']").click(function(){
			if (!$(".group_check:checked").length) {
				$("body").append("<div title='"+_t_adressebookgroup_send_title+"' id='select_groups_id'>"+_t_adressebookgroup_select_groupes+"</div>");
				$("#select_groups_id").dialog({
					autoOpen: true,
					buttons: {
						"Ok": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
				return false;
			}
		});

		

//		$(".addressbook_actions button[name='button_addto_group']").toggle(
//			function(){
//				$(".overlay_choice", $(this).parent()).show();
//			}, function(){
//				$(".overlay_choice", $(this).parent()).hide();
//			}
//		);

		$(".addressbook_actions input[name='addto_group']").click(function() {
			$("#form_addressbook_actions").append("<input type='hidden' name='button_group' />");
			$("#form_addressbook_actions").submit();
		});


		$(".group_select a").click(function() {
			var action = $(this).attr("rel");
			$(".group_check").attr("checked", "");
			$("input:checkbox.entityTypeFilter").attr("checked", "");
			switch(action) {
				case "none" :
					break;
				case "all" :
					$(".group_check").attr("checked", "checked");
					$("input:checkbox.entityTypeFilter").attr("checked", "checked");
					break;
				default :
					$(".group_check."+action).attr("checked", "checked");
					break;
			}
			return false;
		});
		$(".contact_select a").click(function() {
			var action = $(this).attr("rel");
			$(".contact_check").attr("checked", "");
			switch(action) {
				case "none" :
					break;
				case "all" :
					$(".contact_check").attr("checked", "checked");
					break;
				default :
					$(".contact_check."+action).attr("checked", "checked");
					break;
			}
			return false;
		});
		$(".row_container a.checkbox-switcher").click(function() {
			var action = $(this).attr("rel");
			var groupID = $(this).parents('tr.row_container').attr("id");
			groupID = groupID.replace("group_communitygrouplist_", '');
			var group_checkboxe = $(this).parents('tr.row_container').find('input:checkbox.group_check');
			var entity_chekboxes = $("#group_communitygrouplist_"+groupID+" input:checkbox.entityTypeFilter");
			entity_chekboxes.attr("checked", "");
			group_checkboxe.attr("checked", "");
			switch(action) {
				case "none" :
					break;
				case "all" :
					entity_chekboxes.attr("checked", "checked");
					group_checkboxe.attr("checked", "checked");
					break;
				default :
//					$("#container-groupID-"+groupID+" input:checkbox."+action).attr("checked", "checked");
					break;
			}
			return false;
		});
		$(".row_container input:checkbox.group_check").click(function() {
			var groupID = $(this).parents('tr.row_container').attr("id");
			groupID = groupID.replace("group_communitygrouplist_", '');
			var entity_chekboxes = $("#group_communitygrouplist_"+groupID+" input:checkbox.entityTypeFilter");
			
			entity_chekboxes.attr("checked", "");
			if ($(this).is(':checked')) {
				entity_chekboxes.attr("checked", "checked");
			}
		});
		$(".row_container input:checkbox.entityTypeFilter").click(function() {
			var groupID = $(this).parents('tr.row_container').attr("id");
			groupID = groupID.replace("group_communitygrouplist_", '');
			var group_checkboxe = $(this).parents('tr.row_container').find('input:checkbox.group_check');
			var entity_chekboxes = $("#group_communitygrouplist_"+groupID+" input:checkbox.entityTypeFilter");
			
			if (entity_chekboxes.is(':checked')) {
				group_checkboxe.attr("checked", "checked");
			} else {
				group_checkboxe.attr("checked", "");
			}
		});
		
		
		$('.row_container a.action_submit_row').click(function(){
			
			var groupID = $(this).parents('tr.row_container').attr("id");
			groupID = groupID.replace("group_communitygrouplist_", '');
			var entity_chekboxes = $("#group_communitygrouplist_"+groupID+" input:checkbox.entityTypeFilter");
			
			if (entity_chekboxes.is(':checked')) {
				$("#form_addressbook_actions input:submit[name='button_message_group']").remove();
				$('#form_addressbook_actions').append('<input type="hidden" name="entity_send" value="1" />');
				$('#form_addressbook_actions').append('<input type="hidden" name="id" value="'+groupID+'" />');
				$("#form_addressbook_actions").submit();
				return false;
			} else {
				$("body").append("<div title='"+_t_adressebookgroup_send_title+"' id='select_entity_id'>"+_t_adressebookgroup_select_identites+"</div>");
				$("#select_entity_id").dialog({
					autoOpen: true,
					buttons: {
						"Ok": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						$(this).remove();
					}
				});
				return false;
			}
			

		});
		
		
	}


	return {init:_init};
}();




;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
    };
}();


var manageAlreadyRegistered = function(){
    var ltie7 = ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent));

    function _init(){
        $("#idPopupRegistered").dialog({
            autoOpen: true,
            bgiframe: true,
            resizable: false,
            dialogClass :'tooltipDialog',
            height:200,
            width:400,
            //			open : function() {if (ltie7) $('select').css('visibility','hidden');},
            //			close : function() {if (ltie7) $('select').css('visibility','visible');},
            modal: true
        //			buttons: {
        //				"Se connecter": function() {
        //					document.location = "/user/login";
        //				},
        //				"S'inscrire": function() {
        //					$(this).dialog('close');
        //				}
        //			}
        });

        $("#doLogin", "#idPopupRegistered").click(function() {
            document.location = "/user/login";
        });
        $("#doRegister", "#idPopupRegistered").click(function() {
            $("#idPopupRegistered").dialog('close');
        });

    }
    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(_t_contact_confirm_delete_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);
            var name = $(this).attr("name") ? $(this).attr("name") : "application";
            $("#dialogRefuseConfirm").html("Voulez-vous vraiment refuser l'inscription de cet utilisateur à "+name+" ?");
            $("#dialogRefuseConfirm").dialog("open");
        });

        $("button.unregisterCandidate").click(function () {
            manageCandidate.buttonClicked = $(this);
            var name = $(this).attr("name") ? $(this).attr("name") : "application";
            $("#dialogRefuseConfirm").html("Voulez-vous vraiment désinscrire cet utilisateur de "+name+" ?");
            $("#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));
	ltie8 = ($.browser.msie && /MSIE\s(5\.5|6\.|7\.)/.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[src$=.png]').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:600,
					width:800,
					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:300,
			width:470,
			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');} window.location = '/company/edit#visibilityEntityComBlock'; }
			}
		});
	}
	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:not(.messagerie_fil) 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);
		});

		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>"+_t_common_chargement+"</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() {
			//$('#navigation').append('<p>precise_toggle click</p>');
			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) {
		}
//		try {
//			var elemsName	= elem.attr("name") ? "."+elem.attr("name") : null;
//			if (elemsName) {
//				var tmpElt = elem.next();
//				if (tmpElt && tmpElt.hasClass(elem.attr("name")))
//					tmpElt.is(':visible') ? tmpElt.hide() : tmpElt.show();
//				else {
//					elemsName = $(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) {
//				var tmpElt = elem.next();
//				if (tmpElt && tmpElt.hasClass(elem.attr("rel")))
//					tmpElt.css("display" ) != "none" ? tmpElt.hide() : tmpElt.show();
//				else {
//					elemsRel = $(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();
		_manageChooseLangSelect();
	}
		// 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();
		});
	}

	function _manageChooseLangSelect() {
		$('select.form_auto_submit_chooselang').change(function() {
			window.location.href = $(this).val();
		});
	}

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


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() : _t_entity_dialog_title_dialogunsubscribeUsercommunity);
			$("#dialogUnsubscribeUserCommunity").html($(".popupTexte", $(this)).length>0 ? $(".popupTexte", $(this)).html() : _t_entity_dialog_texte_dialogunsubscribeUsercommunity);
			$("#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: {
				_t_entity_dialog_btn_oui: function() {managementUserCommunity.unsubscribeCommunity();$("#dialogUnsubscribeUserCommunity").dialog('close');},
				_t_entity_dialog_btn_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() : _t_entity_dialog_title_dialogunsubscribeUsercommunity);
			$("#dialogUnsubscribeCompanyCommunity").html($(".popupTexte", $(this)).length>0 ? $(".popupTexte", $(this)).html() : _t_entity_dialog_texte_dialogunsubscribeUsercommunity);
			$("#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: {
				_t_entity_dialog_btn_oui: function() {managementCompanyCommunity.unsubscribeCommunity();$("#dialogUnsubscribeCompanyCommunity").dialog('close');},
				_t_entity_dialog_btn_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() {
		var bIsAtive = $("#accordionSubscribe.alone").length > 0 ? 0 : false;
		jQuery("#accordionSubscribe").accordion({header: "h2", collapsible : true, autoHeight: false, active: bIsAtive});
		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() {
			var userId = $(this).attr("rel");
			$("body").append('<div title="'+_t_entity_operation_title_use_delete+'" id="TempDialogValid"></div>');
			$("#TempDialogValid").html(_t_entity_operation_confirm_use_delete).dialog({
				autoOpen: true,
				resizable: false,
				height:100,
				width:400,
				close: function() {
					$("#TempDialogValid").remove();
				},
				buttons: {
					"Oui": function() {
						$.post("/user/delete/format/json", {data: userId}, function (data){
							$("body").append('<div title="'+_t_entity_operation_title_use_delete+'" id="TempDialogConfirm"></div>');
							$("#TempDialogConfirm").html(data).dialog({
								autoOpen: true,
								resizable: false,
								height:100,
								width:350,
								close: function() {
									$("#TempDialogConfirm").remove();
								},
								buttons: {
									"Ok": function() {
										$("#TempDialogConfirm").dialog("close");
									}
								}
							});
						}, "json");
						$("#TempDialogValid").dialog("close");
					},
					"Non": function() {
						$("#TempDialogValid").dialog("close");
					}
				}
			});
		});
	}
	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-fundsdetails .fiche_onglet a, .company-techno .fiche_onglet a, .company-funds .funds_subnav a, .company-fundsdetails .funds_subnav 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};
}();

// Publication EEN
var entityPublish = function() {

	// initialisation : ajout de la dialogBox + mapping OnClick event
	function _init() {
		$(document).ready(function(){
			var btn;
			if ((btn = $('#btnCompanyPublish'))) {
				$('body').append('<div class="jqueryUiDialog" id="publishDialog" title="'+_t_entity_dialog_validate_publication+'"></div>');
				$('#publishDialog').dialog({
					autoOpen: false,
					bgiframe: true,
					resizable: false,
					height:250,
					width:350,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					open: function(event, ui){
						if (ltie7) $('select').css('visibility','hidden');
						$('#publishDialog').load('/company/publishform', {
							'id': btn.attr('href'),
							'LANG_id': $("select#LANG_id_id option:selected").val()
						});
					},
					close : function() {if (ltie7) $('select').css('visibility','visible');},
					buttons: {
						"Publier": function() {
							$("#publishDialog").dialog('close');
							if ($("#publishtypeform").size()>0) {
								$("#publishtypeform").submit();
							}
						},
						"Annuler": function() {
							$("#publishDialog").dialog('close');
						}
					}
				});

				btn.click(function() {
					$('#publishDialog').dialog('open');
				});
			}
		});
	}

	return {init:_init};

}();

var manageCompanyNeeds = function() {
    
        
        
        function _init() {
            $(".numeric_field").numeric();            

            $("#NEEDS_year0").change(function() {
               _manageNeedYears();
            });
            
            _manageNeedYears();
                   
            _manageTextAreas();
        }
        
        function _manageNeedYears()
        {
            var elem = $("#NEEDS_year0");
            
            if ($(elem).val() == '') {
                var d = new Date();
                fYear = d.getFullYear();
            } else {
                fYear = parseInt($(elem).val());
            }
            $(".NEEDS_year").each(function() {
               $(this).attr('value', fYear);
               fYear++; 
            });
        }
        
        function _manageTextAreas()
        {
            $(".COMP_presentation_area").each(function() {
               _manageTextArea($(this));
            });
            
            $(".COMP_presentation_area").keyup(function() {
               _manageTextArea($(this));
            });
            
            $(".COMP_presentation_area").blur(function() {
                _manageTextArea($(this));
             });
        }
        
        function _manageTextArea(area)
        {
               var areaMax = parseInt($(area).attr('maxlength'));
               var areaLength = $(area).val().length;
               var charLeft = areaMax - areaLength;
               $(area).parent().children('.question_maxchar').children('.counter').html(charLeft);
        }
        
        return {init:_init};
}();

;

var manageInvitation = function() {
    var buttonClicked, optionalMessage;

    function _init() {
        $("button#inviteEntityGlobal").click(function () {
            $("#inviteEntityGlobalDialog").dialog("open");
        });

        $("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>" + _t_invite_inviter_en_tant_que + $("#ProfilListe_"+vals[2]).html() + "</p>" +
                "<p style='margin-bottom: 0;'>"+_t_invite_message_optionnel +
                "<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));

        $("#inviteEntityGlobalDialog").dialog({
            autoOpen: false,
            bgiframe: true,
            resizable: true,
            height: ltie8 ? "auto" : 300,
            width: 400,
            modal: false
        });

        $("#conteneur_footer").after('<div class="jqueryUiDialog" id="tooltipInvitationDialog"></div>');
        $("#conteneur_footer").after('<div class="jqueryUiDialog" id="tooltipInvitationSendMessage"></div>');

        $("#tooltipInvitationDialog").attr("title", _t_invite_title_inviter_utilisateur_communite);
        $("#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(_t_invite_notification_invitation);
                            $dialog.html(data["error"]).dialog('open');
                        }
                    }, "json");
                    $("#tooltipInvitationDialog").dialog('close');
                },
                "Non": function() {
                    $("#tooltipInvitationDialog").dialog('close');
                }
            }
        });

        $("#tooltipInvitationSendMessage").attr("title", _t_invite_title_send_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,vdelete:_initDelete,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 />"+_t_uploadu_op_confirm+"</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 structureDocFund = function(){
	var todelete="";
	function _init(){
		$('#STRUCT_documents_fund_id input[type=file]').change(function(){
			var form=$("#entityForm").get()[0];
			form.target="formulaire_upload";
			form.action="/file/upload/type/StructureDocsFund";
//			$("#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_fund_id input[type=file]').size()>0) this.initDialog();
	}
	function _initDialog() {
				$("#dialogDeleteDocsFundStructure").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/"+structureDocFund.todelete);
							$("#STRUCT_documents_fund_id .preview #doc_"+structureDocFund.todelete).remove();
						},
						'Annuler': function() {
							$(this).dialog('close');
						}
					}
				});
	}
	function _delete(hash) {
		this.todelete=hash;
		$("#dialogDeleteDocsFundStructure").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_world_all_id").attr("checked")){
			$("#world_div_id").hide();
		}else{
			$("#world_div_id").show();
		}

		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").click(
			function() {

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

				if (!isCheck){
					$(this).parent().next(".SEARCH_geo_all_display").show();
					$(this).parent().next(".SEARCH_geo_all_display :checkbox").attr("checked","");
				}else{
					$(this).parent().next(".SEARCH_geo_all_display").hide();
					$(this).parent().next(".SEARCH_geo_all_display :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();
			}
			var arrow = $("span.ui-icon", $(this).siblings("label"));
			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");
			}


			$(".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'], .search_active .search_category_title[rel='projet_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>"+_t_advisiosearch_chercher_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(_t_advisiosearch_conseil_financier).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("");
                $("#USER_id").val(idUser);	// 08/06/2010
                $("#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();
	tabMenuHandler.init(); // Onglets accueil communautés

	userProfilPhoto.init();
	structureDoc.init();
    structureDocFund.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();
	manageAlreadyRegistered.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();

	addressbook.init();
	addressbookgroup.init();

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

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

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

	naviCompany.init();
	naviCompanyView.init();
	entityPublish.init(); // entity.js

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

	coinsArrondisIE.init(); // search.js

	investorEditChoice.init(); // Choix type investor
	communityApps.init();		// Comportement relatif aux communautés d'application
	
        manageCompanyNeeds.init();
	// Désynchrinisation de mon OSEO et de Capital PME
	// sso.init();

});


;/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready(function() {
	
	$("#list_entities li input:not(:checked)").siblings("ul").hide();

    input_radio =  $("input[value='all']");

    if (input_radio.attr('checked')) {
    	hideEntities();
    }
  
	$('.visibility').click( function(){
		if($(this).val() == "select") {
			showEntities();
		} else {
			hideEntities();
		}
	});

	$('.entity input').click(function(){
		if($(this).is(':checked')) {
			$(this).siblings("ul").show();

		} else {
			$(this).siblings("ul").hide();
		}
	});

});

function showEntities() {
	$('#list_entities').show();
}

function hideEntities() {
	$('#list_entities').hide();
}

;$(document).ready(function() {
    $('#promote_code').click(function() {
      $('#promote_code').select();
    });
});
;
/**
 * Gestionnaire onglet & menus
 */
var tabMenuHandler = function() {

	var currentPage = $("#tabs a.on-persist");

	function _init() {
		$(document).ready(function() {
//			$("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
//	        $("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');

//			if (!$(".header_community").size() == 0) {
			if (!$("#tabs").size() == 0) {

				var currentPage = $("#tabs a.on-persist");
				var restoreCurrentTabTimer;
				var hideDropDownMenuTimer;


				$("#tabs > li").hover(
					function () {
						$("#tabs li ul.sstabs").hide();
						clearTimeout(restoreCurrentTabTimer);
						if (!$(this).children('a').hasClass('on-persist')) {
							currentPage.removeClass("on-persist");
						}
					},function(){
						clearTimeout(restoreCurrentTabTimer);
						restoreCurrentTabTimer = setTimeout('tabMenuHandler.restoreCurrentTab()', 300);
				});//hover

				$("#tabs > li.item").hover(
					function () {
						clearTimeout(hideDropDownMenuTimer);
						$("#tabs li.item").children("ul.sstabs").stop(true, true);
						$(this).children("a").addClass("on");

						// Positionnement
						var position = $(this).position();
						$(this).children("ul.sstabs").css(position);
						$(this).children("ul.sstabs").css('margin', '35px 0 0 -10px');

						if ($.browser.msie && $.browser.version.substr(0,1)<7) {
							$(this).children("ul.sstabs").css('margin', '30px 0 0 -1px');
						}

						$(this).children("ul.sstabs").show();
						if ($.browser.msie && $.browser.version.substr(0,1)<7) {
							$('#contenu :input').hide();
						}
					},function(){
						clearTimeout(hideDropDownMenuTimer);
						$("#tabs li.item").children("ul.sstabs").stop(true, true);
						$(this).children("a").removeClass("on");
						hideDropDownMenuTimer = setTimeout('tabMenuHandler.hideDropDownMenu()', 50);
						if ($.browser.msie && $.browser.version.substr(0,1)<7) {
							$('#contenu :input').show();
						}
				});//hover

				// Ajotue la classe nécessaire au conteneur
				if ($("#tabs_apps").size() == 0) { // Specific case where VERTICAL navigation exists (apps) then this class isn't required.
					_setClass();
				}
			}

		});
	}

	// Restore current tab after playing with the menu
	function restoreCurrentTab() {
		currentPage.addClass("on-persist");
	}

	// Close the drop down menu
	function hideDropDownMenu() {
		$("#tabs li.item").children("ul.sstabs").stop(true, true).fadeOut('fast');
	}

	/**
	 * Rajoute une classe au div #contenu afin d'activer les styles dépendants du header Community
	 */
	function _setClass() {
			$("div#contenu").addClass("hasCommunityHeader");
	}

	// Preload images used by the dropdown menu
//	dropdownImage = new Image();
//	dropdownImage.src = "/";

	return {init:_init,
			restoreCurrentTab:restoreCurrentTab,
			hideDropDownMenu:hideDropDownMenu
			};
}();
;
var investorEditChoice = function() {

	function _init() {
            var reqUri = '/investor/getvisibility/format/json';
		$('select#INVEST_type_id').change(function(){
			$('option:selected', this).each(function(){
				// 8 -> Investisseur individuel
				if( 8 == $(this).attr('value')) {
					$('h2.INVEST_type_title_8').hide();
					$('h2.INVEST_type_title_16').show();
				} else {
					$('h2.INVEST_type_title_16').hide();
					$('h2.INVEST_type_title_8').show();
				}
				// Gestion des visibilités par défaut
				$.post(reqUri, ({'investorTypeId':$(this).attr('value')}), function(data){

					if (data.Company['1'].checked) {
						$('input#ENTITY_TYPE\\[Company\\]\\[1\\]').attr('checked','true');
					} else {
						$('input#ENTITY_TYPE\\[Company\\]\\[1\\]').removeAttr('checked');
					}
					if (data.Company['2'].checked) {
						$('input#ENTITY_TYPE\\[Company\\]\\[2\\]').attr('checked','true');
					} else {
						$('input#ENTITY_TYPE\\[Company\\]\\[2\\]').removeAttr('checked');
					}
					if (data.Investor.checked) {
						$('input#ENTITY_TYPE\\[Investor\\]').attr('checked','true');
					} else {
						$('input#ENTITY_TYPE\\[Investor\\]').removeAttr('checked');
					}
					if (data.Advisor.checked) {
						$('input#ENTITY_TYPE\\[Advisor\\]').attr('checked','true');
					} else {
						$('input#ENTITY_TYPE\\[Advisor\\]').removeAttr('checked');
					}

				}, "json");
			});
		});
	}

	return {init:_init};
}();;
var communityApps = function() {

	function _init() {

		var oPopup = $(".popup_register_app").dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			height:275,
			width:500,
			modal: true,
			close: function() {
			}/*,
			buttons: {
				'Ok': function() {
					$(this).dialog('close');
				}
			}
/**/
		});

		$("#register_app_no").click(function() {
			oPopup.dialog('close');
			return false;
		});

		$(".register_app").click(function () {
			oPopup.dialog('open');
			return false;
		});

		$("#form-app-register").submit(function(event) {
//			event.preventDefault();
			// Submit internal form using ajax
			var COMMUNITYid = $(this).find('input[name="COMMUNITY_id"]').val();
		    $.post("/community/registerapp/format/json", {'COMMUNITY_id': COMMUNITYid}, function(data, result) {
		    	if (result == "success") {
//		    		// Submit external form (to application's url)
//		    		$('#form-app-external').submit();
					location.reload(true);
					return true;
		    	} else {
		    		return false;
		    	}
		    }, "json");

		});

		$(".connect_app_link").click(function () {
			$('#form-app-external').submit();
			return false;
		});


		$("input.remove_application").click(function(){
			var nameAttr = $(this).attr("name");
			var parentForm = $(this).parents('form:first');
			$("body").append("<div title='"+_t_community_apps_supprimer_application+"' id='confirm_delete_application'>"+_t_community_apps_confirm_supprimer_application+"</div>");
			$("#confirm_delete_application").dialog({
				autoOpen: true,
				buttons: {
					"Oui": function() {
						parentForm.append("<input type='hidden' name='"+nameAttr+"' />");
						parentForm.submit();
						$(this).dialog("close");
					},
					"Annuler": function() {
						$(this).dialog("close");
					}
				},
				close: function() {
					$(this).remove();
				}
			});
			return false;
		});


	}

	return {init:_init};
}();


;
