// showroom.js: general showroom management

var Showroom = function() {
	// configuration
	var DEFAULT_SECTION = 3;

	// private variables & initialization
	var metadata = null;
	var departmentId = null;
	var sectionId = null;
	var productId = null;
	var sections = null;
	var config = null;
	var palette = null;
	var currentMode = null;
	var initializing = true;
	var gridScroll = null;

	// private methods
	function resizeNavbar() {
		var container = document.getElementById('navbar');
		var width = container.offsetWidth;
		var upperTotal = 0;
		var uL = container.children[0].getElementsByTagName('ul');
		for(var i = 0; i < uL.length; i++) {
			var lI = uL[i].parentNode;
			upperTotal += lI.offsetWidth;
			var lowerTotal = 0;
			for(var j = 0; j < uL[i].children.length; j++)
				lowerTotal += uL[i].children[j].offsetWidth;
			var lowerResizedTotal = 0;
			for(var j = 0; j < uL[i].children.length - 1; j++) {
				var w = Math.floor(width * uL[i].children[j].offsetWidth / lowerTotal);
				uL[i].children[j].style.width = w + 'px';
				lowerResizedTotal += w;
			}
			uL[i].children[uL[i].children.length - 1].style.width = (width - lowerResizedTotal) + 'px';
		}
		var upperResizedTotal = 0;
		for(var i = 0; i < uL.length - 1; i++) {
			var lI = uL[i].parentNode;
			var w = Math.floor(width * lI.offsetWidth / upperTotal);
			lI.style.width = w + 'px';
			upperResizedTotal += w;
		}
		uL[uL.length - 1].parentNode.style.width = (width - upperResizedTotal) + 'px'
	}
	
	function getColorName(c) {
		c = c.substr(1).split('-');
		return palette[c[0]].colors[c[1]];
	}

	function convertFloat(n, d) {
		if(typeof d != 'number' || isNaN(d) || d < 0) d = 0;
		else d = Math.floor(d);
		if(typeof n != 'number' || isNaN(n)) return '';
		var s = n.toString();
		var i = s.indexOf('.');
		if(i >= 0) {
			if(d > 0) {
				if(s.length > i + d + 1) s = s.substr(0, i + d + 1);
			} else {
				s = s.substr(0, i);
			}
		}
		// this for italy
		return s.replace(/\./g, ',');
	}
	
	function convertFixed(n, d) {
		if(typeof d != 'number' || isNaN(d) || d < 0) d = 0;
		else d = Math.floor(d);
		if(typeof d != 'number' || isNaN(n)) return '';
		var s = n.toString();
		var i = s.indexOf('.');
		if(d > 0) {
			if(i < 0) {
				i = s.length;
				s += '.';
			}
			while(s.length <= i + d) s += '0';
			s = s.substr(0, i + d + 1);
		} else {
			if(i >= 0) s = s.substr(0, i);
		}
		// this for italy
		return s.replace(/\./g, ',');
	}

	// public methods
	return {
		getSection : function() {
			return sectionId;
		},
		
		getDepartment : function() {
			return departmentId;
		},
		
		setProduct : function(p) {
			productId = p;
		},
		
		getNImages : function() {
			return metadata === null ? 0 : metadata.length;
		},

		getItem : function(id) {
			var title = 'Prodotto';
			var image = '';
			if(typeof metadata[id] != 'undefined') {
				if(metadata[id].title !== null) title = metadata[id].title;
				if(metadata[id].image !== null) image = metadata[id].image;
			}
			return { 'title': title, 'image': image };
		},


		load : function() {
			var response = Core.sendRequest('metadata.json.php?s=' + sectionId);
			if(response.ok) metadata = response.content;
			else {
				metadata = null;
				document.location.reload(true);
			}
		},

		clearDescription : function() {
			var title = document.getElementById('description_title');
			var code = document.getElementById('description_code');
			var text = document.getElementById('description_text');
			var dimensions = document.getElementById('description_dimensions');
			var pieces = document.getElementById('description_pieces');
			var colors = document.getElementById('description_colors');
			var price = document.getElementById('description_price');
			var empty = document.getElementById('description_empty');
			title.innerHTML = '';
			code.innerHTML = '';
			text.innerHTML = '';
			price.innerHTML = '';
			dimensions.innerHTML = '';
			pieces.innerHTML = '';
			colors.innerHTML = '';
			empty.style.display = 'block';
		},

		updateDescription : function(id) {
			if(metadata === null || typeof metadata[id] == 'undefined' || metadata[id] === null)
				return Showroom.clearDescription();
			var title = document.getElementById('description_title');
			var code = document.getElementById('description_code');
			var text = document.getElementById('description_text');
			var dimensions = document.getElementById('description_dimensions');
			var pieces = document.getElementById('description_pieces');
			var colors = document.getElementById('description_colors');
			var price = document.getElementById('description_price');
			var empty = document.getElementById('description_empty');
			empty.style.display = 'none';
			title.innerHTML = metadata[id].title !== null ? metadata[id].title : 'Prodotto';
			code.innerHTML = 'EAN:&nbsp;' + (metadata[id].code !== null ? metadata[id].code : '<i>non&nbsp;disponibile</i>');
			text.innerHTML = metadata[id].text !== null ? metadata[id].text.replace(/\n/g, '<br />') : '<i>Nessuna&nbsp;descrizione</i>';
			price.innerHTML = (metadata[id].price !== null) ? (convertFixed(metadata[id].price, 2) + '&nbsp;&euro;') : '';
			var code = '';
			if(metadata[id].width !== null || metadata[id].height !== null || metadata[id].thickness !== null) {
				if(metadata[id].width !== null) code = convertFloat(parseFloat(metadata[id].width), 1);
				if(metadata[id].thickness !== null) {
					if(code != '') code += '&nbsp;&times;&nbsp;';
					code += convertFloat(parseFloat(metadata[id].thickness), 1);
				}
				if(metadata[id].height !== null) {
					if(code != '') code += '&nbsp;&times;&nbsp;';
//					code += convertFloat(parseFloat(metadata[id].height), 1);
					code += convertFloat(parseFloat(metadata[id].height), 1) + 'H';
				}
			}
//			if(code != '') dimensions.innerHTML = 'Dimensioni: ' + code + ' cm';
			if(code != '') dimensions.innerHTML = 'Dimensioni: cm ' + code;
			dimensions.innerHTML = 'Dimensioni:&nbsp;' + (code != '' ? (code + ' cm') : '<i>non&nbsp;disponibili</i>');
			pieces.innerHTML = 'Pezzi&nbsp;per&nbsp;imballo:&nbsp;' + (metadata[id].pieces !== null ? metadata[id].pieces : '<i>non&nbsp;disponibile</i>');
			code = '';
			if(metadata[id].colors !== null) for(var i = 0; i < metadata[id].colors.length; i++)
				code += '<div><span style="background-image: url(images/colors/24/' + metadata[id].colors[i].substr(1) + '.jpg);"></span>' + getColorName(metadata[id].colors[i]) + '</div>' + "\n";
			colors.innerHTML = code;
		},

		createNavbar : function() {
			var container = document.getElementById('navbar');
			var closing = '</div>';
			var code = '<ul>';
//			code += '<div><li id="department:0" class="selected"><a href="#" onclick="Showroom.select(0);"><span class="homeIcon"></span>' + config.pages.homeLabel + '</a><ul>';
			code += '<div><li id="department:0" class="selected" style="border-right: none;"><a href="#" onclick="Showroom.select(0); return false;"><span>' + config.pages.homeLabel + '</span></a><ul>';
			for(var j = 0; j < config.pages.homePages.length; j++)
				code += '<li id="text:' + j + '" ' + (j == 0 ? ' class="selected"' : '') + 'style="border-right: none;"><a href="#" onclick="Showroom.select(0, \'' + j + '\'); return false;"><span>' + config.pages.homePages[j].label + '</span></a></li>';
			code += '</ul></li>';
			for(var d in sections) {
				i = parseInt(d);
				secSize = container.clientWidth / sections[i].length - 21;
				code += '<div><li id="department:' + (i + 1) + '" style="border-right: none;"><a href="#" onclick="Showroom.select(' + (i + 1) + '); return false;"><span>' + config.departments[i] + '</span></a><ul>';
				for(var j = 0; j < sections[i].length; j++)
					code += '<li id="section:' + sections[i][j].id + '" style="border-right: none;"><a href="#" onclick="Showroom.select(' + (i + 1) + ', \'' + sections[i][j].id + '\'); return false;"' + (j == 0 ? ' class="selected"' : '') + '><span>' + sections[i][j].label + '</span></a></li>';
				code += '</ul></li>'
				closing += '</div>';
			}
			code += closing;
			container.innerHTML = code;
			resizeNavbar();
		},

		drawPage : function() {
			if(departmentId == 0) {
				document.getElementById('text').innerHTML = '';
				document.getElementById('text').className = 'loading';
				Core.loadContent('pages/' + config.pages.homePages[sectionId].name, null, document.getElementById('text'), function(request) { document.getElementById('text').className = ''; if(request.status != 200) document.getElementById('text').innerHTML = '<div class="textError">Impossibile caricare la pagina</div>'; });
				Showroom.setMode('text');
			} else {
				Grid.clear();
				Grid.draw();
			}
		},
		
		unselect : function() {
			var lL = document.getElementsByTagName('li');
			for(var i = 0; i < lL.length; i++)
				Core.removeClass(lL[i], 'selected');
		},

		select : function(d, s, noUpdate) {
			if(typeof noUpdate == 'undefined') noUpdate = false;
			if(d == departmentId && (typeof s == 'undefined' || s == sectionId)) return;
			Showroom.unselect();
			var prefix = d == 0 ? 'text:' : 'section:';
			var departmentElement = document.getElementById('department:' + d);
			var sectionElement;
			if(typeof s != 'undefined')
				sectionElement = document.getElementById(prefix + s);
			else {
				sectionElement = departmentElement.getElementsByTagName('li')[0];
				s = sectionElement.id.split(':')[1];
			}
			Core.addClass(departmentElement, 'selected');
			Core.addClass(sectionElement, 'selected');
			departmentId = d;
			sectionId = s;
			if(departmentId == 0) {
				metadata = null;
				Showroom.setMode('text');
			} else {
				Showroom.load();
				gridScroll = null;
				Showroom.setMode('grid');
			}
			Showroom.drawPage();
			if(!noUpdate && sections.length > 0) Showroom.updateHash();
		},
		
		setMode : function(mode) {
			if(typeof mode == 'undefined') mode = currentMode;
			if(!initializing) {
				switch(mode) {
					case 'text':
						Showroom.clearDescription();
						if(currentMode == 'slide') Slide.reset();
						gridScroll = null;
						document.getElementById('description_box').style.display = 'none';
						document.getElementById('grid').style.display = 'none';
						document.getElementById('slide').style.display = 'none';
						document.getElementById('text').style.display = 'block';
						document.getElementById('home_box').style.display = 'block';
						break;
					case 'grid':
						Showroom.clearDescription();
						if(currentMode == 'slide') Slide.reset();
						document.getElementById('home_box').style.display = 'none';
						document.getElementById('text').style.display = 'none';
						document.getElementById('slide').style.display = 'none';
						document.getElementById('grid').style.display = 'block';
						document.getElementById('description_box').style.display = 'block';
						if(gridScroll !== null) document.getElementById('grid').scrollTop = gridScroll;
						break;
					case 'slide':
						gridScroll = document.getElementById('grid').scrollTop;
						document.getElementById('home_box').style.display = 'none';
						document.getElementById('text').style.display = 'none';
						document.getElementById('grid').style.display = 'none';
						document.getElementById('slide').style.display = 'block';
						document.getElementById('description_box').style.display = 'block';
						break;
				}
			}
			currentMode = mode;
		},
		
		getMode : function() {
			return currentMode;
		},

		initializeSections : function() {
			var response = Core.sendRequest('metadata.json.php');
			if(!response.ok) document.location.reload(true);
			else sections = response.content;
		},
		
		updateHash : function() {
			hash = '/';
			if(departmentId != 0) {
				hash += sectionId;
			}
			if(productId !== null) {
				hash += '/' + metadata[productId].id;
			}
			document.location.hash = hash;
		},
		
		init : function() {
			var position = document.location.hash;
			if(position[0] == '#') position = position.substr(1);
			position = position.split('/')
			position.splice(0, 1);
			config = Core.sendRequest('config.json.php?showroom');
			palette = Core.sendRequest('dict/it/colors.json');
			var temp = document.cookie;
			Showroom.initializeSections();
//			Showroom.load();
			Showroom.createNavbar();
			var d = 0;
			var s = 0;
			if(position.length > 0) {
				for(var i = 0; i < sections.length; i++) {
					for(var j = 0; j < sections[i].length; j++) {
						if(sections[i][j].id == position[0]) {
							d = i + 1;
							s = sections[i][j].id;
							break;
						}
					}
				}
			}
			Showroom.select(d, s, true);
			if(d != 0 && position.length > 1) {
				for(var i = 0; i < metadata.length; i++) {
					if(metadata[i].id == position[1]) {
						Slide.open(i, true);
						Showroom.setMode('slide');
						break;
					}
				}
			}
			initializing = false;
			Showroom.setMode();
//			Showroom.updateHash();
		}
	}
} ();

Core.initLibrary(Showroom);

