//Conf
var imgW = 1300;
var imgH = 860;
var isVisible = false;
var autoTime = 30000;
var isShowAnimate = false;
var isBgAnimate = false;
var isOPFIn = false;
var isHash = (location.hash && location.hash!="" && location.hash!="#") ? true : false;
if(isHash && location.hash=="#index") isHash = false;
else if(isHash && location.hash=="#") isHash = false;

if(!Array.prototype.indexOf){Array.prototype.indexOf = function(object){for(var i = 0; i < this.length; i++){if(this[i] == object){return i;break;}}return -1;};}

// ロゴのファイル名 [小、大];
var logoPath = ["logo.png", "logo_l.png"];
//logo切替の境界
var logoLimit = 1280;
var isLogoS = true;

var btmOffset;


var _volume = 1;

var isJA = true;
    if(navigator.userAgent.indexOf("MSIE")>=0) isJA = (navigator.browserLanguage.indexOf("ja")!=-1);
    else isJA = (navigator.language.indexOf("ja") != -1);
var isIOS = navigator.userAgent.indexOf("iPhone")>=0 || navigator.userAgent.indexOf("iPad")>=0;
var isIE6 = navigator.userAgent.indexOf("MSIE 6.0")>=0;
var isIE7 = navigator.userAgent.indexOf("MSIE 7.0")>=0;
var isIE = navigator.userAgent.indexOf("MSIE")>=0;



if(!isJA && location.href =="http://www.robot.co.jp/") location.href = "./en/index.html";

var flashvars = {};
var params = {
    allowScriptAccess:"always",
    base:"./common/imgs/"
};
var attributes = {
    id:"externalFlash",
    name:"externalFlash",
    align:"middle",
    base:"./common/imgs/"
};
if(!isIOS)swfobject.embedSWF("common/imgs/sound.swf", "externalFlash", "1", "1", "9.0.0", "common/js/expressinstall.swf", flashvars, params, attributes);


//iOS sound
var _soundArr = [];
var _dataDir = "./common/sound/";
var _soundPath = ["robotcojp_rollover.mp3"];

//bg
var $bg;
var defImgArr = [];
var imgArr = [];
var $current;

//instace
var $wrapper;

var $logo;
var $gNavi;
var $feature;
var $conteNews;
var $conteWorks;
var $conteProject;
var $footer;
var $tabArea;
var $tab;

var $btnSound;
var $soundTITLE;
var $soundNEXT;

var _hideArr = [];

//
var _bgInterval;
var _opInterval;

var snTag = ' <a id="soundNEXT">&gt;</a> ';


if(!isHash)$(window).bind("load", function(){$("html,body").animate({ scrollTop: 0 }, 100, "easeInOutQuart" );});


//----- init -----//
(function($){
	$(function() {
		//----- set instance -----//
        $wrapper = $("#wrapper");
		$bg = $("#bg");
		$feature = $(".feature");
		$conteNews = $("#conteNews");
		$conteWorks = $("#conteWorks");
		$conteProject = $("#conteProject");
		$footer = $("#footerWrap");
        $tabArea = $("#tabArea");
        $tab = $("#tab");
		
		$logo = $("#logo");
		$gNavi = $("#headerWrap");

        $btnSound = $("#btnSound");

        $soundTITLE = $("#soundPlayer");
        $soundNEXT = $("#soundNEXT");


        _hideArr = [$gNavi, $feature, $conteNews, $conteWorks, $conteProject, $footer, $("#soundPlayer")];

        btmOffset = $tabArea.position().top;

        if(isIE7){
            $footer.css("paddingBottom", 210);
            $tabArea.css("marginTop",0);
            btmOffset -= 690;
        }


        //----- content init -----//
       for(var i=0; i<_hideArr.length; i++){
           if(isIE7)break;
           if(i==4)continue;
            if(!isHash)_hideArr[i].css("opacity", 0);
        }
        $logo.css("opacity", 0);
        $logo.css("top", 350);
        $gNavi.css("display", "none");

		
		//----- sound init -----//
        $gNavi.find("a").each(function(){
            $(this).bind("mouseover", mouseOverHdl);
        });
        $(".btnMore").find("img").bind("mouseover", mouseOverHdl);
        $logo.bind("mouseover", mouseOverHdl);
        $btnSound.bind("click", muteChange);
        $btnSound.bind("mouseover", mouseOverHdl);
        $btnSound.html();




		//----- bg img init -----//
		$bg.find("img").each(function(){
            defImgArr.push($(this));
			imgArr.push($(this));
			$(this).css("position", "absolute");
			$(this).css("display", "none");
		});

        //----- bgImg shuffle all -----//
		//imgArr.sort( function(a,b){ return Math.random() - 0.5; });


        //----- bgImg cookie load -----//
        var cookieArr = document.cookie.split("; ");
        var isCookie = false;
        var cStr;
        for(var i=0; i<cookieArr.length; i++){
            if(cookieArr[i].substr(0,10) == "robotbgimg"){
                cStr = unescape(cookieArr[i].split("=")[1]);
                isCookie = true;
                break;
            }
        }
        if(isCookie){
            var nameArr = cStr.split("///");
            imgArr.sort( function(a,b){
                var ia = -1;
                var ib = -1;
                for(var q=0; q<nameArr.length; q++){
                    var n = nameArr[q];
                    if(ia == -1 && a.attr("src").indexOf(n) >= 0)ia = q;
                    if(ib == -1 && b.attr("src").indexOf(n) >= 0)ib = q;
                    if(ia != -1 && ib != -1)break;
                }
                return ia - ib;
            });
        }
        else{
            //----- bgImg shuffle exclude index 0-----//
            var firstImg = imgArr.shift();
		    imgArr.sort( function(a,b){ return Math.random() - 0.5; });
            imgArr.unshift(firstImg);
        }
        
		
		$current = imgArr.shift();
		$current.css("opacity", 0);
		$current.css("display","block");

        imgArrSave();
        
        if($soundTITLE.length>0){
            $soundTITLE.html($current.attr("alt"));

            $tab.bind("click", tabClickHdl);
            $tab.bind("mouseover", tabOverHdl)
            $tab.bind("mouseout", tabOutHdl);
        }

        if(isIOS) iOsInit();
        if(isIE6 || isIOS)setInterval("iOSScroll()",100);

		
		$(window).resize(resizeHdl);
		resizeHdl();
		doOP();
	});
})(jQuery);




//----- show -----//
function doOP(){
    if(isHash)$.fx.off = true;
   // if(isHash)location.hash = "";
    $bg.css("display","block");
    $wrapper.css("opacity", 1);
    $wrapper.css("position","relative");
    $footer.css("position", "relative");
    $wrapper.css("top",0);
    $current.delay(500).animate({opacity:1}, 200, "easeOutQuad",function(){
//        if($soundTITLE.length>0){
//            $soundTITLE.html($current.attr("alt"));
//            $tab.bind("click", imgGoNext);
//            $tab.bind("mouseover", mouseOverHdl);
//        }
        _bgInterval = setInterval("imgChange()", autoTime);
    });
    $(window).bind("scroll", scDel);
    $logo.delay(1000).animate({opacity:1, top:160}, 500, "easeOutBack",function(){
        if(isHash){
            doShow();
            return;
        }
        $wrapper.bind("click", doClickShow);
        $(window).bind("mousewheel", doScrollShow);
        _opInterval = setInterval("doTimeShow()", (isHash)? 0 : 15000);
    });
}

// click
function doClickShow(){
    if(!isOPFIn && !isHash){
        var n = Number($footer.position().top);
        n -= 690;
        $wrapper.animate({top:-690}, 1000, "easeInOutQuad");
        $footer.animate({top:-690}, 1000, "easeInOutQuad");
       // $tabArea.animate({top:-690}, 1000, "easeInOutQuad");
    }

    $wrapper.unbind("click", doClickShow);
    $(window).unbind("mousewheel", doScrollShow);
    $(window).unbind("scroll", scDel);
    doShow();
}

// scroll
function doScrollShow(e){
    if(isOPFIn || isHash)return;
    var d = e.wheelDelta;
    if(d>0)return;
    var t = Number($wrapper.css("top").split("px")[0]) + d;

    if(t < -690){
        $wrapper.css("top", -690);
        $footer.css("top", -690);
//        $tabArea.css("top", -690);
        $(window).unbind("mousewheel", doScrollShow);
        $(window).unbind("scroll", scDel);
        doShow();
    }
    else{
        $wrapper.css("top", t);
    }
    e.preventDefault();
}

function scDel(e){
    if($(window).scrollTop() > 360){
        $wrapper.css("top", -690);
        $footer.css("top", -690);
//      $tabArea.css("top", -690);
        $(window).scrollTop(0);
        $(window).unbind("mousewheel", doScrollShow);
        $(window).unbind("scroll", scDel);
        doShow();
    }
    e.preventDefault();
}

// timer
function doTimeShow(){
    if(!isHash){
        $wrapper.animate({top:-690}, 1000, "easeInOutQuad");
        $footer.animate({top:-690}, 1000, "easeInOutQuad");
//      $tabArea.animate({top:-690}, 1000, "easeInOutQuad");
    }

    //if(!isHash) $('html, body').animate({scrollTop:720}, 1000, "easeInOutQuad");
    $(window).unbind("mousewheel", doScrollShow);
    $(window).unbind("scroll", scDel);
    clearInterval(_opInterval);
    doShow();
}

// show element
function doShow(){
    // $logo.fadeOut("slow"); // add 11.06.03 by kowata
    $("#headerWrap").css("display","block");
    isOPFIn = true;
    clearInterval(_opInterval);
    if(isShowAnimate)return;
    isShowAnimate = true;
    isVisible = true;
    $gNavi.css("display", "block");
    for(var i=0; i<_hideArr.length; i++){
        if(!_hideArr[i].html())continue;
        _hideArr[i].css("diaplay", "block");
        if(isIE7)continue;
        if(i==4)continue;
        // _hideArr[i].animate({"opacity": 1}, 700, "easeInOutQuad",function(){isShowAnimate=false;});
		_hideArr[i].animate({"opacity": 1}, 100, "easeInOutQuad",function(){isShowAnimate=false;});
    }
   $(window).bind("scroll", scrollMng);
   $.fx.off = false;
}




//----- btm show / hide -----//
//observer
function scrollMng(){
    if(!isVisible) return;

    if($(window).scrollTop() >= btmOffset - $(window).height()*1.5 - 690){
        doHide();
    }
}

function doHide(){
    if(!isVisible)return;
    $(window).unbind("scroll", scrollMng);
    isVisible = false;

    $wrapper.stop(true, true);
    $footer.animate({"opacity": 0}, 500, "easeInQuad");
    $wrapper.animate({"opacity": 0}, 500, "easeInQuad");
    $gNavi.animate({"opacity": 0}, 500, "easeInQuad",function(){
           isShowAnimate=false;
           $gNavi.css("display","none");
    });

    $(window).bind("scroll", btmShow);

}

function btmShow() {
    if(isVisible) return;
    if($(window).scrollTop() >= btmOffset - $(window).height()*1.5 - 690) return;
    $(window).unbind("scroll", btmShow);

    $gNavi.css("display","block");
    $footer.animate({"opacity": 1}, 500, "easeInQuad");
    $gNavi.animate({"opacity": 1}, 500, "easeInQuad");
    $wrapper.animate({"opacity": 1}, 500, "easeInOutQuad",function(){isShowAnimate=false;});

    isVisible = true;
    $(window).bind("scroll", scrollMng);
}




//----- bg img change -----//
function imgChange(){
    imgGoNext();
    resizeHdl();
   
}


function imgArrSave(){
    var saveStr = $current.attr("src").split("/imgs/")[1];
    for(var i=0; i<imgArr.length; i++){
        var tg = imgArr[i];
        var str = tg.attr("src").split("/imgs/")[1];
        saveStr += "///" + str;
    }
    document.cookie = "robotbgimg=" + escape(saveStr) + ";path = /;";
}

function tabClickHdl() {
    var num;

    for(var i=0; i<defImgArr.length; i++){
        if($current.attr("src") == defImgArr[i].attr("src")){
            num = i;
            break;
        }
    }

    num++;
    if(num == defImgArr.length)num=0;
    var $tg = defImgArr[num];
    imgSwitch($tg);
}

function imgGoNext(){
    if(isBgAnimate)return;
    isBgAnimate = true;
    clearInterval(_bgInterval);
    _bgInterval = setInterval("imgChange()", autoTime);
    imgArr.push($current);
    var $next = imgArr.shift();
	$next.css("display","block");
	$next.css("opacity","1");

    $current.css("display", "none");

    $current = $next;
    isBgAnimate = false;

    if($soundTITLE.length>0){
        $soundTITLE.html($current.attr("alt"));
    }

     imgArrSave();
}

function imgGoBack(){
    if(isBgAnimate)return;
    isBgAnimate = true;
    clearInterval(_bgInterval);
    _bgInterval = setInterval("imgChange()", autoTime);
    imgArr.unshift($current);
    var $next = imgArr.pop();
	$next.css("display","block");
	$next.css("opacity","1");
     $current.css("display", "none");
    
	$current = $next;
    isBgAnimate = false;
    if($soundTITLE.length>0){
        $soundTITLE.html($current.attr("alt"));
    }

     imgArrSave();
}

function imgSwitch($tg) {
     if(isBgAnimate)return;
    isBgAnimate = true;
    clearInterval(_bgInterval);
    _bgInterval = setInterval("imgChange()", autoTime);
    imgArr.unshift($current);

    var $next;
    for(var i=0; i<imgArr.length; i++){
        $next = imgArr.shift();
        if($tg.attr("src") == $next.attr("src")) break;
        imgArr.push($next);
    }

	$next.css("display","block");
	$next.css("opacity","1");
     $current.css("display", "none");

	$current = $next;
    isBgAnimate = false;
    if($soundTITLE.length>0){
        $soundTITLE.html($current.attr("alt"));
    }

     imgArrSave();
}



//----- resize Hdl -----//
function resizeHdl(){
    var windowW = $(window).width();
	var windowH = $(window).height();
	var p = (windowW / imgW > windowH / imgH)? windowW / imgW : windowH / imgH;
    if(p<1)p=1;
	var cW = imgW * p + 0.5 | 0;
	var cH = imgH * p  + 0.5 | 0;

    if(isLogoS && windowW > logoLimit){
        isLogoS = false;
        $logo.removeClass("logo-small");
        $logo.addClass("logo-large");
        $logo.find("img").attr("src", "imgs/index/" + logoPath[1]);
    }
    else if(!isLogoS && windowW <= logoLimit){
        isLogoS = true;
        $logo.removeClass("logo-large");
        $logo.addClass("logo-small");
        $logo.find("img").attr("src", "imgs/index/" + logoPath[0]);
    }

    var offsetY = 0;
    if(isIOS)offsetY = $(window).scrollTop();
	
	$bg.css("top", (windowH - cH) + offsetY);
	$bg.css("left", (windowW - cW) * 0.5);
	$bg.css("width", cW);
	$bg.css("height", cH);
	for(var i=0; i<imgArr.length; i++){
		imgArr[i].attr("width", cW);
		imgArr[i].attr("height", cH);
	}
    $current.attr("width", cW);
    $current.attr("height", cH);
}

//----- tab mouse -----//
function tabOverHdl(e){
    mouseOverHdl();
    $soundTITLE.css("color", "#f05050");
    var img = $tab.find("img");
    var p = img.attr("src").split(".");
    img.attr("src", p[0]+"_ov" + "." + p[1]);
}

function tabOutHdl(e){
    $soundTITLE.css("color", "#000");
     var img = $tab.find("img");
    var p = img.attr("src").split("_ov");
    img.attr("src", p[0] + p[1]);
}


//----- SE -----//
function mouseOverHdl(e){

    if(!isIOS){

        var target = swfobject.getObjectById("externalFlash");
        if(!isIE && target && typeof target.playSound != "undefined"){
            target.playSound(_soundPath.length * Math.random() | 0);
        }
        else if($("#externalFlash").length>0){
            if($('#externalFlash').get(0).playSound){
                $('#externalFlash').get(0).playSound(_soundPath.length * Math.random() | 0);
            }
        }
    }
    else if(_volume!=0){
        var sound = _soundArr[_soundArr.length * Math.random() | 0];
        sound.volume = _volume;
        sound.play();
    }
}

function muteChange(){
    _volume = 1 - _volume;
    $("#soundOn").css("display", (_volume==1)? "block" : "none");
    $("#soundOff").css("display", (_volume==1)? "none" : "block");
    
    if(!isIOS){
        var target = swfobject.getObjectById("externalFlash");
    	if(target)target.setVolume(_volume);
    }
    else{
        document.cookie = "robotsound=" + escape(_volume);
    }
}

function setVolBtn(val){
     _volume = Number(val);
    $("#soundOn").css("display", (_volume==1)? "block" : "none");
    $("#soundOff").css("display", (_volume==1)? "none" : "block");
}

// iOS sound function
function soundLoad(){
    document.body.removeEventListener("touchstart",soundLoad);
    for(var i=0; i<_soundArr.length; i++){
        var sound = _soundArr[i];
        sound.load();
    }
}

function soundCookieLoad(){
    var val = 1;
    var cookieArr = document.cookie.split("; ");
    for(var i=0; i<cookieArr.length; i++){
        if(cookieArr[i].substr(0,10) == "robotsound"){
            val = unescape(cookieArr[i].split("=")[1]);
            break;
        }
    }
    setVolBtn(val);
}


//----- iOs -----//
function iOsInit(){
    soundCookieLoad();
    for(var i=0; i<_soundPath.length; i++){
        var sound = new Audio();
        sound.autoPlay = false;
        sound.loop = false;
        sound.src = _dataDir + _soundPath[i];
        _soundArr.push(sound);
    }
    document.body.addEventListener("touchstart",soundLoad,false);
    $("#copyright").css("width",1024);
}

function iOSScroll(){
    var offsetY = 0;
    offsetY = $(window).scrollTop();
    var windowW = $(window).width();
    var windowH = $(window).height();
	var p = (windowW / imgW > windowH / imgH)? windowW / imgW : windowH / imgH;
    if(p<1)p=1;
    var cH = imgH * p  + 0.5 | 0;

	$bg.css("top", (windowH - cH) + offsetY + 45);
    $gNavi.css("top", offsetY);
}




