/*
 * 项目：中国机床商务网
 * 
 * 开发：乘风破浪
 * 联系：QQ 1218 66618
 */

//window.SITE_URL = 'http://www.xoocoo.com/';
window.SITE_URL = '/';
//window.SITE_URL = 'http://192.168.1.189/';
$(function() {

    img_url2src(); // 显示当前窗口的图片
    $(window).bind("scroll", img_url2src); // 滚动触发显示图片
});

//验证码
function change_captcha(o) {
    var codefile = SITE_URL + 'user/other/checkcode.php';
    $(o).html('<img src="' + codefile + '?t=' + Math.random() + '" title="点击刷新验证码" onClick="this.src=\'' + codefile + '?t=' + Math.random() + '\'" style="cursor:pointer;">');
}

//
function popupmsg(msg, url) {
    popup({
        content: '<div style="height:50px;margin:30px auto auto 20px;">' + msg + '</div>',
        title: '提示',
        of_top: 260,
        of_left: 150,
        black_bg: 'no'
    });
    setTimeout(function() {
        close_popup();
        (url == 'back') ? history.back() : window.location = url;
    }, 1500);

}
//显示填写注册信息
function register() {
    popup({
        url: SITE_URL + 'user/auth/user.php?action=ajax_show_reg&t=' + Math.random(),
        title: '快速注册'
    });
}
//登录
function login() {
    popup({
        url: SITE_URL + 'user/auth/user.php?action=ajax_show_login',
        title: '登录'
    });
}
//忘记密码
function forgotPassword() {
    popup({
        url: SITE_URL + 'user/other/email.php?action=forgot',
        title: '找回密码'
    });
}
//退出
function logout() {
    if (!confirm('确认要退出？')) return;
    $.post(SITE_URL + 'user/auth/user.php?action=ajax_logout&t=' + Math.random(), {},
        function(data) {
            if (!data) return;
            if (data.status == 'ok') {
                //update_login_status();
                window.location = SITE_URL + 'user/login.php';
            } else {
                alert('退出错误，请稍候重试。');
            }
        }, 'json');
}
//更新登录状态
function update_login_status(u) {
    //var username = $.cookie('username');
    var username = u || '';
    if (username) {
        $('#head_login').hide();
        $('#head_loggedin').show().find('tt').html(username);
    } else {
        $('#head_loggedin').hide();
        $('#head_login').show();
    }
}
//=============用户登录 开始=============
//用户登录
function loginSubmit(type) {
    if (type) {
        //login.php 登录
        var idu = 'login_username';
        var idp = 'login_password';
        var idc = 'login_captcha';
        var idw = 'login_captcha_wrapper';
        var ids = 'login_captcha_show';
        var ida = 'login_auto';
    } else {
        //popup 登录
        var idu = 'ajax_login_username';
        var idp = 'ajax_login_password';
        var idc = 'ajax_login_captcha';
        var idw = 'ajax_login_captcha_wrapper';
        var ids = 'ajax_login_captcha_show';
        var ida = 'ajax_login_auto';
    }
    var captcha = $('#' + idc);
    var data = {
        username: $('#' + idu).val(),
        password: $('#' + idp).val(),
        captcha: captcha.val(),
        login_auto: $('#' + ida).val()
    };
    if (data.username.length == '') {
        show_tips_right_red('请输入用户名', idu);
        return;
    }
    if (data.password.length == '') {
        show_tips_right_red('请输入密码', idp);
        return;
    }
    if ($('#' + idw).css('display') != 'none' && data.captcha == '') {
        show_tips_right_red('请填写验证码，如果验证码不显示，请更换验证码', ids);
        captcha.focus();
        return;
    }
    close_all_tips();
    show_popup_loading();
    $.post(SITE_URL + 'user/auth/user.php?action=ajax_login', data, function(data) {
        hide_popup_loading();
        if (!data) return;
        if (data.status == 'ok') {
            popup({
                title: '登录成功',
                content: data.msg
            });
            update_login_status(data.rs['username']);
            setTimeout(function() {
                close_popup();
                window.parent.location = SITE_URL + 'user/';
            }, 500);
        } else {
            if (data.tried > 3) {
                $('#' + idw).show(); //尝试3次登录后，显示验证码
                var callback = function() {
                    if (data.type == 'captcha') {
                        show_tips_right_red(data.msg, ids);
                        captcha.focus();
                    } else if (data.type == 'password') {
                        show_tips_right_red(data.msg, idp);
                    } else {
                        show_tips_right_red(data.msg, idu);
                    }
                    captcha.val('');
                    change_captcha(document.getElementById(ids));
                };
                //显示验证码后，html内容改变，重新计算popup高度
                (document.getElementById('popup')) ? popup_resize({}, callback) : callback();
            } else {
                (data.type == 'password') ? show_tips_right_red(data.msg, idp) : show_tips_right_red(data.msg, idu);
            }
        }
    }, 'json');
}
//=============用户登录 结束=============
//购物车
function goodsbag_show(kid) {
    popup({
        url: SITE_URL + 'goods/goodsbag.php?action=ajax_goodsbag_show&kid=' + kid + '&t=' + Math.random(),
        title: '购物车'
    });
}
//============================================================================================
function up_file_show(of, m) {
    popup({
        url: SITE_URL + 'user/other/upshow.php?model=' + m,
        title: '选择文件',
        //black_bg: 'no',
        offset_id: of
    });
}
//onload="javascript:if(this.width>' + w + '){this.height=this.height*' + w + '/this.width;this.width=' + w + ';
function img_maxWH(o, w, h) {
    if (w > 0) {
        if (o.width > w) {
            o.height = o.height * w / o.width;
            o.width = w;
        }
    } else {
        if (o.height > h) {
            o.width = o.width * h / o.height;
            o.height = h;
        }
    }
}
function up_file_callback(json_code) {
    var data = window['eval']('(' + json_code + ')');
    var status = data[0].status;
    var file_url = data[0].file_url;
    var msg = data[0].msg;
    var CKEditor = data[0].CKEditor;
    var CKEditorFuncNum = data[0].CKEditorFuncNum;

    if (CKEditor) {
        CKEDITOR.tools.callFunction(CKEditorFuncNum, file_url, msg);
    } else {
        if (status == 'ok') {
            up_file_ok(file_url);
            close_popup();

            /*			var img = '<img src="' + file_url + '" onload="img_maxWH(this, 260)" onClick="javascript:window.open(this.src);" style="cursor:pointer;"/>';
             post_file_txt('图片已上传，请关闭此窗口：<br/>' + img);
             document.getElementById('upload_button').disabled = 'disabled';*/
        } else {
            alert(msg);
        }
    }
}
function up_thumb_show(of, tof, m, o) {
    o = $('#' + o);
    if (!o.val()) {
        show_tips_top_red('请先选择图片', tof);
        return false;
    }

    var url = SITE_URL + 'user/other/thumbshow.php?model=' + m + '&pic_url=' + o.val() + '&' + Math.random();
    var title = '缩略图';
    popup({url: url, title: title, offset_id: of});
}
function up_thumb_callback(json_code) {
    var data = eval(json_code);
    var status = data[0].status;
    var thumburl = data[0].thumburl;
    var msg = data[0].msg;

    if (status == 'ok') {
        up_thumb_ok(thumburl);
        close_popup();
    } else {
        alert(msg);
    }
}
function choose_file_callback(file_url) {
    up_file_ok(file_url);
    close_popup();
}
/* ckeditor打开某个对话框
 * 如 图片： onclick="ckExecuteCommand('image');"
 * 如 连接、附件： onclick="ckExecuteCommand('link');"
 */
function ckExecuteCommand(commandName) {
    var oEditor = CKEDITOR.instances.editor1; // 设置编辑id：editor1
    //检查是否是设计模式
    (oEditor.mode == 'wysiwyg') ? oEditor.execCommand(commandName) : alert('请先把编辑器转为设计模式。');
}
// 向ckeditor内插入代码
function ckInsertHTML(value) {
    var oEditor = CKEDITOR.instances.editor1; // 设置编辑id：editor1
    (oEditor.mode == 'wysiwyg') ? oEditor.insertHtml(value) : alert('请先把编辑器转为设计模式。');
}
//============================================================================================
/**
 * 图片延迟加载之随滚动条显示
 * 举例：html代码：<img src="1像素白色.gif" url="imgsrc.gif"/>
 *      js代码：$(function(){img_url2src(); $(window).bind("scroll", img_url2src);})
 */
function img_url2src() {
    var scrollTop = $(document).scrollTop();
    var height = $(window).height();
    $('img[url]').each(function() {
        var _this = $(this);
        _this.attr('src', SITE_URL + 'static/image/comman/space.gif');
        var top = _this.offset().top;
        // 图片在屏幕下 && 在上
        if (top < scrollTop + height && top + 50 > scrollTop) {
            _this
                .attr('src', _this.attr('url'))
                .removeAttr('url')
                .css('opacity', 0).fadeTo(300, 1);
        }
    });
}

/**
 * 窗口平滑滚动到某位置
 * 参数：id
 * if(!window.animate_scroll_do){animate_scroll(_this);}
 * window.animate_scroll_do = false;
 */
function animate_scroll(id) {
    var o = typeof(id) == 'object' ? id : $('#' + id);
    var top = parseInt(o.offset().top);
    // must_scroll 数值（必须下拉滚动条n值后，才滚动）
    //if (must_scroll && $(document).scrollTop() < must_scroll) return;

    var dc; //判断是否有DOCTYPE声明
    if (typeof(document.compatMode) != 'undefined' && document.compatMode != 'BackCompat') {
        dc = document.documentElement;
    } else if (typeof document.body != 'undefined') {
        dc = document.body;
    }
    $(dc).animate({scrollTop:top - 20}, 500);
    //window.animate_scroll_do = true;
}

//=============popup 开始=============
/**
 * 版本：CFPL popup 1.0
 * 参数：data.title                  标题
 *      (data.url || data.content)  内容，popup根据输入内容自动调整宽高。
 *                                  如：<div style="width:350px">内容内容内容</div>
 *      data.black_bg               不显示灰色背景 == 'no'， 默认yes
 *      data.offset_id              相对位置 不设定则位于正中 或定义data.of_top data.of_left
 * 框架：jquery-1.4.2 以上
 * 作者：乘风破浪 QQ：121866618
 * 日期：2010-12-15
 */
function popup(data) {
    close_all_tips();
    hide_selects();
    if (!data.title) data.title = '提示';

    var pageWidth = $(document).width();
    var pageHeight = $(document).height();
    var windowWidth = $(window).width();
    var windowHeight = $(window.parent).height();
    var scrollTop = $(window.parent).scrollTop();

    //插入背景
    if (data.black_bg != 'no' && !document.getElementById('popup_bg')) {
        $('<div id="popup_bg"></div>')
            .css({
                position: 'absolute',
                zIndex: 100000,
                top: 0,
                left: 0,
                width: pageWidth,
                height: pageHeight,
                opacity: 0
            })
            .appendTo(document.body)
            .fadeTo(300, 0.2); //.click(close_popup)
    }
    //默认值，会根据输入内容的尺寸，自动调整。
    data.width = window.popup_last_width || 250;
    data.height = window.popup_last_height || 150;
    if (data.offset_id) {
        var o = typeof(data.offset_id) == 'object' ? $(data.offset_id) : $('#' + data.offset_id);
        //typeof："number"、"string"、"boolean"、"object"、"function"、"undefined"
        data.of_top = parseInt(o.offset().top);
        data.of_left = parseInt(o.offset().left);
    }

    data.top = data.of_top || parseInt(scrollTop + (windowHeight - data.height) / 2);
    data.left = data.of_left || parseInt((windowWidth - data.width) / 2);

    //插入popup
    $('#popup').remove();
    $('<div id="popup"></div>')
        .css({
            position: 'absolute',
            zIndex: 100001,
            top: data.top,
            left: data.left,
            width: data.width,
            height: data.height,
            overflow: 'hidden'
        })
        .html('<div id="popup_top"><span id="popup_top_title">' + data.title + '</span><a id="popup_top_close" href="javascript:close_popup();"></a></div><div id="popup_content"></div>')
        .appendTo(document.body);
    show_popup_loading();
    //插入内容
    var inner_content = function(content) {
        hide_popup_loading();
        $('#popup_content')
            .html(content)
            .css({overflow: 'hidden', opacity: 0})
            .fadeTo(300, 1);
        //popup_resize(data); //自动适应宽高
        setTimeout(function() {
            popup_resize(data); //自动适应宽高
        }, 100);
        if (document.getElementById('imgareaselect_box')) {
            move_div('#popup_top', ['#popup', '.tips_box', '#selection_box', '.imgareaselect-outer']);
        } else {
            move_div('#popup_top', ['#popup', '.tips_box']);
        }
    };
    //输入内容的两种方法
    if (data.url) {
        $.get(data.url, {}, inner_content);
    } else if (data.content) {
        inner_content(data.content);
    }
}
// 计算新的位置
function popup_resize(data, callback) {
    var windowWidth = $(window).width();
    var windowHeight = $(window.parent).height();
    var scrollTop = $(window.parent).scrollTop();
    //新的宽度等
    var popup_content = $('#popup_content');
    var width = popup_content.get(0).scrollWidth;
    var height = popup_content.get(0).scrollHeight;
    popup_content.css({
        width: width,
        height: height
    });
    //把标题的高度加上
    height = height + 34;
    var top = data.of_top || parseInt(scrollTop + (windowHeight - height) / 2);
    var left = data.of_left || parseInt((windowWidth - width) / 2);
    window.popup_last_width = width;
    window.popup_last_height = height;
    //动画到新的大小
    $('#popup').animate({
        top: top,
        left: left,
        width: width,
        height: height
    }, 300, callback);
}
// 关闭popup
function close_popup() {
    close_all_tips();
    $('#popup_bg').remove();
    var popup = $('#popup');
    popup.animate({height: 0}, 300, function() {
        popup.remove();
    });
    show_selects();

    if (document.getElementById('selection_box')) {
        $('.imgareaselect-outer').remove();
        $('#selection_box').remove();
    }
}
//-------------loading-------------
// 显示loading
function show_popup_loading() {
    if (!document.getElementById('popup_loading')) {
        var width = 75;
        var height = 75;

        if (document.getElementById('popup')) { //防止在iframe下错位
            var p = $('#popup');
            var top = parseInt((p.height() - height + 27) / 2 + p.offset().top);
            var left = parseInt((p.width() - width) / 2 + p.offset().left);
        } else {
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            var scrollTop = $(window).scrollTop();
            var top = parseInt((windowHeight - height) / 2 + scrollTop);
            var left = parseInt((windowWidth - width) / 2);
        }

        $('<div id="popup_loading"></div>')
            .css({
                position: 'absolute',
                zIndex: 100003,
                top: top,
                left: left,
                width: width,
                height: height
            })
            .appendTo(document.body);
    }
}
function hide_popup_loading() {
    $('#popup_loading').remove();
}
//-------------下拉列表-------------
function hide_selects() {
    $('select').hide();
}
function show_selects() {
    $('select').show();
}
//=============popup 结束=============

//=============move_div拖曳层 开始=============
/**拖曳多个层
 * 版本：CFPL move div 1.1
 * 参数：clickid    点击按下的html元素
 *      moveid     要移动的层，输入Array，如： ['#popup'] 或 ['#popup', '.tips_box']
 * 举例：move_div('#popup_title', ['#popup', '.tips_box']);
 * 框架：jquery-1.4.2 以上
 * 作者：乘风破浪 QQ：121866618
 * 日期：2010-12-31
 */
function move_div(clickid, moveid) {
    window.moveid_mouse_x = [];
    window.moveid_mouse_y = [];
    window.moveid_opacity = [];

    $(clickid)
        .mousedown(function(e) {
            window.move_div_moving = true; //全局变量
            for (var i in moveid) {
                window.moveid_mouse_x[i] = [];
                window.moveid_mouse_y[i] = [];
                var mi = $(moveid[i]);
                var opacity_i = mi.css('opacity') || 1;
                window.moveid_opacity[i] = opacity_i - 0.2;
                mi.css('opacity', opacity_i - 0.2); //减少 透明度
                for (var j = 0; j < mi.length; j++) { // 对'.class' '#id'拆分
                    window.moveid_mouse_x[i][j] = e.clientX - parseInt(mi.eq(j).css('left'));
                    window.moveid_mouse_y[i][j] = e.clientY - parseInt(mi.eq(j).css('top'));
                    //每个被移动对象的左上角为原点，鼠标的坐标
                }
            }
        })
        .mouseup(function() {
            window.move_div_moving = false;
            for (var i in moveid) {
                $(moveid[i]).css('opacity', window.moveid_opacity[i] + 0.2); //还原 透明度
            }
        });
    //监视鼠标移动区域为document
    $(document).mousemove(function(e) {
        if (!window.move_div_moving) return;
        for (var i in moveid) {
            var mi = $(moveid[i]);
            for (var j = 0; j < mi.length; j++) {
                mi.eq(j).css('left', e.clientX - window.moveid_mouse_x[i][j]);
                mi.eq(j).css('top', e.clientY - window.moveid_mouse_y[i][j]);
//				// popup始终在屏幕
//				var j_left = e.clientX - window.moveid_mouse_x[i][j];
//				var j_top = e.clientY - window.moveid_mouse_y[i][j];
//				j_left = Math.min(Math.max(j_left, 0), windowWidth - popupWidth)
//				j_top = Math.min(Math.max(j_top, 0), windowHeight - popupHeight)
//                mi.eq(j).css('left', j_left);
//                mi.eq(j).css('top', j_top);
            }
        }
    });
}
//=============move_div移动层 结束=============

//=============show_tips 开始=============

function show_tips_right_blue(msg, oid) {
    show_tips({content: msg, id: oid, offset_id: oid, direction: 'right', type: ''});
}
function show_tips_right_red(msg, oid) {
    show_tips({content: msg, id: oid, offset_id: oid, direction: 'right', type: 'red'});
}
function show_tips_right_green_ok(oid) {
    show_tips({content: '完成', id: oid, offset_id: oid, direction: 'right', type: 'green', width: 70});
}
function show_tips_top_red(msg, oid) {
    show_tips({content: msg, id: oid, offset_id: oid, direction: 'top', type: 'red', close_time: 5000});
}
function show_tips_top_green(msg, oid) {
    show_tips({content: msg, id: oid, offset_id: oid, direction: 'top', type: 'green'});
}
/**
 * 版本：CFPL tips 1.0
 * 参数：(data.url || data.content) (必填)内容
 *      data.offset_id             (必填)相对偏移id 如'id_name' 、 $('#id_name') 、 this
 *      data.id                    tips的id标识
 *      data.type                  红绿蓝三种样式 red | green | default
 *      data.direction             位置 left | right | top | top_right | bottom | bottom_right
 *      data.show_close            显示关闭按钮 true | false默认
 *      data.close_time            自动关闭时间
 *      data.show_ico              显示小图标 true默认 | false
 *      data.width                 宽(强制尺寸，不定义则根据输入内容自动调整[可自定义内容尺寸])
 *      data.height                高
 * 框架：jquery-1.4.2 以上
 * 作者：乘风破浪 QQ：121866618
 * 日期：2010-12-17
 */
function close_one_tips(id) {
    $('#' + id + '_tipsbox').remove();
}
function close_all_tips() {
    $('.tips_box').remove();
}
function show_tips(data) {
    if (typeof(data.id) != 'string') data.id = 'temp';
    var id = data.id + '_tipsbox';
    $('#' + id).remove();

    var inner_tips = function(content) {
        var width = 200;
        var height = 25;
        var thistips = $('<div id="' + id + '" class="tips_box"></div>');
        thistips.css({
            position: 'absolute',
            zIndex: 100002,
            display: 'none',
            width: width,
            height: height
        }).appendTo(document.body).fadeIn(300);
        //插入内容 //appendTo('#' + id)appendTo($('#' + id))
        var thistips_content = $('<div id="' + id + '_content" class="tips_content"></div>').html(content).appendTo(thistips);
        //自动调整大小
        var width_c = thistips_content.get(0).scrollWidth;
        var height_c = thistips_content.get(0).scrollHeight;
        width = data.width || (width_c > width ? width_c : width);
        height = data.height || (height_c > height ? height_c + 5 : height);

        var a, b;
        switch (data.type) {
            case 'red':
                a = 0;
                break;
            case 'green':
                a = 1;
                break;
            default:
                a = 2;
                break;
        }
        switch (data.direction) {
            case 'top':
                b = 0;
                break;
            case 'top_right':
                b = 1;
                break;
            case 'bottom':
                b = 2;
                break;
            case 'bottom_right':
                b = 3;
                break;
            case 'left':
                b = 4;
                break;
            default:
                b = 5;
                break;
        }
        //tipsbox
        var id_css = [
            {border: '1px solid #F5ABA9', background: '#F5E0E0', color: '#DB4141'},
            {border: '1px solid #a2d955', background: '#e3ffe1', color: '#1f8418'},
            {border: '1px solid #58dddb', background: '#d5ffff', color: '#108280'}
        ][a];
        var o = typeof(data.offset_id) == 'object' ? $(data.offset_id) : $('#' + data.offset_id);
        var of_top = parseInt(o.offset().top);
        var of_left = parseInt(o.offset().left);
        var o_width = parseInt(o.width());
        var o_height = parseInt(o.height());
        var id_direction = [
            {top: of_top - height - 10, left: of_left},
            //偏移量 10
            {top: of_top - height - 10, left: of_left - width + o_width},
            {top: of_top + o_height + 10, left: of_left},
            {top: of_top + o_height + 10, left: of_left - width + o_width},
            {top: of_top, left: of_left - width - 20},
            //偏移量 20
            {top: of_top, left: of_left + o_width + 20}
        ][b];
        thistips.css(id_css).css(id_direction).css({ width : width, height: height});


        //箭头
        var arrow_css = {};
        arrow_css.margin = [
            height + 'px auto auto 3px',
            height + 'px auto auto ' + (width - 23) + 'px',
            '-8px auto auto 3px',
            '-8px auto auto ' + (width - 23) + 'px', //23=箭头宽18+偏移5
            '3px auto auto ' + width + 'px',
            '3px auto auto -8px'][b];
        arrow_css.backgroundPosition = [
            ['-60px -20px', '-60px -20px', '-40px -20px', '-40px -20px', '-20px -20px', '0px -20px'][b],
            ['-60px -40px', '-60px -40px', '-40px -40px', '-40px -40px', '-20px -40px', '0px -40px'][b],
            ['-60px 0px', '-60px 0px', '-40px 0px', '-40px 0px', '-20px 0px', '0px 0px'][b]][a];
        $('<div id="' + id + '_arrow" class="tips_arrow"></div>').css(arrow_css).appendTo(thistips);

        //显示小图标
        if (data.show_ico !== false) {
            var content_css = [
                {paddingLeft: '20px', backgroundPosition: '-100px -20px'},
                {paddingLeft: '20px', backgroundPosition: '-80px -40px'},
                {paddingLeft: '20px', backgroundPosition: '-120px 0px'}
            ][a];
            thistips_content.css(content_css);
        }
        //显示关闭按钮
        if (data.show_close) {
            var span = $('<span class="tips_close" title="关闭">×</span>');
            span
                .click(function() {
                thistips.remove();
            })
                .mouseover(function () {
                    span.css('fontSize', '16px');
                })
                .mouseout(
                function () {
                    span.css('fontSize', '');
                }).appendTo(thistips);
            thistips_content.css('paddingRight', '5px');
        }
        if (data.close_time) setTimeout(function() {
            thistips.remove()
        }, data.close_time);
    };
    //输入内容的两种方法
    if (data.url) {
        $.get(data.url, {}, inner_tips);
    } else if (data.content) {
        inner_tips(data.content);
    }
}
//=============show_tips 结束=============
