/***********************************************
 other item 関連
***********************************************/
var othersTimer;
var othersInterval = 10000;

function otherItem() {
    var target_url = '/printOtherItems.php?_others=';

    var otherCount = (document.getElementById('otherCount')) ? document.getElementById('otherCount').value : '';
    var otherGenre = (document.getElementById('otherGenre')) ? document.getElementById('otherGenre').value : '';
    var otherCategory = (document.getElementById('otherCategory')) ? document.getElementById('otherCategory').value : '';
    var otherDate = (document.getElementById('otherDate')) ? document.getElementById('otherDate').value : '';
    var otherWidth = (document.getElementById('otherWidth')) ? document.getElementById('otherWidth').value : '';
    var otherHeight = (document.getElementById('otherHeight')) ? document.getElementById('otherHeight').value : '';

    var board = document.getElementById('others');

    var d = new Date();

    target_url += '&count=' + otherCount;
    target_url += '&genre=' + otherGenre;
    target_url += '&category=' + otherCategory;
    target_url += '&date=' + otherDate;
    target_url += '&width=' + otherWidth;
    target_url += '&height=' + otherHeight;
    target_url += '&' + d.getTime();

    var funcRef = function(text_data) {
        var funcChangeText = function() {
            document.getElementById('others').innerHTML = text_data;
            fadeInWindow(board, 0);
            setListenersOtherItem();
        }

        fadeOutWindow(board, 100, null, funcChangeText);

    }
    req = new httpRequest( target_url, funcRef );
    req.doGet();

}

function setListenersOtherItem() {
    if (obj = document.getElementById('others')) {
        obj.style.width = "100%";
        clearTimeout(othersTimer);
        if (othersInterval > 0) {
            othersTimer = setTimeout(otherItem, othersInterval);
        }
    }
}
/***********************************************
 hige関連
***********************************************/
function hige(e)
{
    if (! window.navigator.cookieEnabled) {
        alert("cookieを有効にしてからご利用ください");
        return null;
    }

    var entry_id = $('hige_form').e.value;
        
    var vote_count = checkVotedHige(entry_id);
    if (0 < vote_count && vote_count <= 5) {
        unableVoteHige(vote_count);
        return null;
    }

    var req = getXMLHttpRequest();
    req.open("post", "/printHige3.php", true);
    req.setRequestHeader("content-type", "application/x-www-form-urlencoded;"); 
    var d = sendXMLHttpRequest(req, queryString('hige_form'));
    var voted_count = $('hige_form').c.value;

    var good = function(res) {
        var hige = DIV({"id": "hige"}, null);
        hige.innerHTML = res.responseText;
        swapDOM($('hige'), hige);

        setVotedHige(entry_id, voted_count);
        unableVoteHige(voted_count)
    }

    var bad = function(err) {
        alert(err);
    }

    d.addCallbacks(good, bad);
}


function hige_count(e)
{
    /*
	// Clikされたオブジェクトを取得
	if ( e.target ) {
		target_node = e.target;
        //debug
        alert(e.target);
	} else {
		target_node = e.srcElement;
        alert(e.srcElement);
	}
	// safari対策
	if ( target_node.node==3 ) {
		target_node = target_node.parentNode;
	}
    */
    target_node = e.src();

	// idを取得
	hige_id = target_node.id;

    count = parseInt(hige_id.substr(4, 1));

    hige_count_set(count);
}

function hige_count_set(count)
{
    $('hige_form').c.value = count;
    for (i=1; i<=count; i++) {
        $('hige'+i).src = '/images/hige_up.gif';
    }
    for (i=count+1; i<=5; i++) {
        $('hige'+i).src = '/images/hige_down.gif';
    }
}

/***********************************************
 初期設定
***********************************************/
function setListeners(e) {
    // for Namzu Hige
    // setListenersHige();

    // for Other Item
    setListenersOtherItem();
}

addListener(window, 'load', setListeners, false );




/***********************************************
 追記部分折りたたみ
***********************************************/
function showHide(entryID, entryLink, htmlObj) {
    extTextDivID = ('Text' + (entryID));
    extLinkDivID = ('Link' + (entryID));
    if( document.getElementById ) {
        if( document.getElementById(extTextDivID).style.display ) {
            if( entryLink != 0 ) {
                document.getElementById(extTextDivID).style.display = "block";
                document.getElementById(extLinkDivID).style.display = "none";
                htmlObj.blur();
            } else {
                document.getElementById(extTextDivID).style.display = "none";
                document.getElementById(extLinkDivID).style.display = "block";
            }
        } else {
            location.href = entryLink;
            return true;
        }
    } else {
        location.href = entryLink;
        return true;
    }
}


function show_comment_form(item_id)
{
    var elem = $("comment_form_layer");
    elem.style.display = "block";
    centering_by_window(elem, 0, 0);   
    elem.style.zIndex = "1500";
    var page_size = getPageSize();
    var overlay = DIV({"id": 'overlay', "style": 'height: ' + page_size[1] + 'px; width: ' + page_size[0] + 'px'});
    document.body.appendChild(overlay);
}


function hide_comment_form()
{
    $("comment_form_layer").style.display = "none";
    $("comment_form").reset();
    removeElement("overlay");
}

// ここから先はすべて･･･
// リリース前に直す必要があるかも
function getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) {
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else {
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    if (xScroll < windowWidth) {
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    return arrayPageSize;
}


function getPageScroll() {
    var yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {
        yScroll = document.body.scrollTop;
    }
    arrayPageScroll = new Array("", yScroll);
    return arrayPageScroll;
}


function centering_by_window(element, x, y) {
    element = $(element);
    x = x || 0;
    y = y || 0;
    var w = element.offsetWidth;
    var h = element.offsetHeight;
    var ww = getWindowWidth();
    var wh = getWindowHeight();
    var page_scroll = getPageScroll();
    var top = wh / 2 - h / 2 - y + page_scroll[1] + "px";
    var left = ww / 2 - w / 2 - x + "px";
    element.style.position = "absolute";
    element.style.top = top;
    element.style.left = left;
}


function getWindowWidth() {
    if (window.innerWidth) {
        return window.innerWidth;
    }
    if (document.documentElement && document.documentElement.clientWidth) {
        return document.documentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    }
    return 0;
}


function getWindowHeight() {
    if (window.innerHeight) {
        return window.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
        return document.body.clientHeight;
    }
    return 0;
}



/* cookies.js */
/*
     Example File From "JavaScript and DHTML Cookbook"
     Published by O'Reilly & Associates
     Copyright 2003 Danny Goodman
*/

// utility function to retrieve a future expiration date in proper format;
// pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire; all three
// parameters required, so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}

// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}



function getElementPosition(elemID) {
    var offsetTrail = document.getElementById(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

function getTime()
{
    var date = new Date();
    return date.getTime();
}



function show_comment_all(item_id)
{
    var elem = $("comment_all_div");
    elem.style.display = "block";
    elem.style.zIndex = "1500";
    /*
    var page_scroll = getPageScroll();
    var top = (page_scroll[1] + 200) + "px";
    var left = "300px";
    */
    var pos = getElementPosition("detail_tokushu_comment_" + item_id);
    elem.style.position = "absolute";
    /*
    elem.style.top = top;
    elem.style.left = left;
    */
    elem.style.top = pos.top + "px";
    elem.style.left = pos.left + "px";
    var page_size = getPageSize();
    var overlay = DIV({"id": 'overlay', "style": 'height: ' + page_size[1] + 'px; width: ' + page_size[0] + 'px'}, ' ');
    document.body.appendChild(overlay);
}


function show_comment(feature_id, item_id, flg)
{
    function make_li(data)
    {
        return DIV({'class': 'detail_tokushu_comment'},
            data.comment + "(" + data.created + "　" + data.nickname + ")");
    }

    if (flg == 'all') {
        // 1000に制限？
        var comment_count = 1000;
        var func_disp = function(data)
            {
                var div_id = 'comment_all_div';
                var dom = DIV({'id': div_id},
                            DIV({'id': 'comment_all_hide_button'},
                                INPUT({'type': 'button', 'value': '閉じる', 'onclick': 'hide_comment_all()'}, null)
                            ),
                            map(make_li, data.comment_list)
                        );
                swapDOM(div_id, dom);
                show_comment_all(feature_id);
            }
    } else {
    /*
        var comment_count = 3;
        var func_disp = function(data)
            {
                var dom_id = 'comment_list_' + item_id;
                var dom = UL({'id' : dom_id, 'class': 'user_comment'},
                    map(make_li, data.comment_list));
                swapDOM(dom_id, dom);
            }
            */
    }

    target = '/tokushu/index.php?m=4&id=' + feature_id + '&item_id=' + item_id + '&comment_count=' + comment_count + '&' + getTime();
    var d = loadJSONDoc(target);
    var good = function(data) {
        if (data.errors) {
            return null;
        }

        func_disp(data);
    }
    var bad = function(err) {
        alert('failed');
    }
    d.addCallbacks(good, bad);

}

function hide_comment_all()
{
    $("comment_all_div").style.display = "none";
    removeElement("overlay");
}





/*
function submit_vote(feature_id, item_id)
{
    if (! window.navigator.cookieEnabled) {
        alert("cookieを有効にしてからご利用ください");
        return null;
    }
        
    if (checkVotedItem(item_id)) {
        unableVote(feature_id, item_id);
        return null;
    }

    var req = getXMLHttpRequest();
    req.open("post", "/tokushu/", true);
    req.setRequestHeader("content-type", "application/x-www-form-urlencoded;"); 
    var d = sendXMLHttpRequest(req, 'm=2&id='+feature_id+'&item_id='+item_id);

    var good = function(res) {
        var data = evalJSON(res.responseText);
        var span_id = 'vote_count_' + data.item_id;
        if (e = $(span_id)) {
            new_e = SPAN({'id': span_id}, data.vote_count);
            swapDOM(e, new_e);
        }
        setVotedItem(data.item_id);
        unableVote(data.id, data.item_id);
    }

    var bad = function(err) {
        alert(err);
    }

    d.addCallbacks(good, bad);
}
*/




/* ここからhige Cookieチェック関連 */
function checkVotedHige(entry_id)
{
    var voted_hige = getVotedHige();

    for (var i in voted_hige) {
        if (voted_hige[i].entry_id == entry_id) {
            return voted_hige[i].vote_count;
        }
    }
    return -1;
}

function setVotedHige(entry_id, vote_count)
{
    var voted_hige = getVotedHige();

    var new_voted_hige = new Array();
    //new_voted_hige[0] = {'entry_id': entry_id, 'vote_count': vote_count};
    new_voted_hige[0] = entry_id + ':' + vote_count;

    for (var i in voted_hige) {
        if (voted_hige[i].entry_id != entry_id) {
            e = voted_hige[i].entry_id;
            v = voted_hige[i].vote_count;
            new_voted_hige.push(e + ':' + v);
        }
    }
        
    setCookie("VOTEDHIGE", new_voted_hige.join(","));
}

function getVotedHige()
{
    var cookie_voted_hige = getCookie("VOTEDHIGE");
    if (cookie_voted_hige) {
        var cookie_array = cookie_voted_hige.split(",");
        var tmp_array = new Array();
        var tmp = null;
        for (var i in cookie_array) {
            tmp = cookie_array[i].split(":");
            tmp_array[i] = {'entry_id': parseInt(tmp[0]), 'vote_count': parseInt(tmp[1])};
        }
        return tmp_array;
    } else {
        return null;
    }
}


function enableVoteHige(vote_count)
{
    for (var i=1; i<=5; i++) {
        obj = $('hige' + i);
        obj.style.cursor = 'Pointer';
        connect(obj, 'onclick', hige_count);
    }
    hige_count_set(1);

    obj = $('hige_up_button');
    obj.src = "/images/hige_up_button.gif";
    obj.style.cursor = 'Pointer';
    connect(obj, 'onclick', hige);
}

function unableVoteHige(vote_count)
{
    for (var i=1; i<=5; i++) {
        obj = $('hige' + i);
        obj.style.cursor = 'Default';
        disconnectAll(obj);
    }
    hige_count_set(vote_count);

    obj = $('hige_up_button');
    obj.src = "/images/hige_uped_button.gif";
    obj.style.cursor = 'Default';
}

function setSubmitVoteHige()
{
    var entry_id = $('hige_form').e.value;
    //debug
    //alert('entry_id=' + entry_id);
    var vote_count = checkVotedHige(entry_id);
    //debug
    //alert('vote_count=' + vote_count);
    if (0 < vote_count && vote_count <= 5) {
        unableVoteHige(vote_count);
    } else {
        enableVoteHige(1);
    }
}


function onload_event()
{
    //debug
    //alert("onload_event");
    setSubmitVoteHige();
}

addLoadEvent(onload_event);

