// Easingの追加
jQuery.easing.quart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

//
// 画像の先読み
//
jQuery.preloadImages = function(arguments)
{
	for(var i = 0; i<arguments.length; i++)
	{
		jQuery("<img>").attr("src", temp_dir + arguments[i]);
	}
};


args = new Array("/images/loading.gif",
								 "/images/body_bg.gif",
								 "/images/header_bg.gif",
								 "/images/header_menu01_on.gif",
								 "/images/header_menu02_on.gif",
								 "/images/header_menu03_on.gif",
								 "/images/header_menu04_on.gif",
								 "/images/header_menu05_on.gif",
								 "/images/header_menu06_on.gif",
								 "/images/side_menu01_on.gif",
								 "/images/side_menu02_on.gif",
								 "/images/side_menu03_on.gif");
jQuery.preloadImages(args);

var old = 1;

/*-------------------------------------
 ページ読み込み中
-------------------------------------*/
jQuery(document).ready(function(){
	//
	// <a href="#***">の場合、スクロール処理を追加
	//
	jQuery('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var $target = jQuery(this.hash);
			$target = $target.length && $target || jQuery('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				jQuery('html,body').animate({ scrollTop: targetOffset }, 1200, 'quart');
				return false;
			}
		}
	});

	//
	// <a rel="blank">の時は別ウィンドウで表示させる
	//
	jQuery("a").each(function(){
		if(jQuery(this).attr("rel") == "blank") {
			jQuery(this).attr("target", "_blank");
		}
	});

	//
	// ウィンドウサイズ変更時
	//
	jQuery(window).resize(function(){
		// フッターの位置設定
		set_footer_pos();
		// ページトップに戻る画像の設定
		set_pagetop_pos();
	});

	//
	// id = trackbackurl に処理を追加
	//
	jQuery("#trackbackurl").bind("click", function(){
  	jQuery(this).get(0).select();
	});

	//
	// ロールオーバーの処理
	//
	jQuery("img.rollover").mouseover(function(){
		jQuery(this).attr("src",jQuery(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2"));
	}).mouseout(function(){
		jQuery(this).attr("src",jQuery(this).attr("src").replace(/^(.+)_on(\.[a-z]+)$/, "$1$2"));
	}).each(function(){
		jQuery("<img>").attr("src",jQuery(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2"));
	});

	// フッタの位置設定
	//set_footer_pos();

	// ページトップに戻る画像の設定
	//set_pagetop_pos();

	// お問い合わせ商品の確認
	if(jQuery("#your-order").length && jQuery.cookie("order_val")) {
		jQuery("#your-order").val(jQuery.cookie("order_val"));
		// cookieの消去
		jQuery.cookie('order_val', "", { expires: -1, path: '/', domain: "is-p.cc" });
	}
	jQuery("input,textarea").focus(function() { jQuery(this).addClass("focus"); }).blur(function() { jQuery(this).removeClass("focus"); });

	// ホームのヘッダーメニューのスタート
	jQuery(".scrollable").scrollable({
			vertical: true,
			autoplay: true,
			easing: 'quart',
			onBeforeSeek: function(event, i) {
				var api = jQuery(".scrollable").data("scrollable");
				if(i > 2) api.seekTo(0);
			},
			onSeek: function(event, i) {
				jQuery("#scr_navi"+old).attr("src", jQuery("#scr_navi"+old).attr("src").replace(/^(.+)_on(\.[a-z]+)$/, "$1$2"));
				jQuery("#scr_navi"+(i+1)).attr("src", jQuery("#scr_navi"+(i+1)).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2"));
				old = i+1;
			}
			}).autoscroll({ steps: 1, interval: 10000 }).navigator("#main_navi");

});

// ページトップに戻る画像の位置設定
function set_pagetop_pos() {
	var img_width = 30;
	var img_height = 100;
	if(jQuery(window).width() > 1020) {
		var t = jQuery(window).height() - (img_height + 50);
		//var l = jQuery("#header").offset().left + 950;
		var l = jQuery(window).width() - img_width;

		if(typeof document.documentElement.style.maxHeight != "undefined") {
			// 最近のブラウザー
			jQuery("#pageup").css({ top: t+"px", left: l+"px" });
		} else {
			// IE6
			jQuery("#pageup").get(0).style.setExpression("top", "eval(document.documentElement.scrollTop+" + t + ")");
			jQuery("#pageup").css("left", l+"px");
		}
		jQuery("#pageup").css("display", "block");
	} else {
			jQuery("#pageup").css("display", "none");
	}
}

// フッターの位置調整
function set_footer_pos() {
	var b_h = jQuery("body").height();
	var w_h = jQuery(window).height();
	var h_h = jQuery("#header").height();
	var f_h = jQuery("#footer").height();

	if(w_h > b_h) {
		b_h = w_h - f_h - h_h;
		jQuery("#body").height(b_h);
	}
}


// パーツのお問い合わせ
function order_contact(val) {
	jQuery.cookie('order_val', "", { expires: -1, path: '/', domain: "is-p.cc" });
	jQuery.cookie('order_val', val, { path: '/', domain: "is-p.cc" });
	window.location.href = "./contact";
}

function print_r( obj, maxlevel, maxitem ) {
    if (!maxlevel)  maxlevel = 4;
    if (!maxitem)   maxitem = 150;
    var txt = "";
    var count_obj = 0;
    function _output(str) {
      　txt += str + "<br/>";
    }
    function _print_r(obj, name, level) {
        var s = "";
        if (obj == undefined || level > maxlevel) return;
        for (var i = 0; i < level; i++) { s += " | "; }
        s += " - " + name + ":" + typeof(obj) + "=" + obj;
        _output(s);
        if (name == "document" || typeof(obj) != "object") return;
        for (var key in obj ) {
            if (count_obj++ > maxitem) return;
            _print_r(obj[key], key, level + 1);
        }
    }
    _print_r(obj, "*", 0);
    return txt;
}

//
// YouTubeの動画を呼び出す
//
function youtube(target) {
	var uri = "http://gdata.youtube.com/feeds/api/users/geppettoauto/uploads";
	var req = { "orderby": "updated", "alt": "json", "max-results": 50 };
	if(target == "home") req["max-results"] = 8;

	jQuery.ajax({
		type: "GET",
		url: uri,
		data: req,
		dataType: "jsonp",
		success: function(data) {
			jQuery.each(data.feed.entry, function(i, item) {
				var movie = item.media$group;
				var re = new RegExp("/videos/(.*)$");
				var src = item.id.$t.match(re);
				if(target == "home") {
					// HOME
					var thumb = '<div><a href="movie?src=' + src[1] + '">'
										+ '<img src="' + movie.media$thumbnail[1].url + '" width="' + movie.media$thumbnail[1].width + '" height="' + movie.media$thumbnail[1].height + '" alt="' + movie.media$title.$t + '" title="' + movie.media$title.$t + '" /></a>'
										+ '<p>' + clock_format(movie.yt$duration.seconds) + '</p></div>';
					jQuery("#playlist").append(thumb);
				} else {
					// MOVIE ページ
					if(jQuery("#video_player").attr("src") == "") {
						set_movie(src[1]);
					}
					var thumb = '<div><a href="#body" onclick="set_movie(\'' + src[1] + '\')">'
										+ '<img src="' + movie.media$thumbnail[1].url + '" width="' + movie.media$thumbnail[1].width + '" height="' + movie.media$thumbnail[1].height + '" alt="' + movie.media$title.$t + '" title="' + movie.media$title.$t + '" class="centered" /></a>'
										+ '<p>' + clock_format(movie.yt$duration.seconds) + '</p></div>';
					jQuery("#playlist").append(thumb);
				}
			});
		}
	});
}

//
// 動画をiframeに設定
//
function set_movie(src) {
	var pl = "http://www.youtube.com/embed/" + src + "?rel=0&wmode=transparent";
	var uri = "http://gdata.youtube.com/feeds/api/videos/" + src;
	var req = { "orderby": "updated", "alt": "json" };

	// 動画を設定
	jQuery("#video_player").attr("src", pl);
	jQuery.ajax({
		type: "GET",
		url: uri,
		data: req,
		dataType: "jsonp",
		success: function(data) {
			var item = data.entry;
			var category = "";
			jQuery.each(item.category, function() {
				if(this.term.indexOf("http://") < 0) {
					category += ", " + this.term;
				}
			});
			category = category.substr(2);

			// 動画の情報を設定
			jQuery("#mv_title").html(item.title.$t);
			jQuery("#mv_published").html(formatDate(item.published.$t));
			jQuery("#mv_updated").html(formatDate(item.updated.$t));
			jQuery("#mv_category").html(category);
			jQuery("#mv_content").html(item.content.$t);
			jQuery("#mv_viewcount").html(item.yt$statistics.viewCount);
		}
	});
	
}

var formatDate = function(dateString) {
	var d = Date.str2date(dateString);
	var year = d.getFullYear();
	var month = d.getMonth()+1;
	var day = d.getDate();
	return year+"年"+month+"月"+day+"日";
}

function clock_format(val) {
	var m = Math.floor(val/60);
	var s = Math.floor(val%60);
	var clock = "";

	if(m < 10) m = "0" + m;
	if(s < 10) s = "0" + s;

	clock = m + ":" + s;

	return clock;
}

/*
 文字列 → 日付オブジェクト変換
 http://d.hatena.ne.jp/seuzo/20081125/1227543241
*/
function zen2han(str) {
	var tmp_data = '';
	for (var i =0; i< str.length; i++) {
		var c = str.charCodeAt(i);
		if (c >= 65296 && c <= 65305) {
			tmp_data += String.fromCharCode(c - 65248);
		}else {
			tmp_data += str.charAt(i);
		}
	}
	return tmp_data;
}

function wareki2seireki(str) {
	var wareki = 0;
	var seireki = 0;
	var matched = null;
	
	if (matched = str.match(/(明治?|[MＭmｍ][\.・]?)[ 　]?([0-9元]+)年/)) {
		wareki = parseInt(matched[2].replace('元', '1'));
		seireki = '' + (wareki + 1867) + '年';
		return str.replace(matched[0], seireki);
	} else if (matched = str.match(/(大正?|[TＴtｔ][\.・]?)[ 　]?([0-9元]+)年/)) {
		wareki = parseInt(matched[2].replace('元', '1'));
		seireki = '' + (wareki + 1911) + '年';
		return str.replace(matched[0], seireki);
	} else if (matched = str.match(/(昭和?|[SＳsｓ][\.・]?)[ 　]?([0-9元]+)年/)) {
		wareki = parseInt(matched[2].replace('元', '1'));
		seireki = '' + (wareki + 1925) + '年';
		return str.replace(matched[0], seireki);
	} else if (matched = str.match(/(平成?|[HＨhｈ][\.・]?)[ 　]?([0-9元]+)年/)) {
		wareki = parseInt(matched[2].replace('元', '1'));
		seireki = '' + (wareki + 1988) + '年';
		return str.replace(matched[0], seireki);
	} else {
		return str;
	}
}

Date.str2date = function(str) {
	var str = zen2han(str);
	var str = wareki2seireki(str);
	//alert(str);
	var returnValue = new Date(1900, 0, 1);
	var granularity = 0;
	var tzd = 0;
	var offset = 0;
	var matched = null;

	var yyyy = '(1[89][0-9]{2}|20[0-9]{2})[-年/\\. ]+';
	var mm = '(1[012]|0?[1-9])[-月/\\. ]+';
	var dd = '(0?[1-9]|[12][0-9]|3[01])[日 ]?';
	var hh = 'T?([01]?[0-9]|2[0-3])[-:時/\\. ]+';
	var min = '([0-5]?[0-9])[-:分/\\. ]+';
	var sec = '([0-5]?[0-9])(?:\\.[0-9]+)?[-:秒/\\. ]?';
	var timezone = '(?:Z|TZD|GMT)? ?([+-][0-2][0-9]):?([0-5][0-9])';

	if (matched = str.match(RegExp (yyyy + mm + dd + hh + min + sec + timezone))) {
		granularity = 6;
		tzd = 1;
	} else if (matched = str.match(RegExp (yyyy + mm + dd + hh + min + sec + 'Z?'))) {
		granularity = 6;
		tzd = 2;
	} else if (matched = str.match(RegExp (yyyy + mm + dd + hh + min + timezone))) {
		granularity = 4;
		tzd = 1;
	} else if (matched = str.match(RegExp (yyyy + mm + dd + hh + min + 'Z?'))) {
		granularity = 4;
		tzd = 2;
	} else if (matched = str.match(RegExp (yyyy + mm + dd))) {
		granularity = 3;
	} else if (matched = str.match(RegExp (yyyy + mm))) {
		granularity = 2;
	} else if (matched = str.match(RegExp (yyyy))) {
		granularity = 1;
	}

	switch (granularity) {
		case 6:
		case 5:
			returnValue.setSeconds(parseInt(matched[6], 10));

		case 4:
			returnValue.setMinutes(parseInt(matched[5], 10));
			returnValue.setHours(parseInt(matched[4], 10));

		case 3:
			returnValue.setDate(parseInt(matched[3], 10));

		case 2:
			returnValue.setMonth(parseInt(matched[2], 10) - 1);

		case 1:
			returnValue.setFullYear(parseInt(matched[1], 10));
	}

	switch (tzd) {
		case 1:
			offset = parseInt(matched[matched.length - 2], 10);
			offset = 60 * offset + ((offset < 0) ? -1 : 1) * parseInt(matched[matched.length - 1], 10);

		case 2:
			returnValue.setMinutes(returnValue.getMinutes() - offset - returnValue.getTimezoneOffset());
	}

	return returnValue;
}

