// Copyright (c) 2009-2010 manga24.ru

Cookie = {
	get: function(name, def) {
		var cookies = document.cookie.split(';');
		for(var c in cookies) {
			var c = cookies[c].replace(/^\s*/, '');
			var pos = c.indexOf('=');
			if(c.substr(0, pos) == name) {
				return unescape(c.substr(pos+1));
			}
		}
		return def;
	},
	
	set: function setCookie(name, value, expires, path, domain, secure) {
		document.cookie = name + "=" + escape(value) +
			((expires) ? "; expires=" + expires : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "");
	}
};

Reader = {
	current: null,
	loaded: 0,
	in_window: false,
	
	settings: {
		defaults: {
			style: 1,
			scale_mode: 2,
			chapters_state: 1,
			panel_state: 1
		},
	
		load: function() {
			this.defaults.style = Cookie.get('style', this.defaults.style);
			this.defaults.scale_mode = Cookie.get('scale', this.defaults.scale_mode);
			
			for(var name in this.defaults) {
				this[name] = parseInt(this._get(name, this.defaults[name]));
			}
		},
		
		save: function() {
			for(var name in this.defaults) {
				this._set(name, this[name]);
			}
		},
		
		_prefix: 'r_',
		_get: function(name, def) {
			return Cookie.get(this._prefix + name, def);
		},
		
		_set: function(name, value) {
			Cookie.set(this._prefix + name, value, null, '/');
		}
	},
	
	init: function(data) {
		this.data = data;

		this.images = [];
		for(var i in data.images) {
			var img = data.images[i];
			this.images.push({
				name: img[0],
				width: img[1],
				height: img[2],
				url: this.data.dir + img[0],
				loaded: false
			});
		}
		$('#total_pages').text(this.images.length);
				
		var me = this;
		
		$('.window .close').click(function() {
			me.closeWindow();
			return false;
		});
		
		this.settings.load();
		this.settings.save();
		
		this.setScaleMode(this.settings.scale_mode);
		this.setStyle(this.settings.style);
		this.setPanelState(this.settings.panel_state);
		
		$('#chapters option').each(function() {
			$(this).data('real_text', $(this).text());
		});
		this.setChaptersState(this.settings.chapters_state);
		
		this.setPage(0);
		this.setHandlers();
	},
	
	setHandlers: function() {
		var me = this;
		
		var set_scale = function(scale_mode_mod) {
			me.setScaleMode(me.settings.scale_mode + scale_mode_mod);
			me.settings.save();
			me.updateSize();
		};
		
		$('#scale_mode').click(function(e) {
			set_scale(1);
			return false;
		}).bind('contextmenu', function() {
			set_scale(-1);
			return false;
		});
		
		$('#styles a').click(function(e) {
			me.setStyle(this.id.substr(5));
			me.settings.save();
			e.preventDefault();
			return false;
		});
		
		$('#chapters select').change(function() {
			me.setChapter($(this).val());
		});
		
		$('#page').change(function() {
			me.setPage($(this).val() - 1);
		});
		
		$('#prev_page').click(function() {
			me.prevPage();
			return false;
		});
		
		$('#next_page').click(function() {
			me.nextPage();
			return false;
		});
		
		$('#collapse_chapters').click(function() {
			me.setChaptersState(0);
			me.settings.save();
			return false;
		});
		
		$('#expand_chapters').click(function() {
			me.setChaptersState(1);
			me.settings.save();
			return false;
		});
		
		$('#help').click(function() {
			me.showWindow('help_wnd');
			return false;
		});
		
		$('#problem').click(function() {
			me.showWindow('problem_wnd');
			return false;
		});
		
		$('#show_panel').click(function() {
			me.setPanelState(1);
			me.settings.save();
			return false;
		});
		
		$('#hide_panel').click(function() {
			me.setPanelState(0);
			me.settings.save();
			return false;
		});
		
		$('#submit_problem').click(function() {
			var msg = $('#problem_desc').val();
			if(msg.length < 50) {
				alert('Минимальная длина сообщения - 50 символов!');
				return false;
			}
			me.closeWindow();
			$('#problem_desc').val('');

			$.post('/send_problem', { msg: msg, mirror: me.data.mirror }, function() {
				alert('Ваша заявка принята');
			});
			return false;
		});
		
		$(window).resize(function() {
			me.updateSize();
		});

		$(document).keyup(function(e) {
      if(me.in_window) return;
			switch(e.keyCode) {
				case 32: // Space
					me.setScaleMode(me.settings.scale_mode + 1);
					me.updateSize();
					return false;
				case 37: // Key Left
					me.prevPage();
					return false;
				case 39: // Key Right
					me.nextPage();
					return false;
        case 77:
          if(e.shiftKey) alert(me.data.mirror);
          return false;
			}
		});
	},
	
	setScaleMode: function(scale_mode) {
		scale_mode = (scale_mode + 4) % 4;
		$('#m0,#m1,#m2,#m3').hide();
		$('#m' + (this.settings.scale_mode = scale_mode)).show();
	},
	
	setStyle: function(style) {
		document.body.className = 'style' + style;
		this.settings.style = style;
	},
	
	setPanelState: function(state) {
		if(state) {
			$('#chapters, #menu').show();
			$('#show_panel').hide();
			$('#content').removeClass('mini');
		} else {
			$('#chapters, #menu').hide();
			$('#show_panel').show();
			$('#content').addClass('mini');
		}
		this.settings.panel_state = state;
	},
	
	setChaptersState: function(state) {
		$('#collapse_chapters, #expand_chapters').hide();
		$(state == 1 ? '#collapse_chapters' : '#expand_chapters').show();
		$('#chapters option').each(function() {
			var el = $(this);
			el.text(state == 1 ? el.data('real_text') : el.val());
		});
		this.settings.chapters_state = state;
	},
	
	setChapter: function(num) {
		window.location = this.data.mangaUrl + num + '/';
	},
	
	setPage: function(num) {
		this.current = num;
		$('#page')[0].selectedIndex = num;
		
		num == 0 ? $('#prev_page').hide() : $('#prev_page').show();
		num > 0 ? $('#prev_page_d').hide() : $('#prev_page_d').show();
		num == this.images.length - 1 ? $('#next_page').hide() : $('#next_page').show();
		num < this.images.length - 1 ? $('#next_page_d').hide() : $('#next_page_d').show();
		
		var me = this;
		var img = this.images[num];
		var on_load = function() {
			me.onImageLoad(num);
		};
		
		this.preload(num);
		
		var old = $('#manga');
		var el = $('<img>')
			.load(on_load)
			.click(function() {
				me.nextPage();
			})
			/*
			.bind('contextmenu', function() {
				me.prevPage();
				return false;
			})
			*/
			.error(function() {
				me.onImageError(num, on_load)
			})
			.attr({src: img.url, id: 'manga'});
		
		el.appendTo($('#mc'));
		
		old.remove();
		this.updateSize(el);
		window.scrollTo(0, 0);
	},

	updateSize: function(el) {
		el = el || $('#manga');
		var availHeight = $(window).height() - 7*2 - 5*2 - 1;
		var availWidth  = $(window).width() - 7*2 - 5*2 - 1;
		availWidth -= this.settings.panel_state ? 92 : 24;
    var realWidth  = this.images[this.current].width;
		var realHeight = this.images[this.current].height;
    
		var mode = this.settings.scale_mode;
    if(mode == 0) r = 1;
    else if(mode == 1) {
      var r = Math.min(availWidth / realWidth, availHeight / realHeight);
		
      if(r >= 1) r = 1;
      else if(r < 0.70) r = 0.70;
    } else if(mode == 2) {
      var r = availWidth / realWidth;
      if(r > 1) r = 1;
      var r2 = Math.max(availHeight / realHeight, 0.7);
      if(r2 < r) r = r2;
    } else if(mode == 3) {
      var r = Math.min(availWidth / realWidth, availHeight / realHeight);
		
      if(r >= 1) r = 1;
    }
		el.height(Math.round(realHeight*r)).width(Math.round(realWidth*r));

		$('#overlay_manga')
			.height(el.height())
			.width(el.width())
			.css({
				left: el.offset().left + 'px',
				top:  el.offset().top + 'px'
			});
},
	
	prevPage: function() {
		if(this.current == 0) {
			return;
		}
		this.setPage(this.current - 1);
	},
	
	nextPage: function() {
		if(this.current == this.images.length - 1) {
			if(this.data.nextChapter) this.setChapter(this.data.nextChapter);
      else window.location = this.data.mangaUrl;
			return;
		}
		this.setPage(this.current + 1);
	},
	
	preload: function(num) {
		if(num >= this.images.length) {
			return;
		}
		
		if(this.images[num].loaded) {
			return;
		}
		
		var me = this;
		var on_load = function() {
			me.onImageLoad(num);
		};
		
		$('<img>')
			.load(on_load)
			.error(on_load)
			.attr('src', this.images[num].url)
			.appendTo('#preload');
	},
	
	showWindow: function(name) {
		$('.window').hide();
		$('#overlay, #' + name).show();
		this.in_window = true;
	},
	
	closeWindow: function() {
		$('.window, #overlay').hide();
		this.in_window = false;
	},
	
	onImageLoad: function(num) {
		if(!this.images[num].loaded) {
			this.loaded++;
			this.images[num].loaded = true;
		}
		
		this.preload(num + 1);
		$('#loaded_pages').text(this.loaded);
	},
	
	onImageError: function(num, callback) {
		callback(num);
	}
};
