$(function(){
	$('#promo_top').hide();
	$('#promoNext').hide();
	$('#promoPrev').hide();
	$("#iSlideShow").promoarea(promoConf);
});


(function($){

	$.fn.promoarea = function(options){
		
		var _self = this;
		var _intervalid;
		var _pageintervalid;
		var _currentMouseOver;
		
		var defaults = {
			jsonPath: '../api/promo.json',
			topInterval: 3000,
			promoInterval: 3000,
			categories : {
				TOP:{id:999},
				ALL:{id:0, title:''},
				UR:{id:1, url:'http://www.urban-research.com/UR/', caption:'UR', img:'img/promo/link_ur.gif'},
				iD:{id:2, url:'http://www.urban-research.com/id/', caption:'iD', img:'img/promo/link_id.gif'},
				ROSSO:{id:3, url:'http://www.rosso.me.uk/', caption:'ROSSO', img:'img/promo/link_rosso.gif'},
				DOORS:{id:4, url:'http://urdoors.com/', caption:'DOORS', img:'img/promo/link_doors.gif'},
				KAGURE:{id:5, url:'http://www.kagure.jp', caption:'かぐれ', img:'img/promo/link_kagure.gif'},
				KBF:{id:6, url:'http://www.kbf.tv', caption:'KBF', img:'img/promo/link_kbf.gif'},
				WAREHOUSE:{id:7, url:'http://www.urban-research.com/WH/', caption:'UR WAREHOUSE', img:'img/promo/link_warehouse.gif'},
				PICKUP:{id:8, url:'http://www.urban-research.com/sepecial', caption:'Pick up', img:'img/promo/link_pickup.gif'},
				SHOP:{id:9, url:'http://www.urban-research.jp/', caption:'Online Shop', img:'img/promo/link_onlineshop.gif'},
				STORE:{id:10, url:'', caption:'UR Store', img:'img/promo/link_urstore.gif'}
			}
		}
		var _direction = ["up",'down','left','right'];

		var options = $.extend({}, defaults, options);
		
		this.categories = options.categories;
		
		this.json = {};
		
		this.menus = [];
		
		this.currentCategoryID = this.categories.TOP;
		
		this.currentTarget = null;
		
		this.currentPage = 0;
		
		this.perPage = 8;
		
		this.maxPage = 0;
		
		this.currentCategory = undefined;
		
		this.firstview = true;
		
		this.top = undefined;
		
		this.init = function(){
			var top = this.json.top;
			$('#promo_top').hide();
			this.top = $('<li><a title="' + top.caption + '" href="' + top.url + '" target="blank"><img src="' + top.image + '" width="950" height="371" alt="' + top.caption + '" /></a></li>');
			$('#promoNext').click(function(){
				_self.next();
				$('#nextNumber').text(_getPageText(1));
				return false;
			}).hover(
				function(){
					$('#nextNumber').show();
					$('#nextNumber').text(_getPageText(1));
				}
				,function(){
					$('#nextNumber').hide();
				}
			);
			$('#promoPrev').click(function(){
					_self.prev();
					$('#prevNumber').text(_getPageText(-1));
					return false;
				}).hover(
				function(){
					$('#prevNumber').text(_getPageText(-1));
					$('#prevNumber').show();
				},
				function(){
					$('#prevNumber').hide();
				}
			);
			/*
			$('#promo_top').click(function(){
				_build(_self.categories.ALL.id, $('#iSlideShow_Menu_' + "ALL" + ' > a'));
			});
			*/
			_bind();
		}
		
		function _getPageText(suffix)
		{
			return (_self.currentPage + suffix + 1) + "/" + (Math.ceil(_self.maxPage / _self.perPage) + (_self.currentCategory==0 ? 1 : 0));
		}
		
		function _bind()
		{

			$("#iSlideShow_Menu > li > a").unbind("mouseenter mouseleave");
			
			$("#iSlideShow_Menu > li").each(function(){
				var id = this.id;

				if(this.id != '')
				{
					id = id.split('_')[2];
					$("a", this).attr("href", _self.categories[id].url);
					$("a", this).hover(function(){
					
						var categoryid = _self.categories[id].id;
						var target = this;

						
						if(_self.currentTarget && _self.currentTarget.attr("href") == $(this).attr("href")) return false;

						if(_intervalid) clearInterval(_intervalid);
						_intervalid = setTimeout(function(){
							//$.address.value(id == 'ALL' ? '' : id);
							$.address.value(id);
						}, 300);
					}, function(){
						if(_intervalid) clearInterval(_intervalid);
					}).click(function(){ return false; });
				}
			});
			
			
			$.address.init(function(event){
				debug('init')
			}).change(function(event){
				var q = $.address.value().split("/")[1];
				q = q == '' ? 'ALL' : q;
				_build(_self.categories[q].id, $('#iSlideShow_Menu_' + q + ' > a'))
			}).externalChange(function(event){
				debug('external')
			}).history(true);
			
			if($.address.value() != '' && $.address.value() != '/')
			{
				var q = $.address.value().split("/")[1];
				
				if(q in _self.categories)
				{
					//_build(_self.categories[q].id, $('#iSlideShow_Menu_' + q))

					$('#iSlideShow_Menu_' + q + ' > a').trigger("mouseover")
					_build(_self.categories[q].id, $('#iSlideShow_Menu_' + q + ' > a'))

				}
			}else {
				/*
				_intervalid = setTimeout(function(){
					var q = 'ALL';
					_build(_self.categories[q].id, $('#iSlideShow_Menu_' + q + ' > a'));
				}, options.topInterval)
				*/
				_build();
			}
		}
		
		function _build(categoryid, target)
		{
			if(_intervalid) clearInterval(_intervalid);
			
			$(target).addClass("current");
			if(_self.currentTarget != null){
				_self.currentTarget.removeClass("current");
			}
			_self.currentTarget = $(target);
			_self.build(categoryid);
		}
		
		this.next = function(){
			this.currentPage++;
			var max = Math.min(this.perPage * (this.currentPage + (this.currentCategory==0 ? 0 : 1)), this.maxPage);
			this.buildThumbnail(max);
		}
		
		this.prev = function()
		{
			this.currentPage--;
			var max = Math.min(this.perPage * (this.currentPage + (this.currentCategory==0 ? 0 : 1)), this.maxPage);
			this.buildThumbnail(max);
		}
		
		
		this.hasNext = function(){
			return this.currentPage + 1 < this.maxPage;
		}
		
		this.gotoPage = function(page){
			debug(page);
			this.currentPage = page;
			this.buildThumbnail( this.perPage * (page + (this.currentCategory==0 ? 0 : 1)));
		}
		
		
		this.buildThumbnail = function(max)
		{
			if(_intervalid != undefined)
			{
				clearTimeout(_intervalid);
				_intervalid = undefined;
			}
			
			if(_pageintervalid != undefined)
			{
				clearInterval(_pageintervalid);
				_pageintervalid = undefined;
			}
			
			
			if(this.currentCategory == 0 && max < this.maxPage){
				_pageintervalid = setTimeout(
					function(){
						$('#promoNext').trigger('click');
					},
					options.promoInterval
				);
			}else if(this.currentCategory==0){
				_pageintervalid = setTimeout(
					function(){
						_self.gotoPage(1);
					},
					options.promoInterval
				);
			}
			
			
			
			var cont = $('#iSlideShow');

			if($('ul.iSlideShow_Content', cont).length > 1) {
				$('ul.iSlideShow_Content > li').stop(true);
				$('ul.iSlideShow_Content').remove();
			}
			
			var max2 = $('li', $("ul.iSlideShow_Content")).length;
			

			
			$('li', $("ul.iSlideShow_Content")).each(function(i){
				if(this == _self.top[0]){
					$(this).stop().hide('slide', {ease:'easeInExpo', direction:'left'}, 500, function(){ $(this).parent().remove(); });
				}
				else
				{
					$(this).stop().fadeOut(500, function(){
						if(max2 == (i + 1)){
							$(this).parent().remove();
							$(this).remove();
						}
					});
				}
			});
	
						
			$("ul.iSlideShow_Content.current").removeClass('current');
			
			cont = $('<ul class="iSlideShow_Content current"></ul>');
			$("#iSlideShow").prepend(cont);
			
			var current = this.currentPage - (this.currentCategory == 0 ? 1 : 0);
			
			
			if(current == -1)
			{
				cont.append(this.top);
				this.top.attr('style', '').show("slide", {easing:'easeInOutExpo', direction:'left'}, 500);
				this.naviSet();
				return;
			}
			
			
			var j = 0;
			for(var i= current * this.perPage; i < max; i++)
			{
				var c = this.menus[i];
				c.hover(function(){
					$(this).fadeTo(50, .75)
				}, function(){
					$(this).fadeTo(50, 1)
				});
				cont.append(c);
				c.attr('style', '').show("slide", {easing:'easeInOutExpo', direction:_direction[Math.floor(Math.random()*4)]}, 500);
			}
			
			this.naviSet();
		}
		
		
		this.build = function(categoryId){
			if(_intervalid != undefined){
				clearInterval(_intervalid);
				_intervalid = undefined;
			}
			if(_pageintervalid != undefined)
			{
				clearInterval(_pageintervalid);
				_pageintervalid = undefined;
			}
			
			
			this.currentPage = 0;
			
			if(categoryId === undefined || categoryId==999)
			{
				categoryId = 0;
			}
			if(categoryId == 0 && $.address.value() == '/ALL') this.currentPage = 1;
			
			
			var d = this.json.data;

			while(this.menus.length > 0)
			{
				var c = this.menus.pop();
				c.stop();
				delete c;
			}
			
			
			debug($.address.value());
			
			
			$("ul.iSlideShow_Content").remove();
			
			var cont = $('<ul class="iSlideShow_Content current"><ul>');
			$('#iSlideShow').prepend(cont);
			//$('li', cont).remove();
			
			var j = 0;
			var cat = _getCategory(categoryId);

			d = d.slice();
			if(categoryId != this.categories.ALL.id) d.unshift({categoryId:categoryId, caption:cat.caption, image:cat.img, url:('url' in cat ? cat.url : '')});
			
			if(categoryId == 0 && $.address.value() != '/ALL')
			{
				//d.unshift({categoryId:categoryId, caption:'top', image:'img/promo/top/top.jpg', url:'http://www.yahoo.co.jp'});
				cont.append(this.top);
				debug('categoryid = ' + categoryId);
				///this.top.css({opacity:1}).show("slide", {easing:'easeInOutExpo', direction:'left'}, 500);
				if(this.firstview == true){
					this.firstview = false;
				}else{
					this.top.hide().fadeIn(500);
				}
				_pageintervalid = setTimeout(function(){
					debug('next');
					$('#promoNext').trigger('click');
				}, options.topInterval);
			}else if(categoryId == 0){
				_pageintervalid = setTimeout(function(){
					debug('next');
					$('#promoNext').trigger('click');
				}, options.promoInterval);
			}
			for(var i=0; i<d.length; i++)
			{
				if(categoryId == d[i].categoryId || categoryId == 0){
					if( 'url' in d[i] && d[i].url != '' ){
						c = $('<li><a title="' + d[i].caption + '" href="' + d[i].url + '" target="blank"><img src="' + d[i].image + '" width="237" height="185" alt="' + d[i].caption + '" /></a></li>');
						c.hover(function(){
							$(this).fadeTo(50, .75)
						}, function(){
							$(this).fadeTo(50, 1)
						});
					}else{
						c = $('<li><img src="' + d[i].image + '" width="237" height="185" alt="' + d[i].caption + '" /></li>');
					}
					

					
					if((this.menus.length+1) % 4 == 0) {
						c.addClass('last')
					}
					
					if( j < 8 ) {
						if( categoryId==0 && $.address.value() != '/ALL' )
						{}
						else{
							cont.append(c);
							c.css({opacity:1}).show("slide", {easing:'easeInOutExpo', direction:_direction[Math.floor(Math.random()*4)]}, 500);
						}
						j++;
					}
					this.menus.push(c);
				}
			}

			this.currentCategory = categoryId;
			this.maxPage = this.menus.length;
			this.naviSet();
		}
		
		
		this.naviSet = function()
		{
			if(this.perPage * ((this.currentPage + 1) -  (this.currentCategory==0 ? 1 : 0) ) < this.maxPage)
			{
				$('#promoNext').show();
			}
			else
			{
				$('#promoNext').hide();
				$('#nextNumber').hide();
			}
			
			if(this.currentPage - (this.categoryId==0 ? 0 : 1) >= 0)
			{
				$('#promoPrev').show();
			}
			else
			{
				$('#promoPrev').hide();
				$('#prevNumber').hide();
			}
		}
		
		function _jsonData()
		{
			$.getJSON(options.jsonPath, function(json){

				_self.json = json;
				_self.init();

			});
		}
		
		function _getCategory(id)
		{
			for(var i in _self.categories)
			{
				if(_self.categories[i].id == id){
					return _self.categories[i];
				}
			}
		}
		
		_jsonData();
	}
	

	
	
	function debug($obj) {
		//if (window.console && window.console.log)
		//	window.console.log($obj);
		//else
			//alert($obj)
	};
})(jQuery);
