/**
* Initialize the quicklook, show the nav
*/
var favoriteInfo = {}; // An object to hold all the users favorites

QuickLook.prototype._ref;

function QuickLook(ref){
	this._ref = ref + ".";
	$("#quicklook #qlcontent").css("display", "none");
	
	$("#quicklook").css({
		bottom: 0,
		display: "block"
	});
}

QuickLook.prototype.hideContent = function(){
	$("#quicklook #qlnav #navitems a").removeClass("selected");
	$("#quicklook #qlcontent, #quicklook #qlcontent .contentPane").css("display", "none");
}
QuickLook.prototype.showContent = function(){
	$("#quicklook #qlcontent").css("display", "block");
}

QuickLook.prototype.show = function(){
	$("#quicklook").css("display", "block");
}

QuickLook.prototype.showNav = function(){
	return;
}


/*
* Navigation functions
*/
QuickLook.prototype._navItems = {};

QuickLook.prototype.clearNav = function(){
	this._navItems = {};
}

QuickLook.prototype.addNav = function(linkText, clickevent){
	this._navItems[linkText] = {};
	this._navItems[linkText].text = linkText;
	this._navItems[linkText].onclick = clickevent;
	this.printNav();
}

QuickLook.prototype.printNav = function(){
	$("#quicklook #qlnav #navitems").html('');
	$("#quicklook #qlcontent").html('');
	var i=0;
	for(var t in this._navItems){
	
		var o = this._navItems[t];
	
		i++;
		
		//"<a id='navlink"+ i +"' href='#' onclick='"+ this._ref + o.onclick +"("+ i +");this.blur();return false;'>"+ o.text +"</a>"
		
		$("#quicklook #qlnav #navitems").append(o.text);
		
		$("#quicklook #qlcontent").append('<div id="contentPane'+ i +'" class="contentPane"></div>');
		this._navItems[t].contentPane = i;
	}
}

/*
* Content functions
*/

QuickLook.prototype.hideContentPanes = function(){
	$("#quicklook #qlcontent .contentPane").removeClass("visible");
	// Remove all selection on the nav
	$("#quicklook #qlnav #navitems a").removeClass("selected");
}

// Favorites
QuickLook.prototype._favoritesLoaded = false;
QuickLook.prototype._favoritesVisible = false;

QuickLook.prototype._favoritesData = [];

// The left-most image's index. (will always start with 0)
QuickLook.prototype._favoritesLeftIndex = 0;

QuickLook.prototype.loadFavorites = function(contentPane, callback){
	//show the favorites pane, with a loading thinger.
	this.showContent();
	
	this.showFavorites(contentPane);
	
	var cp = $("#quicklook #qlcontent #contentPane" + contentPane);
	cp.addClass("favorites").addClass("loading");
	cp.html('&nbsp;');
	
	this._favoritesLoaded = true;
	
	var t = this;
		
	$.ajax({
		type: "POST",
		url: "/ajax/planner/",
		data: "method=getFavorites",
		success: function(data){
			cp.removeClass("loading");
			
			var d = eval("(" + data + ")");
			
			for(var i=0, len=d.length; i<len; i++){
				favoriteInfo[d[i].productid] = d[i];
			}
			callback(t, d);
		}
	});
	
}

QuickLook.prototype.showFavorites = function(contentPane){
	if(this._listsVisible){
		this.hideLists();
	}
	$("#quicklook #qlcontent #contentPane" + contentPane).addClass("visible");
	this._favoritesVisible = true;
}
QuickLook.prototype.hideFavorites = function(contentPane){
	$("#quicklook #qlcontent #contentPane" + contentPane).removeClass("visible");
	this._favoritesVisible = false;
	$("#qlcontent").css("height", "");
	$(window).unbind('resize');
}
QuickLook.prototype.toggleFavorites = function(contentPane){
	
	
	
	this.hideContentPanes();
	
	if(this._favoritesVisible){
		this.hideFavorites(contentPane);
		//this.hideContent();
		return;
	}
	
	// Add to the navlink{contentpane}
	$("#quicklook #qlnav #navitems a#navlink" + contentPane).addClass("selected");


	var t = this;


	if(this._favoritesLoaded == false){
		this.loadFavorites(contentPane, t.printFavorites);
	}else{
		this.showContent();
		this.showFavorites(contentPane);
	}
}

QuickLook.prototype.displayFavorites = function(contentPane){
	if(this._favoritesLoaded == false){
		this.loadFavorites(contentPane, this.printFavorites);
	}else{
		this.showContent();
		this.showFavorites(contentPane);
	}
}

QuickLook.prototype.addFavorite = function(productInfo){
	this._favoritesData.push(productInfo);
	this.printFavorites(this);
}

QuickLook.prototype.removeFavorite = function(productid){
	// Delete from the _favoritesData array.
	var t = this;
	// Preserve the height so clearFavorites doesnt make the pane resize (up and down)
	t.preserveHeight();
	$(t._favoritesData).each(function(i){
		var d = t._favoritesData[i];
		if(!d){
			return;
		}
		if(d.productid == productid){
			t._favoritesData.splice(i, 1);
			//$("#favimages img#"+ productid +"-fav").remove();
			t.clearFavorites();
		}
	});
	
	this.printFavorites(this);
}

QuickLook.prototype.clearFavorites = function(){
	if(this._quicklookHeight){
		$("#qlcontent").css("height", this._quicklookHeight);
	}
	var cp = $("#quicklook #qlcontent .contentPane.favorites");
	cp.html('');
	cp.addClass("loading");
}

QuickLook.prototype._quicklookHeight;

var overFav = false;

/**
* Print the favorites list.  Must pass the object (becuase the callback cant reference this)
*/
QuickLook.prototype.printFavorites = function(obj, data){
	if(data){
		obj._favoritesData = data;
	}
	
	
	var t = obj;
	$(window).unbind('resize');
	$(window).resize(function(){
		t._quicklookHeight = $("#qlcontent").height();
		t.clearFavorites();
		t.printFavorites(obj);
	});
	
	var d = obj._favoritesData;
	
	//console.dir(d);
	
	var cp = $("#quicklook #qlcontent .contentPane.favorites");
	
	// If d doesn't exist then there is no data
	if(d.length <= 0){
		cp.html('<div id="emptyfavorites"><p><b>No favorites&hellip;yet!</b></p>\
<p>Add products to Favorites and you&rsquo;ll be able to mix and match them in <a href="/layouts"><b>Layouts</b></a></p>\
</div>');
	}else{
		
		if($("#favimages").length < 1){
			obj.clearFavorites();
			// Add the right and left buttons, as well as an area for the images
			cp.append('<div class="right"></div><div class="left"></div><div id="favimages"><div id="row1" class="favrow"></div><div id="row2" class="favrow"></div></div>');
		}
		var dim = 75; // How wide each image is.
		var margin = 5;
		var sideMargins = 25; // Margins for the buttons (both sides)
		
		// Find out how many images we can show (2 rows).
		var windowWidth = $(window).width();
		
		// Get the image width, which is its dimensions + additional margin
		var imageWidth = dim + margin;
		
		// How many images can fit in 1 row?
		var rowImages = Math.floor((windowWidth - (sideMargins * 2)) / imageWidth);
		
		// Set len to whichever is smaller, rowimages*2 or the total # of images
		var len = rowImages * 2 > d.length ? d.length : rowImages * 2;
		
		obj.favoritesNavigation(obj, len);
		
				
		var row1imgs = '';
		var row2imgs = '';
		var count = 0;
		for(var i=obj._favoritesLeftIndex; i < obj._favoritesLeftIndex + len; i++){
			if(!d[i]){
				count++;
				break;
			}
			if($("#favimages #" + d[i].productid + "-fav").length > 0 ){
				count++;
				continue;	
			}
			
			if(count < rowImages){
				row1imgs += '<img id="'+ d[i].productid +'-fav" src="'+d[i].image.small+'" class="favimg" width="'+dim+'">';
			}else{
				// Put that shiz in the 2nd row.
				row2imgs += '<img id="'+ d[i].productid +'-fav" src="'+d[i].image.small+'" class="favimg" width="'+dim+'">';
			}
			count++;
		}
		
		var doneLoad = function(){
			
			$(".favimg").css("visibility", "visible");
			cp.removeClass("loading");
			
			/*
			$(".favimg").mouseover(function(){
				overFav = true;
			});
			$(".favimg").mouseout(function(){
				overFav = false;
			});
			infoWindowHover(".favimg");
			*/
			$(".fimg").draggable("destroy");
			$(".fimg").draggable({
				helper:'clone',
				/*containment: '#roomcont',*/
				start: function(){
					// If we're not viewing a room, then dont do any of this shiz
					//if(!viewingRoom){
					//	return;
					//}
					//Make the shadow appear over the roomcont area
					var a = $("#canvas").offset();
					$("#shadow").css({
						left: a.left,
						top: a.top,
						zIndex: 1000000,
						position: 'absolute',
						height: $("#canvas").height(),
						width: $("#canvas").width()
					}).fadeTo(5, 0, function(){
						$(this).css("display", "block").fadeTo(5, .2);
					});
				},
				stop: function(e, ui){
					// If not viewing a room, exit all up in hurr
					/*if(!viewingRoom){
						return;
					}*/
					$("#shadow").css("display", "none");
					
					var id = $($(ui.helper).contents()[0]).attr("id").split("-")[0];
					
					
					// Find the location to "drop" the image
 					var topleftParent = $("#canvas").offset();
					
					var style = 'position:absolute;';
					
					var top = ui.absolutePosition.top - topleftParent.top;
					var left = ui.absolutePosition.left - topleftParent.left;
					
					style += 'left:' + left + 'px;';
					style += 'top:' + top + 'px;';
					
					
					$("#canvas").preloadAppend({
						data: '<img id="product-'+ id +'" src="'+ $($(ui.helper).contents()[0]).attr("src") +'" width="150" style="'+ style +'">',
						imageLoad: function(t){
							t.imageBox();
						}
					});
					
					addLayoutProduct(favoriteInfo[id]);
					
					if(hashRoot == 'edit'){
						// Actually save to the room, then update the newly dropped image with product-[productid]-[baseroomproductid]
						
						$.post("/ajax/layouts/", {
							method: 'saveToLayout',
							productid: id,
							baseid: parameters[0]
						}, function(baseroomproductid){
							// Now it's actually saved to the room. update the product in the layout
							var obj = $("#product-" + id);
							obj.attr("id", obj.attr("id") + "-" + baseroomproductid);
							// We can now make it draggable.
							canvas_events(true);
							
							// Now that the item is in the room and everything is ready. We save the current coordinates, because
							//  they might not drag. They may just exit, so we save for later.
							$.post("/ajax/layouts/", {
								method: 'saveLocation',
								baseroomproductid: baseroomproductid,
								top: top,
								left: left,
								height: obj.height(),
								width: obj.width(),
								z: 10000
							});
						});
					}else if(hashRoot == 'new' || hashRoot == 'template'){
						// Take everything in productInfo, save it, and load the layout as editable.
						// We are either empty, or template
						room_create();
						$("#canvas").removeClass("empty");
						canvas_loading();
					}
					$($(ui.helper).contents()[0]).remove();
								
					
				}
			});
		}
		
		$("#favimages #row1").preloadAppend({
			wrap: '<div class="fimg"></div>',
			data: row1imgs,
			doneLoad: doneLoad,
			imageLoad: function(t){
				$(t).imageBox({mw:dim, mh:dim, box:true});
			}
		});
		
		if(len > rowImages){
			// The total # to show is bigger than what fits in 1 row.
			// So we show 2 rows.
			$("#favimages #row2").preloadAppend({
				wrap: '<div class="fimg"></div>',
				data: row2imgs,
				doneLoad: doneLoad,
				imageLoad: function(t){
					$(t).imageBox({mw:dim, mh:dim, box:true});
				}
			});
		}
		
	}

}

QuickLook.prototype.preserveHeight = function(){
	// Set the size of the pane to the current size
	this._quicklookHeight = $("#qlcontent").height();
}

QuickLook.prototype.favoritesNavigation = function(obj, len){
	// We are on the last page
	if(obj._favoritesData.length <= obj._favoritesLeftIndex + len){
		// Last page
		$(".right").addClass("disabled");
	}else{
		// We are not on the last page, allow the right button
		$(".right").removeClass("disabled");
		$(".right").click(function(){
			obj.preserveHeight();
			obj.clearFavorites();
			obj._favoritesLeftIndex += len;
			obj.printFavorites(obj);
		});
	}
	
	// We are on the first page
	if(obj._favoritesLeftIndex < 1){
		// First page
		$(".left").addClass("disabled");
	}else{
		// We are not on the first page, allow the left button
		$(".left").removeClass("disabled");
		$(".left").click(function(){
			obj.preserveHeight();
			obj.clearFavorites();
			obj._favoritesLeftIndex -= len;
			obj.printFavorites(obj);
		});
	}
	
}


//Lists & Layouts
QuickLook.prototype._listsLoaded = false;
QuickLook.prototype._listsVisible = false;
QuickLook.prototype.loadLists = function(contentPane, callback){
	this.showContent();
	
	this.showLists(contentPane);
	
	var cp = $("#quicklook #qlcontent #contentPane" + contentPane);
	cp.addClass("lists").addClass("loading");
	cp.html('&nbsp;');
	
	this._listsLoaded = true;
	setTimeout(function(){
		cp.html('lists n stuff!');
		cp.removeClass("loading");
	}, 1500);
	
	
}
QuickLook.prototype.showLists = function(contentPane){
	if(this._favoritesVisible){
		this.hideFavorites();
	}
	$("#quicklook #qlcontent #contentPane" + contentPane).addClass("visible");
	this._listsVisible = true;
}
QuickLook.prototype.hideLists = function(contentPane){
	$("#quicklook #qlcontent #contentPane" + contentPane).removeClass("visible");
	this._listsVisible = false;
}
QuickLook.prototype.toggleLists = function(contentPane){
	
	this.hideContentPanes();
	
	if(this._listsVisible){
		this.hideLists(contentPane);
		return;
	}
	
	// Add class to the navlink{contentpane}
	$("#quicklook #qlnav #navitems a#navlink" + contentPane).addClass("selected");

	var dothis = function(){
		
	}

	if(this._listsLoaded == false){
		this.loadLists(contentPane, dothis);
	}else{
		this.showLists(contentPane);
		dothis();
	}
}
