﻿$('document').ready(function () {
    $("a[href='#']").attr("href", "javascript:void(0)");
    $('img.checkcode').attr({ src: '/CheckCode/' + parseInt(Math.random() * 10000), title: '点击可更换验证码', alt: '验证码图片' });
    $('img.checkcode').click(function () { $(this).attr('src', '/CheckCode/' + parseInt(Math.random() * 10000)); });
    $('#liulan').click(function () {
        var finder = new CKFinder('/Static/ckfinder/', 500, 500, SetFileField);
        finder.DisableThumbnailSelection = true;
        finder.Popup();
    });
    $('img.shijiantu').attr('src', '/Static/My97DatePicker/skin/datePicker.gif');
    $(".date").click(function () { WdatePicker({ isShowClear: false, readOnly: true, minDate: '%y-%M-{%d}' }); });
    $(".date1").click(function () { WdatePicker({ isShowClear: false, readOnly: true, minDate: '%y-%M-{%d+1}' }); });
    $(".datetime").click(function () { WdatePicker({ startDate: '1980-05-01', dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, readOnly: true }); });
    //表格hover样式
    $('#myTabs table[id!="m"] tr').hover(
        function () {
            $(this).attr('class', 'hover');
        },
        function () {
            $(this).attr('class', '');
        });



    $(".delete").each(function () { $(this).attr("id", (parseInt(Math.random() * 10000)).toString()); });

    DeleteFunction();
});
//弹出提示框
//function alert(content) {
//    $.dialog({
//        window: 'top',
//        content: content,
//        icon: 'succeed',
//        yesFn: function () {
//            this.close();
//            $('img.checkcode').attr({ src: '/CheckCode/' + parseInt(Math.random() * 10000), title: '点击可更换验证码', alt: '验证码图片' });
//            return false;
//        }
//    });
//}
//QQ
function QQ(ele, qq) {
    $(ele).attr("src", "http://wpa.qq.com/msgrd?V=1&Uin=" + qq + "&Site=chinakoc.com&Menu=no");
}
//导航状态
function daohang(array, ccss, defaultid) {

    //导航状态
    var url = window.location.toString();
    var isshou = true;
    jQuery(array).each(function () {
        var curl = jQuery(this).attr('href').toString();
        if (url == curl || url.indexOf(curl) != -1 && curl.indexOf("http://") == -1) {
            jQuery(this).attr('class', ccss);
            isshou = false;
        }
    });
    if (defaultid != null) {
        if (isshou) {
            jQuery(defaultid).attr('class', 'ahover');
        }
    }
}
//加载商品详情的Tab
function tabload(goodsid, status, page) {

    if (page == null || page == '')
    { page = 1; }
    var path = "/Goods/GoodsTab/" + goodsid + "?status=" + status + "&time=" + Math.random().toString() + "&page=" + page;
    loadHtml(path, '#rongqi');
}
//首页搜索
function checkaction(v) {
    //    if ($('#keywords').val() == '请输入关键词' || $('#keywords').val() == "")
    //    { alert('请输入关键词！'); }
    //    else {
    if (v == 0) {
        window.location = "/goods/list?keywords=" + encodeURI($('#keywords').val());
    }
    else {
        window.location = "/Dian/List?keywords=" + encodeURI($('#keywords').val());
    }
    //    }
}
//计算时间差
function DateDiff(sDate1, sDate2) {
    //sDate1和sDate2是年-月-日格式 
    var arrDate, objDate1, objDate2, intDays;
    arrDate = sDate1.split("-");
    objDate1 = new Date(arrDate[1] + '-' + arrDate[2] + '-' + arrDate[0]); //转换为月-日-年格式 
    arrDate = sDate2.split("-");
    objDate2 = new Date(arrDate[1] + '-' + arrDate[2] + '-' + arrDate[0]);
    intDays = parseInt(Math.abs(objDate1 - objDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数 
    return intDays;
} 
//上传图片
function SetFileField(fileUrl) {
    var smallico = fileUrl.replace("/images/", "/_thumbs/Images/");
    $('#liulan').prev().val(fileUrl);
    $('#SmallIco').val(smallico);
    $('#liulan').prevAll('img').remove();
    $('#liulan').prev().before("<img style='float:left;height:150px;'  src='" + fileUrl + "' /><br />");
}
//上传图片
function SetFileField1(fileUrl) {
    $('#liulan1').prev().val(fileUrl);
    $('#liulan1').prevAll('img').remove();
    $('#liulan1').prev().before("<img style='float:left;height:150px;'  src='" + fileUrl + "' /><br />");
}
//使第一个文本框获得焦点
function setAutoFocus(parent) {
    parent = parent || '';
    var selector = parent + ' :input:visible:enabled';
    $(selector).eq(0).focus();
}
//设置回车位Tab
function setEnterToTab(parent, buttons) {
    //    parent = parent || '';
    //    var selector = parent + ' :input:visible:enabled';
    //    buttons = buttons || 1;

    //    $(selector).keydown(function (e) {
    //        e = e || window.event;
    //        key = e.which || e.keyCode;
    //        if (key == 13) {
    //            var ts = this; var fdts = false; var fd = false; var els = $(selector);
    //            els.each(function (i) {
    //                if (fdts && i < els.length - buttons) {
    //                    $(this).focus(); fd = true;
    //                    return false;
    //                }
    //                if (this == ts) { fdts = true; }
    //            });
    //            if (fd) { return false; }
    //        }
    //    });
}
//获得焦点是选中内容
function setSelectOnFocus() {
    $(':text:enabled,:password:enabled,textarea:enabled').focus(function () {
        this.select();
    });
}
//清除回车
function clearEnterToTab(parent) {
    parent = parent || '';
    var selector = parent + ' :input:visible:enabled';
    $(selector).unbind('keydown');
}
//设置不可用
function setDisable(wstr) {
    $(wstr).attr('disabled', 'disabled');
}
//设置可用
function setEnable(wstr) {
    $(wstr).attr('disabled', '');
}
//跳到第一个字段
function setFirstErrorField(json) {

    for (var i in json.Rules) {
        if (json.Rules[0].Field) {
            $('#CheckCode').val('');
            $('#' + json.Rules[i].Field).focus();
            $('#' + json.Rules[i].Field).css("background-color", "#FFFFCC");
            break;
        }
    }
}
//自定义的提交函数
function ajaxSubmit(url, params, success, beforeSend, error, complete, type) {
    if (type == null || type == "")
    { type = 'POST'; }
    if (complete == null || complete == "") {
        complete = function () {
            loaded();
        };
    }
    if (error == null || error == "") {
        error = function () {
            alert('服务器无响应');
            loaded();
        };
    }
    $.ajax({
        async: true,
        cache: false,
        url: url,
        beforeSend: beforeSend,
        complete: complete,
        type: type,
        data: params,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        datatype: 'json',
        error: error,
//      timeout: 10000,
        success: success
    });
}
function ajaxSubmitForm() {
    $('form').submit(function () {
        $("form").ajaxSubmit({
            dataType: 'json',
            success: function (json) {
                if (json.Success) {
                    processMessage('操作成功.');
                }
                else {
                    processJson('操作失败', json);
                }
            },
            //            timeout: 60000,
            error: function () {
                alert('服务器未响应');
            }
        });
        return false;
    });
}
//带验证的Ajax提交函数
function ValidAjaxSubmit(successfun, tip, formid) {
    if (tip == null || tip == "")
    { tip = true; }
    if (formid == null || formid == "")
    { formid = "demo"; }
    $.formValidator.initConfig({ autotip: tip, formid: formid, onerror: function (msg) { alert(msg) }, onsuccess: successfun });
}

//给某个容器加载网页
function loadHtml(path, box) {
    $.ajax({
        cach: true,
        type: 'post',
        url: path,
        contentType: "application/x-www-form-urlencoded; charset=gb2312",
        data: {},
        datatype: 'html',
        beforeSend: function () {
            $(box).html("<center><img src='/Static/Style/Site/images/usercommon/loading.gif'></center>");
        },
        success: function (ms) {
            $(box).html(ms);
        }
    });
}
//对输入的文本进行转码
function htmlEncode(s) {
    s = s + '';
    var rs = '';
    rs = s.replace(/&/g, '&amp;');
    rs = rs.replace(/</g, '&lt;');
    rs = rs.replace(/>/g, '&gt;');
    rs = rs.replace(/"/g, '&quot;');
    rs = rs.replace(/'/g, '&#39;');
    return rs;
}
//解码
function htmlDecode(s) {
    s = s + '';
    var rs = '';
    rs = s.replace(/&amp;/g, '&');
    rs = rs.replace(/&lt;</g, '<');
    rs = rs.replace(/&gt;/g, '>');
    rs = rs.replace(/&quot;/g, '"');
    rs = rs.replace(/&#39;/g, "'");
    return rs;
}
//后台编辑器
function myxheditor(id, width, height) {
    $('#' + id).xheditor(
            {
                tools: "Source,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Align,List,Outdent,Indent,Link,Table,Img,Emot,Fullscreen",
                width: width,
                height: height,
                forcePtag: false,
                emots: { qq: { name: 'QQ', count: 55, width: 25, height: 25, line: 11 }, msn: { name: 'MSN', count: 40, width: 22, height: 22, line: 8} },
                upLinkUrl: '!{editorRoot}UploadGui.aspx',
                upImgUrl: '!{editorRoot}UploadGui.aspx',
                upFlashUrl: '!{editorRoot}UploadGui.aspx',
                upMediaUrl: '!{editorRoot}UploadGui.aspx',
                modalWidth: 1002,
                modalHeight: 600,
                upBtnText: '浏览',
                skin: "default",
                About: false
            });
}
//前台编辑器
function userxheditor(id, width, height) {
    $('#' + id).xheditor(
            {
                tools: "Source,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Align,List,Outdent,Indent,Link,Table,Img,Emot,Fullscreen",
                width: width,
                height: height,
                forcePtag: false,
                emots: { qq: { name: 'QQ', count: 55, width: 25, height: 25, line: 11 }, msn: { name: 'MSN', count: 40, width: 22, height: 22, line: 8} },
                upLinkUrl: '!{editorRoot}UploadGui.aspx',
                upImgUrl: '!{editorRoot}UploadGui.aspx',
                upFlashUrl: '!{editorRoot}UploadGui.aspx',
                upMediaUrl: '!{editorRoot}UploadGui.aspx',
                modalWidth: 1002,
                modalHeight: 600,
                upBtnText: '浏览',
                skin: "default"
            });
}

//消息框显示
function UnReadShow(ele, s) {
    $.dialog({ content: s, follow: $(ele).attr("id"), title: $(ele).text() });
    //    var h = ($(window).height() - $('#Info').height()) / 2;
    //    var w = ($(window).width() - $('#Info').width()) / 2;
    //    $('#Info').css('top', h);
    //    $('#Info').css('left', w);
    //    $('#Info p').html(s);
    //    $('#Info').show();
}
//function InfoHidden() {
//    $('#Info').hide();
//}


//删除功能
function DeleteFunction() {
    $('.delete').click(function () {
        $(this).blur();
        var url = $(this).attr('href');
        var tr = $(this).parent().parent();
        var id = $(this).attr('id');
        if ($(tr).attr("id") == "sli_c_r_t") {
            tr = $(tr).parent().parent();
        }
        $.dialog({
            follow: id,
            icon: 'confirm',
            content: '您确定要删除吗?',
            yesFn: function () {
                ajaxSubmit(url,
                            {},
                            function (json) {
                                if (json.Success) {
                                    tr.remove();
                                    processMessage('删除成功');
                                }
                                else {
                                    processJson('删除失败:', json);
                                }
                            });
            },
            noFn: true
        });
        return false;
    });
}

//列表的多选框
function CheckAll(urlstr) {
    $("#all").click(function () {
        if ($("#all").attr("checked")) {
            $("input[id='Checkbox1']").each(function () {
                $(this).attr("checked", true);
            });
        }
        else {
            $("input[id='Checkbox1']").each(function () {
                $(this).attr("checked", false);
            });
        }
    });
    $(".checkall").click(function () {
        if ($(".checkall").attr("value") == "全 选") {
            $(".checkall").attr("value", "取消全选")
            $("input[id='Checkbox1']").each(function () {
                $(this).attr("checked", true);
            });
        }
        else {
            $(".checkall").attr("value", "全 选")
            $("input[id='Checkbox1']").each(function () {
                $(this).attr("checked", false);
            });
        }
    });
    $(".fancheck").click(function () {
        $("[id='Checkbox1']").each(function () {
            if ($(this).attr("checked")) {
                $(this).removeAttr("checked");
            }
            else {
                $(this).attr("checked", 'true');
            }
        })
    });
    $(".deleteall").click(
    function () {
        if (confirm('您确定要删除吗')) {
            $("[id='Checkbox1'][checked]").each(
            function () {
                var tr = $(this).parent().parent();
                ajaxSubmit(urlstr + $(this).next().val(), {}, function (json) { if (json.Success) { tr.remove(); } });
            });
        }
        processMessage('删除成功');
    });


}
//所有热门推荐的效果
function Show(ele) {
    $(ele).parent().find(".li_rb_tb2").hide();
    $(ele).parent().find(".li_rb_tb1").show();
    $(ele).hide();
    $(ele).prev().show();
}


//弹出框提示
function processJson(title, json) {
    var estr = title + '<br/>';
    $("input[type='text'],textarea,select").css("background-color", "#FFF");
    for (var i in json.Rules) {
        estr += parseInt(i) + 1 + '.' + json.Rules[i].Comment;
        if (i < json.Rules.length - 1) {
            estr += '\t';
        }
        if ((i + 1) % 3 == 0) {
            estr += '\n';
        }
        if (json.Rules[i].Field) {
            $('#' + json.Rules[i].Field).css("background-color", "#FFFFCC");
        }
    }
    if (json.Data) {
        estr += '<br/>错误信息: ' + json.Data;
    }
    //    $('body').append('<div id="msgbg"></div>');
    //    $('#msgbg').css('top', document.documentElement.scrollTop);
    //    $('#msgbg').css('left', document.documentElement.scrollLeft);
    //    alert(estr);
    //    $('#msgbg').remove();
    $.dialog.alert(estr);
    $('img.checkcode').attr({ src: '/CheckCode/' + parseInt(Math.random() * 10000), title: '点击可更换验证码', alt: '验证码图片' });
}
//弹出层提示
function processMessage(msg, title, href) {
    if (title)
        msg = title + '\n\n' + msg;
    //    $('body').append('<div id="msg"><p>' + msg + '</p></div>');
    //    $('#msg').css('marginTop', -31 + document.documentElement.scrollTop);
    //    $('#msg').css('marginLeft', -131 + document.documentElement.scrollLeft);
    //    $('#msg').fadeOut(2000, function () {
    //        $('#msg').remove();

    //    }); 
    $.dialog.tips(msg, 2);
    $('img.checkcode').attr({ src: '/CheckCode/' + parseInt(Math.random() * 10000), title: '点击可更换验证码', alt: '验证码图片' });
    if (href != null) { window.location = href; }
}
//加载
function loading(title) {
    if (!title) {
        title = '正在执行查询, 请稍候...';
    }
    $('body').append('<div id="loading"><p>' + title + '</p></div>');
    $('#loading').css('marginTop', -51 + document.documentElement.scrollTop);
    $('#loading').css('marginLeft', -131 + document.documentElement.scrollLeft);
}
//关闭加载
function loaded() {
    $('#loading').remove();
}
//我要下订单
function pageshow(hid, jid,title) {
    $.dialog.open('/xiang?hid=' + hid + "&jid=" + jid, {
        title: title,
        fixed: true,
        lock: true,
        width: '775px',
        height: '500px'
    });
}

//设为首页
function SetHome() {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage(document.URL);
    } else if (window.sidebar) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {//火狐浏览器
                alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config, 然后将项 signed.applets.codebase_principal_support 值该为true");
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', document.URL);
    }
}
//添加到收藏夹
function AddFavorite(title, url1) {
    var url = window.location.href;
    if (url1 != null || url1 != "")
    { url = url1 }
    try {
        window.external.addFavorite(url, title);
    }
    catch (e) {
        try {
            window.external.addFavorite(window.location.href, title);
        }
        catch (e) {
            alert("加入收藏失败，请使用Ctrl+D进行添加");
        }
    }
}

//图片加载
function LazyLoad(img) {
    $(img).lazyload({
        placeholder: "/Static/Style/Site/images/load.gif",
        effect: "fadeIn",
        failurelimit: 10,
        threshold: 200
    });
}

