/* Sweet Menu! */

$(document).ready( function() {

	// Variables
	var maxDepth = 0;
	var itemHeight = 0;
	var mainColWidth = 0;
	var scrollMenu = undefined;
	var scroller = undefined;
	var parentChain = new Array();

	// Functions
	function swChkChildren( _item ) {
		_item.depth++;
		if ( _item.depth > maxDepth ) {
			maxDepth = _item.depth;
		}
		// Set col
		var currCol = $('#sw #menus #menu_col_'+_item.depth);
		if ( currCol.length == 0 ) {
			$('#sw #menus').append( '<div class="col" id="menu_col_'+_item.depth+'" sw:depth="'+_item.depth+'"></div>' );
			var currCol = $('#sw #menus #menu_col_'+_item.depth);
		}
		// Set parent
		if ( _item.parent == -1 ) {
			var currParent = $('#sw #menus #root_menu');
			if ( currParent.length == 0 ) {
				currCol.append( '<ul id="root_menu"></ul>' );
				var currParent = $('#sw #menus #root_menu');
			}
		} else {
			var currParent = $('#sw #menus #menu_'+_item.parent);
			if ( currParent.length == 0 ) {
				currCol.append( '<ul id="menu_'+_item.parent+'"></ul>' );
				var currParent = $('#sw #menus #menu_'+_item.parent);
			}
		}
		// Do stuff
		if ( _item.items ) {
			_item.type = "menu";
			currParent.append( '<li class="title" id="menu_item_'+_item.id+'" sw:menu="menu_'+_item.id+'" sw:parent="'+_item.parent+'">'+_item.name+'</li>' );
			
			var nextCol = $('#sw #menus #menu_col_'+(_item.depth+1));
			if ( nextCol.length == 0 ) {
				$('#sw #menus').append( '<div id="menu_col_'+(_item.depth+1)+'" class="col" sw:depth="'+(_item.depth+1)+'"></div>' );
				nextCol = $('#sw #menus #menu_col_'+(_item.depth+1));
			}
			nextCol.append( '<ul id="menu_'+_item.id+'" sw:name="'+_item.name+'" sw:parent="'+_item.parent+'"></ul>' );
			
			$.each( _item.items, function(n, item) {
				item.depth = _item.depth;
				item.parent = _item.id;
				item.parentname = _item.name;
				swChkChildren( item );
			});
		} else {
			_item.type = "item";
			currParent.append( '<li class="item" id="item_'+_item.id+'" sw:item="'+_item.id+'" sw:parent="'+_item.parent+'">'+_item.name+'</li>' );
		}
		//console.log( _item.name+" { col: "+currCol.attr("id")+"; parent: "+currParent.attr("id")+"; }" );
	}
	
	function loadSweetmenu() {
		// Hide windows
		$('#window div.item').hide();
		$('#window #front').addClass("sel").show();
		// Prepare load
		if ( $('#sw #working').length == 0 ) {
			$('#sw').append( '<div id="working" style="width: '+$('#sw').width()+'px; height: '+$('#sw').height()+'px; position: absolute; left: 0; top: 0; z-index: 1; display: none"></div>' );
		} else {
			$('#sw #working').css({
				width: $('#sw').width()+"px",
				height: $('#sw').height()+"px"
			});
		}
		// Load JSON
		$.getJSON( "action.php?format=1", function(json) {
			$('#sw #working').fadeIn("fast");
			if ( json.navigation ) {
				$('#sw').append( '<div id="menus" style="z-index: 0"></div>' );
				$.each( json.navigation, function(i, nav) {
					nav.depth = -1;
					nav.parent = -1;
					swChkChildren( nav );
				});
				maxDepth = $('#sw #menus .col').length;
				maxColWidth = $('#sw #menus').width()/maxDepth;
				//console.log( "maxDepth: "+maxDepth+"; colWidth: "+maxColWidth );
				$('#sw #menus .col').each( function(i) {
					//console.log( "#menu_col_"+i+" : "+(i*maxColWidth) );
					$(this).css({
						left: (i*maxColWidth)+"px",
						width: maxColWidth+"px"
					}).find("li").css({
						width: ( maxColWidth-12 )+"px"
					});
				});
				$('#sw #menus').css({
					/*width: $('#sw').width()+'px',*/
					height: $('#sw').height()+'px'
				});
				$('#sw #menus ul').not('#root_menu').hide();
				$('#sw #menus li').click( clickItem );
				// Complete load
				$('#sw #working').fadeOut( "fast", function() {
					//revealSeqNav();
					var jumpto = window.location.href.split("?");
					//console.log( jumpto[1] );
					jumpTo( jumpto[1] );
				});
			} else {
				$('#sw #working').hide();
				$('#sw').prepend( '<div id="msg">Unfortunately, the navigation failed to load!</div>' );
			}
		});
	}
	
	function loadFunctions( _obj ) {
		_obj.find('li').click( clickItem );
	}

	function clickItem() {
		var depth = parseInt( $(this).parent().parent().attr("sw:depth") );
		//console.log( $(this).attr("id")+": "+depth );
		$(this).parent().find('.sel').removeClass("sel");
		$(this).addClass("sel");
		if ( $(this).hasClass("title") ) {
			for ( i=(depth+1); i<=maxDepth; i++ ) {
				$('#sw #menus #menu_col_'+i+' .sel').removeClass("sel");
				$('#sw #menus #menu_col_'+i).hide().find('ul').hide();
				$('#sw #menus #scroll_'+i).hide();
			}
			openMenu( $(this).attr('sw:menu') );
		} else if ( $(this).hasClass("item") ) {
			viewItem( $(this).attr('sw:item') );
			$(this).addClass("visited");
		}
		//console.log( 'Clicked item: '+$(this).attr("id")+' { depth: '+depth+'; menu: '+$(this).attr("sw:menu")+'; item: '+$(this).attr("sw:item")+'; }' );
	}
	
	function openMenu( _menu ) {
		var menu = $('#sw #menus #'+_menu);
		if ( menu.length > 0 ) {
			if ( menu.css("display") == "block" ) {
				//console.log( menu.attr("class")+" is already open!" );
			} else {
				menu.parent().find('ul').hide();
				loadScroll( menu );
				menu.css( "top", 0 ).show().parent().fadeIn( "fast" );
				//console.log( "Open menu: "+menu.parent().attr("class")+" > "+_menu );
			}
		} else {
			//console.log( "No menu exists to open" );
		}
	}
	
	function loadScroll( _menu ) {
		var maxHeight = 0;
		var numItems = _menu.find("li").length;
		var colWidth = parseInt( _menu.parent().width() );
		var colHeight = $('#sw').height();
		var colDepth = parseInt( _menu.parent().attr("sw:depth") );
		var menuHeight = getMenuHeight( _menu );
		//console.log( _menu.attr("class")+" { colWidth: "+colWidth+"px; colHeight: "+colHeight+"px; colDepth: "+colDepth+"; menuHeight: "+menuHeight+"px; parentCol: #menu_col_"+colDepth+"; }" );
		// Hide other scrolls
		$('#sw #menus .scroll').each( function(i) {
			var getDepth = parseInt( $(this).attr("sw:depth") );
			if ( getDepth >= colDepth && $(this).css("display") == "block" ) {
				hideScroll( $(this) );
			}
		});
		// If menu is too tall, display a scroll
		if ( menuHeight > colHeight ) {
			generateScroll( _menu, colWidth, colHeight, colDepth, menuHeight );
		}
	}
	
	function getMenuHeight( _menu ) {
		var output = 0;
		_menu.find("li").each( function(i) {
			output += parseInt($(this).css("border-bottom-width"))+parseInt($(this).css("padding-top"))+parseInt($(this).css("padding-bottom"))+parseInt($(this).css("line-height"));
			var myChildren = $(this).children()
			for( i=0; i<myChildren.length; i++ ) {
				output += parseInt($(this).css("border-bottom-width"))+parseInt($(this).css("margin-top"))+parseInt($(this).css("padding-top"))+parseInt($(this).css("line-height"))+parseInt($(this).css("padding-bottom"))+parseInt($(this).css("margin-bottom"));
			}
		});
		return output;
	}
	
	function generateScroll( _menu, _colWidth, _colHeight, _colDepth, _menuHeight ) {
		// Scroller doesn't exist
		if ( $('#sw #menus #scroll_'+_menu.attr("id")).length == 0 ) {
			$('#sw #menus').append( '<div class="scroll" id="scroll_'+_menu.attr("id")+'" sw:parent="'+_menu.attr("id")+'" sw:depth="'+_colDepth+'" style="left: '+((_colWidth*(_colDepth+1))-4)+'px; display: none; width: 4px; height: 100%;"><div class="handle" style="position: absolute; left: 0; top: 0; height: '+Math.round((_colHeight/_menuHeight)*_colHeight)+'px"></div></div>' );
			$('#sw #menus #scroll_'+_menu.attr("id")+' .handle').draggable({
				axis: "y",
				containment: "parent",
				drag: function(e, ui) {
					var xPos = parseInt( $(this).css("top") );
					var target = $(this).parent().attr("sw:parent");
					var scrollHeight = $('#sw #menus #'+target).height()-$('#sw #menus').height();
					var maxPos = $('#sw #menus').height()-$(this).height();
					var newPos = -((xPos/maxPos)*scrollHeight);
					$('#sw #menus #'+target).css( "top", newPos );
					//console.log( "target = #sw #menus ."+target+" { xPos: "+xPos+"px; scrollHeight: "+scrollHeight+"px; maxPos: "+maxPos+"px; newPos: "+newPos+"px }" );
				}
			});
			$('#sw #menus #scroll_'+_menu.attr("id")).fadeIn( "fast" );
			//console.log( "Created #scroll_"+_menu.attr("class") );
		} else {
			//console.log( "Displaying #scroll_"+_menu.attr("class") );
			showScroll( $('#sw #menus #scroll_'+_menu.attr("id")) );
		}
	}
	
	function showScroll( _scroll ) {
		var getParent = _scroll.attr("sw:parent");
		var getDepth = _scroll.attr("sw:depth");
		for( i=0; i<$('#sw #menus #menu_col_'+getDepth).find('.scroll').length; i++ ) {
			var targetScroll = $('#sw #menus #menu_col_'+getDepth).find('.scroll:eq('+i+')');
			if ( targetScroll != _scroll ) {
				//console.log( targetScroll.attr("class")+" { depth: "+getDepth+" }" );
				hideScroll( $('#sw #menus #menu_col_'+getDepth).find('.scroll:eq('+i+')') );
			}
		}
		_scroll.fadeIn( "fast" );
	}
	
	function hideScroll( _scroll ) {
		var getParent = _scroll.attr("sw:parent");
		var getDepth = _scroll.attr("sw:depth");
		_scroll.find('.handle').css( "top", 0 ).parent().hide();
		$('#sw #menus .'+getParent).css( "top", 0 );
		//console.log( "Hiding "+_scroll.attr("id")+" { parent: "+getParent+"; depth: "+getDepth+"; }" );
	}
	
	function viewItem( _item ) {
		//console.log( "View: "+_item);
		revealSeqNav();
		loadItem( _item );
		/*var oldItem = $('#window .sel');
		var newItem = $('#window '+_item);
		if ( newItem.length > 0 && !newItem.hasClass("sel") ) {
			oldItem.removeClass("sel").css({ zIndex: 50 });
			newItem.addClass("sel").css({ zIndex: 100 }).fadeIn( "def", function() {
				oldItem.hide();
			});
		}*/
	}
	
	function jumpTo( _id ) {
		if ( parseInt(_id) != 0 ) {
			//console.log( "Jumping to: "+_id );
			parentChain = new Array();
			var findItem = $('#sw #menus #item_'+_id);
			if ( findItem.length == 1 ) {
				//console.log( "Item ID is legal" );
				getParent( findItem );
			}
			parentChain.reverse();
			if ( parentChain.length > 0 ) {
				$(parentChain[0]).trigger("click");
				$('#sw .sel').removeClass("sel");
				for ( i=0; i<parentChain.length; i++ ) {
					//console.log( parentChain[i] );
					$(parentChain[i]).addClass("sel");
					openMenu( $(parentChain[i]).attr("sw:menu") );
					if ( i == (parentChain.length-1) ) {
						var depth = parseInt( findItem.attr("sw:depth") );
						for ( i=(depth+1); i<=maxDepth; i++ ) {
							$('#sw #menus #menu_col_'+i+' .sel').removeClass("sel");
							$('#sw #menus #menu_col_'+i).hide().find('ul').hide();
							$('#sw #menus #scroll_'+i).hide();
						}
						findItem.trigger("click");
						scrollSnap( findItem );
						break;
					}
				}
			}
		}
	}
	
	function scrollSnap( _item ) {
		var scrollHandle = $('#sw #scroll_menu_'+_item.attr("sw:parent")+' .handle');
		if ( scrollHandle.length == 1 ) {
			var index = 0;
			var chkThisOut = _item.parent().children();
			for ( i=0; i<chkThisOut.length; i++ ) {
				if ( $(chkThisOut[i]).attr("id") == _item.attr("id") ) {
					index = i;
					scrollHandle.css({
						top: (((scrollHandle.parent().height()-scrollHandle.height())/(_item.parent().find("li").length-1))*index)+"px"
					});
					_item.parent().css({
						top: "-"+(((_item.parent().height()-_item.parent().parent().height())/(_item.parent().find("li").length-1))*index)+"px"
					});
				}
			}
			//console.log( index );
		}
	}
	
	function getParent( _item ) {
		if ( _item.attr("id") != "root_menu" ) {
			var parentItem = "#menu_item_"+_item.attr("sw:parent");
			if ( $(parentItem).length == 1 ) {
				parentChain.push( parentItem );
				getParent( $(parentItem) );
			}
		}
	}
	
	// Scroll Handle stuff
	$().mousedown( function(e) {
		if ( $(e.target).is(".handle") ) {
			$(e.target).parent().addClass("active");
			scrollMenu = $(e.target).parent().attr("sw:parent");
			scroller = $(e.target).parent();
		}
	}).mouseup( function(e) {
		if ( scrollMenu != undefined ) {
			scroller.removeClass("active");
			scroller = undefined;
			scrollMenu = undefined;
		}
	});
	
	function loadItem( _id ) {
		if ( $('#loaditem').length == 0 ) {
			//console.log( "Creating #loaditem" );
			$('#window').append( '<div id="loaditem" style="display: none"></div>' );
		}
		//console.log( "Setting #loaditem properties" );
		// Item has not already been loaded
		if ( $('#window #view_item_'+_id).length == 0 ) {
			$('#window').find("#loaditem").css({
				position: "absolute",
				left: 0,
				top: 0,
				width: $('#window').css("width"),
				height: $('#window').css("height"),
				zIndex: 200
			}).fadeIn( "fast" );
			$.getJSON( 'action.php?format=1&action=view&type=item&id='+_id, function(data) {
				if ( data.reply == 1 ) {
					// Error msg
				} else {
					// Display the item
					var itemDetails = data.results[0];
					var imgSShow = "";
					if ( itemDetails.files.length > 1 ) {
						imgSShow = '<p class="imgsshow"><strong style="display: none">IMAGES: </strong>';
						for ( i in itemDetails.files ) {
							var selected = "";
							if ( i == 0 ) {
								selected = " sel";
							}
							imgSShow += '<span class="viewimg'+selected+'" sw:img="'+i+'">&nbsp;'+(parseInt(i)+1)+'&nbsp;</span>';
						}
						imgSShow += '</p>';
					}
					//console.log( imgSShow );
					var windowItem = '<div id="view_item_'+_id+'" class="item sel" style="display: none"><div class="col1"><img /></div><div class="col2"><div class="wrapper"><h4>'+itemDetails.cat+'</h4><h2>'+itemDetails.title+'</h2><p>'+itemDetails.description+'</p><div class="details">'+imgSShow+'<p><strong>TOOLS:</strong> '+itemDetails.tools+'</p><p><strong>DATE:</strong> '+itemDetails.date+'</p></div></div></div></div>';
					// Set window functions and special properties
					$('#window #loaditem').after( windowItem ).parent().find('#view_item_'+_id+' img').load( function() {
						//console.log( "Loaded item's image" );
						// Previous window
						var prevItem = $('#window .item.sel:visible').not('#view_item_'+_id);
						prevItem.removeClass('sel').css( "z-index", 0 );
						// After fading in remove previous window
						$('#window #view_item_'+_id).fadeIn( "fast", function(e) {
							// Fade out the working animation DIV
							$('#loaditem').fadeOut( "fast", function(e) {
								// Remove the previous item
								prevItem.hide();
							});
						});
					}).attr( "src", itemDetails.files[0] );
					$('#window #view_item_'+_id+' .viewimg').click( function(e) {
						$(this).parent().find(".sel").removeClass("sel").addClass("visited");
						$(this).addClass("sel");
						var currImg = $(this).parent().parent().parent().parent().parent().find("img");
						var newImg = itemDetails.files[parseInt($(this).attr("sw:img"))];
						if ( currImg.attr("src") != newImg ) {
							$('#window #loaditem').css({
								width: currImg.width()+"px"
							}).fadeIn( "fast", function() {
								currImg.attr( "src", newImg );
							});
						}
					});
					$('#window #view_item_'+_id+' a').click( function(e) {
						e.preventDefault();
						var splithref = $(this).attr("href").split("?");
						if ( parseInt(splithref[1]) > 0 ) {
							//console.log( splithref[1] );
							jumpTo( splithref[1] );
						} else {
							window.location = $(this).attr("href");
						}
					});
					//console.dir( itemDetails );
					// View item
				}
			});
		// Item has already been loaded
		} else {
			//console.log( "Showing #window #item_"+_id );
			var prevItem = $('#window .item.sel:visible').not('#view_item_'+_id);
			prevItem.removeClass('sel').css( "z-index", 0 );
			$('#window #view_item_'+_id).css( "z-index", 100 ).addClass('sel').fadeIn( "fast", function(e) {
				prevItem.hide();
			});
		}
	}
	
	function revealSeqNav() {
		if ( $('#seqnav').length == 0 ) {
			$('#window').append( '<div id="seqnav" style="display:none; position: absolute; right: 8px; bottom: 8px; z-index: 200"><span class="previtem" title="View the previous project">&lt; PREV</span><span class="nextitem" title="View the next project">NEXT &gt;</span></div>' ).find('#seqnav').fadeIn( "fast" );
			$('#seqnav .nextitem').click( function(e) {
				var currItem = $('#window .item:visible').attr("id");
				var splitItem = currItem.split("_");
				if ( splitItem.length == 3 ) {
					currItem = splitItem[1] + "_" + splitItem[2];
					var currPos = $('#sw .item:visible').index( $('#'+currItem) );
					var nextItem = $('#sw .item:visible')[(currPos+1)];
					if ( $(nextItem).length > 0 ) {
						jumpTo( $(nextItem).attr("sw:item") );
					}
				}
			});
			$('#seqnav .previtem').click( function(e) {
				var currItem = $('#window .item:visible').attr("id");
				var splitItem = currItem.split("_");
				if ( splitItem.length == 3 ) {
					currItem = splitItem[1] + "_" + splitItem[2];
					var currPos = $('#sw .item:visible').index( $('#'+currItem) );
					var prevItem = $('#sw .item:visible')[(currPos-1)];
					if ( $(prevItem).length > 0 ) {
						jumpTo( $(prevItem).attr("sw:item") );
					}
				}
			});
		}
	}

	// Sweet menu initialisation
	loadSweetmenu();

});