/*
	Les éléments de classe 'flickr' dans les documents HTML seront remplis via AJAX à l'aide de leur tag a href qui pointent vers les requêtes PHP
*/

var $j = jQuery.noConflict(); // Règle le conflit de jQuery avec Google Maps

$j(document).ready(startFlickrApp);

var req = null;

// MAIN //////////////////////////////////////////////////////////////////////////////////////////
function startFlickrApp () {
	// Loop à travers les éléments remplis via AJAX
	$j.each(
		   		$j("div.flickr"),
				function () {
					populateBox($j(this), false);
				}
			);
	
	$j("div.box_share a.share").mouseover(
		function () {
			$j("div.box_share ul.share_services").css({top:$j(this).position().top, left:$j(this).position().left}).show();
		}
	);
	
	$j("div.box_share ul.share_services").hover(
		function () {
			$j(this).show();
		},
		function () {
			$j(this).hide();
		}
	);
}

// Remplis un élément de classe flickr et déclenche les handlers appropriés
function populateBox (__element, __bypass) {
	var path = __element.find("a.path").attr("href");
	
	path = path.substring(path.indexOf("view_"), path.length); // Bug wackos de IE7
	
	showLoading(__element);
	
	if (__bypass) {
		if (req) req.abort();
	}
	
	req = $j.get	(
					  				SITE_ADDRESS + "/application/views/" + path,
									function (responseText, textStatus, XMLHttpRequest) {
										__element.html(responseText);
										
										hideLoading(__element, path);
										
										if (__element.hasClass("flickr_tooltip")) 					handleTooltip(__element);
										if (__element.hasClass("flickr_mosaique")) 				handleMosaique(__element);
										if (__element.hasClass("flickr_pagination")) 				handlePagination(__element, path);
										if (__element.hasClass("flickr_pagination_simple")) 	handlePaginationSimple(__element, path);
										if (__element.hasClass("flickr_share")) 					handleSelect(__element);
										if (__element.hasClass("flickr_scroller")) 					handleScroller(__element);
										if (__element.hasClass("flickr_droplist")) 					handleDroplist(__element);
										if (__element.hasClass("flickr_tagcloud")) 				handleTagCloud(__element);
										
									}
								);
}

function showLoading (__element) {
	var lastHeight = __element.height();
	__element.addClass("loading").children("*:not(a.path)").remove();
	
	if (lastHeight > 50) __element.height(lastHeight);
}

function hideLoading (__element) {
	__element.removeClass("loading").css("height", "auto");
	
	/*
	// Animation height, marche pas vraiment, bug avec les boîtes <50px
	var lastHeight = __element.height();
	var newHeight = __element.css("height", "auto").height();
	__element.height(lastHeight)
	__element.removeClass("loading").animate({height: newHeight});
	__element.fadeIn("slow");
	*/
}

// Handlers
function handleTagCloud (__element) {
	var tagActif = __element.find("span.tag10:first a").addClass("selected").html();
	
	changeTagResults(tagActif);
	
	__element.find("a").click(
		function () {
			$j("ol.pagination");
			
			__element.find("a").removeClass("selected");
			
			$j(this).addClass("selected");
	
			changeTagResults($j(this).html());
			
			return false;
		}
	);
}

function changeTagResults (__tag) {
	var lastHeight = $j("div.box_tag_results").height();
	
	if (SECTION != "membres") {
		$j("div.box_tag_results").html('<div class="flickr flickr_pagination_simple flickr_tooltip"><a class="path" href="view_parcsquebec_tags_results.php?tag=' + __tag + '"></a></div>');
	} else {
		$j("div.box_tag_results").html('<div class="flickr flickr_pagination_simple flickr_tooltip"><a class="path" href="view_group_tags_results.php?tag=' + __tag + '"></a></div>');
	}
	
	$j("div.box_tag_results flickr").height(lastHeight);
	
	populateBox($j("div.box_tag_results").find("div.flickr"), true);
}

function handleMosaique (__element) {
	__element.find("a").hover(
		function (e) {
			e.stopPropagation();
			
			var actif = $j(this);
			
			actif.addClass("hover").find("img").stop(true, false).fadeTo(250, 1);
			
			__element.find("a:not(.hover)").find("img").stop(true, false).fadeTo(250, 0.60);
		}, 
		function (e) {
			e.stopPropagation();
			
			$j(this).removeClass("hover");
			
			__element.find("a").find("img").stop(true, false).fadeTo(250, 1);
		}
	);
}

function handleDroplist (__element) {
	__element.find("select").change(
		function () {
			if ($j(this).val()) __element.find("form").submit();
		}
	);
}

function handleScroller (__element) {
	var scroller = null;
	
	if ($j("div.scroller").length) {
		scroller = $j("div.scroller");
		var offset = 100; // Nb de pixel de chaque élément du scroller (LI).
		var scroller_interval = setInterval(function () {moveScrollerLeft(__element, offset)}, 3000);
	} else if ($j("div.mini_scroller").length) {
		scroller = $j("div.mini_scroller");
		var offset = 64; // Nb de pixel de chaque élément du scroller (LI)
		var scroller_interval = null;
	}
	
	if (scroller) {
		scroller.find("ol.pagination li.prev a").bind	(
													"click", 
													function () {
														moveScrollerRight(__element, offset);
														clearInterval(scroller_interval);
														
														return false;
													}
												);
		scroller.find("ol.pagination li.next a").bind	(
													"click", 
													function () {
														moveScrollerLeft(__element, offset);
														clearInterval(scroller_interval);
														
														return false;
													}
												);
	}
}

function moveScrollerRight (__element, __offset) {
	var scrolling = __element.find(".scrolling ul");
	scrolling.stop(true, true);
	
	var position = parseInt(scrolling.css("left").replace("px", ""));
	
	if (!position) position = 0;
	
	if (position + __offset <= 0) {
		scrolling.animate({left:"+=" + __offset + "px"}, 250);
	}
}

function moveScrollerLeft (__element, __offset) {
	var scrolling = __element.find(".scrolling ul");
	scrolling.stop(true, true);
	
	var position = parseInt(scrolling.css("left").replace("px", ""));
	
	if (!position) position = 0;
	
	if (position - __offset >= -scrolling.width() + __element.parent().width()) {
		scrolling.animate({left:"-=" + __offset + "px"}, 250);
	}
}

function handlePagination (__element, __path) {
	if (__element.hasClass("flickr_share")) {
		$j("ol.pagination").appendTo(__element.parent());
	}
	
	var total = $j("ol.pagination:eq(0) li:not(.prev, .next)").length;
	var active = 1;
			
	changePaginationView($j("ol.pagination"), active, total);
	
	$j("ol.pagination li a").click(
		function () {
			active = parseInt($j(this).attr("rel"));
			
			changePaginationView($j(this).parent().parent(), active, total);
			
			var prev = (active - 1 <= 0) ? 1 : active - 1;
			var next = (active + 1 > total) ? total : active + 1;
			
			// Attribut les prochaines valeurs aux boutons next et previvous
			$j("ol.pagination li.prev a").attr("rel", prev);
			$j("ol.pagination li.next a").attr("rel", next);
			
			$j("ol.pagination li a").removeClass("actif");
			$j("ol.pagination li:not(.prev, .next) a[rel=" + active + "]").addClass("actif");
			
			showLoading(__element);
			
			if (req) req.abort();
			
			req = $j.get	(
					  						SITE_ADDRESS + "/application/views/" + __path + "&page=" + active,
											function (responseText, textStatus, XMLHttpRequest) {
												__element.html(responseText);
												
												hideLoading(__element);
											
												if (__element.hasClass("flickr_tooltip")) 					handleTooltip(__element);
												if (__element.hasClass("flickr_share")) 					handleSelect(__element);
											}
										);
			return false;
		}
	);
}

function changePaginationView (__element, __active, __total) {
	if (__total > 3) {
		__element.find("li:not(.prev, .next)").hide();
		
		if (__active == 1) {
			__element.find("li:lt(" + (__active + 3) + ")").show();
		} else if (__active == __total) {
			__element.find("li:gt(" + (__active - 3) + ")").show();
			
		} else {
			__element.find("li:lt(" + (__active + 2) + "):gt(" + (__active - 2) + ")").show();
		}
	}
}

function handlePaginationSimple (__element, __path) {
	$j("ol.pagination").appendTo(__element.parent());
	
	var active = 1;
	
	$j("ol.pagination li a").click(
		function () {
			active = parseInt($j(this).attr("rel"));
			
			var prev = (active - 1 <= 0) ? 1 : active - 1;
			var next = active + 1;
			
			// Attribut les prochaines valeurs aux boutons next et previvous
			$j("ol.pagination li.prev a").attr("rel", prev);
			$j("ol.pagination li.next a").attr("rel", next);
			
			showLoading(__element);
			
			if (req) req.abort();
			
			req = $j.get	(
					  						SITE_ADDRESS + "/application/views/" + __path + "&page=" + active,
											function () {
												__element.html(responseText);
												
												hideLoading(__element);
												
												if (__element.hasClass("flickr_tooltip")) 					handleTooltip(__element);
												
											}
										);
			return false;
		}
	);
}

function handleTooltip (__element) {
	var lastElement = null;
	var newElement = null;
	
	$j.each(
		   		__element.find("ul li a"),
				function () {
					$j(this).bind("mouseover", showTooltip);
					$j(this).bind("mouseout", hideTooltip);
					/*
					lastElement = newElement;
					newElement = $j(this);
					
					if (lastElement != null && newElement !=null) {
						if (lastElement.position().top != newElement.position().top) {
							lastElement.addClass("linebreak");
						}
					}
					*/
				}
			);
}

function showTooltip () {
	$j("p#tooltip").html($j(this).parent().find("p.tooltip").html()).show();
	$j().bind("mousemove", moveTooltip);
}

function hideTooltip () {
	$j("p#tooltip").css({top:-50, left:0}).hide();
	$j().unbind("mousemove", moveTooltip);
}

function moveTooltip (e) {
	$j("p#tooltip").css(
					{
						left:e.pageX - $j("p#tooltip").width() - 20, 
						top:e.pageY - $j("p#tooltip").height() - 20
					}
				);
}



// PARTAGE //////////////////////////////////////////////////////////////////////////////////////////
function handleClassement () {
	
	$j("form#parcs select option:eq(0)").attr("selected", true);
	
	$j("form#parcs select").change(
		function () {
			$j("div#etape_choisir_confirm").fadeIn(500);
			
			var value = $j(this).val();
			
			$j("ul.select li.selected a").unbind("click");
			
			$j.each(
						$j("ul#selected_history li.selected"),
						function () {
							var id = $j(this).find("img").attr("alt");
							var tag = eval("tags." + value);
							
							addPhotoTag(id, tag);
						}
					);
			
			$j("ul.select li.selected").removeClass("selected");
			$j("ul#selected_history li.selected").removeClass("selected").clone().appendTo("div.box_holder div#" + value + " ul").removeClass("selected chosen");
			
			$j("div.box_holder div").hide();
			$j("div.box_holder div ul:not(:empty)").parent().show();
			
			$j("ul#selected_history").empty();
			
			$j("div.box_holder div ul li a").click(handleDelete);
			
			$j("form#parcs select option:eq(0)").attr("selected", true);
			
			if ($j("div.box_holder div ul:not(:empty)").length) 	$j("a.choix").removeClass("btn_gris_big").addClass("btn_vert_big");
			else 																	$j("a.choix").removeClass("btn_vert_big").addClass("btn_gris_big");
		}
	);
}

function handleDelete () {
	var id = $j(this).find("img").attr("alt");
	var value = $j(this).parent().parent().parent().attr("id");
	
	$j(this).unbind("click");
	
	//$j(this).parent().appendTo("ul.select");
	
	$j(this).parent().remove();
	
	$j("div.box_holder div ul:empty").parent().hide();
	
	if ($j(this).parent().hasClass("removetag")) {
		removePhotoTag(id, true);
	} else {
		removePhotoTag(id, false);
	}
	
	if ($j("div.box_holder div ul:not(:empty)").length) 	$j("a.choix").removeClass("btn_gris_big").addClass("btn_vert_big");
	else 																	$j("a.choix").removeClass("btn_vert_big").addClass("btn_gris_big");
	
	handleSelect($j("ul.select"));
	
	return false;
}

// Add remove input tags
function addPhotoTag (__id, __tag) {
	$j("ul.select li a img[alt=" + __id + "]").parent().parent().addClass("chosen").find("img").animate({opacity:0.5}, 500);
	
	//$j("form#tags ." + __id + "[name=removetag[]]").remove();
	
	if ($j("form#tags ." + __id + "[name=tag[]]").length) {
		$j("form#tags ." + __id + "[name=tag[]]").val(__tag);
	} else {
		$j("form#tags").append('<input type="hidden" name="tag[]" class="' + __id + '" value="' + __id + "|" + __tag + '" />');
	}
}

function removePhotoTag (__id, __removetag) {
	$j("ul.select li a img[alt=" + __id + "]").parent().parent().removeClass("chosen").find("img").animate({opacity:1}, 500);
	
	$j("form#tags ." + __id + "[name=tag[]]").remove();
	
	if (__removetag) {
		if (!$j("form#tags ." + __id + "[name=removetag[]]").length) {
			$j("form#tags").append('<input type="hidden" name="removetag[]" class="' + __id + '" value="' + __id + '" />');
		}
	}
}

// Add remove input tags
function addPhotoSelect (__element) {
	if (!$j("ul#selected_history li a img[alt=" + __element.find("img").attr("alt") +"]").length) {
		__element.clone().appendTo("ul#selected_history");
	}
}

function removePhotoSelect (__element) {
	$j("ul#selected_history li a img[alt=" + __element.find("img").attr("alt") +"]").parent().parent().remove();
}

function handleSelect (__element) {
	// Active les photos qui étaient présélectionnées
	$j.each(
		   		__element.find("li a"),
				function () {
					$j(this).unbind("click");
					
					var id = $j(this).find("img").attr("alt");
					
					if ($j("form#tags ." + id + "[name=tag[]]").length && !$j(this).parent().hasClass("chosen")) {
						$j(this).parent().addClass("chosen").find("img").css({opacity:0.5});
					} else if ($j("ul#selected_history li a img[alt=" + $j(this).find("img").attr("alt") +"]").length) {
						$j(this).parent().addClass("selected");
					}
				}
			);
	
	// Gère la liste de sélection de photos de l'utilisateur
	__element.find("li:not(.chosen) a").click(
		function () {
			var id = $j(this).find("img").attr("alt");
			
			$j("div#etape_choisir_parc").fadeIn(500);
			
			if (!$j(this).parent().hasClass("selected")) { // Photo active
				$j(this).parent().addClass("selected");
				addPhotoSelect($j(this).parent());
			} else {
				$j(this).parent().removeClass("selected");
				removePhotoSelect($j(this).parent());
			}
			
			return false;
		}
	);
}


// UTILITAIRES //////////////////////////////////////////////////////////////////////////////////////////
// Récupère des valeurs dans la query string
function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};