/**
* @author alfred
*/
var beDocReady = false;
var beYoutubeAPIReady = false;
var intervalCheckVideo = -1;
var currentIndex = 0;
var sliding = false;
var beAuto = true;
var checkDocInterval = -1;
var autoSliderInterval = -1;
var watingTime = 5000;
var isWaitingVideo = false;
var marqueeLeft = 0;
var arrVideo = new Array()

$(document).ready(function () {
    $('.chaton').hide();
    $('.chaton').fadeIn(2000);
    // member area interaction 會員專區按鈕
    $("#member-btn").mouseover(function () {
        $("#member-area").show();
    }).mouseout(function () {
        $("#member-area").hide();
    });

    // language selection area 語言選擇專區
    $("#lan-selector").mouseenter(function () {
        $("#lanbox").show();
    }).mouseleave(function () {
        $("#lanbox").hide();
    });
    $("#field-selector").mouseenter(function () {
        $("#fieldbox").show();
    }).mouseleave(function () {
        $("#fieldbox").hide();
    });
    // login area 登入專區
    /*$("#login-btn").mouseover(function () {
    $("#login-area").show();
    }).mouseout(function () {
    $("#login-area").hide();
    });*/

    // 側邊的shopping bag 和 online chat互動
    $("#side-shopchat .close-btn").click(function () {
        $(this).parent().hide();
    });

    setTimeout("updateBagPos( )", 1000);

    /// This is for main nav btns to trigger submenu box
    $(".mainnav-btn").bind("mouseenter",function (e) {
        //$("#logobox>p").html($("#logobox>p").text()+" 1 in >")
        $(this).css({ backgroundColor: '#f05a28' }).addClass('active');
        $(this).find(".submenu-box").slideDown('fast');
    }).mouseleave(function (e) {
        //$("#logobox>p").html($("#logobox>p").text() + " 1 out >")
        $(this).find(".submenu-box").hide();
        $(this).css({ backgroundColor: '#fff' }).removeClass('active');
    });
    $(".mainnav-btn2").mouseenter(function (e) {
        //$("#logobox>p").html($("#logobox>p").text() + " 2 in >")
        $(this).css({ backgroundColor: '#f05a28' }).addClass('active');
    }).mouseleave(function (e) {
        //$("#logobox>p").html($("#logobox>p").text() + " 2 out >")
        $(this).css({ backgroundColor: '#fff' }).removeClass('active');
    });
    //login
    $("#btn-login").bind("click", login)
    setTimeout("startMarquee()", 500);
    beDocReady = true;
    iniVideo()
    setSlideBtns();

});

$.preload(
	'/images/essence_active.jpg',
	'/images/moise_active.jpg',
	'/images/white_active.jpg',
	'/images/acne_active.jpg',
	'/images/age_active.jpg',
	'/images/eyelip_active.jpg',
	'/images/color_active.jpg',
	'/images/finger_active.jpg',
	'/images/endyear_active.jpg',
	'/images/newpro_active.jpg',
    '/images/youtube-replay.jpg',
    '/images/youtube-icon.jpg',
    '/images/youtube-share.jpg'
	);

function OpenDialog(_url) {
    window.open(_url, 'Dialog_' + strSessionId, 'height=480,width=540,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
}
function updateBagPos() {
    var scrollPos = $(window).scrollTop();
    var targetY = scrollPos + 156 + "px";
    $("#side-shopchat").animate({ top: targetY });
    setTimeout("updateBagPos()", 2000);
}
function startMarquee() {
    if ($("#marquee-container") == null) {
        return false;
    }
    marqueeLeft -= 1
    $("#marquee-container").css("left", marqueeLeft + "px");
    setTimeout("startMarquee()", 33);
    var marqueeOb = $("#marquee-container").children("div:eq(1)")
    var w = marqueeOb.width()
    var padding = Number(marqueeOb.css("padding-right").replace(/px/gi, ""))
    var totalW = (w + padding) * $("#marquee-container").children("div").length;
    $("#marquee-container").css("width", totalW + "px");
    if ($("#marquee-container").position().left < -(w + padding)) {
        $("#marquee-container").append("<div style=\"float:left;width:" + w + "px\">" + $("#marquee-container").find("div").first().html() + "</div>");
        $("#marquee-container").find("div:eq(0)").remove();
        $("#marquee-container").css("left", "0px");
        marqueeLeft = 0
    }
}

function login() {
    if ($("#uname").val() == "") {
        alert("請輸入使用者!")
        return;
    }
    if ($("#pw").val() == "") {
        alert("請輸入密碼!")
        return;
    }
    $("#btn-login").val("送出中");
    $("#btn-login").attr("disabled","disabled")
    $.ajax({
        url: "/tch/index.aspx?action=login&qwp2=false",
        type: "POST",
        data: ({ uname: $("#uname").val(), pw: $("#pw").val() }),
        success: function (e) {
            try {
            var obRes = eval(e);
            if (obRes.success) {
                location.reload();
            } else {
                alert(obRes.msg);
            }
            } catch (e) {
            alert("伺服器錯誤的回應，請連絡系統管理員!");
            }
            $("#btn-login").val("登入");
            $("#btn-login").removeAttr("disabled")
        },
        error: function () {
            alert("網路發生錯誤!")
            $("#btn-login").val("登入")
            $("#btn-login").removeAttr("disabled")
        }
    })
}
function pulishToFacebook(img, link, title, summary) {
    var url = "http://www.facebook.com/sharer.php?s=100&p[images][0]={images_0}&amp;p[images][1]={images_1}&p[url]={url}&p[title]={title}&p[summary]={summary}"
    url = url.replace(/{title}/gi, encodeURIComponent(title));
    url = url.replace(/{images_0}/gi, img);
    url = url.replace(/{images_1}/gi, encodeURIComponent("http://mpt1.shopunt.com.tw/images/logo.jpg"));
    url = url.replace(/{url}/gi, encodeURIComponent(link));
    url = url.replace(/{summary}/gi, encodeURIComponent(summary));
    window.open(url, 'sharer', 'toolbar=0,status=0,width=626,height=436');
}
function publishToPlurk(link, title) {
    var url = 'http://www.plurk.com/?qualifier=shares&status=' + (encodeURIComponent(link)) + (' (' + encodeURIComponent(title) + ') ')
    window.open(url)
}
function publishToTwitter(link, title) {
    window.open("https://twitter.com/intent/tweet?source=webclient&text=" + encodeURIComponent(link) + "  (" + title + ") ")
}

function iniVideo() {
    var sliderChildrenLen = $("#slides").children().length;
    for (var i = 0; i < sliderChildrenLen; i++) {
        $("#slides").children().eq(i).attr("id","slider_" + i)
    }
    var videoLen = $(".promvideo").length;
    for (var i = 0; i < videoLen; i++) {
        var key = $(".promvideo:eq(" + i + ")").parent().attr("id").split("_")[1]
        arrVideo[key] = new Array()
        arrVideo[key]["height"] = $(".promvideo:eq(" + i + ")").css("height").replace(/px/gi, "");
        arrVideo[key]["width"] = $(".promvideo:eq(" + i + ")").css("width").replace(/px/gi, "");
        arrVideo[key]["vid"] = $(".promvideo:eq(" + i + ")").attr("vid");
        $(".promvideo:eq(" + i + ")").attr("id", "video_" + key)
    }
    if ($("#slider_0").find(".promvideo").length > 0) {
        generateVideo(0)
    }
    if ($("#slider_0>.promvideo") != null && typeof ($("#slider_0>.promvideo").attr("vid")) != "undefined") {
        if ($("#slider_0>.promvideo").attr("vid").indexOf("autoplay=0") > -1) {
            //第一個 不自動撥放
            var sec = $("#slider_0").attr("sec")
            if (typeof (sec) != "undefined" && sec != 0) {
                autoSliderInterval = setTimeout(autoSlideMain, sec * 1000)
            }
        } else {
            //第一個 自動撥放
            isWaitingVideo = true;
        }
    }
    else {
        var sec = $("#slider_0").attr("sec")
        if (typeof (sec) != "undefined" && sec != 0) {
            autoSliderInterval = setTimeout(autoSlideMain, sec * 1000)
        }
    }
}

function setSlideBtns() {
    $("#slidecontrol li").click(function () {
        if ($(this).text() - 1 == currentIndex) {
            return false;
        }
        if (sliding) {
            return false;
        }
        isWaitingVideo = false;
        beAuto = false;
        sliding = true;
        var tarX = 0
        $("#video_" + currentIndex + ">.end-video-cover").hide();
        $("#video_" + currentIndex + ">.video-main").tubeplayer("destroy");
        $("#video_" + currentIndex).hide();
        if (currentIndex < $(this).text()) {
            tarX = -980
            currentIndex = $(this).text() - 1;
            $("#slides>li:eq(0)").after($("#slider_" + currentIndex))
            $("#slides").animate({
                left: tarX
            }, {
                duration: 600,
                easing: 'swing',
                complete: function () {
                    $("#slidecontrol li").removeClass("activeslide")
                    $("#slidecontrol li:eq(" + currentIndex + ")").addClass("activeslide");
                    $("#slides>li:eq(" + ($("#slides").children().length - 1) + ")").after($("#slides>li:eq(0)"));
                    $("#slides").css("left", "0px");
                    sliding = false;
                    if ($("#slider_" + currentIndex).find(".promvideo").length > 0) {
                        generateVideo(currentIndex)
                    }
                }
            });
        } else {
            tarX = 0
            currentIndex = $(this).text() - 1;
            $("#slides>li:eq(0)").before($("#slider_" + currentIndex));
            $("#slides").css("left", "-980px");
            $("#slides").animate({
                left: tarX
            }, {
                duration: 600,
                easing: 'swing',
                complete: function () {
                    $("#slidecontrol li").removeClass("activeslide");
                    $("#slidecontrol li:eq(" + currentIndex + ")").addClass("activeslide");
                    sliding = false;
                    if ($("#slider_" + currentIndex).find(".promvideo").length > 0) {
                        generateVideo(currentIndex)
                    }
                }
            });
        }
    });
}

function autoSlideMain() {
    worning("auto slide main")
    if (!beAuto) {
        return false;
    }
    worning("be auto:" + beAuto)
    $("#video_" + currentIndex + ">.video-main").tubeplayer("destroy");
    $("#video_" + currentIndex+">.end-video-cover").hide();
    $("#video_" + currentIndex).hide();
    tarX = -980
    currentIndex += 1;
    currentIndex = currentIndex % $("#slides").children().length
    
    //有影片的時候
    if (typeof ($("#video_" + currentIndex).attr("vid")) != "undefined") {
        if ($("#video_" + currentIndex).attr("vid").indexOf("autoplay=0") > -1) {
            isWaitingVideo = false;
        } else {
            isWaitingVideo = true;
        }
    } else {
        isWaitingVideo = false;
    }
    $("#slides>li:eq(0)").after($(".slider_" + currentIndex))
    $("#slides").animate({
        left: tarX
    }, {
        duration: 600,
        easing: 'swing',
        complete: function () {
            $("#slidecontrol li").removeClass("activeslide").eq(currentIndex).addClass("activeslide");
            $("#slides>li:eq(" + ($("#slides").children().length - 1) + ")").after($("#slides>li:eq(0)"));
            $("#slides").css("left", "0px");
            worning("is wait video:" + isWaitingVideo)
            if (!isWaitingVideo) {
                clearInterval(autoSliderInterval)
                var sec = $("#slider_" + currentIndex).attr("sec")
                if (typeof (sec) != "undefined" && sec != 0) {
                    autoSliderInterval = setTimeout(autoSlideMain, sec * 1000)
                }
            }
            generateVideo(currentIndex);
            sliding = false;
        }
    });

}


function generateVideo(key) {
    if (arrVideo[key] == null) {
        return false;
    }
    if(!$.browser.msie){
        $("#video_"+key).find("iframe").show();
    }else{
        $("#video_"+key).find("iframe").show();
    }
    $("#video_" + key).show();
    
    var vid =arrVideo[key]["vid"].toString()
    var video = vid.substring(0, vid.indexOf("?"));
    var videoPlay=false;
    if (vid.indexOf("autoplay=1")>-1){
        videoPlay=true;
    }
    $("#video_" + key + ">.video-main").tubeplayer({
        width: arrVideo[key]["width"], // the width of the player
        height: arrVideo[key]["height"], // the height of the player
        allowFullScreen: "true", // true by default, allow user to go full screen
        autoPlay:videoPlay,
        initialVideo: vid.substring(0, vid.indexOf("?")), // the video that is loaded into the player
        preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
        onPlayerEnded:videoEnd,
        onPlayerPlaying: onVideoPlay,
        onPlayerPaused: videoPause
    });
}


function videoEnd() {
    var widthPx = $("#video_" + currentIndex).css("width");
    var heightPx = $("#video_" + currentIndex).css("height");
    var body = "";
    var w = Number(widthPx.replace(/px/gi, ""));
    var h = Number(heightPx.replace(/px/gi, ""));
    var u = encodeURIComponent("http://www.youtube.com/watch?v=" + $("#video_" + currentIndex).attr("vid"))
    //之後拿掉
    if (!$.browser.msie) {
        $("#video_" + currentIndex).find("iframe").css("display", "none");
        $("#video_" + currentIndex).find("iframe").before(body)
    } else if ($("#vidoe_" + currentIndex).find("object")) {
        $("#video_" + currentIndex).find("object").css("display", "none");
        $("#video_" + currentIndex).find("object").before(body)
    }
    //    $("#video_" + currentIndex + ">.end-video-cover").html()
    $("#video_" + currentIndex + ">.end-video-cover").show()
    if (isWaitingVideo && beAuto) {
        clearInterval(autoSliderInterval)
        var sec = $("#slider_" + currentIndex).attr("sec")
        if (typeof(sec) != "undefined" && sec != 0) {
            autoSliderInterval = setTimeout(autoSlideMain, sec * 1000)
        }
        isWaitingVideo = false;
    }
}
function videoPause() {
    worning("video pause")
    clearInterval(autoSliderInterval)
    var sec = $("#slider_" + currentIndex).attr("sec")
    if (typeof("sec")!="undefined" && sec != 0) {
        autoSliderInterval = setTimeout(autoSlideMain, sec*1000)
    }
}
function worning(msg) {
    //alert(msg)
}
function onVideoPlay() {
    clearInterval(autoSliderInterval)
    isWaitingVideo = true;
}
function replayYoutube(self) {
    try {
        clearInterval(autoSliderInterval)
        $("#video_" + currentIndex + ">.end-video-cover").hide();
        if (!$.browser.msie && !$.browser.mozilla) {
            $("#video_" + currentIndex).find("iframe").css("display", "block")
            $("#video_" + currentIndex + ">.video-main").tubeplayer("seek", 0)
            $("#video_" + currentIndex + ">.video-main").tubeplayer("play")
        } else {
            $("#video_" + currentIndex).find("object").css("display", "block");
            var vid = $("#video_" + currentIndex).attr("vid")
            var video = vid.substring(0, vid.indexOf("?"));
            $("#video_" + currentIndex + ">.video-main").tubeplayer("destroy");
            $("#video_" + currentIndex+">.video-main").tubeplayer({
                width: arrVideo[currentIndex]["width"], // the width of the player
                height: arrVideo[currentIndex]["height"], // the height of the player
                allowFullScreen: "true", // true by default, allow user to go full screen
                autoPlay: true,
                initialVideo: video, // the video that is loaded into the player
                preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
                onPlayerEnded: videoEnd,
                onPlayerPlaying: onVideoPlay,
                onPlayerPaused: videoPause
            });
        }
    } catch (e) {
    }
}

function shareYoutube(self) {
    var u = encodeURIComponent("http://www.youtube.com/watch?v=" + self.parent().parent().attr("vid"))
    url="http://www.facebook.com/sharer/sharer.php?u=" +u
    window.open(url, 'sharer', 'toolbar=0,status=0,width=626,height=436');
}
function soreEpaperMail() {
    if ($("#epaper-email").val() == "") {
        alert("請輸入e-mail");
        return false;
    } else {
        var regEmail = /^(\w+)@([\w.]+)/gi
        if (regEmail.exec($("#epaper-email").val()) == null) {
            alert("請輸入正確的e-mail格式")
            return false;
        }
        window.location.href = "/tch/Member/JoinList.aspx" + "?txtFooterEmail=" + $("#epaper-email").val();
    }
}
