/*Work with items: drag, drop, remove*/
var inspiratorItems = {
	mainWrapper: "#inspirator",
	item: ".inspirator-element",
	itemDim: {
		width: $(".inspirator-element:first").width(),
		height: $(".inspirator-element:first").height()
	},
	dropContainer: "#inspirator-shelf",
	dragContainer: '#inspirator-deposit',
	dragPosition: {},	
	canDeleteAfterDrop: false,
	
	//Initialize draggable, droppable
	init: function(id) {		
		this.startDraggable();				
		this.startDroppable();
		this.startPreview();
	},
	
	//Add draggable event to the items in the deposit
	startDraggable: function() {
		var zis = this;
		
		$(zis.item + ".inspirator-draggable",zis.dragContainer).draggable({
			containment: zis.mainWrapper,
			stack: zis.mainWrapper,
			revert: "invalid",			
			revertDuration: 200,
			opacity: 0.9,
			zIndex: 2,
			helper: function() {
				//Create a helper clone to have the item's id (used to delete after drop)
				return $("<div class='inspirator-draggable inspirator-element ui-draggable' id='" + $(this).attr("id") + "'>" + $(this).html() + "</div>");
			},
			appendTo: zis.mainWrapper,
			start: function(event,ui) {
				$("#inspirator-largeDeposit img").hide();													
			},
			drag: function() {
				$("#inspirator-largeDeposit img").hide();													
			},
			stop: function(event,ui) {
				//After drop, removes the dragged item and the item from the deposit (uses its id)
				if (zis.canDeleteAfterDrop) {
					ui.helper.remove();
					$("#" + ui.helper.attr("id")).remove();	
					zis.canDeleteAfterDrop = false;
					zis.removeEmptyClass();
				}
			}
		});
	},
	
	//Add droppable event to the shelf
	startDroppable: function() {
		var zis = this;
		
		$(zis.dropContainer)
			.unbind()
			.droppable({
				accept: ".inspirator-draggable",
				tolerance: "pointer",
				drop: function(event,ui) {					
					var elem = ui.draggable,
						elemPos = {left: event.pageX, top: event.pageY},
						revert = function(elem) {
							//Revert item or remove
							if (!$.isEmptyObject(zis.dragPosition)) {
								elem.css({
									top: zis.dragPosition.top,
									left: zis.dragPosition.left
								});
							} else if (typeof zis.dragPosition === 'undefined') {								
									//zis.canDeleteAfterDrop = true;
								}							
						};
					
					//Put item on the shelf	- find a target place
					var targetElem = findElementByItsPosition($("li",zis.dropContainer),elemPos);	
					
					//If no target place, revert item or remove
					if (!targetElem) {					
						revert(elem);					
					} else {	
						//Found target place and if unoccupied, put item there
						if (!targetElem.is(".inspirator-occupied")) {
							zis.itemInsert(elem,targetElem);
						} else {
							//If occupied, find empty place
							var next = targetElem.nextAll(":not(.inspirator-occupied)").eq(0);					
							//If empty place found, put item there
							if (next.length) {
								zis.itemInsert(elem,next);
							} else {		
								//If no empty space found, revert item or remove								
								revert(elem);
							}	
						}
					}					
				}
			});
	},
	
	//Add preview to the items in the deposit
	startPreview: function() {
		//Item placeholder dimensions (default: 74x73)
		var zis = this,
			inspOffset = $("#inspirator-category").offset();
		
		if ($("#inspirator-largeDeposit").length) $("#inspirator-largeDeposit").remove();		
		$(zis.dragContainer).after("<div id='inspirator-largeDeposit' />");
		
		//Loop through all big images
		$(zis.item + ".inspirator-draggable:has(img.large)",zis.dragContainer).each(function(i) {
			var $this = $(this),
				id = "img-" + i,
				el = $(".large",$this).addClass(id),				
				small = $(".small",$this).addClass(id);						
				
			//Insert big image into the largeDeposit container below Deposit	
			$("#inspirator-largeDeposit").append(el);				
			
			$this.css("overflow","visible");
			
			//Show big images on hover
			$this
				.unbind("hover")
				.hover(
					function(e) {							
						//Hide all visible big images
						$("#inspirator-largeDeposit .large").hide();						
						//Show current big image
						$("#inspirator-largeDeposit ." + id)
							.inspiratorSetElementPosition({left:e.pageX - inspOffset.left + 10,top:e.pageY - inspOffset.top + 10})
							.show();						
						//Mousemove on small image
						small
							.unbind("mousemove")
							.mousemove(function(e) {
								$("#inspirator-largeDeposit ." + id)
									.inspiratorSetElementPosition({left:e.pageX - inspOffset.left + 10,top:e.pageY - inspOffset.top + 10})
									.show();
							});	
					},
					function() {			
						//Hide big image
						$("#inspirator-largeDeposit ." + id).hide();						
					}
				);
		});
	},
	
	//Remove .occupied and .foster classes from empty spaces
	removeEmptyClass: function() {		
		$(".inspirator-occupied:hasNoImage").removeAttr("class");
		$(".inspirator-foster:hasNoImage").removeAttr("class");	
	},
	
	//Put item on the shelf
	itemInsert: function(what,where) {
		var zis = this,
		    position = $("li",zis.dropContainer).index(where),
			clone = what.clone().removeAttr("style").removeClass("ui-draggable-dragging ui-draggable").unbind("hover");
		
		where
			.html(clone)
			.removeClass("inspirator-foster")
			.addClass("inspirator-occupied");
		
		//Add draggable event and "Remove" link to the item
		zis.startOneShelfDraggable(clone);
		zis.itemRemoveEvent(clone);		
		
		//IE fix: hide all large preview images
		$("#inspirator-largeDeposit .large:visible").hide();
		
		//Remove shelf text if exists
		if ($(zis.dropContainer).next("#inspirator-shelfText").length) {			
			inspirator.removeShelftText();
		}
		
		//Delete the original item from the deposit (uses draggable.stop function)
		zis.canDeleteAfterDrop = true;		
		
		//Save item and its position in a session variable
		if (typeof sessionURL !== 'undefined' && sessionURL) {
			$.get(sessionURL + "&tx_inspirator_pi1[action]=add&tx_inspirator_pi1[position]="+position+"&tx_inspirator_pi1[uid]=" + parseInt(clone.attr("id").replace("inspirator_","")),function(data) {});
		} else {
			alert(sessionURLError);
		}		
	},
	
	//Add draggable event to one item (that is already on the shelf)
	startOneShelfDraggable: function(item) {
		var zis = this;
		
		item
			.unbind()
			.draggable({
				containment: zis.dropContainer,
				stack: zis.dropContainer,
				revert: "invalid",			
				revertDuration: 200,
				opacity: 0.9,
				zIndex: 2,
				appendTo: zis.dropContainer,
				start: function(event,ui) {
					zis.dragPosition = ui.position;
					ui.helper.parent().addClass("inspirator-foster").removeClass("inspirator-occupied");					
				},
				stop: function(event,ui) {
					//After drop, remove the dragged item
					if (zis.canDeleteAfterDrop) {
						ui.helper.remove();						
						zis.canDeleteAfterDrop = false;
						//Remove .occupied and .foster classes
						zis.removeEmptyClass();
					}
				}
			});	
	},
	
	//Add "Remove" link to the item (that is already on the shelf)
	itemRemoveEvent: function(item) {		
		var zis = this,
			id = parseInt(item.attr("id").replace("inspirator_",""));
		
		//Add "Remove" link only once
		if ($(".inspirator-itemDelete",item).length == 0) {
			item
				.append("<div class='inspirator-itemDelete' />")
				.find(".inspirator-itemDelete")
				.html("<a href='javascript:;'>" + removeLabel + "</a>")								
		}
		
		//Add click event on "Remove" link
		item	
			//Show "Remove" link on item hover
			.hover(
				function() {item.find(".inspirator-itemDelete").show();},
				function() {item.find(".inspirator-itemDelete").hide();}
			)
			.find("a")
			.unbind()
			.click(function() {
				if (typeof sessionURL !== 'undefined' && sessionURL) {
					$.get(sessionURL + "&tx_inspirator_pi1[action]=delete&tx_inspirator_pi1[uid]=" + id,function(data) {
						var current = inspirator.getCurrentPage(),
							category = current.split("|");
						
						//Remove item from the shelf
						item.parent().removeAttr("class").end().remove();	
						//Add shelf text if there is no item on the shelf								
						if (!$(".inspirator-occupied",zis.dropContainer).length) {									
							inspirator.addShelfText();
						}
						//Refresh current content
						if (data.indexOf(current) >= 0 || current.indexOf("2|") >= 0) {
							var pType = current.indexOf("2|") >= 0 ? "kitchen" : "category";
							
							inspirator.loadPage(pType,"index.php?id=6&no_cache=1&type=3691&tx_inspirator_pi1[label]=" + category[0] + "&tx_inspirator_pi1[category]=" + category[1],current);									
						}
					});
				} else {
					alert(sessionURLError);
				}	
				return false;
			});
	}
}

/*Ajax navigation*/
var inspirator = {
	mainWrapper: "#inspirator",
	bodyWrapper: "#inspirator-body",
	navigation: ".inspirator-nav",
	header: "#inspirator-header",
	myAccWindowMarginTop: 30,	
	myAccWindowMarginLeft: 60,	
	
	//Put ajax page loader
	pageLoader: function() {
		return "<div id='inspirator-loaderPage' />";
	},
	
	//Put ajax body loader
	bodyLoader: function() {
		return "<div id='inspirator-loaderBody' />";
	},
	
	//Put ajax shelf loader
	shelfLoader: function() {
		return "<div id='inspirator-loaderShelf' />";
	},
	
	//Put Login + Register loader
	putLoginRegisterLoader: function(container) {
		container.addClass("withLoader");
	},
	
	//Remove Login + Register loader
	removeLoginRegisterLoader: function(container) {
		container.removeClass("withLoader");
	},
	
	//Open the inspirator home page
	open: function(link) {
		var zis = this;
		//if(link.indexOf('3690')) _gaq.push(['_trackEvent', 'Click', '3d', 'Keuken']);
		//Set cache:false for all future ajax calls
		$.ajaxSetup({cache:false});
		
		if (!$(zis.mainWrapper).length) {	
			$.ajax({
			  url: link,
			  type: 'GET',
			  success: function(data) {		
					$("body").inspiratorOverlay("inspiratorPageOverlay");					
					$("body").append(data);				
					$(zis.mainWrapper).show();
					zis.bindCloseEvents();
					
					//Inspirator dimensions + position
					var defDim = {},			
						defPos = $(zis.mainWrapper).offset();
							
					defDim.width = $(zis.mainWrapper).width();
					defDim.height = $(zis.mainWrapper).height();	
					
					//Save
					$(zis.mainWrapper).data("dimensions",defDim);
					$(zis.mainWrapper).data("position",defPos);
			  }			  
			});
		}		
	},
	
	//Reload the inspirator
	reload: function(link) {
		var zis = this;
		
		if ($(zis.mainWrapper).length) {	
			$.ajax({
			  url: link,
			  type: 'GET',
			  success: function(data) {		
					$(zis.mainWrapper).replaceWith(data);
					$(zis.mainWrapper).show();
			  }			  
			});
		}		
	},
	
	//Close the inspirator
	close: function() {
		$(this.mainWrapper).remove();
		$(".inspiratorPageOverlay").remove();
		$(document).unbind(".inspiratorEvent");		
	},
	
	bindCloseEvents: function() {	
		var zis = this;
		$(document).bind("mousedown.inspiratorEvent",zis.outsideClick);
	},
	
	//Click outside the inspirator
	outsideClick: function(e) {
		if ($(e.target).hasClass("inspiratorPageOverlay")) inspirator.close();
	},
	
	//After Login/Logout change the link on the site menu
	changeLoginLink: function(changeTo) {
		var lText = "",
			lHref = "",
			lId = "";
			
		switch (changeTo) {
			case "login":
				lText = loginLabel;
				lHref = "javascript:login();";
				lId = "#logout";
				toId= "login";
				break;
			case "logout":
				lText = logoutLabel;
				lHref = "javascript:logout();";
				lId = "#login";
				toId= "logout";
				break;
		}
		
		$(".topMenu " + lId + " a")
			.text(lText)
			.attr("href",lHref)
			.parent()
			.attr("id",toId);
	},
	
	//Add help text to the shelf
	addShelfText: function() {
		$('#inspirator-shelfWrapper').append("<p id='inspirator-shelfText'>" + shelfText + "</p>");
	},
	
	//Remove help text from the shelf
	removeShelftText: function() {
		$("#inspirator-shelfText").remove();
	},
	
	//Open a new full page
	loadFullPage: function(type,page,current) {
		var zis = this;
		
		//Put loader
		$(zis.mainWrapper).html(zis.pageLoader());
		
		//Get new content
		$.ajax({url: page,
			success: function(data) {
				//Insert new content						
				$(zis.mainWrapper).html(data);
				
				//If logout
				if (type == "logout") {
					zis.changeLoginLink("login");
				}
			}
		});
	},
	
	//If the Navigation exsist
	isNavigation: function() {
		if ($(this.navigation,this.mainWrapper).length) return true;
		return false;
	},
	
	//Load the Navigation
	loadNavigation: function(reset) {
		var zis = this;
		
		if (!zis.isNavigation()) {
			//Put loader
			$(zis.bodyWrapper).html(zis.pageLoader());
			//Get Navigation content
			$.ajaxq("loadPage", 
				{
					url: getMenuURL,
					success: function(data) {
						//Remove loader
						$("#inspirator-loaderPage").remove();
						//Insert content
						if (reset == "reset") {
							//Reset the Navigation
							$(zis.bodyWrapper)
								.addClass("hiddenContent")
								.prepend(data)
								.find(".inspirator-nav")
								.addClass("inspirator-defaultNav")
								.find("li.active")
								.removeClass("active")
								.end()
								.end()
								.removeClass("hiddenContent");
						} else $(zis.bodyWrapper).prepend(data);
					}
				}	
			);
		} else {
			//Reset the Navigation
			if (reset == "reset") {
				$(zis.navigation)
					.addClass("inspirator-defaultNav")
					.find("li.active")
					.removeClass("active");
			}		
		}
	},
	
	//Remove the Navigation
	removeNavigation: function() {
		$(this.navigation).remove();
	},
	
	//Load body
	loadBody: function(type,page,current,putLoader) {
		var zis = this,		
			putLoader = typeof putLoader === 'undefined' ? true  : putLoader;
		
		//Remove body content
		zis.removeBody();
		//Remove Save link
		$(zis.navigation)
			.removeAttr("id")
			.find(".inspirator-save")
			.remove();
		//Update the Navigation
		if (type != "myaccount" && type != "save") {	
			zis.updateNavigation(current);				
		}	
		//Put loader
		if (putLoader) $(zis.navigation).after(zis.bodyLoader());	
		//Get new content
		$.ajaxq("loadPage", 
			{			
				url: page,
				success: function(data) {
					//Remove loader
					$("#inspirator-loaderBody").remove();
					//Insert content
					if ($(zis.navigation).length) {
						$(zis.navigation).after(data);						
					} else {
						//Reset navigation
						if (type == "myaccount" || type == "save") {								
							$(zis.bodyWrapper)
								.addClass("hiddenContent")
								.html(data)
								.find(".inspirator-nav")
								.addClass("inspirator-defaultNav")
								.find("li.active")
								.removeClass("active")
								.end()
								.end()
								.removeClass("hiddenContent");
						} else $(zis.bodyWrapper).html(data);
					}	
					
					//Add events to items in the deposit
					inspiratorItems.startDraggable();
					inspiratorItems.startPreview();		
					
					//If Save
					if (type == "save") {
						$(zis.navigation + " li:first a:first").click();
					}
					
					//If Kitchen	
					if (type == "kitchen") {
						//Init kitchen image switch
						inspiratorKitchen.init();
						$(zis.navigation).attr("id","inspirator-kitchen-nav");
						//Add Navigation item: Save
						$.get(getSaveItem,function(data) {
							$(zis.navigation + " li:last").after(data);	
						});
					} 
				}
			}	
		);		
	},
	
	//Remove body divs except navigation
	removeBody: function() {
		$(this.bodyWrapper + " div:not(" + this.navigation + ")",this.mainWrapper).remove();
	},
	
	//If the shelf exists
	isShelf: function() {
		if ($("#inspirator-shelfWrapper",this.mainWrapper).length) return true;
		return false;
	},
	
	//Load the shelf
	loadShelf: function() {
		var zis = this;
		
		if (!zis.isShelf()) {
			//Put loader
			$(zis.bodyWrapper).after(zis.shelfLoader());
			//Get shelf content
			$.ajaxq("loadPage", 
				{	
					url: shelfURL,
					success: function(data) {
						//Insert content
						$(zis.bodyWrapper).after(data);
						//Remove shelf loader
						$("#inspirator-loaderShelf").remove();
						//If shelf is empty put text on it
						if (!$("#inspirator-shelf .inspirator-occupied").length) zis.addShelfText();
						//Init droppable
						inspiratorItems.startDroppable();				
						//Add remove link + draggable event
						if ($(".inspirator-occupied",inspiratorItems.dropContainer).length) {
							$(".inspirator-occupied " + inspiratorItems.item,inspiratorItems.dropContainer).each(function() {
								inspiratorItems.startOneShelfDraggable($(this));
								inspiratorItems.itemRemoveEvent($(this));
							});								
						}						
					}
				}	
			);	
		}
	},
	
	//Remove the shelf
	removeShelf: function() {
		$('#inspirator-shelfWrapper').remove();	
	},
	
	//Update navigation
	updateNavigation: function(current) {
		var zis = this,
			c = current.split("|"),
			mainCat = "categ-" + c[0],
			subCat = "categ-" + c[0] + "-" + c[1];		
		
		$(zis.navigation).removeClass("inspirator-defaultNav");
		$(zis.navigation + " li.active").removeClass("active");		
		$(zis.navigation + " li." + mainCat).addClass("active");
		$(zis.navigation + " li." + subCat).addClass("active");
	},
	
	//Open a new page
	loadPage: function(type,page,current) {
		var zis = this;
		
		//Save current page
		zis.setCurrentPage(current);		
		
		switch (type) {
			//Full page reload
			case "content":				
				zis.loadNavigation();
				zis.loadShelf();
				zis.loadBody(type,page,current,false);				
				break;
			case "category":
				zis.loadShelf();
				zis.loadBody(type,page,current,true);								
				break;
			case "kitchen":
				zis.loadShelf();
				zis.loadBody(type,page,current,true);								
				break;
			case "save":	
				$.get(saveURL,function() {});
			case "myaccount":
				zis.removeShelf();				
				zis.loadNavigation("reset");	
				zis.loadBody(type,page,current,true);		
				break;
			case "login":
				zis.removeNavigation();
				zis.removeShelf();
				zis.loadBody(type,page,current,true);
				break;			
		}
	},
	
	//Save current page into a cookie
	setCurrentPage: function(current) {
		$.cookie("currentPage",current);
	},
	
	//Return current page from the cookie
	getCurrentPage: function() {
		return $.cookie("currentPage");
	}
}

/*Kitchen*/
var inspiratorKitchen = {
	wrapper: "#inspirator-suggestions",
	bigImage: "#inspirator-sFirst",
	
	init: function() {
		var zis = this,
			offset = $("#inspirator-content").offset();
		
		zis.arrangeImages();
		
		//Add hover event
		$(".inspirator-sThree a").each(function() {
			var $this = $(this);
			
			$this.hover(
				function(e) {
					var bigimg = $this.next("img[class^='bigimg']");
					
					bigimg
						.css({
							"left":e.pageX - offset.left + 20 + "px", 
							"top":e.pageY - offset.top - parseInt(bigimg.height() / 2) + "px"
						})
						.show();					
						
					$this
						.mousemove(function(e) {
							bigimg
								.css({
									"left":e.pageX - offset.left + 20 + "px", 
									"top":e.pageY - offset.top - parseInt(bigimg.height() / 2) + "px"
								})
								.show();					
						});
				},
				function() {
					$this.next("img[class^='bigimg']").hide();
				}
			);
		});	
	},
	
	//Put some css classes on images
	arrangeImages: function() {
		var zis = this;
		
		$(".inspirator-sThree:last").addClass("last");
		
		//Move big images next to the small ones
		$(zis.bigImage + " img",zis.wrapper).each(function(i) {
			var id;
			//Add id
			if (i == 0) id = 3; else id = i-1;			
			$(this).addClass("bigimg-" + id);
			
			//Move (we leave the first image there)
			if (id !=3 ) $(".inspirator-sThree:eq(" + id + ")").append($(this));
		});
		
	}
}

/*General dialogbox*/
var inspiratorDialog = {
	wrapper: "inspirator-dialog",
	wrapperInner: "inspirator-dialogInner",
	content: '',
	
	//Open dialog
	open: function() {				
		var wHeight = ($.browser.webkit) ? document.documentElement.clientHeight : $(window).height(),
			wWidth = ($.browser.webkit) ? document.documentElement.clientWidth : $(window).width(),	
			zis = this;			
		
		$("body").inspiratorOverlay("inspiratorDialogOverlay");
		if (!$("#" + zis.wrapper).length) $("body").prepend("<div id='" + zis.wrapper + "' />");
		$("#" + zis.wrapper)
			.html(zis.content)
			.css({
				left: parseInt((wWidth - $("#" + zis.wrapper).width())/2),
				top: parseInt((wHeight - $("#" + zis.wrapper).height())/2) - 50
			})
			.fadeIn("fast");	
			
		//Bind "Esc" to close the dialog
		$(document).keydown(function(e) {
			if (e.keyCode == 27) zis.close();
		});	
		
		//Bind dialog close event
		zis.bindClose();	
		
		//Remove outside-click from inspirator main wrapper (will be put back once the Dialog is closed)
		$(document).unbind(".inspiratorEvent",inspirator.outsideClick);		
	},
	
	//Bind dialog close event
	bindClose: function() {
		var zis = this;

		$(".close","#" + zis.wrapper).click(function() {
			zis.close();
		});
	},
	
	//Close dialog
	close: function() {		
		$("#" + this.wrapper).remove();
		$(".inspiratorDialogOverlay").remove();
		inspirator.bindCloseEvents();
	},
	
	//Alert dialog
	iAlert: function(yesText,yesFunction,content) {
		var dBody = "<div id='" + this.wrapperInner + "' class='clearfix'>" + content;
		
		dBody += "<div class='inspirator-dialogButtons inspirator-alert clearfix'>";	
		dBody += "<a id='inspirator-dialogYes' href='javascript:;'>" + yesText + "</a>";
		dBody += "</div>";
		
		this.content = dBody + "</div>";
		this.open();
		
		$("#inspirator-dialogYes").click(function() {			
			if ($.isFunction(yesFunction)) {
				yesFunction.call(this);
				inspiratorDialog.close();				
			}
		});
	},
	
	//Confirm dialog
	iConfirm: function(yesText,noText,yesFunction,noFunction,content) {	
		var dBody = "<div id='" + this.wrapperInner + "' class='clearfix'>" + content;

		dBody += "<div class='inspirator-dialogButtons clearfix'>";	
		dBody += "<a id='inspirator-dialogYes' href='javascript:;'>" + yesText + "</a>";
		dBody += "<a id='inspirator-dialogNo' href='javascript:;'>" + noText + "</a>";
		dBody += "</div>";
		
		this.content = dBody + "</div>";
		this.open();
		
		//Call "Yes" function
		$("#inspirator-dialogYes").click(function() {			
			if ($.isFunction(yesFunction)) {
				yesFunction.call(this);
				inspiratorDialog.close();
			}
		});
		
		//Call "No" function
		$("#inspirator-dialogNo").click(function() {
			if ($.isFunction(noFunction)) {
				noFunction.call(this);
				inspiratorDialog.close();
			}
		});
	}	
}

/*Put overlay on the page*/
$.fn.inspiratorOverlay = function(overlayClass) {
	return this.each(function() {
		var overlay = $("<div class='inspirator-overlay " + overlayClass + "'></div>"),
			wH = $(window).height(),
			dH = $(document).height(),
			height = (wH > dH) ? wH : dH;
		
		$(this).css("position","relative");		
		overlay.appendTo($(this)).height(height).show();
	});
}

/*Position the element*/
$.fn.inspiratorSetElementPosition = function(poz) {
	return this.each(function() {
		$(this).css({
			"left": poz.left + "px",
			"top": poz.top + "px"
		});
	});
}

/*Select empty places on the shelf*/
$.expr[':'].hasNoImage = function(obj){  
  return ($("img",obj).length == 0);
};

/*Find a place on the shelf by coordinates*/
function findElementByItsPosition(elements,pos) {		
	var elem = '';
	
	elements.each(function() {
		var p = $(this).offset(),
			w = $(this).width(),
			h = $(this).height();
		
		if (p.left <= pos.left && p.left + w >= pos.left && p.top <= pos.top && p.top + h >= pos.top) {
			elem = $(this);
			return false;
		}	
	});
	
	return elem;
}

/*Validate register form*/
function createaccountvalidate() {
	$("#registerForm").validate({
		rules: {
			password: {required: true},
			repassword: {required: true, equalTo: "#password"}
	    }
	});	
}

/*Validate login form*/
function loginvalidate() {
	$("#loginForm").validate();
}

/*Login link on the sites menu*/
function login(){
	inspirator.open(loginURL);
}

/*Logout link on the sites menu*/
function logout(){
	$.get(logoutURL,function(data) {
		inspirator.changeLoginLink("login");		
		inspiratorDialog.iAlert(closeLabel,function() {},logoutText);
	});
}

function afterLoginOrRegister(data) {
	inspirator.changeLoginLink("logout");
	$("#inspirator")
		.addClass("hiddenContent")
		.html(data)
		.find(".inspirator-nav")
		.addClass("inspirator-defaultNav")
		.find("li.active")
		.removeClass("active")
		.end()
		.end()
		.removeClass("hiddenContent")
		.find(".inspirator-nav li:first a:first")
		.click();
}

/*Login*/
function submitLogin(page) {
	var data = "tx_inspirator_pi1[login_email]="+$("#login_email").val()+"&tx_inspirator_pi1[login_password]="+$("#login_password").val()+"&tx_inspirator_pi1[action]="+$("#action").val();
	
	//Put loader
	inspirator.putLoginRegisterLoader($("#inspirator-login-login"));
	
	$.ajax({
	  type: 'POST',
	  url: page,
	  data: data,
	  success: function(data) {
		if (data.indexOf('error') >= 0) {
			$("#loginError").show();
			//Remove loader
			inspirator.removeLoginRegisterLoader($("#inspirator-login-login"));
		} else {			
			afterLoginOrRegister(data);		
		}
	  }
	});
}

/*Register*/
function submitNewAccount(page){
	var data = "tx_inspirator_pi1[email]="+$("#email").val()+"&tx_inspirator_pi1[password]="+$("#password").val()+"&tx_inspirator_pi1[action]="+$("#action_new").val()+"&tx_inspirator_pi1[firstname]="+$("#firstname").val()+"&tx_inspirator_pi1[lastname]="+$("#lastname").val();
	
	//Put loader
	inspirator.putLoginRegisterLoader($("#inspirator-login-register"));
	
	$.ajax({
	  type: 'POST',
	  url: page,
	  data: data,
	  success: function(data) {
		if (data.indexOf('error') >= 0) {
			$("#newAccountError").show();
			//Remove loader
			inspirator.removeLoginRegisterLoader($("#inspirator-login-register"));
		} else {
			afterLoginOrRegister(data);			
		}
	  }
	});
}
