$(document).ready(function() {

	fitHeight();
	
	/* SEARCH BAR */
	$('#req-search').keyup(function(event) {
		var input = $(this);
		var q = input.val();//.replace(/^\s+/g,'').replace(/\s+$/g,'');
		var elem = $('#suggestionsList');
		var $searchTimeout;
		
		if(q.length == 0) {
			elem.html("");
			return;
		}
		
		if($searchTimeout != undefined)
			clearTimeout($searchTimeout);
			
		$searchTimeout = setTimeout(function() {
			$searchTimeout = undefined;
			params = "controller=home&suggest=1&query=" + q;
			elem.html('<div style="text-align:center;padding:10px 0"><img src="/images/interface/load.gif" /><br />Recherche en cours...</div>');
			$.ajax({ mode : 'abort', port : 'ajaxSuggestions', type : 'POST', url : '/', data : params, success : function(msg) {
				if(msg.length > 0 && input.val().length > 0) {
					//var reg = new RegExp("(" + q + ")(?![^';]*';)", "gi");
					//msg = msg.replace(reg, "<span style='color:blue'>$1</span>");
					elem.html(msg);
				}
				else if(input.val().length > 0)
					elem.html('<div class="suggest-noresult">La recherche rapide n\'a pas permis de trouver du contenu en rapport avec le terme recherché. <a id="more-results">Plus de résultats</a></div>');
				else
					elem.html("");
			}});
		}, 500);
	});
	
	$('#more-results').live('click', function() {
		$('#search-form').append('<input type="hidden" name="level2" value="1" />');
		$('#req-submit').trigger('click');

	});
	/* END SEARCH BAR */
	
	/* MOVIE POP UP TOOLBOX */
	var lastScroll;

	function autoScroll(elem, ch) {
		var scrollable = scrollableElement('html', 'body');
		var top = elem.viewportOffset().top;
		var bottom_cover = top + ch;
		var wh = window.innerHeight;
		var eh = 194;
		var diff = wh - bottom_cover;
		if(eh  > diff && elem != lastScroll) {
			$(scrollable).stop().animate({scrollTop : ($(scrollable).scrollTop() + (eh-diff))}, 800);
			lastScroll = elem;
		}
		else if (top < 0) {
			$(scrollable).stop().animate({scrollTop : ($(scrollable).scrollTop() + top - 20)}, 800);
			lastScroll = elem;
		}
		return;
	}
	
	$('.movie').hover(
		function() {
			if($(this).children('.moviepop').length > 0)
				return;
			var pop_container = $('<div class="moviepop"/>');
			if($(this).attr('top')) pop_container.css('top', $(this).attr('top') + 'px');
			if($(this).attr('left')) pop_container.css('left', $(this).attr('left') + 'px');
			var pop_content = $('<div class="pop"/>');
			var title = ($(this).attr('movtitle').toString()).length < 33 ? $(this).attr('movtitle') : $(this).attr('movtitle').substr(0,30) + '...';
			pop_content.html('<p class="pop-title"><a href="' + $(this).children('a').attr('href') + '">' + title +
							 '</a></p><div class="pop-content"><div style="text-align:center"><br /><br /><img src="/images/interface/load.gif" style="height:16px !important; width:16px !important" /></div></div>');
			pop_container.append(pop_content);
			$(this).append(pop_container);
			var param = 'controller=movie&moviepop=1&movieid=' + $(this).attr('movid') + '&movratings=1';
			$(".moviepop").show(50, function() {
				$.ajax({ type: "POST", url: "/", data: param, success: function(msg){
					$('.pop-content').html(msg);
				}});
			});
		//	autoScroll($(this), $(this).children(':first-child').children(':first-child').height());
		},
		function() {
			var elem = $(this).children('.moviepop');
			elem.remove(); //elem.stop().fadeOut(100, function() { elem.remove(); });
		}
	);
	
	$(".pop-back-arrow").live('click', function() {
		$('.pop-content').html('<div style="text-align:center"><br /><br /><img src="/images/interface/load.gif" style="height:16px !important; width:16px !important" /></div>');
		var movid = $(this).parents('.movie').attr('movid');
		var movratings = $(this).parents('.movie').attr('movratings');
		var param = 'controller=movie&moviepop=1&movieid=' + movid + '&movratings=1';
		$.ajax({ type: "POST", url: "/", data: param, success: function(msg){
			$('.pop-content').stop().hide().html(msg).show(100);
		}});
	});
	
	$(".popupmedia").live('click', function() {
		var elem = $(this);
		params = "controller=list&add_movie_to_media=1&media=" + elem.attr("media") + "&mov_id=" + elem.attr("movieid");
		medianame = elem.attr("medianame");
		elem.html('<img src="/images/interface/load.gif" style="height:10px !important; width:10px !important" />');
		$.ajax({ type: "POST", url: "/", data: params, success: function(msg) {
				if(msg == "true") {
					elem.html(elem.attr("medianame"));
					if(!elem.hasClass("selected")) {
						elem.addClass("selected");
					} else if(elem.hasClass("selected")) {
						elem.removeClass("selected");
					}
				}
				else {
					elem.html(elem.attr("medianame"));
					alert(msg);
				} 
		}});
	});
	/* END MOVIE POP UP TOOLBOX */

	/* MOVIE PRELOADED AJAX BACKGROUND */
	function background(mov_id) {
		full = (screen.width >= 1920) ? 1 : 0;
		ajax_bg("controller=movie&load_background=1&mov_id="+mov_id+"&full="+full);
	}

	(function($) {
		var imgList = [];
		$.extend({
			preload: function(imgArr, option) {
				var setting = $.extend({
					init: function(loaded, total) {},
					loaded: function(img, loaded, total) {},
					loaded_all: function(loaded, total) {}
				}, option);
				var total = imgArr.length;
				var loaded = 0;
				
				setting.init(0, total);
				for(var i in imgArr) {
					imgList.push($("<img />")
						.attr("src", imgArr[i])
						//.css("height", (($("body").height()) - 170) + "px")
						.load(function() {
							loaded++;
							setting.loaded(this, loaded, total);
							if(loaded == total) {
								setting.loaded_all(loaded, total);
							}
						})
					);
				}
				
			}
		});
	})(jQuery);

	function ajax_bg(params) {
		$.ajax({ type: "POST", url: "/", data: params, success: function(msg){
			if(msg) {
				$.preload([msg], { loaded: function(img, loaded, total) {
							$("#background").html('<img src="' + msg + '" />');
							$("#background").fadeIn("slow");
						}
				});	
			}
		}});
	}
	/* END MOVIE PRELOADED AJAX BACKGROUND */

	(function($){var a=$(window);$.fn.viewportOffset=function(){var b=$(this).offset();return{left:b.left-a.scrollLeft(),top:b.top-a.scrollTop()}}})(jQuery);

	// use the first element that is "scrollable"
	function scrollableElement(els) {
		for (var i = 0, argLength = arguments.length; i <argLength; i++) {
			var el = arguments[i],
			$scrollElement = $(el);
			if ($scrollElement.scrollTop()> 0) {
				return el;
			} else {
				$scrollElement.scrollTop(1);
				var isScrollable = $scrollElement.scrollTop() > 0;
				$scrollElement.scrollTop(0);
				if (isScrollable) {
					return el;
				}
			}
		}
		return [];
	}
});

function fitHeight() {
		var dheight = $('html').height(),
		cbody = $('#background2').height(),
		wheight = $(window).height(),
		cheight = wheight - dheight + cbody;
			
		if(wheight > dheight)
			$('#background2').height(cheight);
		
		$(window).resize(function() {
			wheight = $(window).height();
			noscroll();
			changepush();
			return;
		});
	
		function noscroll() {
			if(wheight > dheight)
				$('html').addClass('noscroll');
			else if(wheight <= dheight)
				$('html').removeClass('noscroll');
			return;
		}
	
		function changepush() {
			if(wheight > dheight)
				$('#background2').height(wheight-dheight+cbody);
			return;
		}
	}

/**
 * Ajax Queue Plugin
 */
(function($) {
    var ajax = $.ajax;
    var pendingRequests = {};
 
    $.ajax = function(settings) {
        settings = jQuery.extend(
            settings, 
            jQuery.extend(
                {}, 
                jQuery.ajaxSettings, 
                settings
            )
        );	
        var port = settings.port;
 
        switch(settings.mode) {
            case "abort": 
                if ( pendingRequests[port] ) {
                    pendingRequests[port].abort();
                }
                return pendingRequests[port] = ajax.apply(this, arguments);
 
            case "queue": 
                var _old = settings.complete;
                settings.complete = function(){
                    if ( _old )
                        _old.apply( this, arguments );
                    jQuery([ajax]).dequeue("ajax" + port );
                };
 
                jQuery([ ajax ]).queue("ajax" + port, function(){
                    ajax( settings );
                });
                return;
 
            case "dequeue": 
                jQuery([ajax]).dequeue("ajax" + port );
 
                if(jQuery.isFunction(settings.complete))
                    settings.complete(settings);
 
                return;
        }
 
        return ajax.apply(this, arguments);
    };
})(jQuery);

/*

  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

});
*/

