// These functions only run once the page is loaded, so we don't have to worry about that.

/*
* Init the layout. This just resets everything.
*/
var parameters = [];
function layout_init(params){
	parameters = params;
	$("#canvas").html('').attr("class", "");
	$("#rightbar .module").css("display", "none");
	$("#rightbar .module .edit, #rightbar .module .view, #rightbar .module .new, #rightbar .module .template").css("display", "none");
	productInfo = {};
	$("#itemCount, #totalPrice").text('0');
	canvas_loading();
}

/*
* A blank, empty, new layout is created
* An array of parameters sent with the hash is also passed
* These parameters come in the form /#new/{param1}/{param2}/etc...
*/
function layout_new(params){
	layout_init(params);
	$("#canvas").addClass("new").addClass("empty");
	$(".module.edit").css("display", "block");
	
	// Setup the details module with default stuff
	$("#layoutName").text("unnamed - 03/27/09");
	$("#itemCount").text('0');
	$("#totalPrice").text('0');
	
	// On new layouts we want favorites to be open by default.
	ql.displayFavorites(1);
}

/* 
* Editing a already created layout.
* An array of parameters sent with the hash is also passed
* These parameters come in the form /#new/{param1}/{param2}/etc...
*/
function layout_edit(params){
	layout_init(params);
	$(".edit").css("display", "block");
	// params[0] will be the id of the layout we're currently editing.
	// if there params[0] doesn't exist, there was an error!
	if(!params[0]){
		// No id passed, show an error message
		alert('There was an error! Require an id (edit).');
	}else{
		$.post("/ajax/layouts/",
			{
				method: 'isCurrentLayoutOwner',
				baseid: params[0]
			},
			function(response){
				
				// If the user owns what they're trying to edit, load it up.
				if(response){
					$.post("/ajax/layouts/",
						{
							method: 'getLayout',
							baseid: params[0]
						},
						function(data){
						  //alert(data);
							processLayout(data, true);
						}
					);
				}else{
					// They're not the owner, view it.
					//fake the hash and load view.
					var hash = '#view/' + params[0];
					hash = hash.replace(/^.*#/, '');
					// moves to a new page. 
					// pageload is called at once. 
					$.historyLoad(hash);
				}
			}
		);
	}
}

/*
* Viewing a read only layout
* An array of parameters sent with the hash is also passed
* These parameters come in the form /#new/{param1}/{param2}/etc...
*/
function layout_view(params){
	layout_init(params);
	$(".view").css("display", "block");
	// params[0] will be the id of the layout to read only.
	if(!params[0]){
		// No id passed, show an error message
		alert('There was an error! Require an id (view).');
	}else{
		$.post("/ajax/layouts/",
			{
				method: 'getLayout',
				baseid: params[0]
			},
			function(data){
			  //alert(data);
				processLayout(data, false);
			}
		);
	}
}

/*
* Viewing a template
*/
function layout_template(params){
	layout_init(params);
	$(".template").css("display", "block");
	// params[0] will be the id of the template.
	if(!params[0]){
		// No id passed, show an error message
		alert('There was an error! Require an id (template).');
	}else{
		$.post("/ajax/layouts/",
			{
				method: 'getTemplateById',
				templateId: params[0]
			},
			function(data){
			  //alert(data);
				var info = eval("(" + data + ")");
				var roomDescription = info.primary;
				if(info.secondary != ""){
					roomDescription += ' meets ' + info.secondary;
				}
				$("#roomStyle").text(roomDescription);
				
				processLayout(data, false);
			}
		);
	}
}

var productInfo = {}; // An object to hold infos for all the 
var lastProductid; // The last productid to be hovered over
var zIndexCount = 1000; // A counter so the last dragged image is always on top
/*
* Process a layout.
* @param layoutInfo - oject describing a layout
* @param draggable - whether or not it is allowed to be draggable
*/
function processLayout(layoutInfo, dragable){

	productInfo = {};

	canvas_loading();

	layoutInfo = eval("(" + layoutInfo + ")");
	
	if(layoutInfo.name){
	
		// Update the name of the current layout
		$("#layoutName").text(layoutInfo.name);
		
		
	
		// If there is a layout with no images, show the empty prompt
		if(layoutInfo.room.images.length <= 0){
			$("#canvas").addClass("invalid");
		}
	
	}
	
	var imgs = '';
	
	// Get a random mapping
	var map = mapping[Math.round(Math.random() * 2)];

	// Keep track of overlapping categories when melissa mapping
	var categoryCount = [];
	
	for(var i in layoutInfo.productdetails){
		
		var d = layoutInfo.productdetails[i];
		
		addLayoutProduct(d);
		
		var s = "";
		
		var category = d.category;
		
		// If we have a melissamap, and no product map; we melissa map.
		if(map[category] && !d.map){
			s += "position:absolute;";
			s += "z-index:" + map[category]['z-index'] + ";";
			
			if(!categoryCount[category]){
				categoryCount[category] = 1;
				
				s += "top:" + parseInt(map[category].top) + "px;";
				s += "left:" + parseInt(map[category].left) + "px;";

			}else{
				
				var curcount = categoryCount[category];
				
				s += "top:" + (parseInt(map[category].top) + (75 * curcount)) + "px;";
				s += "left:" + (parseInt(map[category].left) + (75 * curcount)) + "px;";
			
				categoryCount[category]++;
			}
		
		}else if(d.map){
			var m = d.map;
			//console.dir(m);
			s += "position:absolute;";
			s += "top:" + parseInt(m.top) + "px;";
			s += "left:" + parseInt(m.left) + "px;";
			s += "z-index:" + m['z-index'] + ";";
		}else{
			// Nothing!
		}
		// The id's are product-{productid}-{baseroomproductid}
		imgs += "<img id='product-"+ d.productid +"-"+ d.baseroomproductid +"' src='" + d.image.small + "' width='150' style='visibility:hidden;"+ s +"'>";
	}
	
	$("#canvas").preloadAppend({
		data: imgs,
		imageLoad: function(t){
			t.imageBox();
		},
		doneLoad: function(){
			$("#canvas img").css("visibility", "visible");
			canvas_doneload();
			
			//canvas_draggable(dragable);
			
			canvas_events(dragable);
			
		}
	});
}

var imgClickable = true; // Whether or not the canvas image is able to be clicked.
var popupDelay;
var popupHideDelay;

function canvas_events(saveable){
	// Draggable Stuff
	$("#canvas img").draggable("destroy");
	
	if(hashRoot != 'view'){
		$("#canvas img").draggable({
			containment: "parent",
			helper: "original",
			drag: function(){
				$("#infowindow").css("display", "none");
			},
			start: function(){
			
				//this var is defined before productsLoadedEents();
				//it is used to not toggle the sidebar when dragging is done
				//required b.c. when dragging ends the click event is fired.
				imgClickable = false;
				
				//hideInfoWindow();
			
				$(this).fadeTo(5, .7);
				$(this).css({
					"z-index": zIndexCount,
					"cursor":"move"	
				});
				zIndexCount++;
			},
			stop: function(e, ui){
				$(this).css({
					"cursor":"default"
				});
				
				$(this).fadeTo(5, 1);
				
				var top = $(this).css("top");
				var left = $(this).css("left");
				var height = $(this).css("height");
				var width = $(this).css("width");
				
				if(saveable){
				
					baseroomproductid = $(this).attr("id").split('-')[2];
				
					// Save the dragged item with new coordinates.
					$.post("/ajax/layouts/", {
						method: 'saveLocation',
						baseroomproductid: baseroomproductid,
						top: top,
						left: left,
						height: height,
						width: width,
						z: zIndexCount - 1
					});
				
				}
				
				// Delay a moment to prevent the click event from going.
				setTimeout(function(){
					imgClickable = true;
				}, 100);
				
			}
		});
	}
	
	// Product Info stuff
	$("#canvas img").click(function(){
		if(imgClickable){
			showSidebar(this.id.split('-')[1]);
		}
	});
	
	// Product hover window
	$("#canvas img").mouseover(function(){
		clearTimeout(popupDelay); //remove the old delay, incase its still lingerin around
		clearTimeout(popupHideDelay);
		
		var t = this;
		
		lastProductid = t.id.split('-')[1];
		
		popupDelay = setTimeout(function(){
			// Pass the productid to showInfoWindow	
			showInfoWindow(t);
			
		}, 500);
	});
	$("#canvas img").mouseout(function(){
		clearTimeout(popupHideDelay); //remove the hide delay
		clearTimeout(popupDelay);
		popupHideDelay = setTimeout(function(){
			
			$("#infowindow").css("display", "none");
			
		}, 250);
	});
	
	$("#infowindow").unbind();
	$("#infowindow").mouseover(function(){
		clearTimeout(popupHideDelay);
	});
	$("#infowindow").mouseout(function(){
		popupHideDelay = setTimeout(function(){
			$("#infowindow").css("display", "none");
		}, 250);
	});
	
}

/*
* Create a room based on what is in productInfo, and then load that room.
*/
function room_create(){
	var pids = [];
	
	var mapping = '{';
	
	for(var i in productInfo){
		pids.push(i);
		
		var p;
		$("#canvas img").each(function(){
			if($(this).attr("id").split('-')[1] == i){
				p = this;
			}
		});

		mapping += '"'+i+'":{"top":"'+ $(p).offset().top +'","left":"'+ $(p).offset().left +'"},';
	}
	
	mapping = mapping.substr(0, mapping.length-1);
	mapping += "}";
	if(mapping == "{}"){
		mapping = "";
	}
	
	$.post("/ajax/layouts/",
		{
			'method': 'createBaseRoom',
			'baseid': parameters[0],
			'productids': pids.join(','),
			'mapping': mapping
		}, function(baseroomid){
			//fake the hash and load it.
			var hash = '#edit/' + baseroomid;
			hash = hash.replace(/^.*#/, '');
			// moves to a new page. 
			// pageload is called at once. 
			$.historyLoad(hash);
		}
	);
	
}

function showInfoWindow(target){
	var productid = target.id.split('-')[1];
	
	lastProductid = productid;
	
	$("#infowindow ul li").css("display", "none");
	
	$("#infowindow").fadeTo(5, 0, function(){
		var iw = $("#infowindow");
		iw.css("display", "block");
		
		// Find out if the hover elements top + it's height + the height of the info window
		//	is higher than the windows height.
		if(parseInt($(target).offset().top) + parseInt($(target).height()) + 5 + parseInt(iw.height()) > $(window).height() + $(window).scrollTop()){
			// If it is then show the info window on top
			iw.css({
				"left":$(target).offset().left,
				"top":$(target).offset().top - iw.height() - 5
			});
		}else{
			iw.css({
				"left":$(target).offset().left,
				"top":$(target).offset().top + $(target).height() + 5
			});
		}
		iw.fadeTo(5, 1);
	});
	
	var info = productInfo[productid];
	
	$("#productname").text(info.name);
	$("#productprice").text("$" + info.price);
	
	$("#buy a").attr("href", info.url);
	
	$("#info, #buy, #remove, #share").css("display", "block");
	
}

/*
* Record information about a product that exists in the canvas
*/
function addLayoutProduct(productinfo){
	productInfo[productinfo.productid] = {
		name: productinfo.name,
		image: productinfo.image,
		price: productinfo.price,
		program: productinfo.program,
		url: productinfo.url,
		permalink: productinfo.permalink,
		category: productinfo.category,
		description: productinfo.description
	};
	
	// Number of items
	$("#itemCount").text(parseInt($("#itemCount").text()) + 1);
	
	// Total price of the room
	$("#totalPrice").text(parseInt($("#totalPrice").text()) + parseInt(productinfo.price));
}

/*
* Remove a product from the current layout
*/
function removeFromRoom(productid){
	if(!productid){
		productid = lastProductid;
	}
	$("#canvas img").each(function(){
		if($(this).attr("id").split('-')[1] == productid){
			$(this).fadeOut(function(){
				$(this).remove();
			});
			$("#infowindow").css("display", "none");
		}
	});
	
	$.post("/ajax/layouts/",
		{
			method: 'removeProduct',
			baseid: parameters[0],
			productid: productid
		}
	);
	
	var productinfo = productInfo[productid];
	
	// Clean up the productInfo data structure, and the budget and total # of items
	$("#itemCount").text(parseInt($("#itemCount").text()) - 1);
	$("#totalPrice").text(parseInt($("#totalPrice").text()) - parseInt(productinfo.price));
	
}

function showSidebar(productid){
	var info = productInfo[productid];
	
	$(".right_sidebar h3").text(info.name);
	$(".right_sidebar #sideprice").text("$" + info.price);
	
	$(".right_sidebar #moreinfo").attr("href", info.url);
	$(".right_sidebar #vendor_name").text(info.program);
	
	$(".right_sidebar #viewCategory").text("See other " + getPluralCategory(info.category)).attr("href", "/planner/#/category/" + info.category);
	
	$(".right_sidebar .product_image").attr("src", info.image.small);
	
	$(".right_sidebar #shareUrl").attr("value", info.permalink.share);
	
	$(".right_sidebar #description").text(info.description);
	
	$("#sbremove a").unbind('click');
	$("#sbremove a").click(function(){
		removeFromRoom(productid);
		return false;
	});
	
	$("#sbremove, #sbbuy").css("display", "block");
	
	$(".right_sidebar").css("visibility", "visible");
	
	a2a_linkname=info.name + ' - ' + info.program + " | Sproost - Furniture and Interior Design";
	a2a_linkurl=info.permalink.public;
	$.getScript("http://static.addtoany.com/menu/page.js");
}
function hideSidebar(){
	$(".right_sidebar").css("visibility", "hidden");
	$(".right_sidebar .product_actions li").css("display", "none");
}



/*
* Rename the layout (#layoutName holds the current name)
* The DOM object clicked is passed
*/
// Keep track of whether we are editing the rename or not.
var editingName = false;
function rename(object){

	var ln = $("#layoutName");
	
	if(!editingName){
		// We are editing the name.
		editingName = true;
		
		ln.html('<input type="text" value="'+ ln.text() +'">');
		
		$(object).text('save');
		$(object).blur(); //remove the 'selection' (looks nicer)
	}else{
		// We are saving the rename.
		editingName = false;
		ln.text(ln.children("input").val());
		$(object).text('rename');
		$(object).blur(); //remove the 'selection' (looks nicer)
		
		$.post("/ajax/layouts/",
			{
				method: 'saveName',
				baseid: parameters[0],
				newName: ln.text()
			}
		);
	}
}

function canvas_loading(){
	$("#canvas").addClass("loading");
}

function canvas_doneload(){
	$("#canvas").removeClass("loading");
}

/* 3 different loose lay mapping options, setup by melissa */
var mapping = [
	{
		'accessory':{'height':90,'width':90,'top':110,'left':96,'z-index':10},
		'lounge chair':{'height':150,'width':150,'top':260,'left':612,'z-index':9},
		'coffee table':{'height':160,'width':160,'top':246,'left':418,'z-index':8},
		'media cabinet':{'height':170,'width':170,'top':259,'left':180,'z-index':7},
		'entertainment unit':{'height':170,'width':170,'top':259,'left':180,'z-index':7},
		'table lamp':{'height':100,'width':100,'top':62,'left':580,'z-index':6},
		'side table':{'height':120,'width':120,'top':151,'left':553,'z-index':5},
		'floor lamp':{'height':160,'width':160,'top':87,'left':196,'z-index':4},
		'throw pillow':{'height':100,'width':100,'top':58,'left':454,'z-index':3},
		'sofa':{'height':210,'width':210,'top':131,'left':342,'z-index':2},
		'rug':{'height':150,'width':150,'top':322,'left':298,'z-index':1}
	},
	{
		'accessory':{'height':90,'width':90,'top':150,'left':645,'z-index':10},
		'floor lamp':{'height':160,'width':160,'top':108,'left':548,'z-index':9},
		'lounge chair':{'height':150,'width':150,'top':230,'left':141,'z-index':8},
		'coffee table':{'height':160,'width':160,'top':319,'left':441,'z-index':7},
		'media cabinet':{'height':170,'width':170,'top':237,'left':619,'z-index':6},
		'entertainment unit':{'height':170,'width':170,'top':237,'left':619,'z-index':6},
		'table lamp':{'height':100,'width':100,'top':62,'left':183,'z-index':5},
		'side table':{'height':120,'width':120,'top':138,'left':255,'z-index':4},
		'throw pillow':{'height':100,'width':100,'top':70,'left':412,'z-index':3},
		'sofa':{'height':210,'width':210,'top':206,'left':391,'z-index':2},
		'rug':{'height':150,'width':150,'top':323,'left':257,'z-index':1}
	},
	{
		'throw pillow':{'height':100,'width':100,'top':63,'left':278,'z-index':10},
		'accessory':{'height':90,'width':90,'top':140,'left':641,'z-index':9},
		'floor lamp':{'height':160,'width':160,'top':85,'left':554,'z-index':8},
		'lounge chair':{'height':150,'width':150,'top':199,'left':230,'z-index':7},
		'coffee table':{'height':160,'width':160,'top':244,'left':413,'z-index':6},
		'media cabinet':{'height':170,'width':170,'top':260,'left':584,'z-index':5},
		'entertainment unit':{'height':170,'width':170,'top':260,'left':584,'z-index':5},
		'table lamp':{'height':100,'width':100,'top':140,'left':114,'z-index':4},
		'side table':{'height':120,'width':120,'top':265,'left':116,'z-index':3},
		'sofa':{'height':210,'width':210,'top':139,'left':412,'z-index':2},
		'rug':{'height':150,'width':150,'top':316,'left':310,'z-index':1}
	}
];

function getPluralCategory(cat){
	var p = {
		'bench': 'benches',
		'accessory': 'accessories'
	};
	if(p[cat.toLowerCase()]){
		return p[cat.toLowerCase()];
	}
	return cat + 's';
}