/**
 * Main control for room configuration in search form
 * @param {Object} divEl 
 * @param {Object} checkEl Optional
 */
window.RoomConfigBuilder = Class.extend({
	init: function (divEl, checkEl) {
		var _t = this;
		// define visibility controller and contaner
		_t.togglerCheck = checkEl;
		_t.domEl = divEl;
		// define caches 
		_t.checkCache = _t.togglerCheck ? _t.togglerCheck.checked : true;
		_t.htmlCache = _t.domEl.innerHTML;
		_t.roomConfigModel = $('div.book-room:first', _t.domEl).clone();
		_t.maxRoomQuantity = parseInt($('input.max-room-quantity', _t.domEl).val(), 10) || 10;
		_t.rooms = [];
		_t.configPossibilities = [];
		
		// hide the panel when starting if not checked
		_t.domEl.style.display = _t.checkCache ? 'block' : 'none';
		
		// config the RoomConfig model setting default values and removing unnecesary select boxes
		_t.roomConfigModel.find('div.book-children-ages').hide('').find('select').remove();
		
		// register rooms when starting but not launching triger events
		_t.registerAllRooms(false);

		// Events
		$(_t.togglerCheck).bind('change', function () {
			_t.toggleVisibility();
		});
		
		// -- delegate this event so that it doesn't need to be reassigned every reset
		$(_t.domEl).delegate('p.add-room', 'click', function () {
			_t.registerRoomConfig(_t.addRoomConfig());
		})
		// -- listen to deletion request 
		.delegate('a.delete', 'click', function () {
			var _a = this;
			// if the checkbox exists and there is only one room left
			if (_t.togglerCheck && _t.rooms.length === 1) {
				_t.togglerCheck.checked = false;
				$(_t.togglerCheck).trigger('change');
			}
			else if (_t.rooms.length > 1) {
				_t.destroyRoomConfig($('a.delete', _t.domEl).index(_a));
			}
		})
		// -- listen to each change to check validity
		.bind('change', function () {
			_t.setError(!_t.checkConfigs());
		});
		
	},
	toggleVisibility: function () {
		var _t = this,
			$form = $(_t.domEl).closest('form'),
			boolChecked = !_t.togglerCheck || _t.togglerCheck.checked;
		$(_t.domEl)[boolChecked ? 'show' : 'hide']('slide', {direction:'left'});
		// TODO: tratamiento para la casuistica especifica del formulario estandar (en el header lateral))
		if ($(_t.domEl).closest('#header').length) {
			// hide/show original button
			$form.find('button:submit').css('marginLeft', [boolChecked ? -10000 : 0, 'px'].join(''));
			if (boolChecked) {
				$form.find('div.book-room-config-builder').append($form.find('button:submit').clone().removeAttr('style'));
			}
			else {
				$form.find('div.book-room-config-builder button:submit').remove();
			}
		}
		return _t;
	},
	addRoomConfig: function () {
		var _t = this,
			lastRoomEl = _t.rooms[_t.rooms.length - 1].domEl,
			newRoomEl = $(_t.roomConfigModel.clone());
		// insert the element and trigger change so that it bubbles up to the form element where a listener awaits
		newRoomEl.insertAfter(lastRoomEl);
		return newRoomEl.get(0);
	},
	destroyRoomConfig: function (nIndex) {
		var _t = this;
		$(_t.rooms.splice(nIndex, 1)[0].domEl).remove();
		while (_t.rooms[nIndex]) {
			_t.setRoomIndex(nIndex);
			nIndex++
		}
		_t._roomQuantityChangeActions();
	},
	registerRoomConfig: function (roomConfigElement, boolTrigger) {
		var _t = this,
			nIndex = _t.rooms.length;
		_t.rooms.push(new RoomConfig(roomConfigElement));
		_t.setRoomIndex(nIndex);
		_t.rooms[nIndex].setConfigPossibilities(_t.configPossibilities);
		_t._roomQuantityChangeActions(boolTrigger);
		return _t.rooms[nIndex];
	},
	registerAllRooms: function (boolTrigger) {
		var _t = this;
		$('div.book-room', _t.domEl).each(function (n) {
			_t.registerRoomConfig(this, boolTrigger);
		});
	},
	/**
	 * Calls setRoomIndex for all rooms or for an individual room
	 * @param {Object} index Optional, if it is not set defaults to all the rooms
	 */
	setRoomIndex: function (nIndex) {
		var _t = this;
		if (nIndex) {
			_t.rooms[nIndex].setRoomIndex(nIndex);
		}
		else {
			$.each(_t.rooms, function (n) {
				this.setRoomIndex(n);
			});
		}
		return _t;
	},
	/**
	 * Resets the control to its default state
	 */
	reset: function () {
		var _t = this,
			$domEl = $(_t.domEl),
			boolChecked = _t.checkCache;
		// check and visibility
		if (_t.togglerCheck) {
			_t.togglerCheck.checked = _t.checkCache;
			//$(_t.togglerCheck).trigger('change');
		}
		if (($domEl.is(':visible') && !boolChecked) || (!$domEl.is(':visible') && boolChecked)) {
			_t.toggleVisibility();
		}
		// reset rooms
		$domEl.html(_t.htmlCache);
		_t.rooms = [];
		_t.registerAllRooms();
		return _t;
	},
	setConfigPossibilities: function (aPossib) {
		var _t = this,
			aHtml = [];
		_t.configPossibilities = aPossib;
		// set the config for each room
		$.each(_t.rooms, function (index, roomConfig) {
			roomConfig.setConfigPossibilities(aPossib);
		});
		// build the config table
		aHtml.push('<tbody>');
		$.each(aPossib, function (index, oConf) {
			aHtml.push('<tr>');
			aHtml.push('<td>', oConf.adults ,'</td>');
			aHtml.push('<td>', oConf.kids ,'</td>');
			aHtml.push('<td>', oConf.babies ,'</td>');
			aHtml.push('</tr>');
		});
		aHtml.push('</tbody>');
		$('div.book-config-builder-explanation table', _t.domEl).find('tbody').remove().end()
		.append(aHtml.join(''));
		// now that we just set the configs, check that everything is fine
		_t.setError(!_t.checkConfigs());
	},
	checkConfigs: function () {
		var _t = this,
			bool = true;
		$.each(_t.rooms, function (index, thisRoom) {
			bool = thisRoom.checkConfig();
			return bool;
		});
		return bool;
	},
	setError: function (bool) {
		var _t = this;
		$('div.book-config-builder-explanation', _t.domEl)[bool ? 'slideDown' : 'slideUp']();
	},
	_roomQuantityChangeActions: function (boolTrigger) {
		var _t = this,
			nRooms = _t.rooms.length;
		// hide/show a.delete
		$('a.delete', _t.domEl)[(nRooms === 1 && !_t.togglerCheck)? 'hide' : 'show']();
		// hide/show p.add-room
		$('p.add-room', _t.domEl)[(nRooms === _t.maxRoomQuantity)? 'hide' : 'show']();
		// input value and trigger change event for the parent form to listen
		$('input[name=roomQuantity]',_t.domEl).val(nRooms);
		if (boolTrigger !== false) {
			$(_t.domEl).trigger('change');	
		}
	}
});

/**
 * Individual room to be passed to RoomConfigBuilder.registerRoomConfig
 * @param {Object} domEl
 */
window.RoomConfig = Class.extend({
	init: function (domEl) {
		var _t = this;
		_t.domEl = domEl;
		_t.index,
		_t.$title = $('h4', _t.domEl),
		_t.$adults   = $('label.book-adults select'  , _t.domEl);
		_t.$children = $('label.book-children select', _t.domEl);
		_t.configPossibilities = [];
		_t.minAdults = Infinity;
		_t.maxAdults = 0;
		_t.maxChildren = 0;
		_t.maxBabies = 0;
		_t.maxChildPlusBaby = 0;
		_t.babyMaxAge = parseInt($( _t.domEl).closest('fieldset').find('input.max-baby-age').val(), 10) || 2; 
		
		// init icons and children
		_t.setOccupationIcons();
		_t.setChildrenQuantity(parseInt(_t.$children.val(), 10));
		
		// events
		$('label select', _t.domEl).bind('change', function () {
			_t.setOccupationIcons();
		});
		_t.$adults.bind('change', function () {
			_t.setChildrenPossibilities();
		});
		_t.$children.bind('change', function () {
			_t.setChildrenQuantity(parseInt(_t.$children.val(), 10));
		});
		$(_t.domEl).delegate('select', 'change', function () {
			_t.setError(!_t.checkConfig());
		});
	},
	setRoomIndex: function (nIndex) {
		var _t = this;
		_t.index = nIndex;
		// title number
		_t.$title.html(_t.$title.html().replace(/\d+/g, _t.index + 1));
		// input names
		$('select', _t.domEl).each(function (n) {
			var aReplace = [this.name.replace(/(_\d)+$/g, ''), nIndex];
			if (n > 1) {
				// if n > 1 we are in the children ages select
				aReplace.push(n - 2);
			}
			this.name = aReplace.join('_');
		});
		return _t;
	},
	setOccupationIcons: function () {
		var _t = this,
			nAdults   = _t.$adults.val(),
			nChildren = _t.$children.val();
		_t.$title.find('span').remove();
		for (i = 0; i < nAdults; ++ i) {
			_t.$title.append('<span class="adult-icon"></span>');
		}
		for (i = 0; i < nChildren; ++ i) {
			_t.$title.append('<span class="child-icon"></span>');
		}
	},
	setChildrenQuantity: function (nQ) {
		var _t = this,
			$container = $('div.book-children-ages', _t.domEl),
			$current = $container.find('select'),
			nCurLength = $current.length,
			aTempHtml,
			i, j;
		// check visibility
		$container[nQ === 0 ? 'hide' : 'show']();
		
		
		
		
		if (nQ < nCurLength) {
			$current.eq(nQ).nextAll().andSelf().remove();
		}
		else  if (nQ > nCurLength) {
			for (i = nCurLength; i < nQ; ++i) {
				aTempHtml = [];
				aTempHtml.push('<select name="childAge_', _t.index, '_', i, '">');
				for (j = -1; j <= 12; ++j) {
					if (j === -1) {
						aTempHtml.push('<option value=""> </option>');
					}
					else if (
						(_t.maxChildren > 0 && j > _t.babyMaxAge ) ||
						(_t.maxBabies > 0 && j <= _t.babyMaxAge )
					) {
						aTempHtml.push('<option value="', j, '">', j === 0 ? '<1' : j, '</option>');
					}
				}
				aTempHtml.push('</select>');
				$container.append(aTempHtml.join(''));
				
				$container.children().last().rules('add', {
					required: true
				});
			}
		}
	},
	setConfigPossibilities: function (aPossib) {
		var _t = this;
		_t.configPossibilities = aPossib;
		_t.minAdults = Infinity;
		_t.maxAdults = 0;
		// if aPossib is empty we ought to stop here to avoid the destruction of the form
		if (!aPossib || !aPossib.length) return false;
		// if not, begin iterating to find out min and max adults
		$.each(aPossib || [], function (index, oPossib) {
			_t.minAdults 		= Math.min(_t.minAdults, oPossib.adults);
			_t.maxAdults 		= Math.max(_t.maxAdults, oPossib.adults);
		});
		// cap adults options
		if (parseInt(_t.$adults.val(), 10) > _t.maxAdults) {
			_t.$adults.val(_t.maxAdults).trigger('change');
		}
		if (parseInt(_t.$adults.val(), 10) < _t.minAdults) {
			_t.$adults.val(_t.minAdults).trigger('change');
		}
		var indexSelected;
		_t.$adults.find('option:selected').each(function (index) {
			indexSelected = $(this).text();
		});
		_t.$adults.children().remove();
		for(var index = _t.minAdults; index <= _t.maxAdults; index++){
			$option = $('<option />'),
			$option.text(index);
			if(indexSelected && indexSelected == index){
				$option.attr("selected", "selected");
			}
			_t.$adults.append($option);
		}
		
		// proceed to children
		_t.setChildrenPossibilities();
	},
	setChildrenPossibilities: function () {
		var _t = this;
		_t.maxChildren = 0;
		_t.maxBabies = 0;
		_t.maxChildPlusBaby = 0;
		$.each(_t.configPossibilities || [], function (index, oPossib) {
			if (oPossib.adults == parseInt(_t.$adults.val(), 10)) {
				_t.maxChildren 		= Math.max(_t.maxChildren, oPossib.kids);
				_t.maxBabies 		= Math.max(_t.maxBabies, oPossib.babies);
				_t.maxChildPlusBaby = Math.max(_t.maxChildPlusBaby, oPossib.kids + oPossib.babies);
			}
		});
		
		// enable / disbable
		if (_t.maxChildPlusBaby === 0) {
			_t.$children.attr('disabled', 'disabled');
		}
		else {
			_t.$children.removeAttr('disabled');
		}
		// cap children options
		if (parseInt(_t.$children.val(), 10) > _t.maxChildPlusBaby) {
			_t.$children.val(_t.maxChildPlusBaby).trigger('change');
		}
		var indexSelected;
		_t.$children.find('option:selected').each(function (index) {
			indexSelected = $(this).text();
		});
		_t.$children.children().remove();
		for(var index = 0; index <= _t.maxChildPlusBaby; index++){
			$option = $('<option />'),
			$option.text(index);
			if(indexSelected && indexSelected == index){
				$option.attr("selected", "selected");
			}
			_t.$children.append($option);
		}
		// trigger change to check that the default config is good to go
		$(_t.domEl).trigger('change');
	},
	setError: function (bool) {
		var _t = this;
		$(_t.domEl)[bool ? 'addClass' : 'removeClass']('room-config-error');
	},
	checkConfig: function () {
		var _t = this,
			boolReturn = false,
			currentConfig = {
				'adults':parseInt(_t.$adults.val(), 10),
				'kids': 0,
				'babies': 0
			}
		// find out the current config
		$('div.book-children-ages select', _t.domEl).each(function () {
			if ($(this).val() > _t.babyMaxAge) {
				currentConfig.kids++;
			}
			else if ($(this).val()) {
				currentConfig.babies++;
			}
		});
		// iterate the possible configs to see if one of them is correct
		$.each(_t.configPossibilities, function () {
			boolReturn = this.adults == currentConfig.adults &&
				this.kids == currentConfig.kids &&
				this.babies == currentConfig.babies;
			return !boolReturn;
		});
		return boolReturn;
	}
});


/**
 * 
 */
function synchronizeDatepickers($arrival, $departure) {
	$arrival.datepicker('option', {
		onClose: function (dateText, inst) {
			var date = new Date(inst.currentYear, inst.currentMonth, parseInt(inst.currentDay, 10) + 1)
				currentDeparture = false
			try {
				currentDeparture = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $departure.val());
			} 
			catch (e) {	};
			if (currentDeparture && date > currentDeparture) {
				$departure.datepicker('setDate', date);
				if (typeof $departure.valid === 'function') {
					$departure.valid();
				}
			}else if(!currentDeparture){
				$departure.datepicker('setDate', date);
				if (typeof $departure.valid === 'function') {
					$departure.valid();
				}
			}
		}
	});
	// -- si el primero tiene un valor predeterminado fijamos la fecha minima del segundo
	$departure.datepicker('option', {
		minDate:1,
		beforeShow: function () {
			var date = false;
			try {
				date = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $arrival.val());
			}
			catch (e) {};
			if (date) {
				date.setDate(date.getDate() + 1)
				$departure.datepicker('option', {
					minDate: date
				});
			}
		}
	});
}

HttpCom.extensions.bookingSearchForm = function (scope) {
	var $form = $(scope).is('form') ? scope : $('#book form', scope),
		$destination = $form.find('select, input').filter('.destination'), 
		fDestination,
		$hotel = $form.find('select, input').filter('.hotel'),
		$roomType = $form.find('#book-room-type'),
		$accomType = $form.find('#book-accom-type'),
		roomConfigBuilder, 
		$datepicker = $form.find('input.datepicker'),
		sHtmlRoom = ['<div class="book-room">', $.trim($form.find('div.book-room').eq(0).html()), '</div>'].join(''),
		selectedDest = $form.find('input.selected-destination').val(),
		selectedHotel = $form.find('input.selected-hotel').val();
	
	if ($form.length === 0) return;
	
	// inicializacion del selector de destino
	if ($destination.length) {
		$destination.bind('change', fDestination = function(event){
			var $t = $(this), sDestination = ['destination-code-', $t.val().toLowerCase()].join(''), $hotels = $hotel.children(), $selectableHotels;
			// reset the hotels to the "all hotels" option
			// event is not defined if the funcion is called through fDestination.call (in the next line outside the event)
			if (event) {
				$hotel.val('');
			}
			
			// mostramos u ocultamos en funcion del valor
			if (!$t.val()) {
				//$hotels.show();
				$hotels.removeAttr('disabled');
			}
			else {
				$hotels.each(function(nIndex){
					var $t = $(this);
					if ($t.hasClass(sDestination) || !$t.val()) {
						$t.removeAttr('disabled');
					}
					else {
						$t.attr('disabled', 'disabled');
					}
				});
			}
			
			// if only two are left visible we select the second and hide the first (all hotels)
			$selectableHotels = $hotels.filter(':not([disabled])');
			if ($selectableHotels.length === 2) {
				$selectableHotels.get(1).selected = 'selected';
				$selectableHotels.eq(0).attr('disabled', 'disabled');
			}
			else if ($hotels.filter(':selected').is('[disabled]')) {
				$hotels.get(0).selected = 'selected';
			}
		});
		fDestination.call($destination.get(0));
	}
	
	// inicializacion del selector de hotel
	if ($hotel.length) {
		$hotel.change(function () {
			var sHotelDestination = $(this).children(':selected').attr('className').replace(/.*destination-code-(\w+)\s?.*/g, '$1');
			if (sHotelDestination && $destination.find(":visible").size()!=0) {
				$destination.children().each(function () {
					var $t = $(this);
					if ($t.val().toLowerCase() === sHotelDestination) {
						$t.attr('selected', 'selected');
						$form.validate().element($destination);
						return false;
					}
				});	
			}
		});	
	}
	
	// validacion del form
	$form.validate({
		focusInvalid: false,
		focusCleanup: true
	});
	
	$datepicker.each(function(index) {
		var $t = $(this);
		$t.rules('add', {
			required:function () {
				return Boolean($datepicker.eq( 1 - index ).val());
			}
		});
		if (index === 1) {
			$t.rules('add', {
				laterThan:$datepicker.get(0)
			});
		}
	});
	// el evento de validacion se debe llamar otra vez, porque al hacer blur esta aun el valor antiguo
	$datepicker.bind('blur', function () {
		$datepicker.valid();
	}).datepicker('option', {
		onSelect: function () {
			$(this).closest('form').change();
			$datepicker.valid();
		}
	});
	
	// these JS must be executed after validation to prevent errors from unexisting validator
	// synchronize datepicker fields
	synchronizeDatepickers($datepicker.eq(0), $datepicker.eq(1));
	
	// add RoomConfigBuilder
	if ($form.find('div.book-room-config-builder').length) {
		roomConfigBuilder = new RoomConfigBuilder($form.find('div.book-room-config-builder').get(0), $form.find('fieldset').eq(0).find('input[type=checkbox]').get(0));
		// avoid submission if there is an error
		$form.bind('submit', function () {
			if ($('div.book-config-builder-explanation', roomConfigBuilder.domEl).is(':visible')) {
				return false;
			}
		});
	}
	
	// reset form fields and load AJAX config
	// assign destination select
	if ($destination.length) {
		$destination.data('cache', $destination.val())	// cache
		.children(':not([value=""])').remove();			// reset options
	}
	// assign hotel select
	if ($hotel.length) {
		$hotel.data('cache', $hotel.val())		// cache
		.children(':not([value=""])').remove();	// reset options		
	}
	// init roomType select
	if ($roomType.length) {
		$roomType.children(':not([value=""])').remove();
	}
	// assign accomType select
	if ($accomType.length) {
		$accomType.data('cache', $accomType.val())	// cache
		.children(':not([value=""])').remove();		// reset options
	}
	var lang = $('input[name=lang]').val();
	// once all the setup is ready we must load the JSON config object and set the options
	$.ajaxSetup( {
	    cache : false
	});
	$.ajax({
		url: '/'+lang+'/CallManager?call=search_engine&ctx=presentation',
		data: $form.serialize(),
		error: function () {
			fancyAlert(reserva_error_title, reserva_error_call, "");
		},
		success: function (oResponse, xhr) {
			var json = oResponse.result,
				data = json.dataResponse,
				aDestinations;
			if (data && json.returnCode !== 0 || (typeof json.errorMessages === 'array' && json.errorMessages[0])) {
				alert(json.errorMessages.join('\n'));
				return false;
			}
			// assign vars (in case routes change)
			aDestinations = data.destinations[0].destination;
			aAccomTypes = data.mealPlans[0].mealplan;
			aDefaultPaxconfs = data.paxconfs[0].paxconf;
			
			if(aDestinations){
				if (!aDestinations[0]) aDestinations = [aDestinations];
			}
			if (!aAccomTypes[0]) aAccomTypes = [aAccomTypes];
			if (!aDefaultPaxconfs[0]) aDefaultPaxconfs = [aDefaultPaxconfs];
			
			// populate $destination
			if(aDestinations){
				$.each(aDestinations, function () {
					var oDestination = this,
						$option = $('<option />');
					$option.attr('value', oDestination.code)
					.text(oDestination.title);
					$destination.append($option);
				});
			}
			$destination.val(selectedDest);
			$destination.data('cache', $destination.val());
			
			// populate $hotel (move into destination?)
			$hotel.data('paxconf', aDefaultPaxconfs);
			if(aDestinations){
				$.each(aDestinations, function () {
					var oDestination = this,
						aHotels = oDestination.hotels[0].hotel;
					if (!aHotels[0]) aHotels = [aHotels];
					
					$.each(aHotels, function () {
						var oHotel = this,
							$option = $('<option />'),
							aPaxConfs,
							aRooms;
							
						$option.attr('value', oHotel.code)
						.addClass(['destination-code-', oDestination.code.toLowerCase()].join(''))
						.text(oHotel.name);
						if (oHotel.paxconfs) {
							aPaxConfs = oHotel.paxconfs[0].paxconf;
							if(aPaxConfs){
								if (!aPaxConfs[0]) aPaxConfs = [aPaxConfs];
								$option.data('paxconf', aPaxConfs);
							}
						}
						if (oHotel.rooms) {
							aRooms = oHotel.rooms[0].room;
							if(aRooms){
								if (!aRooms[0]) aRooms = [aRooms];
								$option.data('rooms', aRooms);
							}
						}
						$hotel.append($option);
					});
	
				});
			}
			$hotel.val(selectedHotel);
			$hotel.data('cache', $hotel.val());
			
			if ($destination.find(":visible").size()!=0) {
				$destination.rules('add', {
					required: true
				});
			}else{
				if ($hotel.find(":visible").size()!=0) {
					$hotel.rules('add', {
						required: true
					});
				}
			}
			
			// population of $roomType depends on $hotel change
			$hotel.bind('change', function () {
				var $opt = $('option:selected', this);
				$roomType.children(':not([value=""])').remove(); // reset options
				$.each($opt.data('rooms') || [], function () {
					var oRoomType = this,
						$option = $('<option />');
					$option.attr('value', oRoomType.code)
					.text(oRoomType.name);
					$roomType.append($option);
				});
				// besides, we must restrict room uses
				if (roomConfigBuilder) {
					roomConfigBuilder.setConfigPossibilities($opt.data('paxconf') || aDefaultPaxconfs);
				}
			});
			
			// populate $accomType
			$.each(aAccomTypes, function () {
				var oAccomType = this,
					$option = $('<option />');
				$option.attr('value', oAccomType.code)
				.text(oAccomType.name);
				$accomType.append($option);
			});
			$accomType.val($accomType.data('cache'));
			
			// set default config possibilities
			if (window.roomConfigBuilder || roomConfigBuilder) {
				roomConfigBuilder.setConfigPossibilities($hotel.find('option:selected').data('paxconf') || aDefaultPaxconfs);
			}
			// hide both reset and submit
			$form.find('button[type=reset]').hide().closest('form').find('button[type=submit]').hide();
		}
	});
	
	// definimos evento del reset (de haberlo)
	$form.find('button[type=reset]').click(function () {
		roomConfigBuilder.reset();
		$form.find('button').filter('[type=reset],[type=submit]').hide();
		$form.find('label.error').remove();
		$form.find('.error').removeClass('error');
	})
	// if reset exists we add a change event to show that bubbles to $form ...
	// (note that if propagation of the event is cancelled this event won't trigger)...   
	.hide().closest('form').bind('change', function () {
		$(this).find('button').filter('[type=reset],[type=submit]').show();
	})
	// and hide both reset and submit
	.find('button[type=submit]').hide();
};


function fancyAlert(msg1, msg2, url) {
	jQuery.fancybox({
	'modal' : true,
	'content'  : "<div id=\"fancybox-wrapper\"><div class=\"fancybox-content-header\"><a id=\"fancybox-close\" style=\"display: inline;\" onClick=\"$.fancybox.close()\"></a></div><div class=\"fancybox-main main\"><div class=\"text-content\"><h1>" + msg1 + "</h1><p>" + msg2 + "</p></div></div></div>",
	'onClosed' : function(){
	        if (url != ""){
	                window.location = url;
	        }
	}

	});
}

function sendForm(msgOK, msgERROR, urlDest){
    var str = "";
    var lang = $('input[name=lang]').val();
    var $form = $('form[id='+ $('#formcodeF').val()+ ']');


    $(':input', $form).each(function(i) {
          if ((this.type == 'radio') || (this.type == 'checkbox')) {
               if (this.checked) {
                    str += this.name + "=" + this.value + "&";
               }
          } else {
               str += this.name + "=" + this.value + "&";
          }
    });


        $.ajaxSetup({cache: false});
        $.getJSON( "/" + lang + "/CallManager", {
                        call: "sendForm",
                        ctx: "mail",
                        params         : str,
                        formcode       : $('#formcodeF').val(),
                        formsite       : $('#formsiteF').val()
        },
        function(data){
              if(data!=null && data.result!=null && data.result.dataResponse!=null){
                  if (data.result.dataResponse.$ == 'false'){
                          fancyAlert(msgERROR, msgERROR, urlDest);
                  }
                  else{
                          fancyAlert(msgOK, msgOK, urlDest);
                  }
              }
            }
        );

        return false;
}

function sendFriendEmail(msgOK,msgERROR){

	  jQuery("#main-slider-images").find("li").each(function(){
	                if ($(this).css("display") == "list-item" || $(this).css("display") == "block"){
	                                $('#main-slider-email-imagesrc').val($(this).find("img").attr("src"));
	                }
	  });

	  var lang = $('input[name=lang]').val();
	           $.ajaxSetup({cache: false});
	           $.getJSON( "/" + lang + "/CallManager", {
	                        call: "sendToFriend",
	                        ctx: "mail",
	                        nameSender  : $('#main-slider-email-yname').val(),
	                        nameFriend  : $('#main-slider-email-hname').val(),
	                        mailTo          : $('#main-slider-email-email').val(),
	                        imgURL          : $('#main-slider-email-imagesrc').val(),
	                        message     : $('#main-slider-email-message').val(),
	                        formcode        : $('#formcode').val(),
	                        formsite        : $('#formsite').val()
	           },
	            function(data){
	              if(data!=null && data.result!=null && data.result.dataResponse!=null){
	                  if (data.result.dataResponse.$ == 'false'){
	                	   fancyAlert(msgERROR, msgERROR,"");	                        
	                  }
	                  else{
	                	   fancyAlert(msgOK, msgOK,"");	                       
	                  }
	              }
	            }
	          );

	 return false;
}

function subscribe(subscriptionOK, alreadySubscribed,subscriptionKO){
	var lang = $('input[name=lang]').val();
	$.ajaxSetup({ 
        accepts: "UTF-8",
        contentType: "application/json; charset=utf-8"
	});
	
	$.ajax({
		url: '/' + lang + '/CallManager?call=subscribe&ctx=newsletter',
		data: $('#subscribe').serialize(),
		error: function () {
			alert(subscriptionKO);
		},
		success: function (oResponse, xhr) {
			var json = oResponse.result,
				data = json.dataResponse;
			if (data && json.returnCode !== 0 || (typeof json.errorMessages === 'array' && json.errorMessages[0])) {
				if (json.errorMessages[0].string === 'WARN_USER_SUBSCRIBED') {
					alert(alreadySubscribed);
				}
				return false;
			}else{
				alert(subscriptionOK);
			}
		}
	});
}


