(function ($, document, window) {
    var
    defaults = {
        transition: "elastic",
        speed: 300,
        width: false,
        initialWidth: "600",
        innerWidth: false,
        maxWidth: false,
        height: false,
        initialHeight: "450",
        innerHeight: false,
        maxHeight: false,
        scalePhotos: true,
        scrolling: true,
        inline: false,
        html: false,
        iframe: false,
        fastIframe: true,
        photo: false,
        href: false,
        title: false,
        rel: false,
        opacity: 0.6,
        preloading: true,
        current: "image {current} of {total}",
        previous: "previous",
        next: "next",
        close: "close",
        open: false,
        returnFocus: true,
        loop: true,
        slideshow: false,
        slideshowAuto: true,
        slideshowSpeed: 2500,
        slideshowStart: "start slideshow",
        slideshowStop: "stop slideshow",
        onOpen: false,
        onLoad: false,
        onComplete: false,
        onCleanup: false,
        onClosed: false,
        overlayClose: true,		
        escKey: true,
        arrowKey: true,
        top: false,
        bottom: false,
        left: false,
        right: false,
        fixed: true,
        data: undefined
    },
	
    // Abstracting the HTML and event identifiers for easy rebranding
    colorbox = 'colorbox',
    prefix = 'cbox',
    boxElement = prefix + 'Element',
    
    // Events	
    event_open = prefix + '_open',
    event_load = prefix + '_load',
    event_complete = prefix + '_complete',
    event_cleanup = prefix + '_cleanup',
    event_closed = prefix + '_closed',
    event_purge = prefix + '_purge',
    
    // Special Handling for IE
    isIE = $.browser.msie && !$.support.opacity, // Detects IE6,7,8.  IE9 supports opacity.  Feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome, hence the user-agent test.
    isIE6 = isIE && $.browser.version < 7,
    event_ie6 = prefix + '_IE6',
    
    // Cached jQuery Object Variables
    $overlay,
    $box,
    $wrap,
    $content,
    $topBorder,
    $leftBorder,
    $rightBorder,
    $bottomBorder,
    $related,
    $window,
    $loaded,
    $loadingBay,
    $loadingOverlay,
    $title,
    $current,
    $slideshow,
    $next,
    $prev,
    $close,
    $groupControls,
    
    // Variables for cached values or use across multiple functions
    settings,
    interfaceHeight,
    interfaceWidth,
    loadedHeight,
    loadedWidth,
    element,
    index,
    photo,
    open,
    active,
    closing,
    loadingTimer,
    publicMethod,
    div = "div";

	// ****************
	// HELPER FUNCTIONS
	// ****************
    
	// Convience function for creating new jQuery objects
    function $tag(tag, id, css) {
        var element = document.createElement(tag);
        
        if (id) {
            element.id = prefix + id;
        }
        
        if (css) {
            element.style.cssText = css;
        }
        
        return $(element);
    }

	// Determine the next and previous members in a group.
	function getIndex(increment) {
		var 
		max = $related.length, 
		newIndex = (index + increment) % max;
		
		return (newIndex < 0) ? max + newIndex : newIndex;
	}

	// Convert '%' and 'px' values to integers
	function setSize(size, dimension) {
		return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : $window.height()) / 100) : 1) * parseInt(size, 10));
	}
	
	// Checks an href to see if it is a photo.
	// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
	function isImage(url) {
		return settings.photo || /\.(gif|png|jpe?g|bmp|ico)((#|\?).*)?$/i.test(url);
	}
	
	// Assigns function results to their respective properties
	function makeSettings() {
        var i;
        settings = $.extend({}, $.data(element, colorbox));
        
		for (i in settings) {
			if ($.isFunction(settings[i]) && i.slice(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
			    settings[i] = settings[i].call(element);
			}
		}
        
		settings.rel = settings.rel || element.rel || 'nofollow';
		settings.href = settings.href || $(element).attr('href');
		settings.title = settings.title || element.title;
        
        if (typeof settings.href === "string") {
            settings.href = $.trim(settings.href);
        }
	}

	function trigger(event, callback) {
		$.event.trigger(event);
		if (callback) {
			callback.call(element);
		}
	}

	// Slideshow functionality
	function slideshow() {
		var
		timeOut,
		className = prefix + "Slideshow_",
		click = "click." + prefix,
		start,
		stop,
		clear;
		
		if (settings.slideshow && $related[1]) {
			start = function () {
				$slideshow
					.text(settings.slideshowStop)
					.unbind(click)
					.bind(event_complete, function () {
						if (index < $related.length - 1 || settings.loop) {
							timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
						}
					})
					.bind(event_load, function () {
						clearTimeout(timeOut);
					})
					.one(click + ' ' + event_cleanup, stop);
				$box.removeClass(className + "off").addClass(className + "on");
				timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
			};
			
			stop = function () {
				clearTimeout(timeOut);
				$slideshow
					.text(settings.slideshowStart)
					.unbind([event_complete, event_load, event_cleanup, click].join(' '))
					.one(click, function () {
						publicMethod.next();
						start();
					});
				$box.removeClass(className + "on").addClass(className + "off");
			};
			
			if (settings.slideshowAuto) {
				start();
			} else {
				stop();
			}
		} else {
            $box.removeClass(className + "off " + className + "on");
        }
	}

	function launch(target) {
		if (!closing) {
			
			element = target;
			
			makeSettings();
			
			$related = $(element);
			
			index = 0;
			
			if (settings.rel !== 'nofollow') {
				$related = $('.' + boxElement).filter(function () {
					var relRelated = $.data(this, colorbox).rel || this.rel;
					return (relRelated === settings.rel);
				});
				index = $related.index(element);
				
				// Check direct calls to ColorBox.
				if (index === -1) {
					$related = $related.add(element);
					index = $related.length - 1;
				}
			}
			
			if (!open) {
				open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
				
				$box.show();
				
				if (settings.returnFocus) {
					try {
						element.blur();
						$(element).one(event_closed, function () {
							try {
								this.focus();
							} catch (e) {
								// do nothing
							}
						});
					} catch (e) {
						// do nothing
					}
				}
				
				// +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5'
				$overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show();
				
				// Opens inital empty ColorBox prior to content being loaded.
				settings.w = setSize(settings.initialWidth, 'x');
				settings.h = setSize(settings.initialHeight, 'y');
				publicMethod.position();
				
				if (isIE6) {
					$window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () {
						$overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
					}).trigger('resize.' + event_ie6);
				}
				
				trigger(event_open, settings.onOpen);
				
				$groupControls.add($title).hide();
				
				$close.html(settings.close).show();
			}
			
			publicMethod.load(true);
		}
	}

	// ****************
	// PUBLIC FUNCTIONS
	// Usage format: $.fn.colorbox.close();
	// Usage from within an iframe: parent.$.fn.colorbox.close();
	// ****************
	
	publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
		var $this = this;
		
        options = options || {};
        
		publicMethod.init();
		
		if (!$this[0]) {
			if ($this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit.
                return $this;
            }
            // if no selector was given (ie. $.colorbox()), create a temporary element to work with
			$this = $('<a/>');
			options.open = true; // assume an immediate open
		}
		
		if (callback) {
			options.onComplete = callback;
		}
		
		$this.each(function () {
			$.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options));
			$(this).addClass(boxElement);
		});
		
        if (($.isFunction(options.open) && options.open.call($this)) || options.open) {
			launch($this[0]);
		}
        
		return $this;
	};

	// Initialize ColorBox: store common calculations, preload the interface graphics, append the html.
	// This preps ColorBox for a speedy open when clicked, and minimizes the burdon on the browser by only
	// having to run once, instead of each time colorbox is opened.
	publicMethod.init = function () {
		if (!$box) {
			
			// If the body is not present yet, wait for DOM ready
			if (!$('body')[0]) {
				$(publicMethod.init);
				return;
			}
			
			// Create the markup and append to BODY
			$window = $(window);
			$box = $tag(div).attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''});
			$overlay = $tag(div, "Overlay", isIE6 ? 'position:absolute' : '').hide();
			$wrap = $tag(div, "Wrapper");
			$content = $tag(div, "Content").append(
				$loaded = $tag(div, "LoadedContent", 'width:0; height:0; overflow:hidden'),
				$loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")),
				$title = $tag(div, "Title"),
				$current = $tag(div, "Current"),
				$next = $tag(div, "Next"),
				$prev = $tag(div, "Previous"),
				$slideshow = $tag(div, "Slideshow").bind(event_open, slideshow),
				$close = $tag(div, "Close")
			);
			
			$wrap.append( // The 3x3 Grid that makes up ColorBox
				$tag(div).append(
					$tag(div, "TopLeft"),
					$topBorder = $tag(div, "TopCenter"),
					$tag(div, "TopRight")
				),
				$tag(div, false, 'clear:left').append(
					$leftBorder = $tag(div, "MiddleLeft"),
					$content,
					$rightBorder = $tag(div, "MiddleRight")
				),
				$tag(div, false, 'clear:left').append(
					$tag(div, "BottomLeft"),
					$bottomBorder = $tag(div, "BottomCenter"),
					$tag(div, "BottomRight")
				)
			).find('div div').css({'float': 'left'});
			
			$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none');
			
			$('body').prepend($overlay, $box.append($wrap, $loadingBay));
			
			// Cache values needed for size calculations
			interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6
			interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
			loadedHeight = $loaded.outerHeight(true);
			loadedWidth = $loaded.outerWidth(true);
			
			// Setting padding to remove the need to do size conversions during the animation step.
			$box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide();
			
			// Setup button events.
			// Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.
			$next.click(function () {
				publicMethod.next();
			});
			$prev.click(function () {
				publicMethod.prev();
			});
			$close.click(function () {
				publicMethod.close();
			});
			
			$groupControls = $next.add($prev).add($current).add($slideshow);
			
			$overlay.click(function () {
				if (settings.overlayClose) {
					publicMethod.close();
				}
			});
			
			// Set Navigation Key Bindings
			$(document).bind('keydown.' + prefix, function (e) {
				var key = e.keyCode;
				if (open && settings.escKey && key === 27) {
					e.preventDefault();
					publicMethod.close();
				}
				if (open && settings.arrowKey && $related[1]) {
					if (key === 37) {
						e.preventDefault();
						$prev.click();
					} else if (key === 39) {
						e.preventDefault();
						$next.click();
					}
				}
			});
		}
	};
	
	publicMethod.remove = function () {
		$box.add($overlay).remove();
		$box = null;
		$('.' + boxElement).removeData(colorbox).removeClass(boxElement);
	};

	publicMethod.position = function (speed, loadedCallback) {
        var top = 0, left = 0, offset = $box.offset();
        
        $window.unbind('resize.' + prefix);

        // remove the modal so that it doesn't influence the document width/height        
        $box.css({top: -99999, left: -99999});

        if (settings.fixed && !isIE6) {
            $box.css({position: 'fixed'});
        } else {
            top = $window.scrollTop();
            left = $window.scrollLeft();
            $box.css({position: 'absolute'});
        }

		// keeps the top and left positions within the browser's viewport.
        if (settings.right !== false) {
            left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0);
        } else if (settings.left !== false) {
            left += setSize(settings.left, 'x');
        } else {
            left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
        }
        
        if (settings.bottom !== false) {
            top += Math.max($window.height() - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0);
        } else if (settings.top !== false) {
            top += setSize(settings.top, 'y');
        } else {
            top += Math.round(Math.max($window.height() - settings.h - loadedHeight - interfaceHeight, 0) / 2);
        }
        
        $box.css({top: offset.top, left: offset.left});
        
		// setting the speed to 0 to reduce the delay between same-sized content.
		speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed || 0;
        
		// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
		// but it has to be shrank down around the size of div#colorbox when it's done.  If not,
		// it can invoke an obscure IE bug when using iframes.
		$wrap[0].style.width = $wrap[0].style.height = "9999px";
		
		function modalDimensions(that) {
			// loading overlay height has to be explicitly set for IE6.
			$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
			$loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
		}
		
		$box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, {
			duration: speed,
			complete: function () {
				modalDimensions(this);
				
				active = false;
				
				// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
				$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
				$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
				
				if (loadedCallback) {
					loadedCallback();
				}
                
                setTimeout(function () {  // small delay before binding onresize due to an IE8 bug.
                    $window.bind('resize.' + prefix, publicMethod.position);
                }, 1);
			},
			step: function () {
				modalDimensions(this);
			}
		});
	};

	publicMethod.resize = function (options) {
		if (open) {
			options = options || {};
			
			if (options.width) {
				settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
			}
			if (options.innerWidth) {
				settings.w = setSize(options.innerWidth, 'x');
			}
			$loaded.css({width: settings.w});
			
			if (options.height) {
				settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
			}
			if (options.innerHeight) {
				settings.h = setSize(options.innerHeight, 'y');
			}
			if (!options.innerHeight && !options.height) {
				$loaded.css({height: "auto"});
				settings.h = $loaded.height();
			}
			$loaded.css({height: settings.h});
			
			publicMethod.position(settings.transition === "none" ? 0 : settings.speed);
		}
	};

	publicMethod.prep = function (object) {
		if (!open) {
			return;
		}
		
		var callback, speed = settings.transition === "none" ? 0 : settings.speed;
		
		$loaded.remove();
		$loaded = $tag(div, 'LoadedContent').append(object);
		
		function getWidth() {
			settings.w = settings.w || $loaded.width();
			settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
			return settings.w;
		}
		function getHeight() {
			settings.h = settings.h || $loaded.height();
			settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
			return settings.h;
		}
		
		$loaded.hide()
		.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
		.css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'})
		.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
		.prependTo($content);
		
		$loadingBay.hide();
		
		// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
		//$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'});
		
        $(photo).css({'float': 'none'});
        
		// Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
		if (isIE6) {
			$('select').not($box.find('select')).filter(function () {
				return this.style.visibility !== 'hidden';
			}).css({'visibility': 'hidden'}).one(event_cleanup, function () {
				this.style.visibility = 'inherit';
			});
		}
		
		callback = function () {
            var preload, i, total = $related.length, iframe, frameBorder = 'frameBorder', allowTransparency = 'allowTransparency', complete, src, img;
            
            if (!open) {
                return;
            }
            
            function removeFilter() {
                if (isIE) {
                    $box[0].style.removeAttribute('filter');
                }
            }
            
            complete = function () {
                clearTimeout(loadingTimer);
                $loadingOverlay.hide();
                trigger(event_complete, settings.onComplete);
            };
            
            if (isIE) {
                //This fadeIn helps the bicubic resampling to kick-in.
                if (photo) {
                    $loaded.fadeIn(100);
                }
            }
            
            $title.html(settings.title).add($loaded).show();
            
            if (total > 1) { // handle grouping
                if (typeof settings.current === "string") {
                    $current.html(settings.current.replace('{current}', index + 1).replace('{total}', total)).show();
                }
                
                $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next);
                $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous);
				
                if (settings.slideshow) {
                    $slideshow.show();
                }
				
                // Preloads images within a rel group
                if (settings.preloading) {
					preload = [
						getIndex(-1),
						getIndex(1)
					];
					while ((i = $related[preload.pop()])) {
						src = $.data(i, colorbox).href || i.href;
						if ($.isFunction(src)) {
							src = src.call(i);
						}
						if (isImage(src)) {
							img = new Image();
							img.src = src;
						}
					}
                }
            } else {
                $groupControls.hide();
            }
            
            if (settings.iframe) {
                iframe = $tag('iframe')[0];
                
                if (frameBorder in iframe) {
                    iframe[frameBorder] = 0;
                }
                if (allowTransparency in iframe) {
                    iframe[allowTransparency] = "true";
                }
                // give the iframe a unique name to prevent caching
                iframe.name = prefix + (+new Date());
                if (settings.fastIframe) {
                    complete();
                } else {
                    $(iframe).one('load', complete);
                }
                iframe.src = settings.href;
                if (!settings.scrolling) {
                    iframe.scrolling = "no";
                }
                $(iframe).addClass(prefix + 'Iframe').appendTo($loaded).one(event_purge, function () {
                    iframe.src = "//about:blank";
                });
            } else {
                complete();
            }
            
            if (settings.transition === 'fade') {
                $box.fadeTo(speed, 1, removeFilter);
            } else {
                removeFilter();
            }
		};
		
		if (settings.transition === 'fade') {
			$box.fadeTo(speed, 0, function () {
				publicMethod.position(0, callback);
			});
		} else {
			publicMethod.position(speed, callback);
		}
	};

	publicMethod.load = function (launched) {
		var href, setResize, prep = publicMethod.prep;
		
		active = true;
		
		photo = false;
		
		element = $related[index];
		
		if (!launched) {
			makeSettings();
		}
		
		trigger(event_purge);
		
		trigger(event_load, settings.onLoad);
		
		settings.h = settings.height ?
				setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
				settings.innerHeight && setSize(settings.innerHeight, 'y');
		
		settings.w = settings.width ?
				setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
				settings.innerWidth && setSize(settings.innerWidth, 'x');
		
		// Sets the minimum dimensions for use in image scaling
		settings.mw = settings.w;
		settings.mh = settings.h;
		
		// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
		// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
		if (settings.maxWidth) {
			settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
			settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
		}
		if (settings.maxHeight) {
			settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
			settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
		}
		
		href = settings.href;
		
        loadingTimer = setTimeout(function () {
            $loadingOverlay.show();
        }, 100);
        
		if (settings.inline) {
			// Inserts an empty placeholder where inline content is being pulled from.
			// An event is bound to put inline content back when ColorBox closes or loads new content.
			$tag(div).hide().insertBefore($(href)[0]).one(event_purge, function () {
				$(this).replaceWith($loaded.children());
			});
			prep($(href));
		} else if (settings.iframe) {
			// IFrame element won't be added to the DOM until it is ready to be displayed,
			// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
			prep(" ");
		} else if (settings.html) {
			prep(settings.html);
		} else if (isImage(href)) {
			$(photo = new Image())
			.addClass(prefix + 'Photo')
			.error(function () {
				settings.title = false;
				prep($tag(div, 'Error').text('This image could not be loaded'));
			})
			.load(function () {
				var percent;
				photo.onload = null; //stops animated gifs from firing the onload repeatedly.
				
				if (settings.scalePhotos) {
					setResize = function () {
						photo.height -= photo.height * percent;
						photo.width -= photo.width * percent;	
					};
					if (settings.mw && photo.width > settings.mw) {
						percent = (photo.width - settings.mw) / photo.width;
						setResize();
					}
					if (settings.mh && photo.height > settings.mh) {
						percent = (photo.height - settings.mh) / photo.height;
						setResize();
					}
				}
				
				if (settings.h) {
					photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px';
				}
				
				if ($related[1] && (index < $related.length - 1 || settings.loop)) {
					photo.style.cursor = 'pointer';
					photo.onclick = function () {
                        publicMethod.next();
                    };
				}
				
				if (isIE) {
					photo.style.msInterpolationMode = 'bicubic';
				}
				
				setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise.
					prep(photo);
				}, 1);
			});
			
			setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise.
				photo.src = href;
			}, 1);
		} else if (href) {
			$loadingBay.load(href, settings.data, function (data, status, xhr) {
				prep(status === 'error' ? $tag(div, 'Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents());
			});
		}
	};
        
	// Navigates to the next page/image in a set.
	publicMethod.next = function () {
		if (!active && $related[1] && (index < $related.length - 1 || settings.loop)) {
			index = getIndex(1);
			publicMethod.load();
		}
	};
	
	publicMethod.prev = function () {
		if (!active && $related[1] && (index || settings.loop)) {
			index = getIndex(-1);
			publicMethod.load();
		}
	};

	// Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
	publicMethod.close = function () {
		if (open && !closing) {
			
			closing = true;
			
			open = false;
			
			trigger(event_cleanup, settings.onCleanup);
			
			$window.unbind('.' + prefix + ' .' + event_ie6);
			
			$overlay.fadeTo(200, 0);
			
			$box.stop().fadeTo(300, 0, function () {
                 
				$box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide();
				
				trigger(event_purge);
				
				$loaded.remove();
				
				setTimeout(function () {
					closing = false;
					trigger(event_closed, settings.onClosed);
				}, 1);
			});
		}
	};

	// A method for fetching the current element ColorBox is referencing.
	// returns a jQuery object.
	publicMethod.element = function () {
		return $(element);
	};

	publicMethod.settings = defaults;
    
	// Bind the live event before DOM-ready for maximum performance in IE6 & 7.
	$('.' + boxElement, document).live('click', function (e) {
        // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt.
        // See: http://jacklmoore.com/notes/click-events/
        if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) {
            e.preventDefault();
            launch(this);
        }
    });

	// Setup ColorBox
	publicMethod.init();

}(jQuery, document, this));


( function( $ ) {
$.scrollFollow = function ( box, options )
	{ 
		// Convert box into a jQuery object
		box = $( box );
		
		// 'box' is the object to be animated
		var position = box.css( 'position' );
		
		function ani()
		{		
			// The script runs on every scroll which really means many times during a scroll.
			// We don't want multiple slides to queue up.
			box.queue( [ ] );
		
			// A bunch of values we need to determine where to animate to
			var viewportHeight = parseInt( $( window ).height() );	
			var pageScroll =  parseInt( $( document ).scrollTop() );
			var parentTop =  parseInt( box.cont.offset().top );
			var parentHeight = parseInt( box.cont.attr( 'offsetHeight' ) );
			var boxHeight = parseInt( box.attr( 'offsetHeight' ) + ( parseInt( box.css( 'marginTop' ) ) || 0 ) + ( parseInt( box.css( 'marginBottom' ) ) || 0 ) );
			var aniTop;
			
			// Make sure the user wants the animation to happen
			if ( isActive )
			{
				// If the box should animate relative to the top of the window
				if ( options.relativeTo == 'top' )
				{
					// Don't animate until the top of the window is close enough to the top of the box
					if ( box.initialOffsetTop >= ( pageScroll + options.offset ) )
					{
						aniTop = box.initialTop;
					}
					else
					{
						aniTop = Math.min( ( Math.max( ( -parentTop ), ( pageScroll - box.initialOffsetTop + box.initialTop ) ) + options.offset ), ( parentHeight - boxHeight - box.paddingAdjustment ) );
					}
				}
				// If the box should animate relative to the bottom of the window
				else if ( options.relativeTo == 'bottom' )
				{
					// Don't animate until the bottom of the window is close enough to the bottom of the box
					if ( ( box.initialOffsetTop + boxHeight ) >= ( pageScroll + options.offset + viewportHeight ) )
					{
						aniTop = box.initialTop;
					}
					else
					{
						aniTop = Math.min( ( pageScroll + viewportHeight - boxHeight - options.offset ), ( parentHeight - boxHeight ) );
					}
				}
				
				// Checks to see if the relevant scroll was the last one
				// "-20" is to account for inaccuracy in the timeout
				if ( ( new Date().getTime() - box.lastScroll ) >= ( options.delay - 20 ) )
				{
					box.animate(
						{
							top: aniTop
						}, options.speed, options.easing
					);
				}
			}
		};
		
		// For user-initiated stopping of the slide
		var isActive = true;
		
		if ( $.cookie != undefined )
		{
			if( $.cookie( 'scrollFollowSetting' + box.attr( 'id' ) ) == 'false' )
			{
				var isActive = false;
				
				$( '#' + options.killSwitch ).text( options.offText )
					.toggle( 
						function ()
						{
							isActive = true;
							
							$( this ).text( options.onText );
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
							
							ani();
						},
						function ()
						{
							isActive = false;
							
							$( this ).text( options.offText );
							
							box.animate(
								{
									top: box.initialTop
								}, options.speed, options.easing
							);	
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
						}
					);
			}
			else
			{
				$( '#' + options.killSwitch ).text( options.onText )
					.toggle( 
						function ()
						{
							isActive = false;
							
							$( this ).text( options.offText );
							
							box.animate(
								{
									top: box.initialTop
								}, 0
							);	
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
						},
						function ()
						{
							isActive = true;
							
							$( this ).text( options.onText );
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
							
							ani();
						}
					);
			}
		}
		
		// If no parent ID was specified, and the immediate parent does not have an ID
		// options.container will be undefined. So we need to figure out the parent element.
		if ( options.container == '')
		{
			box.cont = box.parent();
		}
		else
		{
			box.cont = $( '#' + options.container );
		}
		
		// Finds the default positioning of the box.
		box.initialOffsetTop =  parseInt( box.offset().top );
		box.initialTop = parseInt( box.css( 'top' ) ) || 0;
		
		// Hack to fix different treatment of boxes positioned 'absolute' and 'relative'
		if ( box.css( 'position' ) == 'relative' )
		{
			box.paddingAdjustment = parseInt( box.cont.css( 'paddingTop' ) ) + parseInt( box.cont.css( 'paddingBottom' ) );
		}
		else
		{
			box.paddingAdjustment = 0;
		}
		
		// Animate the box when the page is scrolled
		$( window ).scroll( function ()
			{
				// Sets up the delay of the animation
				$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
				
				// To check against right before setting the animation
				box.lastScroll = new Date().getTime();
			}
		);
		
		// Animate the box when the page is resized
		$( window ).resize( function ()
			{
				// Sets up the delay of the animation
				$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
				
				// To check against right before setting the animation
				box.lastScroll = new Date().getTime();
			}
		);

		// Run an initial animation on page load
		box.lastScroll = 0;
		
		ani();
	};
	
	$.fn.scrollFollow = function ( options )
	{
		options = options || {};
		options.relativeTo = options.relativeTo || 'top';
		options.speed = options.speed || 500;
		options.offset = options.offset || 0;
		options.easing = options.easing || 'swing';
		options.container = options.container || this.parent().attr( 'id' );
		options.killSwitch = options.killSwitch || 'killSwitch';
		options.onText = options.onText || 'Turn Slide Off';
		options.offText = options.offText || 'Turn Slide On';
		options.delay = options.delay || 0;
		
		this.each( function() 
			{
				new $.scrollFollow( this, options );
			}
		);
		
		return this;
	};
})( jQuery );


function IEVersion(){
	return parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf('MSIE')+5), 10);
}
function addCurrency(n) {
	return n + hotelCurrency;
}

	function fliter_1(){
	var hebergeurPush = [];
	var filterValues = [];
	Prixmin = $('Prixmin');
	Prixmax = $('Prixmax');

    filterHebergeur.each(function(hebergeur){
	if (hebergeurPush.indexOf(hebergeur.prix) == -1) {
	hebergeurPush.push(hebergeur.prix);
	}
	});



	filtreMinValue = hebergeurPush.min();
	filterMaxValue = hebergeurPush.max();
	filterValues = hebergeurPush.sortBy(function(n){return n});
	
    Slider = new Control.Slider($$('.handle'), 'filterprix', {
					range : $R(filtreMinValue, filterMaxValue),
					values : filterValues,
					sliderValue : [filtreMinValue, filterMaxValue],
					restricted : true,
					onSlide: function(v) {
						if (v[0] == v[1]) {
							return;
						}
						Prixmin.update(addCurrency(v[0]));
						Prixmax.update(addCurrency(v[1]));
					},
					onChange: function(v) {
						if (v[0] == v[1]) {
							var valueIndex, neareastValue;
							if (filtreMinValue != v[0]) {
								valueIndex = Slider.allowedValues.indexOf(v[0]);
								neareastValue = Slider.allowedValues[valueIndex - 1];
								Slider.setValue(neareastValue, 0);
							}
							if (filterMaxValue != v[1]) {
								valueIndex = Slider.allowedValues.indexOf(v[1]),
								neareastValue = Slider.allowedValues[valueIndex + 1];
								Slider.setValue(neareastValue, 1);
							}
						}
						Prixmin.update(addCurrency(v[0]));
						Prixmax.update(addCurrency(v[1]));
						filtreMinValue = v[0];
						filterMaxValue = v[1];
						resultats_hebergeur();
					}
			    });

    Prixmin.update(addCurrency(filtreMinValue));
	Prixmax.update(addCurrency(filterMaxValue));
	
}

//Initialise le filtre
function filter_zero(){
	$('select_etoile').selectedIndex = 0;
}
//hotel results filter
function resultats_hebergeur() {
	var selectville = $('select_ville'), selectetoile = $('select_etoile'),
		hebergeur_n_afficher = [],etoile_value = 0,hebergeur_afficher = [], ville_value = '' ;

	if (selectetoile.selectedIndex != 0) {
		etoile_value = selectetoile.options[selectetoile.selectedIndex].value;
		etoile_value = parseInt(etoile_value, 10);
	}
	if (selectville.selectedIndex != 0) {
		ville_value = selectville.options[selectville.selectedIndex].text;
	}


	filterHebergeur.each(function(hebergeur){
		if ((hebergeur.etoile == etoile_value || etoile_value == 0) &&
			(hebergeur.ville == ville_value || ville_value == '') &&
			(hebergeur.prix >= filtreMinValue && hebergeur.prix <= filterMaxValue))
		{
			hebergeur_afficher.push($('hebergeur'+hebergeur.id));
		} else {
			hebergeur_n_afficher.push($('hebergeur'+hebergeur.id));
		}
	});

	hebergeur_afficher.invoke('show');
	hebergeur_n_afficher.invoke('hide');


//hide/show demandeDispoTitle



/*  var needToHide = true;
	$('hebergeurnAfficher').childElements().each(function(hebergeur){
		if (hebergeur.visible()) needToHide = false;
	});
	var elementToHide = $$('#right_trie')[1];
	elementToHide.show();
	if (needToHide) elementToHide.hide();

	//ie6 dom refresh
	if (Prototype.Browser.IE) {
		var content = $('#right_liste');
		content.innerHTML = content.innerHTML;
	}
*/


}


var trieHebergeur = {
	trie : function(option) {
		if(option.value == ''){
			return;
		}
		this.right_liste = $('right_liste');
		this.hebergeurnAfficher = $('hebergeurnAfficher');
		this[option.value]();
	},
	croissant : function() {
		this.trie_Hebergeur('desc');
	},
	decroissant : function() {
		this.trie_Hebergeur('asc');
	},
	trie_Hebergeur : function(ty) {
		filterHebergeur = filterHebergeur.sortBy(function(heb){
		return heb['prix'];
		});
		var hebergeur_new = [], hebergeur_clone = filterHebergeur.clone();
		if (ty == 'desc') {
			hebergeur_clone = hebergeur_clone.reverse();
		}

		['right_liste', 'hebergeurnAfficher'].each(function(newh) {
			hebergeur_new[newh] = new Element('div', {
												'id': newh+'Copy',
												'style': 'display:none'
											});
			var prem = true;
			hebergeur_clone.each(function(newa){
				if ($('hebergeur' + newa.id).descendantOf(newh)) {
					var elementClass = '';
					if (prem) {
						elementClass = 'produit_large';
						prem = false;
					} else {
						elementClass = 'produit_large';
					}
					var hotelCopy = new Element('div', {
						'class': elementClass,
						'id': 'hebergeur' + newa.id
					}).update($('hebergeur' + newa.id).innerHTML);
					hebergeur_new[newh].insert(hotelCopy);
				}
			});
			this[newh].update(hebergeur_new[newh].innerHTML);
		}, this);
	},
		opinion : function() {
		var opinionheb, opinionsvalue, hebergeur_new = [];
		['right_liste', 'hebergeurnAfficher'].each(function(newh) {
			if (this[newh]) {
				opinionheb = {};
				opinionsvalue = [];
				hebergeur_new[newh] = new Element('div', {
												'id': newh+'Copy',
												'style': 'display:none'
											});
				var opinion_new = $$('#'+newh+' .cont_note i');

				if (opinion_new.size == 0) {
					return;
				}

				opinion_new.each(function(opinion){
					var heb_id = opinion.up('.produit_large').id;
					heb_id = heb_id.gsub('hebergeur', '');
					heb_id = parseInt(heb_id, 10);
					var opinionvalue = parseInt(opinion.innerHTML, 10);
					if(isNaN(opinionvalue)){
						opinionvalue = 0;
					}
					if (typeof opinionheb[opinionvalue] == 'undefined') {
						opinionheb[opinionvalue] = [];
					}
					opinionheb[opinionvalue].push(heb_id);
					opinionsvalue.push(opinionvalue);
				});
				opinionsvalue = opinionsvalue.uniq();
				opinionsvalue = opinionsvalue.sortBy(function(e){
					return e * -1;
				});

				var first = true;
				opinionsvalue.each(function(opinion){
					opinionheb[opinion].each(function(heb_id){
						if ($('hebergeur' + heb_id).descendantOf(newh)) {
							var elementClass = '';
							if (first) {
								elementClass = 'produit_large';
								first = false;
							} else {
								elementClass = 'produit_large';
							}
							var hotelCopy = new Element('div', {
								'class': elementClass,
								'id': 'hebergeur' + heb_id
							}).update($('hebergeur' + heb_id).innerHTML);
							hebergeur_new[newh].insert(hotelCopy);
						}
					});
				});
				this[newh].update(hebergeur_new[newh].innerHTML);
			}
		}, this);
	}
	}
function myVerifMail(mail) {
	var email = document.getElementById(mail).value;
	var posat = email.indexOf('@');
	var lstposat = email.lastIndexOf('@');
	var longueur = email.length;
	var splitMail = email.split('@');
	var username = splitMail[0];
	var domaine = '';
	var pospt = -1;
	var lstpospt = -1;
	if (posat != -1) {
	  domaine = splitMail[1];
	  pospt = domaine.indexOf('.');
	  lstpospt = domaine.lastIndexOf('.');
	}
	var count = 0;
	var nbErrors = 0;
	var bool = false;

	if (posat == -1) {
	  nbErrors++;
	}
	
	if (posat != lstposat) {
	  nbErrors++;
	}
	
	if (username == '') {
	  nbErrors++;
	}
	
	if (domaine == '') {
	  nbErrors++;
	}
	
	if (pospt == -1 || pospt == 0) {
	  nbErrors++;
	}
	
	if (lstpospt == (domaine.length - 1)) {
	  nbErrors++;
	}
	
	for (var i = 0; i < domaine.length; i++) {
	  var ch = domaine.substring(i, i+1);
	  if (ch == '.')
	    count++;
	}
	
	if (count > 2) {
	  nbErrors++;
	}
	
	if (nbErrors == 0) {
	  bool = true;
	} else {
	  bool = false;
	}
	   return bool;
}

function vemail(email) {
	var regex = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
    return !(email == '' || !regex.test(email));
}
function verif_email(mail) {
	var email = document.getElementById(mail).value;
if(!vemail(email)) {
		return false;
	}
	return true;
}
	
$j(document).ready(function() {



	$j("#submit_news").click(function() {
		if(verif_email("mail")==false) {
						$j("#mail").animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120);

		}else{			

			$j("#mail").css({"border":"1px solid #e6e4d8"});
			var queryString = $j("#form_news").serialize();
			$j.ajax({type: "POST", url: "/news-"+$j(".current").attr('id'), data: queryString, success: function(msg){
				$j("#mail").attr('value','');				

					$j('#newsletter').block({ 
					message: msg, 
					fadeIn: 600, 
					fadeOut: 600, 
					timeout: 3000, 
					showOverlay: false, 
					css: { 
						width: '100%', 
						height: '100%', 
						border: 'none', 
						padding: '5px', 
						backgroundColor: '#EAE7D8', 
 						opacity: .8, 
						color: '#514014'
					}

							  });}});}
							  });




	
	$j('#bookbuttons').click(function(){
 		var total = 0;
						var queryString = $j('.leschambre').serialize();
		  
	  $j.ajax({type: "POST", url: "/bookmar.html", data: queryString, success: function(msg){
		 
		  document.forms['roomsbook'].submit();
			}});
			
			
		 // $j.ajax({type: "POST", url: "/bookmar.html"});
	});
	


	});

	




function openDiv(title, html, width, height) {
	var barHeight = 20;
	_htmlModal = new Control.Modal(false,{
		overlayCloseOnClick: true,
		width: width,
		height: height + barHeight
	});

	_htmlModal.mode = 'named';
	_htmlModal.html = '<div id="maptil" style=" height:'+barHeight+'px;">'+
						'<b class="title">'+title+'</b>'+
						'<a href="javascript:_modalFrame.close();" style="position:absolute; top:2px; right:10px; text-decoration:none; color:#ffffff;"><strong style="font-size:14px; color:#ffffff"> x</strong></a>'+
					'</div>'+html;
	_htmlModal.open();
}

function roomsfram(titl, page, widt, heigh,scr) {


$j.browser.msie&&IEVersion()<=7&&(height+=25);
$j.colorbox({iframe:!0,title:titl,href:page,width:widt,height:heigh,scrolling:scr})
}




function map(title,lien) {
	title = (title == null) ? 'Google Map' : title;
	var queryStr = '';
	roomsfram(title,lien, 700, 410,false);
}







function map_a(idhe, title) {
	title = (title == null) ? 'Google Map' : title;
	var queryStr = '';
	if (idhe > 0) {
		qhe = '?ville='+idhe;
	}
	roomsfram(title, 'emap.php'+qhe, 350, 220,false);
}




function map_(idhe, title) {
	title = (title == null) ? 'Google Map' : title;
	var queryStr = '';
	if (idhe > 0) {
		qhe = '?idhe='+idhe;
	}
	roomsfram(title, 'http://uk.marocrooms.com/emap.php'+qhe, 350, 220,false);
}
 
function map_aa(idhe, title) {
	title = (title == null) ? 'Google Map' : title;
	var queryStr = '';
	if (idhe > 0) {
		qhe = '?ville='+idhe;
	}
	roomsfram(title, 'http://uk.marocrooms.com/emap.php'+qhe, 350, 220,false);
}
function yass_promo(){
	var details_ch=document.getElementById("promo");
 
	 
	
	
	
	if(details_ch.style.display=="block"){
		details_ch.style.display="none";
 
		}else{
	details_ch.style.display="block";
 }
	
	}
function promo_showhide(id){
	var details_ch=document.getElementById(id);
 
	 
	
	
	
	if(details_ch.style.display=="block"){
		details_ch.style.display="none";
 
		}else{
	details_ch.style.display="block";
 }
	
	}





/******************************          script heberger               *************************************/

function getcords(e){
var mouseX = Event.pointerX(e);
var mouseY = Event.pointerY(e);
/*$j('mouseX').value = mouseX;
$j('mouseY').value = mouseY;
*/}




function getTop(){
    var valTop;
    if($j.browser.mozilla || $j.browser.msie || $j.browser.opera ){
        valTop = document.documentElement.scrollTop;
    }else{
        valTop = document.body.scrollTop;
    }

    var divSelect = $('selection_affi');
	
    if (divSelect) {
        if ($('favoriTop')) {
            $('favoriTop').value = valTop;
        }
        if(!$j.browser.mozilla){
            divSelect.setStyle({'top': '0px'});
        }else{
            valTop = 0;
            divSelect.setStyle({'top': valTop+'px'});
        }
    }
	

	
	
	
}










function favoriAnim(){
if($('div_hotel_favorie_add') != null){
$('div_hotel_favorie_add').setStyle({height : ''});
if(parseFloat($('div_hotel_favorie_add').getStyle('height')) >= 200){
$('div_hotel_favorie_add').setStyle({height : '200px'});
}
}
}
Event.observe(window, 'scroll', getTop);
Event.observe(document, 'mousemove', getcords);
document.observe('dom:loaded', function() {
accr = new accordion('selection_affi');
});


var animer_er=1;
function animer(num){
for(i=1;nbr_prd>=i;i++){
		$j("#slider_d_"+i).removeClass("slider_c");
}

$j("#slider_d_"+num).addClass("slider_c");
$j(".slider_m").animate({left:(-(num-1)*174)+"px"},118);
animer_er=num;
}
function next(){
	animer_er=animer_er+1;
	if(animer_er>nbr_prd){
		animer_er=1;
	}
	animer(animer_er);
}

function prev(){
	animer_er=animer_er-1;
	if(1>animer_er){
	
	animer_er=nbr_prd;
	}
	animer(animer_er);
}



function selectLoc(locID,locType, name)
{
	$j('#input_search_hotel').val(name);
	$j('#hotelidSearch').val(locID);
	if(locType=="1"){
	$j('#hotelidSearch2').val(2);
	}else{
	$j('#hotelidSearch2').val(1);
	}$j('#popup_city').hide();
	$j("#send_search").css({"cursor":"pointer"});
	$j('#search_type1').attr('checked', true);
	$j('#search_type1,#search_type2').attr('disabled', false);
}

function   offsetImage(){
if($j("#photos_g")){
	
var img_gr = $j("#photos_g");
var loader_s = $j("#loader_photo");
var loading = $j("<img/>").attr("src", "/img/loader.gif").css({"border":"none", "position":"absolute", "display":"none", "z-index":5}).appendTo(document.body);
$j(".photos_v").mouseover(function(){
var self = $j(this);
$j("#loader_photo").html(loading);
loading.css("display", "block")
petit_updat = self.attr("src").replace("/p_", "/g_");
$j("#photos_g").attr("src", petit_updat)
.load(function(){
loading.css("display", "none")
img_gr.css("opacity", 0.5)
$j(img_gr).animate({
opacity: 1
}, 200)
})
});




		
		
		
		

$j("#btn_n").click(function(e){
//e.preventDefault();
$j("#photos_p").scrollTo({
left: "+=102px",
top: "0px"
}, 400);
});
$j("#btn_p").click(function(e){
//e.preventDefault();
$j("#photos_p").scrollTo({
left: "-=102px",
top:"0px"
}, 400);
});

}
}

function btn_x($num){
$j("#photos_p").removeClass("slider_c");
$j("#photos_p").scrollTo({
left:"+=102px",
top: "0px"
}, 400);
}
		  // Une fois le chargment de la page termin? ...
		  $j(document).ready(function(){
									  
var protoB = Prototype.Browser;
		if (protoB.IE && IEVersion() <= 6) {
		$j("#selection_affi").hide('slow');} else {
		$j("#selection_affi").show();}
					
					
$j( '.votrereservation' ).scrollFollow();
 offsetImage();
        if (location.hash == '#disponibilite') {
        c_onglet('#t_disponibilite');	
		}
		else if (location.hash == '#description') {
 	   $j.scrollTo('.pix_paging', 500);
       c_onglet('#t_description');	
	    }
		else if (location.hash == '#opinion') {
			$j.scrollTo('.pix_paging', 500);
			c_onglet('#t_opinion');
		}
		else if (location.hash == '#map') {
			$j.scrollTo('.pix_paging', 500);
			c_onglet('#t_map');
		}
		
$j("#menu_service,#img_service").click(function() {
  	roomsfram($j(this).attr("title"), '/services_clientele-fr', 500, 550,false);
});
$j("#menu_envoyer").click(function() {
  	roomsfram($j(this).attr("title"), '/envoyer_a_un_amie.php', 500, 400,false);
});

$j("#menu_facebook").click(function() {

    var pageId = '220961132027',
		cssLink = 'http://marocrooms.com/style.css';
    roomsfram($j(this).attr("title"), 'http://www.facebook.com/connect/connect.php?id='+pageId+'&connections=10&stream=1&css='+cssLink, 320, 620,false);
});
$j("#menu_favoris").click(function(event) {

		var url = location.href;
        var title = $j(this).attr("title");
        if (window.sidebar) { // Mozilla Firefox Bookmark
           window.sidebar.addPanel(title, url,"");
        } else if( window.external ) { // IE Favorite
            window.external.AddFavorite( url, title);
	        } else if(window.opera) { // Opera 7+
            return false; // do nothing - the rel="sidebar" should do the trick
        } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
             alert('Unfortunately, this browser does not support the requested action,'
	             + ' please bookmark this page manually.');
        }

});
/*$j(".submit_re,.bookebutton").click(function() {

if($('nbnight2').innerHTML==""){
	                     $j.scrollTo('.pix_paging', 500);
						 $j('#arrivee2,#depart2').animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: 'white' }, 120);
						selectarrivee(2);
						return false;}
                else{
                $val1 = $j('#hotelid').val();//Caching product object
                $val2 = $j('#arrivee2').val();//Caching product object
                $val3 = $j('#depart2').val();//Caching product object
				$j.ajaxSetup({
				'beforeSend': function(xhr){
				xhr.overrideMimeType('text/html; charset=ISO-8859-1');
				}});			
                 $chambres_dispo = $j('.chambres_dispo');//Caching product object
                $chambres_message =  $j('#chambres_message');//Caching ajaxMessage object
                $chambres_message.css({display:'block'});
                $chambres_dispo.find('.leschambre').css({opacity:.2});
				$chambres_dispo.load('/chambres_dispo.php?id='+$val1+'&lang='+$j(".current").attr('id')+'&date1='+$val2+'&date2='+$val3,'',function(){
				$chambres_message.css({display:'none'});
                });
				return false;
				}

	});	
	*/	  
$j("#top").click(function() {
			$j.scrollTo('#main', 500);
			return false;
});
$j("#link_map").click(function() {
			$j.scrollTo('.pix_paging', 500);
			c_onglet('#t_map');
			return false;
});
$j("#link_opinion").click(function() {
			$j.scrollTo('.pix_paging', 500);
			c_onglet('#t_opinion');
			return false;
});
$j("#link_description").click(function() {
			$j.scrollTo('.pix_paging', 500);
			c_onglet('#t_description');
			return false;
});
function c_onglet($ong){
$j(".active").removeClass("active");
$j($ong).addClass("active");
$j(".content").slideUp();
var contenu_aff = $j($ong).attr("title");
$j("#" + contenu_aff).slideDown();	  





}
	  
		  
			// Lorsqu'un lien a.tab est cliqu?
			$j("a.tab").click(function () {		
				// Mettre toutes les onglets non actif
				$j(".active").removeClass("active");
				
				// Mettre l'onglet cliqu? actif
				$j(this).addClass("active");
				
				// Cacher les bo?tes de contenu
				$j(".content").slideUp();
				
				// Pour afficher la bo?te de contenu associer, nous
				// avons modifier le titre du lien par le nom de
				// l'identifiant de la boite de contenu
				var contenu_aff = $j(this).attr("title");
				$j("#" + contenu_aff).slideDown();	  
			});


$j("#input_search_hotel").autocomplete(hotelNames, {
            delay:10,
			minChars:0,
			matchSubset:1,
			matchContains: "word",
		autoFill:false,
			maxItemsToShow:20,
			selectOnly:1,
			selectFirst:1,
			width: 300,
		formatItem: function(row, i, max) {
			return row.name + "<i>(" + row.city + ")</i>";			
		},
		formatMatch: function(row, i, max) {			
			return row.name+'_'+row.id+'_'+row.ville;
		},
		formatResult: function(row) {
			return row.name;
		}
		})
		.click(
		function(){
		if($j(this).attr('value') ==$j(this).attr('title')){
		$j(this).val('');
		}}
		)
		.blur(
		function(){
		if($j(this).attr('value') ==''){
		$j(this).val($j(this).attr('title'));
		}}
		);


	$j("#popup_city_wih").click(function(){
		$j("#popup_city").toggle();
	});	

	$j("#popup_city .close,#input_search_hotel").click(function(){
		$j("#popup_city").hide();
	});


	function log(event, data, formatted) {
	
		if(!data){

		}
		else{
			var str = formatted.split('_');
			$j("#hotelidSearch").val(str[1]);
			$j("#hotelidSearch2").val(str[2]);
			//$j("#hotelidSearch").val(0);
 	        if(str[2]=="1"){
			$j('#search_type1').attr('checked', true);
			$j('#search_type1,#search_type2').attr('disabled', false);
			}else{
			$j('#search_type1,#search_type2').attr('checked', false); 
			$j('#search_type1,#search_type2').attr('disabled', true);
            }
		}
	}
	$j("#input_search_hotel").result(log);
		
	
		$j("#hotelsearch").submit(function()
	{
		$j(this).prev().search();
	
	if($j("#hotelidSearch").val()==0){
		$j('#input_search_hotel').animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
			.animate( { backgroundColor: 'white' }, 120)
			.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
			.animate( { backgroundColor: 'white' }, 120);
	 		return false; //not to post the  form physically

}
	else{
		
		
		
		
		$j("#verif").removeClass().addClass('messagebox').text('').fadeIn(1000);
		$j.post("/search-"+$j(".current").attr('id'),{ hotel1:$j('#hotelidSearch').val(),date1:$j('#arrivee1').val(),date2:$j('#depart1').val(),hotel2:$j('#hotelidSearch2').val(),type1:$j('input[type=radio][name=search_type]:checked').val()} ,function(data)
        {
			var data1 = data.split('_');
//alert(data1[1]);
		  if(data1[1]=='yes') //if correct login detail
		  {
			$j("#verif").fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $j(this).html(data1[2]).removeClass('messagebox').addClass('messageboxok').fadeTo(900,1,
              function()
			  { 
				window.parent.document.location.href =data1[3];
			  });
			});
		  }
		  else 
		  {
		  	$j("#verif").fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $j(this).html(data1[2]).removeClass('messagebox').addClass('messageboxerror').fadeTo(900,1);
			});		
          }
        });
 		return false; //not to post the  form physically
}	});


	
	/*ddddddddddddddddddddddddddddddddddddddddddddddddddddddd*/
	
	
	






























	param_url=document.location.hash;
	if(param_url!=''){
		url_param=param_url.substring(1);
		if(!isNaN(url_param))
			animer(1);
			
	}
	
	

		$j(".vus_img").hover(function(){
 		$j(".vus_supp",this).show();
		},
		function(){
		$j(".vus_supp",this).hide();
		});
		$j(".vus_img .vus_supp").click(function(){
		var id_hotel=$j(this).attr("IDHotel");
						$j('.vus_img[id="' + id_hotel + '"]').fadeTo("slow", 0, function(){
								$j(this).remove();
							});
						if($j("#vus_hotel .vus_supp").length<=1){
		                $j("#vus").fadeTo("slow", 0, function(){
								$j(this).hide();
							});
						}
					$j.get("/recemment-"+id_hotel+".html");
		});


















	$j(".currency a").click(function(){
			var queryString = $j(this).serialize();
			var dev = $j(this).attr('title');
			
			$j.ajax({type: "POST", url: "/currency-"+dev, data: queryString,success: function(msg){
		  if(msg=="yes"){
		 //document.location="index.php";
		 location.reload(true);
		 // document.location=location.href;
		   }}
			});
			
    });
	
	$j("#annulerDate").click(function(){
			var queryString = $j(this).serialize();
			$j.ajax({type: "POST", url: "/datecancel.html", data: queryString,success: function(msg){
		 if(msg=="yes"){
		 location.reload(true);
		   }}
			});
			
    });
		$j("#submit_affiliation").click(function(){
                   boole=true;
		if(document.getElementById("nom").value=="") {
			$j("#nom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#nom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("hotel").value=="") {
			$j("#hotel").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#hotel").css({"border":"1px solid #D1D2D3"});
		}
		if(verif_email("email")==false) {
			$j("#email").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#email").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("tel").value=="") {
			$j("#tel").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#tel").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("ville").value=="") {
			$j("#ville").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#ville").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("site").value=="") {
			$j("#site").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#site").css({"border":"1px solid #D1D2D3"});
		}
		if(boole==true){
			var queryString = $j("#formulaire_services").serialize();
	  $j.ajax({type: "POST", url: "/romaffiliate-"+$j(".current").attr('id'), data: queryString, success: function(msg){
				$j("#nom").attr('value','');				
				$j("#hotel").attr('value','');				
				$j("#email").attr('value','');				
				$j("#tel").attr('value','');				
				$j("#ville").attr('value','');				
				$j("#site").attr('value','');				
				$j("#message").attr('value','');				

$j("#formulaire_services").block({ 
                    message: msg, 
					fadeIn: 700, 
					fadeOut: 700, 
					timeout: 4000, 
					showOverlay: false, 
					css: { 
						width: '40%', 
						height: '200px', 
						border: 'none', 
						padding: '100px', 
						backgroundColor: '#EAE7D8', 
						border: '1px solid #D9D9D5', 
						color: '#514014'
					}
				});
				}
			});
	}
	});
	
		$j("#submit_services").click(function(){
                   boole=true;
		if(document.getElementById("nom").value=="") {
			$j("#nom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#nom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("prenom").value=="") {
			$j("#prenom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#prenom").css({"border":"1px solid #D1D2D3"});
		}
		if(verif_email("email")==false) {
			$j("#email").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#email").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("tel").value=="") {
			$j("#tel").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#tel").css({"border":"1px solid #D1D2D3"});
		}
		if(boole==true){
			var queryString = $j("#formulaire_services").serialize();
	  $j.ajax({type: "POST", url: "/romservices-"+$j(".current").attr('id'), data: queryString, success: function(msg){
				$j("#nom").attr('value','');				
				$j("#prenom").attr('value','');				
				$j("#email").attr('value','');				
				$j("#tel").attr('value','');				
				$j("#sujet").attr('value','');				
				$j("#message").attr('value','');				

$j("#formulaire_services").block({ 
                    message: msg, 
					fadeIn: 700, 
					fadeOut: 700, 
					timeout: 4000, 
					showOverlay: false, 
					css: { 
						width: '40%', 
						height: '200px', 
						border: 'none', 
						padding: '100px', 
						backgroundColor: '#EAE7D8', 
						border: '1px solid #D9D9D5', 
						color: '#514014'
					}
				});
				}
			});
	}
	});
		$j("#submit_transfert").click(function(){
                   boole=true;
		if(document.getElementById("nom").value=="") {
			$j("#nom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#nom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("prenom").value=="") {
			$j("#prenom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#prenom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("vol").value=="") {
			$j("#vol").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#vol").css({"border":"1px solid #D1D2D3"});
		}
		if(verif_email("email")==false) {
			$j("#email").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#email").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("tel").value=="") {
			$j("#tel").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#tel").css({"border":"1px solid #D1D2D3"});
		}
		
		if(document.getElementById("ville").value=="") {
			$j("#ville").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#ville").css({"border":"1px solid #D1D2D3"});
		}
		if($j('input:[name=acceptCondition]:checked').val()!="1") {
			$j("#ConditionAccept").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#ConditionAccept").css({"border":"1px solid #D1D2D3"});
		}
		if(boole==true){
			var queryString = $j("#formulaire_transfert").serialize();
	  $j.ajax({type: "POST", url: "/transferts.html", data: queryString, success: function(msg){
		      	$j("#nom").attr('value','');				
				$j("#prenom").attr('value','');				
				$j("#email").attr('value','');				
				$j("#tel").attr('value','');				
				$j("#vol").attr('value','');				
				$j("#ville").attr('value','');				
				$j("#hotel").attr('value','');				
				$j("#sujet").attr('value','');				
				$j("#message").attr('value','');				


$j("#formulaire_transfert").block({ 
                    message: msg, 
					fadeIn: 700, 
					fadeOut: 700, 
					timeout: 4000, 
					showOverlay: false, 
					css: { 
						width: '40%', 
						height: '200px', 
						border: 'none', 
						padding: '100px', 
						backgroundColor: '#EAE7D8', 
						border: '1px solid #D9D9D5', 
						color: '#514014'
					}
				});
				}
			});
	}
	});
$j(".chambre_titre").click(function() {
  	roomsfram($j(this).attr("title"), '/chambre-'+$j(this).attr("id")+'-'+$j(".current").attr('id'), 520, 590,false);
									});


$j("#comptenv").click(function() {
	$j("#FormCompte").hide('slow');
	$j("#comptemp").show();
                                });
$j("#comptedj").click(function() {
		var user=0;		if(user==0)		
			$j("#FormCompte").show('slow');
		$j("#comptemp").hide();
	                              });
	
$j("#PConditions").click(function() {
ConditionsBook();
});
$j("#checkboxtransfer").click(function() {
$j('#checkboxtransferretour').removeAttr("checked");
check(this,"montant_transfert");
});

$j("#checkboxtransferretour").click(function() {
$j('#checkboxtransfer').removeAttr("checked");
check(this,"montant_tr_transfert");

});



$j("#ulterieur").click(function() {
if($j(this).attr("checked")==true){
$j("#heurearrive,#minarrive,#heuredepart,#mindepart").attr('disabled', true);
}
else{
$j("#heurearrive,#minarrive,#heuredepart,#mindepart").attr('disabled', false);
}
});


		$j("#submit_info").click(function(){
                   boole=true;
		if(document.getElementById("nom").value=="") {
			$j("#nom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#nom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("prenom").value=="") {
			$j("#prenom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#prenom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("tel").value=="") {
			$j("#tel").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#tel").css({"border":"1px solid #D1D2D3"});
		}

		if(document.getElementById("code_postal").value=="") {
			$j("#code_postal").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#code_postal").css({"border":"1px solid #D1D2D3"});
		}

		if(document.getElementById("adresse").value=="") {
			$j("#adresse").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#adresse").css({"border":"1px solid #D1D2D3"});
		}

		if(boole==true){
			
		}
		else {return false;}

	});



		$j("#submit_book").click(function(){
                   boole=true;
		if(document.getElementById("nom").value=="") {
			$j("#nom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#nom").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("prenom").value=="") {
			$j("#prenom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#prenom").css({"border":"1px solid #D1D2D3"});
		}
		if(verif_email("email")==false) {
			$j("#email").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#email").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("tel").value=="") {
			$j("#tel").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#tel").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("city").value=="") {
			$j("#city").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#city").css({"border":"1px solid #D1D2D3"});
		}
		userIn=$j('input:radio[name=user]:checked').val();
		
		if(userIn=="0"){
		if(document.getElementById("passwd").value=="") {
			$j("#passwd").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#passwd").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("passwd2").value=="") {
			$j("#passwd2").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#passwd2").css({"border":"1px solid #D1D2D3"});
		}
		}
		if($j('input:[name=acceptCondition]:checked').val()!="1") {
			$j("#ConditionAccept").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#ConditionAccept").css({"border":"1px solid #D1D2D3"});
		}
		
		
		//alert($j('input:radio[name=user]:checked').val());
		
		if(boole==true){
		/*
		var queryString = $j("#formBook").serialize();
	  $j.ajax({type: "POST", url: "/bookmir.html", data: queryString, success: function(msg){
	
				$j("#nom").attr('value','');				
				$j("#prenom").attr('value','');				
				$j("#email").attr('value','');				
				$j("#tel").attr('value','');				
				$j("#sujet").attr('value','');				
				$j("#message").attr('value','');			

$j("#formBook").block({ 
                    message: msg, 
					fadeIn: 700, 
					fadeOut: 700, 
					//timeout: 44000, 
					showOverlay: false, 
					css: { 
						width: '40%', 
						height: '200px', 
						border: 'none', 
						padding: '100px', 
						backgroundColor: '#EAE7D8', 
						border: '1px solid #D9D9D5', 
						color: '#514014'
					}
				});
				}
			});
			return false;*/
			return true;
	}
	else{return false;}
	});

	$j(".logout").click(function(){
			var queryString = $j(this).serialize();
			$j.ajax({type: "POST", url: "/usercancel.html", data: queryString,success: function(msg){
		 if(msg=="yes"){
		 //location.reload(true);
		 var href = $(this).attr('href');
		window.location= href;
		return false; 

		   }}
			});
			
    });

$j("#recupererPwd").click(function() {
  	roomsfram($j(this).attr("title"),'/oublie-'+$j(".current").attr('id'), 320,180,false);
});
        $j("#booklogin").click(function(){
                   boole=true;		
		if(verif_email("login")==false) {
			$j("#login").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#login").css({"border":"1px solid #D1D2D3"});
		}
		if(document.getElementById("password").value=="") {
			$j("#password").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#password").css({"border":"1px solid #D1D2D3"});
		}
				if(boole==true){
				document.forms['formBook'].submit();
			}
	else{return false;}

		
		});
		
		
		
/**********************  transfert  ***************************/		
		
		
		
	$j("#transfert1,#transfert2").submit(function() {
	
	
	cid=$j(this).attr("cid");
	if($j("#nbr"+cid).val()==0){
		$j("#nbr"+cid).animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
			.animate( { backgroundColor: 'white' }, 120)
			.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
			.animate( { backgroundColor: 'white' }, 120);
	 		return false;
}
	else{
		$j("#Tverif"+cid).removeClass().addClass('messagebox').text('').fadeIn(1000);
		$j.post("/transferts.html",{dep1:$j('#departure'+cid).val(),dep2:$j('#destination'+cid).val(),dep3:$j('#nbr'+cid).val(),dep4:cid} ,function(data)
        {
		  var data1 = data.split('_');
		  if(data1[1]=='yes') //if correct login detail
		  {
			$j("#Tverif"+cid).fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $j(this).html(data1[0]).removeClass('messagebox').addClass('messageboxok').fadeTo(900,1,
              function()
			  { 
			 document.forms['transfert'+cid].submit();
			   });
			});
		  }
		  else 
		  { 
		  	$j("#Tverif"+cid).fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  $j(this).html(data1[0]).removeClass('messagebox').addClass('messageboxerror').fadeTo(900,1);
			});		
          }
        });
 		return false; 
	}


	
	
	
	});


		
$j("#allerRetour").click(function() {
$j("#datesRetour").show('slow');
			$j('table.transfert .allerPrix').each(function() {
						 $j(this).animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#E6E1C9' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#E6E1C9' }, 120);
			            $j(this).html($j(this).attr('prixRetour'));
			            $j('#prix').val($j(this).attr('prixRetour'));
			});





                                });
$j("#allerSimple").click(function() {
	var aller=0;		
		if(aller==0)		
		$j("#datesRetour").hide();
			$j('table.transfert .allerPrix').each(function() {
						 $j(this).animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#E6E1C9' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#E6E1C9' }, 120);
			            $j(this).html($j(this).attr('prixSimple'));
				        $j('#prix').val($j(this).attr('prixSimple'));
		});













});
		
/**********************  transfert  ***************************/		
$j('#like').click(function() {
			var url = $j(this).attr('rel');
			url = url.replace('facebookname', document.title);
			url = url.replace('facebookurl', window.location);
			window.open(url);
		});
		
		

/****************************    rating    ************************************/

	var monitor		=	false;
	
	var marker		=	false;
	var indicator	=	false;
	var buttons		=	false;
	var save		=	false;
	
	// Stop selection while dragging
	/*document.body.ondrag = function () { return false; };
	document.body.onselectstart = function () { return false; }; 
	*/
	var updatePosition = function(e){
		initMarker($j(this).parent());
		var index = parseInt( $j(this).attr('alt').split(" ").pop() );
		var t = Math.ceil(index+1);
		var b = Math.floor(index);
		
		setMarker(t,b);
	}
	
	
	var initMarker = function(parent){
		indicator	=	$j(parent);
		marker		=	$j(".marker",indicator);
		buttons		=	$j(".button",indicator);
		save		=	indicator.parent().find("input[type='hidden']").eq(0);
	}
	
	var setMarker = function(high,low,override)
	{
		if(high < 1)	high	=	0;
		if(high > 10)	high	= 	10;
				
		if(low < 0)		low		=	0;
		if(low > 9)		low		=	9;
				
		buttons.each(function(i){
			if(i < high)	$j(this).attr("src",this.src.replace("-0","-1"));
			else			$j(this).attr("src",this.src.replace("-1","-0"));
		});
		
		if(override!=undefined) high = override;
		
		marker.html(high);
		save.val(high);
		var pos = (low*marker.width())+low;
		
		marker.css("left",pos+"px");
	}
	
	
	var resetMarker = function(node,state)
	{
		var i = $j(".indicator",node);
		
		if(state){
			$j(".hbox-right",node).hide("slow");
		}else{
			$j(".hbox-right",node).show("slow");
		}
		
		initMarker(i);
		setMarker(0,0,"");
	}
	//$j(".indicator .marker").mousedown(startMouse);
	$j(".indicator img").click(updatePosition);

		
	$j("#reset_comment").click(function() {
		var p = $j("table.Tablerating");
		resetMarker(p);
	});
		
	
	$j("#validaccept1").click(function() {
	$j("#validaccept3").hide('slow');
    });
	$j("#validaccept2").click(function() {
	$j("#validaccept3").show('slow');
    });


		$j("#submit_accept").click(function(){
                   boole=true;
		if(document.getElementById("nom").value=="") {
			$j("#nom").css({"border":"1px solid #F93"});
			boole=false;
		}else{
			$j("#nom").css({"border":"1px solid #D1D2D3"});
		}
		if(boole==true){
		return true;
		}
		else{return false;}
	});
		
		
		
		
		
		

			
		
		
		
		

});


function informat(xdiv,zdiv){
			informaLeft = $j('informaLeft');
		var informaLeftSlide = $('informaLeftSlide'),
			topHeight = $('header').getDimensions().height;

		Event.observe(window,'scroll',(function(){
			var protoB = Prototype.Browser;
			if (document.viewport.getScrollOffsets().top >= topHeight) {
				if (protoB.IE && IEVersion() <= 6) {
					informaLeftSlide.style.position = 'relative';
					verticalCenterElem(informaLeft);
				} else {
					informaLeftSlide.style.position = 'fixed';
				}
				informaLeftSlide.style.top = '5px';
				informaLeftSlide.style.width = '193px';
				if (protoB.WebKit) {
					informaLeftSlide.style.marginLeft = '-8px';
				}
			} else {
				informaLeftSlide.style.top = 'auto';
				informaLeftSlide.style.position = 'absolute';
				informaLeftSlide.style.marginLeft = '0';
			}
		}), false);
}


function check(xdiv,zdiv){
if($j(xdiv).attr("checked")==true){
check1(xdiv,zdiv);
$j("#nbrPlace").change(function () {
			if($j(this).attr('value')>3){
                $j('#montant_transfert').html($j('#montant_transfert').attr('prixsup'));
                $j('#montant_tr_transfert').html($j('#montant_tr_transfert').attr('prixsup'));
                check1(xdiv,zdiv);

			}
			else{
			   $j('#montant_transfert').html($j('#montant_transfert').attr('prix'));
			   $j('#montant_tr_transfert').html($j('#montant_tr_transfert').attr('prix'));
			   check1(xdiv,zdiv);
   }
});

}
else{
$j("#div_allee").hide('slow');
$j("#div_retour").hide('slow');
$j(".DivTransfert").hide('slow');
$j("#PrixTransfert").html('');
$j(".PrixTotalTransfert").html(parseFloat($j(".PrixTotalTransfert").attr('prix')));
$j(".PrixDepotTransfert").html(parseFloat($j(".PrixDepotTransfert").attr('prix')));
}
	
	
	
}

function check1(xdiv,zdiv){
if(zdiv=="montant_tr_transfert"){
$j("#div_retour").show('slow');
}
else{$j("#div_retour").hide('slow');
}	
$j("#div_allee").show('slow');
$j(".DivTransfert").show('slow');
$j("#PrixTransfert").html($(zdiv).innerHTML);
$j(".PrixTotalTransfert").html(parseFloat($j(".PrixTotalTransfert").attr('prix'))+parseFloat($(zdiv).innerHTML));
$j(".PrixDepotTransfert").html(parseFloat($j(".PrixDepotTransfert").attr('prix'))+parseFloat($(zdiv).innerHTML));
DivAnimate(".DivTransfert");
DivAnimate(".PrixTotalTransfert");
DivAnimate(".PrixDepotTransfert");
}
function ConditionsBook() {
	//height:333
openDiv(langue['CTitle'], $("bookConditions").innerHTML, 531,'auto');

}
function DivAnimate(xdiv) {
							 $j(xdiv).animate({ backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#F4F2E8' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#F4F2E8' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#F4F2E8' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#F4F2E8' }, 120)
						.animate( { backgroundColor: 'rgb(254,239,131)' }, 120)
						.animate( { backgroundColor: '#F4F2E8' }, 120);

	}




	
	
	
	
	
	
	
	
	
