/**
 * @version    2010-03-11 03:30:42
 * @copyright  Copyright (c) 2010, SOFTBANK MOBILE Corp.
 */

(function ($) {
var self = SBM.extra._09wi = SBM.plugin.tabs.extend({
	config:      {},
	index:       [],
	events:      {},
	model:       SBM.env.hash.replace(/\/.+$/, ''),
	hash:        SBM.env.hash.replace(/^.+\//, ''),
	transferred: true,
	xhr_content: null,
	xhr_caption: null,
	xhr_nav:     null,
	is_ie6:      /MSIE (\d)/.test(navigator.userAgent) && (parseFloat(RegExp.$1) < 7),
	
	/**
	 */
	init: function () {
		this.tpl.url = location.href.replace(/(09wi\/).*/, '$1');
		this.ajax.load('config.xml', { async: false, cache: false }, function (r) {
			this.each(r('model'), function (i, model) {
				model = $(model);
				var data = {
					index: i,
					id:    model.attr('id'),
					src:   model.attr('src'),
					title: model.find('title').text()
						.replace(/{n}/g,  '<br />')
						.replace(/{r}/g,  '&reg;')
						.replace(/{c}/g,  '&copy;')
						.replace(/{tm}/g, '&trade;'),
					css: this.map(model.find('link'),   function (link)   { return $(link).attr('href'); }),
					js:  this.map(model.find('script'), function (script) { return $(script).attr('src'); }),
					contents: {},
					getflashplayer: model.find('getflashplayer').attr('src')
				};
				this.each(model.find('content'), function (j, content) {
					content = $(content);
					var type = content.attr('type');
					data.contents[type] = content.attr('src');
					if (j == 0)
						data.contents.first = type;
				});
				
				self.config[data.id] = data;
				self.index.push(data.id);
				if (i == 0)
					self.config.first = data.id;
			});
			
			var model = self.model;
			self.validate(self.model, self.hash);
			if (model != self.model) {
				setTimeout(function () {
					location.href = 'lineup.html';
				}, 10);
				return;
			}
			
			$(function () {
				self.open($('#tabs li.' + self.hash + ' a'));
				self.console();
			});
		});
	},
	
	/**
	 */
	ready: function () {
		if (!window.adpsp_track)
			window.adpsp_track = function () {};
		
		$('#tabs li:first').remove();
		$('#tabs li').each(function () {
			var el = $('<div id="' + this.className + '"></div>');
			$('#tabs').parent().prepend(el.css({ padding: 0, margin: 0, 'float': 'none' }));
		});
		$('#tabs_bottom').html($('#tabs').html());
		
		$('#tabs, #tabs_bottom').find('a').click(function () {
			return self.open(this);
		});
		
		this.plugin.history.change(function (next, prev) {
			var prev_model = prev.replace(/\/.+$/, '') || self.config.first;
			var next_model = next.replace(/\/.+$/, '');
			var next_hash  = next.replace(/^.+\//, '');
			
			self.validate(next_model, next_hash);
			if (prev_model != self.model)
				self.transferred = true;
			
			self.open($('#tabs li.' + self.hash + ' a'), true);
		});
	},
	
	/**
	 * @param  {string}  model
	 * @param  {string}  hash
	 */
	validate: function (model, hash) {
		this.model = (model && this.config[model]) ? model : this.config.first;
		var contents = this.config[this.model].contents;
		this.hash = (hash && contents[hash]) ? hash : contents.first;
	},
	
	/**
	 * @return  {object}
	 */
	position: function () {
		var index = this.config[this.model].index;
		return {
			prev: (index > 0) ? index - 1 : this.index.length - 1,
			next: (index < this.index.length - 1) ? index + 1 : 0
		};
	},
	
	/**
	 */
	updateTitle: function () {
		var model = this.config[this.model];
		var title = $('<div>' + model.title + '</div>').text();
		document.title = title + ' | ソフトバンクモバイル';
		$('#tabs_bottom_wrap p').text(title);
		$('#frm-H-bcs li:last').text(title);
	},
	
	/**
	 * @param   {string|element}  el
	 * @param   {boolean}         [onchange]
	 * @return  {boolean}
	 */
	open: function (el, onchange) {
		var model = this.config[this.model];
		var tabs  = $('#tabs, #tabs_bottom');
		
		this.hash = $(el).parent().attr('class');
		
		tabs.find('a.on').removeClass('on');
		this.each(tabs.find('li'), function (tab) {
			tab = $(tab);
			tab[model.contents[tab.attr('class')] ? 'show' : 'hide']();
		});
		tabs.find('li.' + this.hash + ' a').addClass('on');
		
		this.updateTitle();
		
		if (!this.content) {
			if (/\//.test(this.env.hash))
				this.win.scroll('#' + this.hash);
		}
		else {
			var hash = this.transferred ? 'frm-H-bcs' : this.hash;
			if (!onchange)
				this.win.scroll('#' + hash, function () {
					adpsp_track(this.env.path.replace(/index\.html.*/, '') + '#' + self.model + '/' + self.hash, '');
					if (!self.is_ie6)
						this.plugin.history.add(self.model + '/' + self.hash);
				});
			else
				this.win.scroll('#' + hash);
		}
		
		if (this.transferred) this.transfer();
		this.load();
		
		return false;
	},
	
	/**
	 */
	transfer: function () {
		var model = this.config[this.model];
		
		$('body').attr({ 'class': 'm' + this.model });
		this.each(model.css, model.js, function (file) {
			switch (file.replace(/^.+\.(\w+)$/, ('$1').toLowerCase())) {
				case 'css':
					$('head').append('<link href="' + file + '" rel="stylesheet" type="text/css" media="all" />');
					break;
				case 'js':
					var e = self.events[self.model] = {};
					$.getJSON(file, function (json) {
						self.each(json, function (key, value) {
							e[key] = value;
						});
					});
					break;
			}
		});
		model.css = model.js = [];
		
		if (this.xhr_caption) this.xhr_caption.abort();
		if (this.xhr_nav)     this.xhr_nav.abort();
		
		this.xhr_caption = this.ajax.load(model.contents.caption, { cache: false }, function (r) {
			$('#caption').html(r.get('text'));
			self.xhr_nav = this.ajax.load(model.contents.nav, { cache: false }, function (r) {
				$('#nav').html(r.get('text'));
				self.transferred = false;
			});
		});
		
		if (this.content) {
			$('#externalMain').get(0).loadModel(this.model);
			this.plugin.enquete.ready();
			$('#enquete div.form').show();
			$('#enquete div.thanks, #enquete div.error').hide();
		}
	},
	
	/**
	 */
	load: function () {
		var contents  = this.config[this.model].contents;
		var signature = this.model + '-' + this.hash;
		
		if (this.content)     this.content.hide();
		if (this.xhr_content) this.xhr_content.abort();
		
		$('#layout div.content').hide();
		
		if ($('#' + signature).size()) {
			this.content = $('#layout div.content[id=' + this.hash + ']');
			this.content.show();
			$('#loading').hide();
		}
		else {
			$('#loading').show();
			$('#layout div.content[id=' + this.hash + ']').remove();
			this.xhr_content = this.ajax.load(contents[this.hash], { cache: false }, function (r) {
				$('#layout').prepend(r.get('text'));
				self.content = $('#layout div.content[id=' + self.hash + ']');
				self.content.append('<span id="' + signature + '"></span>');
				self.content.show();
				$('#loading').hide();
				
				var e = self.events[self.model];
				if (e) {
					if (e.id) {
						if (e[self.hash]) e[self.hash]();
					}
					else
						var timer = setInterval(function () {
							if (e.id) {
								if ((e.id == self.model) && e[self.hash])
									e[self.hash]();
								clearInterval(timer);
							}
						}, 10);
				}
			});
		}
	},
	
	/**
	 * @param  {string}  season
	 */
	main: function (season) {
		if (this.flash.version() >= 8) {
			var FlashVars = [
				'id='     + this.model,
				'season=' + season,
				'url='    + this.env.path.replace(/index\.html/, '')
			].join('&');
			
			var options = {
				id:                'externalMain',
				bgcolor:           '#000000',
				scale:             'noscale',
				salign:            'LT',
				allowScriptAccess: 'always',
				allowFullScreen:   'false',
				wmode:             'opaque',
				FlashVars:         FlashVars
			};
			if (this.env.query == 'introskip')
				options.FlashVars += '&introskip=1';
			$('#main').html('');
			this.flash.create('/mb/product/shared/swf/main.swf', 960, 484, options);
		}
		else {
			$('#main h1').remove();
			$('#main img').attr({ src: this.config[this.model].getflashplayer }).show();
		}
	},
	
	/**
	 */
	console: function () {
		var el = $('#console');
		
		el.show();
		el.after('<div style="height: 25px"></div>');
		el.find('a.prev, a.next').click(function () {
			var pos   = this.className;
			var index = self.position()[pos];
			
			self.validate(self.index[index], self.config[self.index[index]].contents.first);
			self.transferred = true;
			self.open($('#tabs li.' + self.hash + ' a'));
			$(this).mouseover();
			
			return false;
		}).mouseover(function () {
			var pos   = this.className;
			var index = self.position()[pos];
			var src   = self.config[self.index[index]].src;
			$('#console div.' + pos).html('<img src="' + src + '" />').show();
		}).mouseout(function () {
			var pos   = this.className;
			$('#console div.' + pos).hide();
		});
		
		if (this.is_ie6) {
			var d  = $(document);
			var w  = $(window);
			setInterval(function () {
				el.css({ top: d.scrollTop() + w.height() - 25 });
			}, 10);
		}
	},
	
	/**
	 * @param  {string}  url
	 */
	getURL: function (url) {
		if (/\/([3GX]+)\/09wi\//.test(url)) {
			var to   = RegExp.$1;
			var from = this.env.path.replace(/^.*\/([3GX]+)\/09wi\/.*$/, '$1');
			if (to == from) {
				var model = url.replace(/^.+#/, '');
				this.validate(model, null);
				this.transferred = true;
				this.open($('#tabs li.' + this.hash + ' a'));
				
				return;
			}
		}
		location.href = url;
	}
});

SBM.extra._09wi.init();
SBM.plugin.tabs = SBM.extra._09wi;
SBM.use('hub.product.view');
})(jQuery);
