function StructureView()
{
    this.prototype = BookessBase.call(this);
    this.requirement = ['jquery', 'tooltip', 'vote'];
    var self = this;

    this.urlCalls = {};

    this.messages =
    {
    	upgradeBrowser: 'O navegador que você está utilizando é muito antigo e, em breve, não ofereceremos mais suporte . <a href="http://www.whatbrowser.org/pt-br/" rel="external">Instale um navegador mais moderno</a> para uma melhor experiência na internet.',
    	booktip: 
    	{
    		pages: 'páginas'
    	}
    };

    this.urlBooktip = null;
    this.urlBookRate = null;
    this.urlBookList = null;
    this.urlBookListSave = null;
    this.urlLogin = null;
    this.urlLoginReturn = null;
    this.isLogged = false;
    var requestCache = {};
    var lastRequest = null;

    /*
	 * * Init
	 */    
    this.init = function()
    {
    	// Ativa PNG transparente para o IE 6
		if ($.browser.msie && $.browser.version <= 6) 
		{
			DD_belatedPNG.fix('.pngfix, .cover-small img, .cover-medium img, .cover-big img');
			
			var $upgradeBox = $('#upgrade-browser');
			
			$('.content', $upgradeBox).fadeTo(0, 0.96);
			$('.icon-windowclose-grey', $upgradeBox).click(function(){ $upgradeBox.fadeOut(); });
		}
		
		// Bordas arredondadas
		$('.rounded').roundedCorners(5);
		
		// Sombras
		$('.shadow').css
		({
			'-moz-box-shadow' : '0 0 5px #555555', /* Firefox */
			'-webkit-box-shadow' : '0 0 5px #555555', /* Safari and Chrome */
			'box-shadow' : '0 0 5px #555555'
		});

		$('.truncate').widthTruncate();
		
		$('#booktip').css
		({
			'-moz-box-shadow' : '0 0 1em #c0c0c0', 
			'-webkit-box-shadow' : '0 0 1em #c0c0c0', 
			'box-shadow' : '0 0 1em #c0c0c0'
		});
		
		$("*[title^='tooltip']").each
		(function() 
		{
			$(this).attr('title', this.title.replace(/^tooltip:\s*/i, ''))
				   .tooltip({
						track : true,
						showURL : false,
						fade : 250
					});
		});
		
		$("*[title^='booktip']").mouseenter(self.showBookTip);
		
		
		$(".network-checkbox").each(function()
		{
			$(this).hide();
			
			var $input = $(this);
			var name = this.name;
			var classes = $input.attr('className').replace(/network-checkbox\s*/, '');
			var className = 'icon-service-' + name;
			var checked = $input.is(':checked');
			var $checkbox = $('<span />').html('&nbsp');
			$checkbox.attr({
				className: className + '-' + (checked ? '' : 'un') + 'checked ' + classes,
				title: $input.attr('title')
			})
			.css('cursor', 'pointer');

			$checkbox.click(function()
			{
				if($input.is(':checked'))
				{
					$input.attr('checked', false);
					$checkbox.attr('className', className + '-unchecked');
				}
				else
				{
					$input.attr('checked', true);
					$checkbox.attr('className', className + '-checked');
				}
			});
			
			$checkbox.insertBefore($input);
		});
		
		
		
		$('.rate-box').each(function()
		{
			try
			{
				eval('var infos = ' + this.title + ';');
				$(this).attr('title', '');

				$(this).html('').vote(
				{
					url: self.urlBookRate,
					enabled: typeof(infos.enabled) != 'undefined' ? infos.enabled : self.isLogged,
					average: infos.media,
					params: {
						id: infos.bookId
					},
					onError: function()
					{
						alert('treste');
					}
				});
			}
			catch (e) {
				
			}
		});
		
		self.addHeaderEvents();
		self.addCoversEvents();
		self.addBookSelectList();
    };
    
    this.addBookSelectList = function()
    {
    	var last = {};
    	
    	$('.selectbox').each(function()
    	{
	    	var $selectbox = $(this);
			var $selectlist = $('.selectlist', $selectbox.parent());	
			var book = $selectbox.get(0).id.replace(/[^0-9]+([0-9]+)$/, '$1');
			
			/*		
				1 => favorito, 2 => já lido, 3 => lendo, 4 => relendo, 5 => pretende, 6 => possui, 7 => ganhar

				2 -> não 3, 5 	 		// quem já leu não pode estar lendo nem pretendendo ler
				3 -> não 2, 4, 5 		// quem está lendo não pode estar lendo, relendo nem pretender
				4 -> não 3, 5, sim 2 	// quem está relendo não pode estar lendo, pretendendo e deve ter lido
				5 -> não 2, 3, 4		// quem pretende ler não pode ter lido, está lendo ou relendo
			*/
			
			var rules = {2: {n: [3, 5]}, 3: {n:[2, 4, 5]}, 4:{n: [3, 5], y: [2]}, 5:{n: [2, 3, 4]}};
			
			if(!self.isLogged)
			{
				$('a', $selectlist).attr('href', self.urlLoginReturn);
			}
			else
			{
				$('a', $selectlist).click(function(event)
				{
					var $lists = $('a', $selectlist);
					var index = $lists.index(this);
					var $radio = $('.radio', this);

					if($radio.hasClass('icon-radio-unchecked'))
					{
						if(typeof(rules[index+1]) != 'undefined')
						{
							var types = ['n', 'y'];
							for(var t in types)
							{
								if(typeof(rules[index+1][types[t]]) != 'undefined')
								{
									for(var idx in rules[index+1][types[t]])
									{
										var $list = $('a:eq('+(rules[index+1][types[t]][idx]-1)+')', $selectlist);
										
										if([types[t]] == 'n')
										{
											$('.radio', $list).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-unchecked');
											$('input', $list.parents('li')).attr('checked', false);
										}
										else
										{
											$('.radio', $list).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-checked');
											$('input', $list.parents('li')).attr('checked', true);
										}
									}
								}
							}
							
							$lists.each(function(i) {
								if(i == index) return;
								
								if(typeof(rules[i+1]) != 'undefined' && typeof(rules[i+1].n) != 'undefined' && $.inArray(index+1, rules[i+1].n) >= 0 && $('.radio', this).hasClass('icon-radio-checked')) {
									$('.radio', this).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-unchecked');
									$('input', $(this).parents('li')).attr('checked', false);
								}
							});
						}
						
						$('.radio', this).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-checked');
						$('input', $(this).parents('li')).attr('checked', true);
					}
					else {
						
						if(typeof(rules[index+1]) != 'undefined')
						{
							$lists.each(function(i) {
								if(i == index) return;
								
								if(typeof(rules[i+1]) != 'undefined' && typeof(rules[i+1].y) != 'undefined' && $.inArray(index+1, rules[i+1].y) >= 0 && $('.radio', this).hasClass('icon-radio-checked')) {
									$('.radio', this).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-unchecked');
									$('input', $(this).parents('li')).attr('checked', false);
								}
							});
						}
						
						$('.radio', this).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-unchecked');
						$('input', $(this).parents('li')).attr('checked', false);
					}
					
					var data = {book: book};
					var name, checked;
					$('input[type=checkbox]', $selectlist).each(function()
					{
						name = /^[a-z]+\[([^\]]+)\]$/.exec(this.name);
						name = name[1];
						
						checked = $(this).is(':checked');
						if(checked != last[name]) {
							var $count = $('.lists .count-'+name);
							$count.parents('li').fadeOut('slow');
							$count.text(parseInt($count.text()) + (checked ? 1 : -1));
							$count.parents('li').fadeIn('slow');
						}
						
						data[this.name] = checked ? '1' : '0';
						last[name] = checked;
					});
		
					$.ajax({
					   type: 'POST',
					   url: self.urlBookListSave,
					   data: data
					 });
					
					event.stopPropagation();
					return false;
				});
			}
	
			$selectbox.disableSelection();
			$('span', $selectbox).text('Carregando lista...');
			
			$selectbox.each(function()
			{
				var onLoad = function(values)
				{
					 $('.radio', $selectlist).removeClass('icon-radio-checked icon-radio-unchecked').addClass('icon-radio-unchecked');
					 $('input', $selectlist).attr('checked', false);
	
					 for(var name in values) {
						last[name] = values[name];
						if(values[name]){
							var $radio = $("input[name='userlist["+name+"]']", $selectlist).attr('checked', true);
							$('span:first', $radio.next()).removeClass('icon-radio-unchecked').addClass('icon-radio-checked');
						}
					}
					
					$selectbox.hover(function() {
			    		$(this).addClass('selectbox-hover');
			    	},
			    	function() {
			    		$(this).removeClass('selectbox-hover');
			    	})
			    	.click(function(event) {
			    		if($selectlist.css('display').toLowerCase() == 'block')
			    			return;
			    		
			    		var onClick = function() {
			    			$selectbox.removeClass('selectbox-selected');
			    			$selectlist.hide();
			    			$(document).unbind('click', onClick);
			    		};
			    		
			    		$selectbox.addClass('selectbox-selected');
			    		$selectlist.show();
			    		
			    		$(document).click(onClick);
			    		
			    		event.stopPropagation();
			    	});
					
					$('span', $selectbox).text('Adicione à sua lista');
				};
				
				if(self.isLogged)
				{
					$.ajax({
					   type: 'POST',
					   url: self.urlBookList,
					   data: {book: book},
					   dataType: 'json',
					   success: onLoad
					 });
				}
				else {
					onLoad({});
				}
			});
    	});
    };
    
    /*
	 * * Add Header Events
	 * 
	 * - Criar os menus dropdowns
	 * - Cria os menus da busca
	 */
	this.addHeaderEvents = function()
	{
		$('#search-options').hide();

		// Dropdown menus
		$('.subnav').mouseenter(function() 
		{
			var $button = $(this);
			var $menu = $('.sublinks', $button.parent());
			
			$menu.show();
			$button.addClass('selected');
			
			$button.parent().mouseleave(function()
			{
				$menu.hide();
				$button.removeClass('selected');
			});
		});
		
		var baseDir = $('#search-form').attr('action');

		// Dropdown busca
		$('#search-options li').hover(function()
		{
			$(this).addClass('hover');
		}, 
		function() 
		{
			$(this).removeClass('hover');
		})
		.click(function() 
		{
			var urls = [ 
        	{
				field : 'search',
				url : 'books/listing/'
			}, 
			{
				field : 'usersearch',
				url : 'members/listing/'
			} ];

			var $parent = $(this).parent();
			var $label = $('#search-box .search-where span span');
			var $search = $('#search');
			var index = $('#search-options li').index(this);

			$('.radio', $parent).removeClass('checked');
			$('.radio', this).addClass('checked');

			$('#search-form').attr('action', baseDir + urls[index].url);
			$('#search').attr('name', urls[index].field);

			$label.text($(this).text());

			$parent.trigger('mouseleave');

			$search.focus();
			
			if($search.val())
			{
				var searchVal = $search.val();
				// move o cursor para o final do texto
				$search.focus().val(searchVal);
				
				// Opera bugfix
				if (!$.browser.msie)
				{
					$search[0].setSelectionRange(searchVal.length, searchVal.length);
				}
			}
			
		}).filter(':eq(0)').trigger('click');

		$('#search-box .search-where').mouseenter(function() 
		{
			var onHide = function() 
			{
				$('#search-options').unbind().hide();
				$(document).unbind('mousedown', onHide);
			};

			$(document).mousedown(onHide);
			$('#search-options').show().css('z-index', 10).mouseleave(onHide).mousedown(function(evt) 
			{
				evt.stopPropagation();
			});
		});

		$('#search-submit').click(function() 
		{
			$('#search-form').submit();

			return false;
		});

		$('#search-form').submit(function()
		{
			return $('#search').val().length > 2;
		});

		$('#search, .autoclean').autoclean();
	};

	/*
	 * * Add Covers Events
	 * 
	 * - Adicionar efeito de page flip às capas
	 * - Adiciona BookTip
	 */
	this.addCoversEvents = function()
	{
		$('.cover-small, .cover-medium, .cover-big').each(function()
		{
			self.addCoverEvent($(this));
		});
	};
	
	this.addCoverEvent = function($cover) {
		$cover.hover(function() 
		{
			$('.book-curl', this).show();
		
		}, function() 
		{
			$('.book-curl', this).hide();
		})
		.each(function()
		{
			var $container = $(this);
			var $curl = $('.book-curl', this).hide();
			var $cover = $('img', this);
			var $wrap = $('.cover-wrap', this);
			
			$cover.load(function()
			{				
				$(this).unbind('load');
				var cssWidth = parseInt($(this).css('width'));
				//$(this).css('width', 'auto');
				var width = parseInt($(this).width());
				var height = parseInt($(this).height());
				
				$container.css('width', width);
				
				if(height > width)
				{
					$wrap.addClass('portrait');
				}
				else if(height < width)
				{
					$wrap.addClass('landscape');
				}	
				else
				{
					$wrap.addClass('square');
				}
			})
			.each(function()
			{
				this.src = this.src;
			});
			
			if($cover[0].width > 0)
			{
				$cover.trigger('load');
			}
			
			$('img, .sale', this).tooltip
			({ 
			    track: true, 
			    showURL: false, 
			    fade: 250
			});
		});
	};
	
	/*
	 * * Show Book Tip
	 * - Adiciona um popup com mais informações sobre um livro
	 */   	
	this.showBookTip = function()
	{
		if (lastRequest) {
			lastRequest.abort();
			lastRequest = null;
		}
		
		$(document).trigger('mousemove');
		
		$(this).attr('title', '');		
		var $elm     = $(this).unbind('mouseenter');
		var $booktip = $('#booktip').stop().show().fadeTo(0, 1);	
		var $booktipContent = $('.booktip-content', $booktip).stop().show().fadeTo(0, 1);
		var bookId   = parseInt($(this).attr('id').replace(/[^0-9]+/g, ''));
		
		// Reset content
		$('h4', $booktip).text('');
		$('.authors a', $booktip).html('');
		$('.cite p', $booktip).text('');
		$('.pages', $booktip).text('');
		$('.rate-box', $booktip).html('');
		$('a.category', $booktip).text('');
				
		$booktip.addClass('booktip-loading');
		$booktipContent.hide();
		
		var onComplete = function(response)
		{
			if(response.result)
			{
				requestCache[bookId] = response;
				
				var data = response.data;
				
				$('h4', $booktip).text(data.title);
				//$('.photo', $booktip).attr({src: data.authorPhoto, title: data.author, alt: data.author});
				$('.authors a', $booktip).attr('href', data.authorProfile).html(data.author);
				$('.cite p', $booktip).text(data.synopsis);
				$('.pages', $booktip).text(data.pages + ' ' + self.messages.booktip.pages);
				$('.rate-box', $booktip).html('').vote({
					url: self.urlBookRate,
					enabled: data.logged,
					average: data.media,
					callback: function(rate)
					{
						requestCache[bookId].data.media = rate;
					},
					params: {
						id: bookId
					}
				});
				$('a.category', $booktip).attr('href', data.categoryUrl).text(data.category);
				
				$('.price-and', $booktip).hide();
				$('.mobile', $booktip).hide();
				
				if(data.price)
				{
					$('.price', $booktip).show();
					$('.price-paper', $booktip).text(data.price).show();
				}
				else
				{
					$('.price-paper', $booktip).hide();
				}

				if(data.digitalPrice)
				{
					$('.price', $booktip).show();
					$('.price-digital span:eq(1)', $booktip).text(data.digitalPrice).parent().show();
				}
				else
				{
					$('.price-digital', $booktip).hide();
				}
				
				if(!data.price && !data.digitalPrice )
				{
					$('.price', $booktip).hide();
				}
				else if(data.price && data.digitalPrice)
				{
					$('.price-and', $booktip).show();
				}
				
				
				$booktip.removeClass('booktip-loading');
				$booktipContent.fadeIn();				
			}
		};

		var stopPropagation = function(event) {
			event.stopPropagation();
		};
		
		var onMousemove = function()
		{
			$booktip.stop().fadeTo(0, 1).fadeOut();
			$(document).unbind('mousemove', onMousemove);
			$booktip.unbind('mousemove', stopPropagation);
			$elm.unbind('mousemove', stopPropagation).mouseenter(self.showBookTip);
		};
		
		var offset = $(this).offset();
				
		$booktip.css( {
			'left' : offset.left,
			'top' : offset.top
		});

		$booktip.fadeTo(0, 0).show().animate( {
			left : '+=' + $(this).width() + 'px',
			opacity : 1

		}, 300, 'swing').mousemove(stopPropagation);
		
		$(this).mousemove(stopPropagation);
		
		$(document).mousemove(onMousemove);
		
		
		if(self.util.inArray(self.util.arrayKeys(requestCache), bookId))
		{
			onComplete(requestCache[bookId]);
		}
		else
		{
			var request = self.httpRequest(self.urlBooktip, {id: bookId}, onComplete);	
			lastRequest = request;
		}
	};
	
	
	this.showMessage = function(text, type, autoClose, focus)
    {
        type = type ? 'dialog'+type : 'dialogsuccess';
        $.dialog(text, {className: type, autoClose: autoClose, closeButton: 'Fechar'}, focus);
    };
}
