// -*- coding: utf-8-unix -*-
window.name='yyc-www';

// # XXX Tempolary use 
function getCenterWindowX(cont) {
    var wx = jQuery(window).scrollLeft() + (jQuery(window).width() - cont.outerWidth()) / 2;
    if (wx < 0) wx = 0;
    return wx;
}

function getCenterWindowY(cont) {
    var wy = jQuery(window).scrollTop() + (jQuery(window).height() - cont.outerHeight()) / 2;
    if (wy < 0) wy = 0;
    return wy;
}

function showIFrameLightBox(url, width, height) {
    var lboxIf  = jQuery("#lbox-if");
    var lboxIfp = jQuery("#lbox-ifp");
    var bodyWidth  = jQuery( document.body ).width();
    var bodyHeight = jQuery( document.body ).height();
    jQuery("#lbox-shade").width(bodyWidth).height(bodyHeight).fadeTo("fast", 0.5);

    if (url.indexOf('?') == -1) {
        url = url + "?.wc=window";
    } else {
        url = url + "&.wc=window";
    }
    lboxIf.attr("src", url);
    lboxIf.removeAttr("disabled");
    if (width == undefined) {
        lboxIf.css({ "overflow": "auto" });
        width = 800;
    }
    if (height == undefined) {
        lboxIf.css({ "overflow": "auto" });
        height = 400;
    }
    lboxIf.attr("width", width);
    lboxIf.attr("height", height);
    lboxIf.show();

    var wx, wy;
    wx = getCenterWindowX(lboxIfp);
    wy = getCenterWindowY(lboxIfp);

    lboxIfp.css({ "position": "absolute", "top": wy, "left": wx });
    lboxIfp.show();

}

function iFrameLightBox(url, width, height) {
    var lboxIf = jQuery("#lbox-if");
    jQuery("#lbox-shade").click(function() {
        jQuery("#lbox-if").remove();
        jQuery("#lbox-ifp").remove();
        jQuery(this).fadeOut("fast");
        return false;
    });
    jQuery("body").append('<div id="lbox-ifp"><iframe disabled="disabled" frameborder="0" id="lbox-if"></iframe></div>');
    showIFrameLightBox(url, width, height);
}

function appendFloating(url) {
    var s = document.createElement('script'),
    h = document.getElementsByTagName('head')[0];
    s.charset = 'utf-8';
    s.type = 'text/javascript';
    s.src = '/js/floating.js?'+(+new Date);
    s.id  = 'floatingScript';
    if (url.indexOf('?') == -1) {
        url = url + "?.wc=window";
    } else {
        url = url + "&.wc=window";
    }
    s.setAttribute("event", url);

    setTimeout(function () {
        h.appendChild(s);
    }, 1);
}

function showFloatingBoxMulti(id, url, width, height, header_text) {
    if (FloatingBoxMulti && FloatingBoxMulti.boxes.length > 0) {
        return;
    }
    if (url.indexOf('?') == -1) {
        url = url + "?.wc=window";
    } else {
        url = url + "&.wc=window";
    }
    FloatingBoxMulti.create_or_show({
        background_image: '',
        box_id: id,
        content_url: url,
        header_height: 62, // 32 + 30(inner margin)
        width: width,
        height: height + 30,
        without_toggle: 1,
        without_help: 1,
        header_text: header_text || ''
    });
    FloatingBoxMulti.hide_callback = function(box_id) { this.boxes = []; };
}

function showNotice(noticeString) {
    // var top = jQuery(window).scrollTop();
    var width  = jQuery( document.body ).width();
    var noticeList = jQuery("#notice-list");
    var errorList = jQuery("#error-list");
    noticeList.css({"width": width });
    errorList.css({"width": width });
    if (noticeString.length > 0) {
        noticeList.find("li.notice-item").each(function() {
            jQuery(this).remove();
        });
        var li = jQuery("#notice-list ul").append("<li>");
        // li.css('class', 'notice-item');
        li.addClass('notice-item');
        li.html(noticeString);
    }
    if (jQuery(".notice-item").size() > 0) {
        noticeList.slideDown("slow").queue(function() {
            setTimeout(function(){
                noticeList.slideUp("slow");
                noticeList.dequeue();
            }, 3000);
        });
    }
    if (jQuery(".error-item").size() > 0) {
        errorList.slideDown("slow").fadeTo("fast", 0.8).queue(function() {
            setTimeout(function(){
                errorList.slideUp("slow");
                errorList.dequeue();
            }, 3000);
        });
    }
    /*
    setTimeout(function(){
        noticeList.attr('id', 'already-noticed');
        errorList.attr('id', 'already-noticed');
    }, 5000);
    */
}

function showBackground() {
    var body_width  = jQuery( document.body ).width();
    var body_height = jQuery( document.body ).height();
    var lBFSafe = jQuery("#lbox-shade");
    lBFSafe.css({ "width": body_width, "height": body_height });
    return lBFSafe;
}

function inlineDivLightBox( classname ) {
    var lBFSafe = showBackground().css({ display: 'block', opacity: 0 }).animate({
        opacity: 0.5
    });
    var inlinediv = jQuery("." + classname);
    lBFSafe.attr('event', classname);

    var contents = jQuery("#" + inlinediv.attr('event'));

    var wx, wy, ty;

    if (inlinediv.outerWidth() > contents.attr('width') + 20) {
        inlinediv.css({ "width": contents.attr('width') + 20 });
    }

    wx = getCenterWindowX(inlinediv);

    ty = jQuery(window).height() * 0.8;
    if (ty > contents.attr('height') + 20) {
        inlinediv.css({ "height": contents.attr('height') + 20 });
    } else {
        inlinediv.css({ "height": ty });
    }

    wy = getCenterWindowY(inlinediv);

    inlinediv.css({ "z-index": "100", "position": "absolute", "top": wy, "left": wx });
    inlinediv.slideDown();
}


jQuery(function() {
    /* close float box */
    $_("#lbox-close, #cancel_floatbtn, #floatbox-photo-close").bind('click', function () {
        $_("#lbox-shade").trigger('click');
    })
    $_("#lbox-shade").bind('click', hideLboxShade);

    // toggle checked state　all
    jQuery("#check-all-item-header, #check-all-item-footer").bind("change", function () {
        var _checked = jQuery(this).attr('checked');
        jQuery(".item-check, #check-all-item-header, #check-all-item-footer").attr('checked', _checked);
    });
    // initialize checked state
    jQuery(".item-check, #check-all-item-header, #check-all-item-footer").attr("checked", false);

    // ---- show detail image ** /picture_bbs/adult/article/?id=xxxx
    jQuery(".lbox-div").click(function() {
        // inlineDivLightBox(jQuery(this).attr('event'));
        var imageBox    = $_('#lbox-inline-image'),
            imageDetail = $_('#image-detail-div');
        /*
        if ( imageBox.outerWidth() > imageDetail.attr('width') + 20 ) {
            imageBox.css({ width : imageDetail.attr('width') + 20 });
        }
        var ty = jQuery(window).height() * 0.8;
        if ( ty > imageDetail.attr('height') + 10 ) {
            imageBox.css({ height: imageDetail.attr('height') + 10, paddingTop: 10 });
        } else {
            imageBox.css({ height: ty });
        }
        */
        showFloatBox('lbox-inline-image');
        return false;
    });

    // ---- show detail image ** /my/mail_box/history/?id=xxxx
    jQuery('.lbox-detail-image').bind('click', function () {
        var path   = this.getAttribute('detail_path'),
            width  = this.getAttribute('detail_width'),
            height = this.getAttribute('detail_height'),
            id     = this.getAttribute('detail_id');
        if ( !jQuery('#'+id).size() ) {
            jQuery('<span>')
                .attr({
                    id: id
                })
                .css({
                    position   : 'absolute',
                    zIndex     : 100,
                    padding    : '10px 10px 30px 10px',
                    background : 'white',
                    border     : '5px solid #8080A0',
                    width      : width,
                    height     : height
                })
                .html(
                    '<a onclick="$_(\'#lbox-shade\').trigger(\'click\')" style="float:right" href="javascript:void(0)"><img src="/img/member/floatbox/close.gif" width="16" height="16" /></a><br clear="all" />' +
                    '<span class="image-cover-style" style="width:{width}px;height:{height}px;">'.format_ex({ src:path, width:width, height:height }) +
                    '<img src="{src}" width="{width}" height="{height}" />'.format_ex({ src:path, width:width, height:height }) +
                    '<img class="cover-img" style="width:{width}px;height:{height}px;" src="/img/common/1x1.gif" /></span>' .format_ex({ src:path, width:width, height:height })
                )
                .appendTo( document.body );
        }
        showFloatBox( id );
        return false;
    });

    // ---
    var radios = $_("input:radio");
    radios.bind('click', function () {
        var name = this.name;
        radios.each(function (i, radio) {
            if ( radio.name == name && $_( radio ).hasClass('toggleOn') ) {
                $_( radio ).parent()[ ( radio.checked ? 'add' : 'remove' ) + 'Class' ]('on');
            }
        });
    });
    $_("input:radio:checked").trigger('click');
    // ----- xxxx
    showNotice("");

    // $("img#image-detail").lazyload({ threshold : 60, effect : "fadeIn" });
});

$.extend(String.prototype, {
   format_ex: function (args) {
        function clone (obj) {
            var clone_obj = {};
            for ( var i in obj ) clone_obj[i] = obj[i];
            return clone_obj;
        }
        function each (ary, callback) {
            for ( var i = 0, l = ary.length; i < l; i++ ) {
                callback(i, ary[i], ary);
            }
        }
        function escape (str) {
            return String( str ).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }
        var filter_list = {
            parseInt: function (val) {
                return parseInt.apply(null, arguments);
            },
            html: function (val) {
                return escape(val);
            },
            nl2br: function (val) {
                return val.replace(/\r\n|\r|\n/g, '<br />');
            }
        };
        return this.replace(/\{([a-zA-Z_0-9.|]+)\}/g,function(){
             var _ = arguments[1].split("|"), str = _[0], filters = _.slice(1), val = clone(args);
             // hash or string
             each(str.split("."), function (i,k) { val = val[k] });
             // filter
             filters.length && each(filters, function (i,f) { filter_list.hasOwnProperty(f) && ( val = filter_list[f](val) ) });
             // return val if not undefined value
             return /^(string|number)$/.test( typeof val ) ? val : "";
        });
    }
});

function cancelEvent (event) {
    event.preventDefault  ? event.preventDefault()  : (event.returnValue  = false);
    event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true);
}

/*****************************************

*****************************************/
var $_ = jQuery;
function showFloatBox (content_id) {
    var bodyWidth  = $_( document.body ).width();
    var bodyHeight = $_( document.body ).height();
    $_("#lbox-shade").css({
        width   : bodyWidth,
        height  : bodyHeight,
        display : 'block',
        opacity : 0
    }).animate({ opacity: 0.5 }).attr('content_id', content_id);

    var lboxIfp = $_('#'+content_id);
    var offset_top = Math.max( ( document.documentElement.clientHeight / 2 ) - ( lboxIfp.outerHeight() / 2 ) + ( document.documentElement.scrollTop || document.body.scrollTop ), 100 );
    lboxIfp.css({
        top     : offset_top,
        left    : parseInt( ( bodyWidth / 2 ) - ( lboxIfp.outerWidth() / 2 ) ) + "px",
        display : 'block',
        opacity : 0
    }).animate({
        opacity : 1
    });
}
function showFloatBoxAbsolute (content_id) {
    var memoBox    = $_('#' + content_id),
        bodyWidth  = $_( document.body ).width(),
        bodyHeight = $_( document.body ).height(),
        offset_top = ( document.documentElement.clientHeight / 2 ) - ( memoBox.height() / 2 ) + ( document.documentElement.scrollTop || document.body.scrollTop );
    memoBox.css({
        top: offset_top,
        left: ( bodyWidth / 2 ) - ( memoBox.width() / 2 )
    }).fadeTo('fast', 1).show();
}
function showConfirmFloatBox () {
    showFloatBox('confirm_floatbox');
}
function showAreaCheckFloatBox () {
    showFloatBox('area_check_floatbox');
}
function hideFloatBox (content_id) {
    var hids = ['#lbox-shade'];
    if ( content_id ) {
        hids.push('#'+content_id);
    }
    $_( hids.join(',') ).fadeTo(400, 0, function () {
        $_( this ).hide();
    });
}
function hideLboxShade () {
    var cid  = $_( this ).attr('content_id'),
        hids = ['#lbox-shade'];
    if ( cid ) {
        hids.push('#'+cid);
    }
    $_( hids.join(',') ).fadeTo(400, 0, function () {
        $_( this ).hide();
    });
}
function submitByLink (form, values) {
    values = values || {};
    $_.each(values, function (k,v) {
        $_( form ).append( $_('<input type="hidden" />').attr({
            name  : k,
            value : v
        }) );
    });
    setTimeout(function () {
        $_( form ).submit();
    }, 20);
}
function changeImageDetail(src, width, height, target_id) {
    var imagedetail = jQuery("#" + ( target_id ? target_id : "image-detail" ) );
    changeStyle(width, height, 'image-detail-wrap');
    changeStyle(width, height, 'image-detail-cover');
    imagedetail.attr('src', src);
    imagedetail.attr('width', width);
    imagedetail.attr('height', height);
    return false;
}
function changeStyle(width, height, target_id) {
    var imagedetail = jQuery("#" + ( target_id ? target_id : "image-detail" ) );
    imagedetail.css({'width': width, 'height': height});
    return false;
}
function animateProfileBar (bar, to_width, from_width) {
    if ( from_width ) {
        bar.css({ width: from_width });
    }
    bar.animate({
        width: to_width
    }, 1000);
}

/******* xxxxx *******/
Array.from = function(array) {
    if(array.callee){
        return Array.prototype.slice.call(array,0)
    }
    var length = array.length;
    var result = new Array(length);
    for (var i = 0; i < length; i++)
        result[i] = array[i];
    return result;
};
![].forEach && ( Array.prototype.forEach = function (callback, bindObj) {
    for ( var i = 0; i < this.length; i++ ) {
        callback.apply(bindObj, [this[i], i, this]);
    }
});
![].map && ( Array.prototype.map = function (callback, bindObj) {
    var res = [];
    for ( var i = 0; i < this.length; i++ ) {
        res.push( callback.apply(bindObj, [this[i], i, this]) );
    }
    return res;
});
![].filter && ( Array.prototype.filter = function (callback, bindObj) {
    var res = [];
    for ( var i = 0; i < this.length; i++ ) {
        callback.apply(bindObj, [this[i], i, this]) && res.push( this[i] );
    }
    return res;
});
Function.prototype.bind = function () {
    var self = this, args = Array.from( arguments ), bindObj = args.shift();
    return function () {
        self.apply(bindObj, args.concat( Array.from( arguments ) ));
    }
};
function class_tabs (o) {
    var t = {
        init: function () {
            if ( !o ) o = {
                buttons: []
            };
            var buttons = o.buttons.filter(function (button_id) {
                     return document.getElementById( button_id );
                }),
                button_ids = [];
            this.buttons = buttons.map(function (button) {
                button_ids[ button_ids.length ] = button;
                return document.getElementById( button );
            });
            this.button_ids = button_ids;
            this.active_button = this.buttons[0];
            this.callback = o.callback;
            this.equal_callback = o.equal_callback;
            this.init_callback = o.init_callback || {};
            this.dispatch({});
            return this;
        },
        switcher: function (a) {
            if ( !this.equal_callback && ( a == this.active_button ) ) return;
            if ( this.equal_callback  && ( a == this.active_button ) ) return this.equal_callback(this.active_button);
            jQuery(this.active_button).removeClass('active');
            jQuery(a).addClass('active');
            this.callback(this.active_button, a);
            this.active_button = a;
        },
        dispatch: function (o) {
            var h = o.handler || 'click', self = this;
            this.buttons.forEach(function (button) {
                jQuery(button).bind(h, function () {
                    if ( self.init_callback && self.init_callback[button.id] ) {
                        self.init_callback[ button.id ](button);
                        self.init_callback[ button.id ] = null;
                    }
                    self.switcher(button);
                });
            });
        }
    };
    return t.init();
}

