jQuery.noConflict();

if(VVF === undefined) {
	var VVF = {};
}

// pour les flashs
function playPause() {
	document.getElementById('diaporama').playPause();
}

function showInfo(infos) {
	// for(var p in infos) {
	// 	console.log(p+': '+infos[p]);
	// }
	// alert('showInfo '+ infos.id+'  '+infos.name+'  '+infos.description)
}

function get_random() {
	var ranNum= Math.floor(Math.random()*1000);
	return ranNum;
}
var rand = get_random();

(function($) {
	var module = {
		calendar: !!VVF.Calendar,
		fauxFields: !!VVF.FauxFields,
		showHide: !!VVF.ShowHide
	};
	
	VVF.playPauseFlashBGInit = function() {
		VVF.playPauseBtn = $('#controlVideo img');
		VVF.playPauseBtn.click(VVF.playPauseClick);
	};
	VVF.playPauseClick = function(e) {
		if(VVF.ie6PNG) {
			if(this.runtimeStyle.filter.indexOf('play_video') > -1) {
				this.runtimeStyle.filter = this.runtimeStyle.filter.replace('play_video.', 'pause_video.');
			} else {
				this.runtimeStyle.filter = this.runtimeStyle.filter.replace('pause_video.', 'play_video.');
			}
		} else {
			if(this.src.indexOf('play_video') > -1) {
				this.src = this.src.replace('play_video.', 'pause_video.');
			} else {
				this.src = this.src.replace('pause_video.', 'play_video.');
			}
		}
		playPause();
		e.preventDefault();
	}
	
	VVF.updateContentFocus = function(o) {
		// remplir l'élément clubFocus
	};
	
	// write all page flashs
	VVF.writeFlashs = function(datas) {
		var d, home = !!datas.home, club = !!datas.club;
		
		if(datas.mediator && document.getElementById('mediatorSWF')) {
			d = datas.mediator;
			
			VVF.swfMediator = new SWFObject(d.url, "mediator", "1", "1", "8", "#FFFFFF");
			VVF.swfMediator.addParam("scale", "noScale");
			VVF.swfMediator.addParam("allowScriptAccess", "always");
			VVF.swfMediator.addVariable("sessionId", rand);
			VVF.swfMediator.addVariable("nbrConnect", 2);
			VVF.swfMediator.addVariable("isHome", home);
			VVF.swfMediator.addVariable("configPath", d.config);
			VVF.swfMediator.addVariable("isLocal", true);
			if(datas.mapTool && datas.mapTool.region) {
				VVF.swfMediator.addVariable("region", datas.mapTool.region);
			}
			VVF.swfMediator.write("mediatorSWF");
		}
		
		if(datas.flashBG && VVF.swfMediator && document.getElementById('flashBG')) {
			d = datas.flashBG;
			var bgH = (home || club) ? '457' : '291';
			
			VVF.swfFlashBG = new SWFObject(d.url, "diaporama", "100%", bgH, "8", "#FFFFFF");
			VVF.swfFlashBG.addParam("wmode", 'transparent');
			VVF.swfFlashBG.addParam("scale", "noScale");
			VVF.swfFlashBG.addParam("allowScriptAccess", "always");
			VVF.swfFlashBG.addVariable("sessionId", rand);
			if(d.image) {
				VVF.swfFlashBG.addVariable("file", d.image);
			}
			if(d.resort) {
				VVF.swfFlashBG.addVariable("idRef", d.resort);
			}
			VVF.swfFlashBG.write("flashBG");
			
			if(d.image && d.image.indexOf('.swf') == -1) {
				$('#controlVideo').addClass('off');
			} else {
				VVF.playPauseFlashBGInit();
			}
		}
		
		if(datas.mapTool && VVF.swfMediator && VVF.swfFlashBG && document.getElementById('mapToolSWF')) {
			d = datas.mapTool;
			
			VVF.swfMap = new SWFObject(d.url, "map", "279", "239", "8", "#9E0B73");
			VVF.swfMap.addParam("wmode", "transparent");
			VVF.swfMap.addParam("scale", "noScale");
			VVF.swfMap.addParam("allowScriptAccess", "always");
			VVF.swfMap.addVariable("sessionId", rand);
			VVF.swfMap.addVariable("isHome", home);
			VVF.swfMap.addVariable("configPath", d.config);
			if(d.region) {
				VVF.swfMap.addVariable("regionId", d.region);
			}
			VVF.swfMap.addVariable("isLocal", true);
			VVF.swfMap.write("mapToolSWF");
		}
		
		if(datas.signature && document.getElementById('signature')) {
			d = datas.signature;
			var sigW = home ? '421' : '677',
				sigH = home ? '273' : '244';
			
			VVF.swfSignature = new SWFObject(d.url, "signatureSWF", sigW, sigH, "8", "#FFFFFF");
			VVF.swfSignature.addParam("wmode", 'transparent');
			VVF.swfSignature.write("signature");
		}
		
		if(datas.club && document.getElementById('clubSwap')) {
			d = datas.club;
			
			VVF.clubSwap = new SWFObject(d.url, "clubSwapSWF", "471", "138", "7", "#FFFFFF");
			VVF.clubSwap.addParam("quality", 'best');
			VVF.clubSwap.addParam("wmode", 'transparent');
			VVF.clubSwap.addVariable("xmlPath", d.xml);
			VVF.clubSwap.addVariable("imgPath", d.img);
			VVF.clubSwap.write("clubSwap");
		}
	};
	
	// Calendar
	VVF.makeCalendar = function(datas) {
		datas.accessor.method = datas.accessor.method || 'append';
		datas.calendar.url = 'fake_calendar_update.php';
		jQuery(datas.accessor.target)[datas.accessor.method](
			'<div id="' + datas.accessor.contentID + '" class="openCalendar">'+
			'	<div class="fauxSelect"><span id="' + datas.accessor.dateID + '">' + l10n.get('calendar', 'dateHolder') + '</span></div>'+
			'	<a href="#" class="open">' + l10n.get('calendar', 'altImageOpen') + '</a>'+
			'</div>'
		);
		VVF[datas.calendar.id] = VVF.Calendar.Create({
			id: datas.calendar.id,
			target: datas.calendar.target,
			insert: datas.calendar.insert,
			firstDay: datas.calendar.firstDay,
			fields: datas.calendar.dayID + ', ' + datas.calendar.monthID + ', ' + datas.calendar.yearID,
			disable: datas.calendar.disable,
			min: {},
			max: {y: 1, method: 'add'}/*,
			ajax: {
				url: datas.calendar.url,
				getDatas: function(c) {
					return {year: c.last.y, month: c.last.m};
				}
			}*/
		});
		VVF[datas.calendar.id].addListener('dateselect', function() {
			$(datas.calendar.dayID).val(this.last.d).change().blur();
			$(datas.calendar.monthID).val(this.last.m).change().blur();
			$(datas.calendar.yearID).val(this.last.y).change().blur();
		});
	};
	
	if(module.calendar) {
		VVF.Calendar.setConfig({
			dateFormat: l10n.get('calendar', 'format'),
			prevMonth: {txt: l10n.get('calendar', 'prevMonth'), cName: 'prev'},
			nextMonth: {txt: l10n.get('calendar', 'nextMonth'), cName: 'next'}
		});
	}
	
	// Enable/Disable fields
	VVF.disableFields = function(target) {
		if(typeof target == 'string') {
			var h = $(target).get(0).offsetHeight;
			return $('<div class="maskFields" style="margin-bottom:-' + h + 'px; height:' + h + 'px;"></div>').insertBefore(target);
		} else {
			target.removeClass('hide');
		}
	};
	
	VVF.enableFields = function(obj) {
		obj.addClass('hide');
	};
	
	// Input text management
	VVF.clearInputText = function() {
		if(this.value == this.defaultValue) {
			this.value = '';
		}
	};
	
	VVF.restoreInputText = function() {
		if(/^\s*$/.test(this.value)) {
			this.value = this.defaultValue;
		}
	};
	
	VVF.inputText = function(context) {
		context = context || document;
		$('input[type=text], input[type=password]', context).filter(function() {
			if(this.defaultValue) {return this;}
		}).focus(VVF.clearInputText).blur(VVF.restoreInputText);
	};
	
	// Scripts
	VVF.js = {
		common: function() {
			$(document.body).addClass('js');
			
			VVF.inputText();
			
			$(document).click(function(e) {
				var t = $(e.target);
				if(t.hasClass('openPopinMax') || t.hasClass('openPopinMin')) {
					e.preventDefault();
					var url = t.attr('href'),
						mask = t.hasClass('openPopinMax'),
						thumbs, img;
					
					function popinOnLoad(e) {
						if(VVF.ie6PNG) {
							VVF.ie6PNG(VVF.cachePopin[this.url].popin);
						}
						VVF.inputText(VVF.cachePopin[this.url]);
						thumbs = $('#thumbnails', this.popin);
						img = $('#selectedImage img', this.popin);
						
						if(thumbs.length) {
							VVF.cachePopin[this.url].gallery = new VVF.SlideCycle({
								context: thumbs,
								next: 'a.down',
								prev: 'a.up',
								items: 'li',
								itemsDisplayed: 4,
								move: 91,
								direction: 'top',
								offScreen: -10000
							});
							VVF.cachePopin[this.url].gallery.items.click(function(e) {
								img.attr('src', $('a', this).attr('href'));
								e.preventDefault();
							});
						}
						VVF.cachePopin[this.url].addListener('open', popinOnOpen);
					}
					
					function popinOnOpen(e) {
						if(VVF.cachePopin[this.url].gallery && this.openings > 1) {
							VVF.cachePopin[this.url].gallery.reassignEvents();
							VVF.cachePopin[url].gallery.items.click(function(e) {
								img.attr('src', $('a', this).attr('href'));
								e.preventDefault();
							});
						}
					}
					
					VVF.Popin.manager(url, mask, popinOnLoad);
				}
			});
		},
		
		languages: function(id) {
			if(module.fauxFields && document.getElementById(id)) {
				VVF.languagesFS = VVF.FauxFields.Select({field: 'fLang', maxHeight: 200});
				VVF.languagesFS.addListener('change', function() {
					__doPostBack(this.field.name, '');
				});
			}
		},
		
		support: function(id) {
			if(module.showHide && document.getElementById(id)) {
				// Show/Hide
				VVF.ShowHide.Title({
					trigger: '#support div.on h2, #support div.off h2'
				});
				
				VVF.multiSearchSH = VVF.ShowHide.Simple({
					element: $('<a href="#multiSearchToolMore">' + l10n.get('showHide', 'more') + '</a>').prependTo('#multiSearchTool div.submit'),
					solo: true
				});
				VVF.multiSearchSH.addListener('open', function(e, target, trigger) {
					trigger.innerHTML = l10n.get('showHide', 'less');
				}).addListener('close', function(e, target, trigger) {
					trigger.innerHTML = l10n.get('showHide', 'more');
				});
			}
		},
		
		bookingTool: function(id) {
			if(module.fauxFields && module.calendar && document.getElementById(id)) {
				function fClubDisableEnable() {
					if(!this.lastValue) {
						VVF.bookingToolCalendar.disable();
						VVF.toolsFS.fLength.disable();
					} else {
						VVF.bookingToolCalendar.enable();
					}
				}
				
				// Calendar
				VVF.makeCalendar({
					accessor: {
						target: '#bookingTool fieldset.startDate',
						contentID: 'bookingToolOpenCalendar',
						dateID: 'bookingToolDate'
					},
					calendar: {
						id: 'bookingToolCalendar',
						target: 'bookingToolDate',
						insert: 'bookingToolOpenCalendar',
						firstDay: l10n.get('calendar', 'firstDay'),
						dayID: '#fStartDateDay',
						monthID: '#fStartDateMonth',
						yearID: '#fStartDateYear',
						disable: '#bookingTool fieldset.startDate'
					}
				});
				VVF.bookingToolCalendar.addListener('dateselect', function() {
					VVF.toolsFS.fLength.enable();
				});
				
				// Faux Select
				VVF.toolsFS = {};
				VVF.toolsFS.fLength = VVF.FauxFields.Select({field: 'fLength', maxHeight: 200, disable: '#support div.stayLength'});
				VVF.toolsFS.fClub = VVF.FauxFields.Select({field: 'fClub', maxHeight: 200, onload: fClubDisableEnable});
				VVF.toolsFS.fClub.addListener('change', fClubDisableEnable);
				VVF.toolsFS.fAdults = VVF.FauxFields.Select({field: 'fAdults'});
				VVF.toolsFS.fChildren = VVF.FauxFields.Select({field: 'fChildren'});
				VVF.toolsFS.fBabies = VVF.FauxFields.Select({field: 'fBabies'});
			}
		},
		
		multiSearchTool: function(id) {
			if(module.fauxFields && module.calendar && document.getElementById(id)) {
				// Faux Checkbox
				VVF.toolsFC = VVF.FauxFields.Composite({
					context: 'support',
					field: 'checkbox'
				});
				
				// Faux Radio
				VVF.toolsFR = VVF.FauxFields.Composite({
					context: 'support',
					field: 'radio'
				});
				// TODO : add disable/enable controls
				
				// Calendar
				VVF.makeCalendar({
					accessor: {
						target: '#multiSearchToolMore p',
						contentID: 'multiSearchToolOpenCalendar',
						dateID: 'multiSearchToolDate',
						method: 'before'
					},
					calendar: {
						id: 'multiSearchToolCalendar',
						target: 'multiSearchToolDate',
						insert: 'multiSearchToolOpenCalendar',
						firstDay: l10n.get('calendar', 'firstDay'),
						dayID: '#fStartDateDayMulti',
						monthID: '#fStartDateMonthMulti',
						yearID: '#fStartDateYearMulti'
					}
				});
				
				if($('#core').hasClass('multi')) {
					function disable() {
						VVF.cacheMaskMultiSearchTool = VVF.disableFields('#multiSearchTool div.content');
					}
					function enable() {
						if(VVF.cacheMaskMultiSearchTool) {VVF.enableFields(VVF.cacheMaskMultiSearchTool);}
					}
					function requestResults() {
						disable();
						// TODO faire passer les bons paramètres et injecter au bon endroit
						$.get('fake_multisearch_request.php', function() {
							setTimeout(enable, '1000');
						});
					}
					
					VVF.multiSearchToolCalendar.addListener('dateselect', function() {
						disable();
						$.get('fake_multisearch_request.php', function() {
							setTimeout(enable, '1000');
						});
					});
					
					$.each(VVF.toolsFC.collection, function() {
						this.addListener('change', requestResults);
					});
					$.each(VVF.toolsFR.collection, function() {
						this.addListener('change', requestResults);
					});
				}
			}
		},
		
		openingForm: function(id) {
			var verif = document.getElementById(id);
			if(module.fauxFields && module.calendar && verif && $('input', verif).length) {
				// Calendar
				VVF.makeCalendar({
					accessor: {
						target: '#opening fieldset.startDate',
						contentID: 'openingOpenCalendar',
						dateID: 'openingDate'
					},
					calendar: {
						id: 'openingCalendar',
						target: 'openingDate',
						insert: 'openingOpenCalendar',
						firstDay: l10n.get('calendar', 'firstDay'),
						dayID: '#fStartDateDay',
						monthID: '#fStartDateMonth',
						yearID: '#fStartDateYear',
						disable: '#opening fieldset.startDate'
					}
				});
				
				if($(document.body).hasClass('special')) {
					function fClubDisableEnable() {
						if(!this.lastValue) {
							VVF.openingCalendar.disable();
							VVF.openingFS.fLength.disable();
						} else {
							VVF.openingCalendar.enable();
						}
					}
					
					VVF.openingCalendar.addListener('dateselect', function() {
						VVF.openingFS.fLength.enable();
					});
					
					// Faux Select
					VVF.openingFS = {};
					VVF.openingFS.fLength = VVF.FauxFields.Select({field: 'fLength', maxHeight: 200, disable: '#opening div.stayLength'});
					VVF.openingFS.fClub = VVF.FauxFields.Select({field: 'fClub', maxHeight: 200, onload: fClubDisableEnable});
					VVF.openingFS.fClub.addListener('change', fClubDisableEnable);
					VVF.openingFS.fAdults = VVF.FauxFields.Select({field: 'fAdults'});
					VVF.openingFS.fChildren = VVF.FauxFields.Select({field: 'fChildren'});
					VVF.openingFS.fBabies = VVF.FauxFields.Select({field: 'fBabies'});
				} else {
					// Faux Select
					VVF.openingFS = VVF.FauxFields.Composite({
						context: 'opening',
						field: 'select',
						maxHeight: 200
					});
					
					// Faux Checkbox
					VVF.FauxFields.Composite({
						context: 'opening',
						field: 'checkbox'
					});
				}
			}
		},
		
		contentForm: function(id) {
			var verif = document.getElementById(id);
			if(module.fauxFields && verif && $('input', verif).length) {
				// Faux Select
				VVF.FauxFields.Composite({
					context: 'content',
					field: 'select',
					maxHeight: 200
				});
				
				// Faux Checkbox
				VVF.FauxFields.Composite({
					context: 'content',
					field: 'checkbox'
				});
				
				// Faux Radio
				VVF.FauxFields.Composite({
					context: 'content',
					field: 'radio'
				});
				
				// Calendar
				if(document.getElementById('considerNextDate')) {
					VVF.makeCalendar({
						accessor: {
							target: '#considerNextDate',
							contentID: 'nextDateOpenCalendar',
							dateID: 'nextDateDisplay'
						},
						calendar: {
							id: 'nextDateCalendar',
							target: 'nextDateDisplay',
							insert: 'nextDateOpenCalendar',
							firstDay: l10n.get('calendar', 'firstDay'),
							dayID: '#fConsiderNextDateDay',
							monthID: '#fConsiderNextDateMonth',
							yearID: '#fConsiderNextDateYear'
						}
					});
				}
				
				if(document.getElementById('lastStayDates')) {
					VVF.makeCalendar({
						accessor: {
							target: '#lastStayDatesFrom',
							contentID: 'lastStayDatesFromOpenCalendar',
							dateID: 'lastStayDatesFromDisplay'
						},
						calendar: {
							id: 'lastStayDatesFromCalendar',
							target: 'lastStayDatesFromDisplay',
							insert: 'lastStayDatesFromOpenCalendar',
							firstDay: l10n.get('calendar', 'firstDay'),
							dayID: '#fLastStayFromDay',
							monthID: '#fLastStayFromMonth',
							yearID: '#fLastStayFromYear'
						}
					});
					VVF.makeCalendar({
						accessor: {
							target: '#lastStayDatesTo',
							contentID: 'lastStayDatesToOpenCalendar',
							dateID: 'lastStayDatesToDisplay'
						},
						calendar: {
							id: 'lastStayDatesToCalendar',
							target: 'lastStayDatesToDisplay',
							insert: 'lastStayDatesToOpenCalendar',
							firstDay: l10n.get('calendar', 'firstDay'),
							dayID: '#fLastStayToDay',
							monthID: '#fLastStayToMonth',
							yearID: '#fLastStayToYear'
						}
					});
				}
			}
		},
		
		menuContextual: function(id) {
			if(module.showHide && document.getElementById(id) && $('#core')[0].className.indexOf('offers') == -1) {
				VVF.tabsSH = VVF.ShowHide.Toc({
					context: '#menuContextual'
				});
			}
		},
		
		toc: function(id) {
			if(module.showHide && document.getElementById(id) && !$('#core').hasClass('groups')) {
				VVF.tocSH = VVF.ShowHide.Toc({
					context: '#toc'
				});
				
				$('#content ul.dates').each(function() {
					VVF.ShowHide.Simple({
						context: this
					});
				});
				
				VVF.offersTitles = VVF.ShowHide.Title({
					trigger: '#content div.section h3',
					unique: true
				});
				VVF.tocSH.addListener('open', function(e, target) {
					VVF.offersTitles.lastTarget = target;
				});
				VVF.offersTitles.addListener('open', function(e, target) {
					var id = '#' + target.attr('id');
					location.hash = id + 'JS';
					VVF.tocSH.open(target, $('a[href=' + id + 'JS]', VVF.tocSH.context).parent());
				}).addListener('close', function(e, target, lastTarget) {
					if(target[0] == lastTarget[0]) {
						VVF.tocSH.close(target, $('a[href=#' + target.attr('id') + 'JS]', VVF.tocSH.context).parent());
					}
				});
			}
		},
		
		homeOffers: function(id) {
			if(!$('#core').hasClass('home')) {return;}
			var offers = $('#offers'),
				lastItem = $('div.on', offers),
				lastLink = $('li.on', lastItem),
				desc = $('#offerDescription');
			
			function selectLink(lk, li) {
				$.get('/fake_offers_update.php', $(lk).attr('href').replace('?', ''), updateOffer);
				lastItem.removeClass('on');
				lastLink.removeClass('on');
				lastLink = $(li).addClass('on');
				var div = lastLink;
				while(!div.hasClass('item')) {
					div = div.parent();
				}
				lastItem = div.addClass('on');
			}
			
			function updateOffer(data) {
				desc[0].innerHTML = data;
				if(VVF.ie6PNG) {
					VVF.ie6PNG(desc[0]);
				}
			}
			
			offers.click(function(e) {
				var t = e.target,
					p = t.parentNode;
				if(t.nodeName.toLowerCase() == 'a' && p.nodeName.toLowerCase() == 'li') {
					if(!$(p).hasClass('on')) {
						selectLink(t, p);
					}
					e.preventDefault();
				}
			});
		},
		
		validateForms: function() {
			if(!VVF.validate) {
				VVF.validate = {};
			}
			
			$('input[type=image]').each(function() {
				var f = this.parentNode;
				while(!f.id && !(/Form$/).test(f.id) && f.parentNode) {f = f.parentNode;}
				var id = f.id;
				if(f && (/Form$/).test(id) && VVF.validation && VVF.validation[id]) {
					VVF.validate[id] = VVF.Validator(this, f, VVF.validation[id]);
				}
			});
		}
	};
})(jQuery);

if(jQuery && document.getElementById && document.getElementsByTagName && document.createElement && document.createTextNode) {
	// TODO change this implementation (too much controls for the modules)
	jQuery(document).ready(function() {
		VVF.js.common();
		VVF.js.languages('languages');
		VVF.js.support('support');
		VVF.js.bookingTool('bookingTool');
		VVF.js.multiSearchTool('multiSearchTool');
		VVF.js.openingForm('opening');
		VVF.js.contentForm('content');
		VVF.js.menuContextual('menuContextual');
		VVF.js.toc('toc');
		VVF.js.homeOffers('offers');
		VVF.js.validateForms();
	});
	jQuery(window).unload(function() {
		VVF = null;
	});
}