/**
 * Scripts for [Space Shower TV Plus]
 * using jQuery JavaScript Framework
 *
 * @author     RaNa design associates, inc.
 * @copyright  2011 RaNa design associates, inc.
 *
 * @Update     2011-06-02 17:25:42
 */

(function($) {

$.sstvGlobal = {
// set class "os_mac" or "os_win" to <body> element
	osClass: function() {
		if (navigator.userAgent.indexOf("Mac") != -1) {
			jQuery("body").addClass("os_mac");
		} else if (navigator.userAgent.indexOf("Windows") != -1) {
			jQuery("body").addClass("os_win");
		} else {
			return false;
		}
	},

// auto rollover
	autoRollOver: function() {
		var conf = {
			suffix: "_on",
			selector: "img.rollover, input[type=image].rollover"
		};
		$(conf.selector).each(function() {
			var src = $(this).attr("src");
			var extpos = src.lastIndexOf(".");
			var srcOn = src.slice(0, extpos) + conf.suffix + src.slice(extpos, src.length);
			if (src.slice(extpos - 3, extpos) === conf.suffix) { return true; }
			new Image().src = srcOn;
			$(this).hover(function() {
				$(this).attr("src", srcOn);
			}, function() {
				$(this).attr("src", src);
			});
			
		});
	},

// set style for external site link
	externalLink: function() {
		var conf = {
			context: 'body',
			linkClassName: 'external'
		},
		$link,
		$linkS,
		domain = location.hostname;

		if (conf.context) {
			$link = $('a[href^="http:"]:not([href^="http://' + domain + '"]):not([href^="http://www.spaceshowertvplus.com"])', $(conf.context));
			$linkS = $('a[href^="https:"]:not([href^="https://' + domain + '"]):not([href^="https://login.spaceshowertv.com"])', $(conf.context));
		} else {
			$link = $('a[href^="http:"]:not([href^="http://' + domain + '"])');
			$linkS = $('a[href^="https:"]:not([href^="https://' + domain + '"])');
		}
		$link.each(function () {
			var $this = $(this);
			var data = $this.data("clickReserved");
			if (!data) {
				$this.click(function(e) {
					window.open($this.attr('href'), '_blank');
					e.preventDefault();
				}).addClass(conf.linkClassName);
			}
		});
		$linkS.each(function () {
			var $this = $(this);
			var data = $this.data("clickReserved");
			if (!data) {
				$this.click(function(e) {
					window.open($this.attr('href'), '_blank');
					e.preventDefault();
				}).addClass(conf.linkClassName);
			}
		});
	},

// scroll to inside page link
	scroll: function() {
		$('a[href^="#"]').each(function() {
			$(this).click(function(e) {
				var href = $(this).attr('href');
				var targetOffset = Math.floor($(href).offset().top);
				$('html,body').animate({'scrollTop': targetOffset}, 1250, 'easeOutExpo');
				e.preventDefault();
			});
		});
	},

// open search window
	openSearch: function (args) {
		var args = args ? args : {};
		var url = args.url ? args.url : "about:blank",
			name = args.name ? args.name : "sstv";
		window.open(url, name).focus();
	},
// set open search window
	setOpenSearch: function ($element) {
		$element.each(function() { 
			$(this)
			.data("clickReserved", 1)
			.unbind("click")
			.click(function (e) {
				$.sstvGlobal.openSearch({ url: $(this).attr("href") });
				e.preventDefault();
			});
		});
	}
};

// ui.currentNav//{{{
$.widget("ui.currentNav", {
	_create: function() {
		var currentDir = location.pathname.slice(1, location.pathname.indexOf("/", 1));
		if (currentDir != "" && this.element.attr("href").indexOf(currentDir) != -1) {
			this.element.addClass("on");
		}
	}
});
//}}}
// ui.adjustHeight//{{{
// adjust height of multiple element
$.widget("ui.adjustHeight", {
	_create: function () {
		var max = 0;
		this.element.each(function () {
			var height = $(this).height();
			if (max < height) {
				max = height;
			}
		});
		this.element.height(parseInt(max));
	}
});
//}}}
// ui.sideSearch//{{{
// form of artist / tune name search
$.widget("ui.sideSearch", {
	_create: function () {
		var $form = $("form", this.element);
		$form.attr("target", "search_win")
			.submit(function (e) {
				var type = $("input[name='sidesearch']:checked", $form),
					text = $("input[name='search01']", $form).val(),
					paramClass = "searchType";
				var $param = $("input." + paramClass, $form);
				if (!$param[0]) {
					$param = $("<input/>", {
							"type": "hidden",
							"class": paramClass
						});
				}
				if (type.val() == 1) {
					$param.attr("name", "music");
				} else {
					$param.attr("name", "artist");
				}

				$param.attr("value", text);
				$form.append($param);
				if (text) {
					this.submit();
				} else {
					alert("キーワードを入力してください");
				}
				e.preventDefault()
			});
	}
});
//}}}
// ui.nowOnAir //{{{
$.widget("ui.nowOnAir", {
	options: {
		data: {}
	},
	_create: function () {
		var self = this,
			$box = this.element,
			$boxInner = $(".moduleInner", $box),
			$item = $(this.options.data).find("item");
		var pgDate = $item.attr("programdate"),
			pgTime = $item.attr("programtime"),
			pgUrl = $item.attr("programurl"),
			pgTitle = $item.attr("programname"),
			song = $item.attr("songname"),
			artist = $item.attr("artistname"),
			xmlpath = $item.attr("imgxml"),
			ac = $item.attr("ac"),
			mu = $item.attr("mu"),
			ch = ($item.attr("ch") || ""),
			path = null;

		$.ajax(xmlpath, {
			dataType: "xml",
			cache: false,
			success: function (data) {
				$img = $(data).find("img");
				path = $img.attr("path");
				this.display();
			},
	        error:function(XHR, status, errorThrown){
				this.display();
			},
			display: function () {
				var $boxHd = $('<div class="hl02"/>');
				$('<h2>NOW ON AIR</h2>').appendTo($boxHd);
				// date
				$('<p class="date"/>')
					.html(pgDate)
					.appendTo($boxHd);
				$boxInner.before($boxHd);
				// img
				var $pgBox = $('<div class="mod_topPrograms"/>')
					.append('<h3 class="hl03_program">PROGRAM</h3>');
				if (path) {
					$('<p class="img"/>')
						.html($("<img/>", {
								"src": path,
								"alt": pgTitle
							}))
						.appendTo($pgBox);
				} else {
					$('<p class="img"/>')
						.append($("<img/>", {
								"src": "/images/common/noimg_68x51.png",
								"alt": pgTitle
							})
						)
						.appendTo($pgBox);
				}
				// time
				var $pgContent = $('<dl/>');
				$('<dt class="time"/>')
					.html(pgTime)
					.appendTo($pgContent);
				// title
				if (pgUrl) {
					$('<dd class="title"/>')
						.html($("<a/>", {
								"href": pgUrl,
								"text": pgTitle
							}))
						.appendTo($pgContent);
				} else {
					$('<dd class="title"/>')
						.text(pgTitle)
						.appendTo($pgContent);
				}
				$pgBox.append($pgContent);
				// onAirList (song & artist name)
				var songHTML = '';
				if (song) {
					songHTML = '<div class="onAirList"><ul><li><span>';
					if (mu) {
						songHTML += '<a href="http://www.spaceshowertv.com/search/detail.cgi?mu=' + mu + '&ch=' + ch + '">' + song + '</a>';
					} else {
						songHTML += song;
					}
					songHTML += ' / ';
					if (ac) {
						songHTML += '<a href="http://www.spaceshowertv.com/search/artist.cgi?ac=' + ac + '">' + artist + '</a>';
					} else {
						songHTML += artist;
					}
					songHTML += '</span></li></ul></div>';
					$pgBox.append(songHTML);
				} else {
					songHTML = '<div class="onAirList"><ul><li></li></ul></div>';
					$pgBox.append(songHTML);
				}
				$(".mod_sideTimeTable", $box).before($pgBox);
				// set song/artist name ticker
				this.ticker($('.onAirList span', $box));
			},
			ticker: function($element) {
				if (!$element[0]) { return; }
				var txtWidth = $element.width();
				var initPos = (txtWidth < 138) ? 158 : txtWidth + 20,
					duration = txtWidth * 60;
				$element.css("left", initPos);
				function move() {
					var pos = $.curCSS($element[0], "left");
					var leftpos = parseInt(pos.replace("px", ""));
					if (leftpos <= -txtWidth) {
						$element.css("left", initPos);
					} else {
						$element.css("left", leftpos - 2);
					}
				}
				var timer = setInterval(move, 50);
			}

		});

	}
	
});
//}}}
// ui.timeTable//{{{
$.widget("ui.timeTable", {
	options: {
		data: {}
	},
	_create: function() {
		var $scPane = $('.scrollTable', this.element),
			$scContent = $('.scrollContent', this.element);
		this._buildTable(this.options.data, $scContent);
		this._buildSlider($scPane, $scContent);
		this._lineStyle($("tr", this.element));
	},
	
	_buildTable: function (data, $box) {
		var $item = $("item", data),
			$table = $("<table/>");
		$item = this._filterItem($item);
		$item.each(function () {
			var $this = $(this);
			var url = $this.attr("url"),
				time = $this.attr("time"),
				content1 = '<th>';
			if (url) {
				content1 += '<a href="'
				content1 += url;
				content1 += '">';
				content1 += time;
				content1 += '</a>';
			} else {
				content1 += time;
			}
			content1 += '</th>';

			var name = $this.attr("name"),
				content2 = '<td>';
			if (url) {
				content2 += '<a href="'
				content2 += url;
				content2 += '">';
				content2 += name;
				content2 += '</a>';
			} else {
				content2 += name;
			}
			content2 += '</td>';

			$("<tr/>", {
				html: content1 + content2
			}).appendTo($table);
		});
		$box.append($table);
	},

	_filterItem: function ($item) {
		var item = [];
		var now = new Date();
		var nowDatetime = now.getTime();
		$item.each(function (i) {
			var $this = $(this);
			var time = $this.attr("time");
			var datetime = parseTime(time);
			if (nowDatetime < datetime) {
				item.push($item[i - 1]);
			}
		});

		// last item must be pushed
		item.push($item[$item.length - 1]);

		function parseTime(HH_MM) {
			var hm = HH_MM.split(":");
			var h = parseInt(hm[0], 10),
				m = parseInt(hm[1], 10);
			var dateObj = new Date();
			if (dateObj.getHours() < 4) { // 日付が変わった深夜時間帯
				dateObj.setDate(dateObj.getDate() - 1);
			}
			dateObj.setHours(h, m);
			datetime = dateObj.getTime();
			return datetime;
		}

		delete $item;
		return $(item);
	},

	_buildSlider: function ($scPane, $scContent) {
/**
 * Thanks for following article
 * http://www.simonbattersby.com/blog/vertical-scrollbar-using-jquery-ui-slider/
 */
		$scPane.css('overflow', 'hidden');
		var difference = $scContent.height() - $scPane.height();
		var $slWrap = $('<div class="sliderWrap"/>'),
			$slV = $('<div class="sliderVertical"/>');
		//if the scrollbar is needed, set it up...
		if (difference > 0) {
			$scPane.append($slWrap.append($slV));
			$slWrap.height($scPane.height());

			//set up the slider 
			$slV.slider({
				orientation: 'vertical',
				min: 0,
				max: 100,
				value: 100,
				slide: function(event, ui) {
					var topValue = -((100 - ui.value) * difference / 100);
					$scContent.css({ top: topValue });
				},
				change: function(event, ui) {
					var topValue = -((100 - ui.value) * difference / 100);
					$scContent.css({ top: topValue });
				}
			});

			var proportion = difference / $scContent.height();
			var handleHeight = Math.round((1 - proportion) * $scPane.height());
			handleHeight -= handleHeight % 2;

			var $slHandle = $('.ui-slider-handle', $scPane);
			var slBdWidth = parseInt($slHandle.css('border-top-width').replace('px', ''));
			slBdWidth += parseInt($slHandle.css('border-bottom-width').replace('px', ''));
			if (isNaN(slBdWidth)) { slBdWidth = 0; } // for IE
			$slHandle.css({
				height: handleHeight,
				'margin-bottom': -0.5 * handleHeight
			});
			var origSlHeight = $slV.height();
			var slHeight = origSlHeight - handleHeight - slBdWidth;
			var slMargin =  (origSlHeight - slHeight + slBdWidth) * 0.5;
			$slV.css({
				height: slHeight,
				'margin-top': slMargin
			});
		}

		//code to handle clicks outside the slider handle
		$slV.click(function(e) {
			e.stopPropagation();
		});

		$slWrap.click(function(e){
			var offsetTop = $(this).offset().top;
			var clickValue = (e.pageY - offsetTop) * 100 / $(this).height();
			$slV.slider("value", 100 - clickValue);
		}); 

		//additional code for mousewheel
		$scContent.mousewheel(mousewheelFunc);
		$slWrap.mousewheel(mousewheelFunc);
		function mousewheelFunc(e, delta) {
			var speed = 5;
			var sliderVal = $slV.slider("value");
			sliderVal += (delta * speed);
			$slV.slider("value", sliderVal);
			e.preventDefault();
		}
	},
	
	_lineStyle: function ($rows) {
		$rows.each(function (i) {
			if ((i % 2) === 0) {
				$(this).addClass("odd");
			} else {
				$(this).addClass("even");
			}
		});
	}
});
//}}}
// ui.topChart//{{{
$.widget("ui.topChart", {
	options: {
		data: {}
	},
	_create: function () {
		var $item = $("item", this.options.data),
			$table = $('<table/>');
		$item.each(function(i) {
			if (i >= 3) { return; }
			var $this = $(this);
			var no = $this.attr("no"),
				songname = $this.attr("songname"),
				mu = $this.attr("mu"),
				artistname = $this.attr("artistname"),
				ac = $this.attr("ac"),
				ch = $this.attr("ch");
			var $tr = $('<tr/>', {
					"class": (i % 2 === 0) ? "odd" : "even"
				}),
				$th = $('<th/>'),
				$td = $('<td/>'),
				$icon = $('<img/>', {
					"src": "/images/common/ico_no" + no + ".gif",
					"alt": no
				}),
				$linkTune = $('<a/>', {
					"href": "http://www.spaceshowertv.com/search/detail.cgi?mu=" + mu + "&ch=" + ch,
					"class": "tune"
				}).click(function (e) {
					$.sstvGlobal.openSearch({ url: $(this).attr("href") });
					e.preventDefault();
				}),
				$linkArtist = $('<a/>', {
					"href": "http://www.spaceshowertv.com/search/artist.cgi?ac=" + ac + "&ch=" + ch,
					"class": "artist"
				}).click(function (e) {
					$.sstvGlobal.openSearch({ url: $(this).attr("href") });
					e.preventDefault();
				}),
				$br = $('<br/>');
			$tr.append($th.append($icon));
			$td.append($linkTune.append(songname));
			$td.append($br);
			$td.append($linkArtist.append(artistname));
			$tr.append($td);
			$table.append($tr);
		});
		this.element.empty().append($table);
	}
});
//}}}
// ui.sideNewVideos//{{{
$.widget("ui.newVideo", {
	options: {
		data: {}
	},
	_create: function () {
		var $item = $("item", this.options.data),
			$ul = $('<ul class="newVideos"/>');
		$item.each(function () {
			var $this = $(this);
			var songname = $this.attr("songname"),
				artistname = $this.attr("artistname"),
				mu = $this.attr("mu"),
				ac = $this.attr("ac"),
				ch = $this.attr("ch");
			var $li = $('<li/>'),
				$span = $('<span/>'),
				$a1 = $('<a/>', {
					"text": songname,
					"href": "http://www.spaceshowertv.com/search/detail.cgi?mu=" + mu + "&ch=" + ch
				}).click(function (e) {
					$.sstvGlobal.openSearch({ url: $(this).attr("href") });
					e.preventDefault();
				}),
				$a2 = $('<a/>', {
					"text": artistname,
					"href": "http://www.spaceshowertv.com/search/artist.cgi?ac=" + ac + "&ch=" + ch
				}).click(function (e) {
					$.sstvGlobal.openSearch({ url: $(this).attr("href") });
					e.preventDefault();
				});
			$li.append($span.append($a1)).append($a2);
			$ul.append($li);
		});
		this.element.empty().append($ul);
	}
});
//}}}
// ui.loginStatus//{{{
$.widget("ui.loginStatus", {
	_create: function () {
		var $box = $("div.mod_head03");
		this.reload($box);
	},
	reload: function ($box) {
		$("ul", $box).remove();
		this._build($box);
	},
	_build: function ($box) {
		var cookieData = document.cookie + ";";
		var startPoint1 = cookieData.indexOf("SSNW-LOGIN");
		var startPoint2 = cookieData.indexOf("=",startPoint1);
		var endPoint = cookieData.indexOf(";",startPoint1);
		var $UL = $('<ul/>');
		if (startPoint2 < endPoint && startPoint1 > -1){
			// login
			var $LI1 =  $('<li class="login"/>');
			var $A1 = $('<a/>', {
					"text": "ログアウト",
					"href": "http://www.spaceshowertv.com/logout/location.cgi?tg=" + document.URL
				});
			$UL.append($LI1.append($A1));
			$box.addClass("login");
		} else {
			// not login
			var $LI1 =  $('<li class="login"/>');
			var $A1 = $('<a/>', {
					"text": "ログイン",
					"href": "https://login.spaceshowertv.com/pc/login/index.cgi"
				}).data("clickReserved", 1)
				.unbind("click")
				.click(function(e) {
					$.sstvGlobal.openSearch({ url: $(this).attr("href") });
					e.preventDefault();
				});
			var $LI2 =  $('<li class="member"/>');
			var $A2 = $('<a/>', {
					"text": "会員登録",
					"href": "https://login.spaceshowertv.com/pc/member07/entry/entry01.html"
				}).data("clickReserved", 1)
				.unbind("click")
				.click(function(e) {
					$.sstvGlobal.openSearch({ url: $(this).attr("href") });
					e.preventDefault();
				});
			$UL.append($LI1.append($A1)).append($LI2.append($A2));
			$box.removeClass("login");
		}
		$("p.howToBtn", $box).before($UL);
	}
});
//}}}
$(function () {
	// global function
	$.sstvGlobal.osClass();
	$.sstvGlobal.autoRollOver();
	$.sstvGlobal.externalLink();
	$.sstvGlobal.scroll();
	$.sstvGlobal.setOpenSearch($("a.musicvideoSearch, div.mod_newvideoList div.mod_itemTable1 a"));

	// current directory detection (: global navigation)
	$("div.mod_glonav a").currentNav();

	// artist/tune title search
	$("div.mod_sideSearch").sideSearch();

	// login status
//    var loginStatus = new $.ui.loginStatus();
//    loginStatus._create();

	// "now on air" module ajax content
	$.ajax("/xml/plus_nowonair.xml", {
		dataType: "xml",
		cache: false,
		success: function (data) {
			$("#nowOnAir").nowOnAir({ data: data });
		}
	});

	// Time table
	$.ajax("/xml/plus_today_program.xml", {
		dataType: "xml",
		cache: false,
		success: function (data) {
			$("#nowOnAir").timeTable({ data: data });
		}
	});

	// Perfect ranking
	$.ajax("/xml/plus_top_chart_jp.xml", {
		dataType: "xml",
		cache: false,
		success: function (data) {
			$("div.mod_sidePerfectRanking .content").topChart({ data: data });
		}
	});

	// New video
	$.ajax("/xml/plus_newvideo.xml", {
		dataType: "xml",
		cache: false,
		success: function (data) {
			$("div.mod_sideNewVideos .content").newVideo({ data: data });
		}
	});

$('a.sstvTop').unbind('click').click(function (e) {
	window.open($(this).attr('href'), 'sstv');
	e.preventDefault();
});
});

})(jQuery);

