//日期格式化
Date.prototype.pattern = function (fmt) { var o = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, "H+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S": this.getMilliseconds() }; var week = { "0": "/u65e5", "1": "/u4e00", "2": "/u4e8c", "3": "/u4e09", "4": "/u56db", "5": "/u4e94", "6": "/u516d" }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)) } if (/(E+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]) } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))) } } return fmt }
//获取表单中的元素
var GetFormData = function (form) {
    var formData = {};
    $(form).find("input[type='text']").each(function () {
        if ($(this).attr("name").length == 0) return true;
        formData[$(this).attr("name")] = $(this).val();
    });
    $(form).find("input[type='hidden']").each(function () {
        if ($(this).attr("name").length == 0) return true;
        formData[$(this).attr("name")] = $(this).val();
    });
    return formData;
}
//关键词组件
var KeyWords = function (keyWordsJson, keyWordsHiddenName, container) {
    var parent = this;
    //关键词Json串，如果null，指定默认一行的Json串
    try {
        this.KeyWordsJson = keyWordsJson == null || keyWordsJson == undefined ? null : JSON.parse(keyWordsJson.replace(/&quot;/g, '"'));
    }
    catch (e) { this.KeyWordsJson = null; }
    if ((this.KeyWordsJson == null ? 0 : this.KeyWordsJson.length) == 0) { this.KeyWordsJson = [{ "KeyWords": "", "PutOnLimit": "", "PutOnProportion": "", "Ranking": "" }]; }
    //关键词隐藏域名称
    this.KeyWordsHiddenName = keyWordsHiddenName;
    //关键词组件所在容器
    this.Container = container;
    //console.log($(this.Container).html());
    //每个关键词组合的Html模板代码
    this.KeyWordsHtmlTmp =
        "<div>\
            <input type=\"text\" data-valid=\"KeyWords\" data-type=\"KeyWords\"  placeholder=\"关键词\" style=\"width: 50px;\" class=\"m-wrap required\" onkeyup=\"this.value=this.value.replace(/^ +| +$/g,'')\" value=\"{KeyWords}\" />\
            <input type=\"text\" data-valid=\"PutOnLimit\" data-type=\"PutOnLimit\" placeholder=\"投放量级\" style=\"width: 50px;\" class=\"m-wrap required\" onkeyup=\"this.value=this.value.replace(/^ +| +$/g,'')\" value=\"{PutOnLimit}\" />\
            <input type=\"text\" data-valid=\"PutOnProportion\" data-type=\"PutOnProportion\" placeholder=\"搜索占比\" style=\"width: 50px;\" class=\"m-wrap required\" onkeyup=\"this.value=this.value.replace(/^ +| +$/g,'')\" value=\"{PutOnProportion}\" />\
            <input type=\"text\" data-valid=\"Ranking\" data-type=\"Ranking\" placeholder=\"排名\" style=\"width: 50px;\" class=\"m-wrap required\" onkeyup=\"this.value=this.value.replace(/^ +| +$/g,'')\" value=\"{Ranking}\" />\
            <a href=\"javascript:;\" data-type=\"add\" style=\"text-decoration:none;font-weight:bold;font-size:26px;\">+</a>\
            <a href=\"javascript:;\" data-type=\"delete\" style=\"text-decoration:none;font-weight:bold;font-size:26px;\">×</a>\
            <span data-type=\"tip\" style=\"color:red\"></span>\
        </div>";
    //将关键词Json串生成控件
    this.Init = function () {
        var keyWordsHtml = "";
        $(parent.KeyWordsJson).each(function () {
            keyWordsHtml += parent.KeyWordsHtmlTmp.replace(/{KeyWords}/g, this.KeyWords).replace(/{PutOnLimit}/g, this.PutOnLimit == undefined ? this.PutOnProportion : this.PutOnLimit).replace(/{PutOnProportion}/g, this.PutOnProportion).replace(/{Ranking}/g, this.Ranking);
        });
        $(parent.Container).html(keyWordsHtml);
        $(parent.Container).find("a[data-type='delete']").eq(0).hide();
        if ($(parent.Container).attr("data-readonly") == "true") {
            $(parent.Container).find("a[data-type='delete']").hide();
            $(parent.Container).find("a[data-type='add']").hide();
            $(parent.Container).find("input[type='text']").attr("readonly", "readonly");
        }
        parent.AddHidden();
        parent.Add();
        parent.Delete();
        parent.Update();
        parent.FormSubmitValidate();
    }
    //添加隐藏域
    this.AddHidden = function () {
        if ($("input[name='" + parent.KeyWordsHiddenName + "']").size() == 0) {
            $(parent.Container).after("<input type=\"hidden\" name=\"" + parent.KeyWordsHiddenName + "\" />");
        }
        parent.UpdateKeyWordsJsonHidden();
    }
    //更新关键词Json串
    this.UpdateKeyWordsJsonHidden = function () {
        var keyWordsJsonUpdate = "[", keyWords = "", putOnLimit = "", putOnProportion = "", ranking = "";
        var success = true, message = "";
        var keyWordsList = [];
        $(parent.Container).find("input[data-type='KeyWords']").each(function () {
            keyWords = $(this).val();
            putOnProportion = $(this).parent().find("input[data-type='PutOnProportion']").val();
            putOnLimit = $(this).parent().find("input[data-type='PutOnLimit']").val();
            //if (keyWordsList.indexOf(keyWords) > -1) {
            //    success = false;
            //    message = "关键词重复,修改失败";
            //    return false;
            //}
            //keyWordsList.push(keyWords);
            ranking = $(this).parent().find("input[data-type='Ranking']").val();
            if (keyWords.length > 0 || putOnLimit.length > 0 || putOnProportion.length > 0 || ranking.length > 0) {
                keyWordsJsonUpdate += "{\"KeyWords\":\"" + keyWords + "\",\"PutOnLimit\":\"" + putOnLimit + "\",\"PutOnProportion\":\"" + putOnProportion + "\",\"Ranking\":\"" + ranking + "\"},";
            }
        });
        if (success) {
            keyWordsJsonUpdate = (keyWordsJsonUpdate.length == 1 ? "[" : keyWordsJsonUpdate.substring(0, keyWordsJsonUpdate.length - 1)) + "]";
            $("input[name='" + parent.KeyWordsHiddenName + "']").val(keyWordsJsonUpdate);
        }
        else {

        }
    }
    //添加操作
    this.Add = function () {
        $(parent.Container).find("a[data-type='add']").each(function () {
            $(this).unbind("click").bind("click", function () {
                var keyWordsHtml2 = parent.KeyWordsHtmlTmp.replace(/{KeyWords}/g, "").replace(/{PutOnLimit}/g, "").replace(/{PutOnProportion}/g, "").replace(/{Ranking}/g, "");
                $(this).parent().after(keyWordsHtml2);
                parent.UpdateKeyWordsJsonHidden();
                parent.Update();
                parent.Delete();
                parent.Add();
            });
        });
    }
    //删除操作
    this.Delete = function () {
        $(parent.Container).find("a[data-type='delete']").each(function (idx) {
            //if (idx > 0) $(this).show();
            $(this).unbind("click").bind("click", function () {
                $(this).parent().remove();
                parent.UpdateKeyWordsJsonHidden();
            });
        });
    }
    this.GetRank = function (obj) {
        $.ajax({
            type: "post",
            url: "/putonplan/GetKeyWordsRank",
            data: { keyword: $(obj).val(), adid: $("#AdId").val() },
            success: function (data) {
                $(obj).parent().find("input[data-type='Ranking']").val(data.res);
            }
        });
    }
    //验证控件值有效性
    this.ValidateControl = function (control) {
        //投放量级发生变化，同步更改投放比例
        if ($(control).attr("data-type") == "PutOnLimit") {
            var putOnLimitTotal = 0, putOnLimitNow = 0;
            $(control).parents("div[data-name='KeyWords']").find("input[data-type='PutOnLimit']").each(function () { putOnLimitTotal += (isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val())); });
            var putOnProportions = $(control).parents("div[data-name='KeyWords']").find("input[data-type='PutOnProportion']");
            var proportionCount = 0, proportionNow = 0;
            for (var i = 0; i < putOnProportions.length; i++) {
                putOnLimitNow = parseInt($(putOnProportions[i]).parent().find("input[data-type='PutOnLimit']").val());
                if (!isNaN(putOnLimitNow)) {
                    putOnLimitNow = isNaN(putOnLimitNow) ? 0 : putOnLimitNow;
                    proportionNow = putOnLimitNow == 0 || putOnLimitTotal == 0 ? 0 : Math.round(putOnLimitNow * 100 / putOnLimitTotal)
                    if (i == putOnProportions.length - 1) proportionNow = 100 - proportionCount;
                    proportionCount += proportionNow;
                    $(putOnProportions[i]).val(proportionNow);
                }
            }
        }
        //如果组件只含有一个关键词，不验证控件值有效性
        if ($(control).parent().parent().children().length == 1) return true;
        var legal = true, tip = "";
        if ($(control).attr("data-type") == "PutOnProportion" || $(control).attr("data-type") == "PutOnLimit" || $(control).attr("data-type") == "Ranking") {
            var te = /^[1-9]+[0-9]*]*$/;
            legal = te.test($(control).val());
            tip = "请输入大于0的整数";
        }
        else if ($(control).attr("data-type") == "KeyWords") {
            legal = $(control).val().length > 0;
            tip = "关键词不可为空";
        }
        var errControlIdx = parent.ErrControlList.indexOf(control);
        if (legal) {
            if (errControlIdx > -1)
                parent.ErrControlList.slice(errControlIdx, 1);
        }
        else {
            //$(control).focus();
            if (errControlIdx == -1)
                parent.ErrControlList.push(control);
            $(control).parent().find("span[data-type='tip']").html(tip);
            setTimeout(function () {
                $(control).parent().find("span[data-type='tip']").html("");
            }, 1000);
        }
        //console.log(parent.ErrControlList);
        return legal;
    }
    //错误控件列表
    this.ErrControlList = new Array();
    //文本框更新事件
    this.Update = function () {
        $(parent.Container).find("input[type='text']").unbind("blur").bind("blur", function () {
            //console.log($(this).attr("data-valid"));
            if (parent.ValidateControl(this))
                parent.UpdateKeyWordsJsonHidden();
            if ($(this).attr("data-valid") == "KeyWords")
                parent.GetRank(this);
        });
    }
    //表单提交验证
    this.FormSubmitValidate = function () {
        $("form").submit(function () {
            if (parent.ErrControlList.length > 0) {
                parent.ValidateControl(parent.ErrControlList[0]);
                return false;
            }
        });
    }
    var putOnLimitBefore = 0, putOnLimitAfter = 0;
    //监视投放量级
    this.MonitorPutOnLimit = function (putOnLimitObj) {
        $(putOnLimitObj).unbind("keydown").bind("keydown", function () { putOnLimitBefore = isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val()); })
        $(putOnLimitObj).unbind("keyup").bind("keyup", function () {
            putOnLimitAfter = isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
            if (putOnLimitAfter != putOnLimitBefore) {
                parent.UpdateKeyWordsPutOnLimit(putOnLimitAfter);
            }
        })
    }
    //根据投放量级和关键词投放比例，更新关键词投放量级
    this.UpdateKeyWordsPutOnLimit = function (putOnLimit) {
        var keyWordsPutOnLimit = 0;
        $(parent.Container).find("input[data-type='PutOnProportion']").each(function (idx) {
            if (!isNaN(parseInt($(this).val()))) {
                keyWordsPutOnLimit = Math.round(putOnLimit * parseInt($(this).val()) / 100);
                $(this).parent().find("input[data-type='PutOnLimit']").val(keyWordsPutOnLimit);
            }
        });
        parent.UpdateKeyWordsJsonHidden();
    }
}
//审核广告配置
var CheckAdvertiseConfig = function (adId, planId) {
    if (adId == "" || adId == undefined || adId == 0) return true;
    var result = false;
    $.ajax({
        url: "/AdsManage/CheckAdvertiseConfig?AdId=" + adId + "&PlanId=" + planId,
        method: "get",
        async: false,
        success: function (data) {
            if (data.success.toString() == "true") {
                result = true;
            }
            else {
                result = confirm(data.message);
                //result = !confirm(data.message);
                //if (!result) {
                //    window.location.href = "/PublicFrame/Index?Controller=AdsManage&action=AdsConfig&AdId=" + adId;
                //}
            }
        }
    });
    return result;
    //$.get("/AdsManage/CheckAdvertiseConfig?AdId=" + adId, {}, function (data) {
    //    if (data.success.toString() == "true") {
    //        return true;
    //    }
    //    else {
    //        return confirm(data.message);
    //    }
    //})
}

//绑定select值和事件
var BindSelectEvents = function () {
    $("select").each(function () {
        if (typeof ($(this).attr("value")) == "undefined") return true;
        var parentform = $(this).closest("form").eq(0);
        var dataSelectItem = $(this).attr("data-selecttexthidden");
        $(this).val($(this).attr("value"));
        //下拉框所选项value保存至隐藏域
        if ($(parentform).find("input[name='" + $(this).attr("id") + "']").size() == 0) {
            $(this).before("<input type='hidden' name='" + $(this).attr("id") + "' value='" + $(this).attr("value") + "'/>")
        }
        //下拉框显示内容保存至隐藏域
        if (dataSelectItem != null && dataSelectItem != undefined && dataSelectItem.length > 0 && $("input[name='" + dataSelectItem + "']").size() == 0) {
            $(this).before("<input type='hidden' name='" + dataSelectItem + "' value='" + $(this).find("option:selected").text() + "'/>");
        }

        $(this).change(function () {
            $(parentform).find("input[name='" + $(this).attr("id") + "']").val($(this).val());
            $(parentform).find("input[name='" + dataSelectItem + "']").val($(this).find("option:selected").text());
        });
    });
}

//加载复选框数组选中项
var LoadCheckBox = function () {
    $(":input[data-checkboxname]").each(function () {
        $(this).attr("name", $(this).attr("data-checkboxname"));
    });
    $(":input[type='checkbox']").each(function () {
        var checkBoxList = $(":input[name='" + $(this).attr("name") + "'][type='checkbox']");
        var checkBoxValueList = $(":input[data-checkboxname='" + $(this).attr("name") + "']").val();
        if (checkBoxValueList != null && checkBoxValueList != undefined
            && (checkBoxList.length == 1 ? checkBoxValueList.indexOf($(this).val()) > -1
                : checkBoxValueList.indexOf("," + $(this).val() + ",") > -1)) {
            $(this).prop("checked", true);
        }
        $(this).change(function () {
            var checkboxValue = checkBoxList.length == 1 ? "" : ",";
            $(":checkbox[name='" + $(this).attr("name") + "']:checked").each(function () {
                checkboxValue += $(this).val() + (checkBoxList.length == 1 ? "" : ",");
            });
            $(":input[data-checkboxname='" + $(this).attr("name") + "']").val(checkboxValue);
            //console.log(checkboxValue);
        });
    });
    //单复选框
    $(":input[data-skbname]").each(function () {
        if ($("input[name='" + $(this).attr("data-skbname") + "'][type='hidden']").length == 0) {
            $(this).before("<input type='hidden' name='" + $(this).attr("data-skbname") + "' value='" + $(this).attr("data-skbvalue") + "'></input>");
        }
        if (parseInt($(this).attr("data-skbvalue")) == 1) {
            $(this).prop("checked", true);
        }
        $(this).change(function () {
            $("input[name='" + $(this).attr("data-skbname") + "'][type='hidden']").val($(this).is(':checked') ? 1 : 0);
        });
    });
}

//点击拷贝激活
var ClickCopyActivate = function () {
    try {
        if ($("#ClickActivateCopyType") && $("#SourceSettlementType")) {
            var ClickActivateCopyTypeChange = function () {
                if ($("#ClickActivateCopyType").val() == 1) {
                    $("#SourceSettlementType").val(0).trigger("change");
                    $("#SourceSettlementType").attr("disabled", "disabled");
                }
                else {
                    $("#SourceSettlementType").removeAttr("disabled");
                }
            }
            ClickActivateCopyTypeChange();
            $("#ClickActivateCopyType").change(function () { ClickActivateCopyTypeChange(); });
        }
    }
    catch (e) { }
}

//关键词操作
var KeyWordsOperate = function () {
    $('*[data-keywords]').each(function () {
        //console.log($(this).attr("data-keywords") + "," + $(this).attr("data-name"));
        //console.log($(this).html());
        new KeyWords($(this).attr("data-keywords"), $(this).attr("data-name"), this).Init();
    });
}

//设置Table中行单击时选中，其他行不选中
var SetTableRowClick = function () {
    $("table").removeClass("table-striped");
    $("tbody").find("tr").click(function () {
        $(this).parent().find("tr").css("background-color", "");
        $(this).css("background-color", "#f1f1f1");
    });
}

//设置tbody滚动时，thead固定不动
var SetTableScroll = function () {
    $(window).scroll(function () {
        var minTop = 60;
        var tbodyTop = ($("tbody").offset().top - $(".navbar-inner").offset().top);
        var theadHeight = $("thead").height();

        console.log(tbodyTop);

        if (tbodyTop - theadHeight <= minTop) {
            $("thead").css({
                "position": "absolute"
            });
            $("thead").css("top", minTop + "px");
            $("thead").css("background-color", "#f1f1f1");
            $("tbody").find("tr").eq(0).find("td").each(function (idx, item) {
                //console.log(idx + "___" + $(this).width());
                console.log(item);
                $("thead").find("tr").eq(0).find("th").eq(idx).width($(item).width());
            });

        }
        else {
            $("thead").css("position", "");
            $("thead").css("top", "");
            $("thead").css("background-color", "");
        }
        //console.log($("thead").offset().top);
        //console.log($(".navbar-inner").offset().top);
    });
}

$(document).ready(function () {
    BindSelectEvents();
    LoadCheckBox();
    ClickCopyActivate();
    KeyWordsOperate();
    SetTableRowClick();
    //SetTableScroll();
});