/*
 * 检查字段是否为空或只包括空字符串
 * @param field 待检查字段
 * @param message 提示信息
 */
function checkNull(field, message)
{
    var value = packStr(field.value);
    if (value.length < 1)
    {
        alertField(field, message);
        return true;
    }
    return false;
}

/*
 * 检查字段长度是在指定长度之间(去除前面空格和后面空格)
 * @param field 待检查字段
 * @param min 指定最小长度
 * @param max 指定最大长度
 * @param message 提示信息
 */
function checkString(field, min, max, message)
{
    var value = packStr(field.value);
    if ((min != null && value.length < min) || (max != null && value.length > max))
    {
        alertField(field, message);
        return false;
    }
    return true;
}

/*
 * 检查日期,如果指定min和max,则日期必须在min和max之间
 * @param field 待检查字段
 * @param min 指定日期范围的最小值
 * @param max 指定日期范围的最大值
 * @param message 提示信息
 */
function checkDate(field, min, max, message)
{
    var value = packStr(field.value);

    var patten = "^[\\d]{4}-[\\d]{1,2}-[\\d]{1,2}$";
    if (!verify(value, patten))
    {
        alertField(field, message);
        return false;
    }

    //如果不需要检验月份是否超出12月或者每月是否实际月份的天数,则可以去掉以下代码
    var dateFields = value.split("-");
    var year = parseInt(dateFields[0]);
    var month = parseInt(dateFields[1]);
    var day = parseInt(dateFields[2]);

    var trueMonthDays = getDays(year, month);

    if (month > 12 || day > trueMonthDays)
    {
        alertField(field, message);
        return false;
    }
    //结束月份和天数检查

    var date = parseDate(value);
    if (min != null)
    {
        var minDate = parseDate(min);
        if (date < minDate)
        {
            alertField(field, message);
            return false;
        }
    }

    if (max != null)
    {
        var maxDate = parseDate(max);
        if (date > maxDate)
        {
            alertField(field, message);
            return false;
        }

    }

    return true;
}

function getDays(year, month)
{
    var d = new Date();
    d.setFullYear(year);
    d.setMonth(month);
    d.setDate(0);
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);

    var trueMonthDays = d.getDate();
    return trueMonthDays;
}

/**
 *  对年月日的下拉列表中的年份和月份重新生成当月的天数
 *  dayField是天的下拉列表,yearstr是year的下拉列表的值,monthstr是month的下拉列表的值
 */
function changeDays(dayField, yearstr, monthstr)
{
    var year = parseInt(yearstr);
    var month = parseInt(monthstr);
    var days = getDays(year, month);
    for (var i = dayField.length - 1; i >= 28; i--)
    {
        dayField.remove(i);
    }
    for (var day = 29; day < days + 1; day++)
    {
        dayField.options[dayField.length] = new Option(day, day);
    }
}

/**
 * 解析日期字符串,将其转化成Date类型, 字符串格式为yyyy-M-d
 */
function parseDate(dateStr)
{
    var dateFields = dateStr.split("-");
    var year = parseInt(dateFields[0]);
    var month = parseInt(dateFields[1]) - 1;
    var day = parseInt(dateFields[2]);

    var d = new Date();
    d.setFullYear(year);
    d.setMonth(month);
    d.setDate(day);
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);

    return d;
}

/**
 * 比较开始时间和结束时间
 */
function compare(sdate, edate)
{
    var sd = parseDate(sdate);
    var ed = parseDate(edate);
    return ed >= sd;
}

/**
 * 日期下拉组件的生成
 * yearField,monthField,dayField分别为年月日的下拉框,
 * yearValue,monthValue,dayValue分别为年月日的选中的值.
 * monthValue的值在0-11之间
 */
function initDateValue(yearField, monthField, dayField, yearValue, monthValue, dayValue)
{
    for (var i = 2000; i < 2020; i++)
    {
        yearField.options[yearField.length] = new Option(i, i);
        if (i == yearValue)
        {
            yearField.options[yearField.length - 1].selected = true;
        }
    }
    for (var i = 1; i < 13; i++)
    {
        monthField.options[monthField.length] = new Option(i, i);
        if (i == monthValue)
        {
            monthField.options[monthField.length - 1].selected = true;
        }
    }
    var days = getDays(yearValue, monthValue);

    for (var i = 1; i < days + 1; i++)
    {
        dayField.options[dayField.length] = new Option(i, i);
        if (i == dayValue)
        {
            dayField.options[dayField.length - 1].selected = true;
        }
    }
}


function chanageDate(yearField, monthField, dayField, date)
{
    var dateFields = packStr(date).split("-");
    var yearValue = parseInt(dateFields[0]);

    var monthStr = dateFields[1];
    if (monthStr.charAt(0) == "0")
    {
        monthStr = monthStr.substring(1, 2);
    }
    var monthValue = parseInt(monthStr);

    var dayStr = dateFields[2];
    if (dayStr.charAt(0) == "0")
    {
        dayStr = dayStr.substring(1, 2);
    }
    var dayValue = parseInt(dayStr);

    var yearIndex = yearValue - yearField[0].value;
    yearField.options[yearIndex].selected = true;

    var monthIndex = monthValue - monthField[0].value;
    monthField.options[monthIndex].selected = true;

    var dayIndex = dayValue - dayField[0].value;
    dayField.options[dayIndex].selected = true;
}

function setDateFieldValue(year, month, day, dateField)
{
    dateField.value = year + "-" + month + "-" + day;
}

/**
 * 日期下拉组件的生成
 * yearField,monthField,dayField分别为年月日的下拉框,
 * date为yyyy-M-d的日期格式
 */
function initDateValueD(yearField, monthField, dayField, date)
{
    var dateFields = packStr(date).split("-");
    var yearValue = parseInt(dateFields[0]);
    var monthStr = dateFields[1];
    if (monthStr.charAt(0) == "0")
    {
        monthStr = monthStr.substring(1, 2);
    }
    var monthValue = parseInt(monthStr);

    var dayStr = dateFields[2];
    if (dayStr.charAt(0) == "0")
    {
        dayStr = dayStr.substring(1, 2);
    }
    var dayValue = parseInt(dayStr);
    initDateValue(yearField, monthField, dayField, yearValue, monthValue, dayValue)
}

/**
 * 日期下拉组件的生成
 * yearField,monthField,dayField分别为年月日的下拉框,
 */
function initDate(yearField, monthField, dayField)
{
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    initDateValue(yearField, monthField, dayField, year, month, day)
}

/**
 * 检查表单域的值是否为整型,并且大小在min和max之间
 * 检查出错时候是否弹出消息
 * field    表单域
 * min      最小值
 * max      最大值
 * message  弹出对话框的消息,null值或者空消息就不弹出
 */
function checkInt(field, min, max, message)
{
    var b = isInt(field.value);
    if (b)
    {
        var value = parseInt(field.value);
        if ((min != null && value < min) || (max != null && value > max))
        {
            b = false;
        }
    }
    if (!b && message != "" && message != null)
    {
        alertField(field, message);
    }
    return b;
}

function alertField(field, message)
{
    alert(message);
    field.select();
    field.focus();
}

/**
 * 检查表单域的值是否为float型,并且大小在min和max之间
 * 检查出错时候是否弹出消息
 * field    表单域
 * min      最小值
 * max      最大值
 * message  弹出对话框的消息,null值或者空消息就不弹出
 */
function checkFloat(field, min, max, dot, message)
{

    var b = isFloat(field.value);
    if (b)
    {
        if (isInt(dot))
        {
            var dotnum = parseInt(dot);
            var valueStr = packStr(field.value);
            if (dotnum > 0 && valueStr.lastIndexOf(".") > 0 && valueStr.length - valueStr.lastIndexOf(".") - 1 > dotnum)
            {
                b = false;
            }
        }
    }
    if (b)
    {
        if (isFloat(min))
        {
            min = parseFloat(min);
        }
        if (isFloat(max))
        {
            max = parseFloat(max);
        }
        value = parseFloat(field.value);
        if ((min != null && value < min) || (max != null && value > max))
        {
            b = false;
        }
    }
    if (!b && message != "" && message != null)
    {
        alertField(field, message);
    }
    return b;
}

function isFloat(number)
{
    return (!isNaN(parseFloat(number))) ? true : false;
}

/**
 * 去除value的前面空格和后面空格
 */
function packStr(value)
{
    if (value == null)
    {
        return "";
    }
    var index = 0;
    do{
        index = value.indexOf(" ");
        if (index == 0)
        {
            value = value.substring(1);
        }
    }
    while (index == 0)

    do{
        index = value.lastIndexOf(" ");
        if (index == value.length - 1)
        {
            value = value.substring(0, value.length - 1);
        }
    }
    while (index == value.length)
    return value;
}
/**
 *  从一个select移动选中的option到另一个select,
 *  不在目标添加已包含的项目
 *  @param from 源
 *  @param target 目标
 *  @param remove 若为真，则将选中的项目从源去除
 */
function oneToOne(from, target, remove, targetMaxLength)
{
    if (remove == null)
    {
        remove = false;
    }

    if (targetMaxLength == null)
    {
        targetMaxLength = 100000;
    }

    for (var i = 0; i < from.length; i++)
    {
        var temp = null;
        if (from[i].selected)
        {
            temp = from[i];
            if (remove)
            {
                from[i--] = null;
            }

        }

        if (temp != null && target.length < targetMaxLength)
        {
            var add = true;
            for (var j = 0; j < target.length; j++)
            {
                if (target[j].value == temp.value)
                {
                    add = false;
                    break;
                }
            }
            if (add)
            {
                target.options[target.length] = new Option(temp.text, temp.value);
                target.options[target.length - 1].selected = true;
            }
        }
    }

}

function oneToOneIdValue(from, target, remove, targetMaxLength)
{
    if (remove == null)
    {
        remove = false;
    }

    if (targetMaxLength == null)
    {
        targetMaxLength = 100000;
    }

    for (var i = 0; i < from.length; i++)
    {
        var temp = null;
        if (from[i].selected)
        {
            temp = from[i];
            if (remove)
            {
                from[i--] = null;
            }

        }

        if (temp != null && target.length < targetMaxLength)
        {
            var add = true;
            for (var j = 0; j < target.length; j++)
            {
                if (target[j].value == temp.value)
                {
                    add = false;
                    break;
                }
            }
            if (add)
            {
                target.options[target.length] = new Option(temp.id, temp.value);
                target.options[target.length - 1].selected = true;
            }
        }
    }

}

/**
 * 移除下拉列表中选中的项目
 */
function removeOption(from)
{
    for (var i = 0; i < from.length; i++)
    {
        if (from[i].selected)
        {
            from[i--] = null;
        }
    }
}

/**
 * 选中下拉列表中选所有的项目
 */
function selectAllOption(from)
{
    for (var i = 0; i < from.length; i++)
    {
        from[i].selected = true;
    }
}

function removeSelectOption(from)
{
    for (var i = 0; i < from.length; i++)
    {
        from[i].selected = false;
    }
}

function doRequest1(url, checkfield, parameterName)
{
    doRequest(url, checkfield, parameterName, 400, 260);
}

function doRequest(url, checkfield, parameterName, width, height)
{
    url += "&";
    var idlength = 0;
    var ids = checkfield;
    if (ids != null)
    {
        for (i = 0; i < ids.length; i++)
        {
            if (ids[i].checked)
            {
                url += "&" + parameterName + "=" + ids[i].value;
                idlength++;
            }
        }
        if (idlength <= 0)
        {
            if (ids.checked)
            {
                url += "&" + parameterName + "=" + ids.value;
                idlength++;
            }
        }
    }
    if (idlength == 0)
    {
        alert("请选择至少一个记录");
        return;
    }
    window.open(url, '', 'width=' + width + ',height=' + height);
}
/**
 * 提交申请，checkbox列表只选中一个
 */
function doRequestOne(url, checkfield, parameterName, width, height)
{
    url += "&";
    var idlength = 0;
    var ids = checkfield;
    if (ids != null)
    {
        for (i = 0; i < ids.length; i++)
        {
            if (ids[i].checked)
            {
                url += "&" + parameterName + "=" + ids[i].value;
                idlength++;
            }
        }
        if (idlength <= 0)
        {
            if (ids.checked)
            {
                url += "&" + parameterName + "=" + ids.value;
                idlength++;
            }
        }
    }
    if (idlength == 0 || idlength > 1)
    {
        alert("请选择至少一个记录");
        return;
    }
    window.open(url, 'newWindow', 'width=' + width + ',height=' + height + ' ,left=0, top=0, scrollbars=yes, resizable=yes');
}

function openWindow(url1)
{
    var win1 = window.open(url1, 'newWindow', 'width=' + (screen.width - 10) + ',height=' + (screen.height - 50) + ' ,left=0, top=0, scrollbars=yes, resizable=yes');
    win1.focus();
    return win1;
}

function openWindow1(url1, windowname1, width, height)
{
    var x = screen.width / 2 - width / 2;
    var y = screen.height / 2 - height / 2;
    var win1 = window.open(url1, windowname1, 'width=' + width + ',height=' + height + ' ,left=' + x + ', top=' + y + ', scrollbars=yes, resizable=yes');
    win1.focus();
    return win1;
}

function openWindow2(url1, windowname1)
{
    var win1 = window.open(url1, windowname1, 'width=' + (screen.width - 10) + ',height=' + (screen.height - 50) + ' ,left=0, top=0, scrollbars=yes, resizable=yes');
    win1.focus();
    return win1;
}

/**
 * 检查是否有且仅有一个checkbox被选中，若是返回checkbox value;
 */
function checkOneCheck(checkfield)
{

    var idlength = 0;
    var ids = checkfield;
    var value = null;
    if (ids != null)
    {
        for (i = 0; i < ids.length; i++)
        {
            if (ids[i].checked)
            {
                value = ids[i].value;
                idlength++;
            }
        }
        if (idlength <= 0)
        {
            if (ids.checked)
            {
                ids = ids.value;
                idlength++;
            }
        }
    }
    if (idlength != 1)
    {
        return null;
    }
    else
    {
        return value;
    }

}


function doRequestBig(url, checkfield, parameterName)
{
    doRequest(url, checkfield, parameterName, (screen.width - 10), (screen.height - 50));
}

/**
 * 检查参数是否为整型
 */
function isInt(value)
{
    var tmp = parseInt(value)
    if (isNaN(tmp))
    {
        return false
    }
    else if (tmp.toString() == value)
    {
        return true
    }
    else
    {
        return false
    }
}

function goToPage(submitForm, pageNoInputField, pageNoField, totalPageNoValue)
{
    var field = pageNoInputField;
    var min = 1;
    var max = parseInt(totalPageNoValue);
    var message = "请输入1-" + max + "之间的数字";
    if (!checkInt(field, min, max, message))
    {
        return;
    }
    pageNoField.value = field.value;
    submitForm.submit();
}

function firstPage(form, pageNoField)
{
    pageNoField.value = 1;
    form.submit();
}

function lastPage(form, pageNoField, totalPageNoValue)
{
    pageNoField.value = totalPageNoValue;
    form.submit();
}

function prePage(form, pageNoField)
{
    if (pageNoField.value == 1 || pageNoField.value == 0)
    {
        //        alert("当前第一页");
        return false;
    }
    pageNoField.value = parseInt(pageNoField.value) - 1;
    form.submit();
}

function nextPage(form, pageNoField, totalPageNoField)
{
    if (pageNoField.value == totalPageNoField.value)
    {
        //        alert("当前为最后一页");
        return false;
    }
    pageNoField.value = parseInt(pageNoField.value) + 1;
    form.submit();
}

function goPageNo(pageNoField, pageNoValue)
{
    pageNoField.value = pageNoValue;
    pageNoField.form.submit();
}


function empty(field)
{
    var value = packStr(field.value);
    return (value.length < 1);
}

function isEmpty(value)
{
    return (packStr(value).length < 1);
}


function isAscii(ascii1)
{
    for (i = 0; i < ascii1.length; i++)
    {
        av = ascii1.charCodeAt(i);
        if (av < 0 || av > 255)
        {
            return false;
        }
    }
    return true;
}


function checkMail(mailField, message)
{
    regexp = "^[\\s]*[-\\.\\w]*@[-\\w]+\\.\\w{2,6}[-\\.\\w]*[\\s]*$";
    if (verify(mailField.value, regexp))
    {
        return true;
    }
    mailField.select();
    mailField.focus();
    alert(message);
    return false;
}

function verify(source, regexp)
{
    var pattern = new RegExp(regexp);
    return (pattern.test(source))
}


function delete1(url)
{
    if (confirm('确定需要删除吗?'))
    {
        window.location.href = url;
    }
}

function initOpenWindow(x, y)
{
    if (opener != null)
    {
        self.moveTo(screen.width / 2 - x / 2, screen.height / 2 - y / 2);
        self.resizeTo(x, y);
    }
}

function oneMoreCheck(checkField)
{
    var len = 0;
    //选种个数
    if (checkField != null)
    {
        for (i = 0; checkField.length != null && i < checkField.length; i++)
        {
            if (checkField[i].checked)
            {
                len++;
            }
        }
        if (len == 0 && checkField.checked)
        {
            len++;
        }
    }
    if (len == 0)
    {
        alert("没有选中任何记录！");
        return false;
    }
    return true;
}

function oneCheck(checkField)
{
    var len = 0;
    //选种个数
    if (checkField != null)
    {
        for (i = 0; checkField.length != null && i < checkField.length; i++)
        {
            if (checkField[i].checked)
            {
                len++;
            }
        }
        if (len == 0 && checkField.checked)
        {
            len++;
        }
    }
    if (len != 1)
    {
        alert("确认选中了一条记录！");
        return false;
    }
    return true;
}

function checkAll(checkField)
{
    if (checkField != null)
    {
        if (checkField.length == null)
        {
            checkField.checked = true;
        }
        for (i = 0; checkField.length != null && i < checkField.length; i++)
        {
            checkField[i].checked = true;
        }
    }
}

function unCheckAll(checkField)
{
    if (checkField != null)
    {
        if (checkField.length == null)
        {
            checkField.checked = false;
        }
        for (i = 0; checkField.length != null && i < checkField.length; i++)
        {
            checkField[i].checked = false;
        }
    }
}

function checkOrNot(checkField, isChecked)
{
    if (isChecked)
    {
        checkAll(checkField);
    }
    else
    {
        unCheckAll(checkField);
    }
}

function postData(url, data)
{
    var xmlhttp = getXmlHttp();
    xmlhttp.open("post", url, false);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-Length", data.length);
    xmlhttp.send(data);

    var strResp = xmlhttp.responseText;

    return strResp;
}

function getXmlHttp()
{
    var xmlhttp = null;
    try
    {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            xmlhttp = null;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != "undefined")
    {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}
/**
 * email:validate,message,(required default=false)
 * int:validate,(min,max),message,(required default=false)
 * float:validate,(min,max,dot),message,(required default=false)
 * string:validate,(min,max),message,(required default=false)
 * regex:validate,pattern,message,(required default=false)
 **/
function validForm(validForm)
{
    var tags = validForm.getElementsByTagName("input");
    for (var i = 0; i < tags.length; i++)
    {
        var validateType = tags[i].getAttribute("validate");
        var name = tags[i].getAttribute("name");
        var field = validForm.elements[name];
        if (validateType != null)
        {
            var required = tags[i].getAttribute("required");
            var message = tags[i].getAttribute("message");
            if (packStr(message).length < 1)
            {
                message = "请重新输入!";
            }
            if (required == "true" || packStr(field.value).length > 0)
            {
                if (required == "true")
                {
                    if (checkNull(field, message))
                    {
                        return false;
                    }
                }
                if ("email" == validateType)
                {
                    if (!checkMail(field, message))
                    {
                        return false;
                    }
                }
                else if ("int" == validateType)
                {
                    var min = tags[i].getAttribute("min");
                    var max = tags[i].getAttribute("max");
                    if (!checkInt(field, min, max, message))
                    {
                        return false;
                    }
                }
                else if ("float" == validateType)
                {
                    var min = tags[i].getAttribute("min");
                    var max = tags[i].getAttribute("max");
                    var dot = tags[i].getAttribute("dot");
                    if (!checkFloat(field, min, max, dot, message))
                    {
                        return false;
                    }
                }
                else if ("string" == validateType)
                {

                    var min = tags[i].getAttribute("min");
                    var max = tags[i].getAttribute("max");
                    if (!checkString(field, min, max, message))
                    {
                        return false;
                    }
                }
                else if ("date" == validateType)
                {
                    var min = tags[i].getAttribute("min");
                    var max = tags[i].getAttribute("max");
                    if (!checkDate(field, min, max, message))
                    {
                        return false;
                    }
                }
                else if ("regex" == validateType)
                {
                    var pattern = tags[i].getAttribute("pattern");

                    if (!verify(field.value, pattern))
                    {
                        alertField(field, message)
                        return false;
                    }
                }
            }//if
        }//if
    }
    //for
    return true;
}
//end

//获取参数
//@parameters 的格式如title=test&description=test2&name=test4
//@parameterName 参数名称
//@return 返回指定参数的值,如果不存在,返回长度为0的字符串
function getParameter(parameters, parameterName)
{
    var temp = parameters;
    if (temp == null)
    {
        return "";
    }
    var postion1 = temp.indexOf(parameterName);

    if (postion1 >= 0)
    {

        var beginPosition = temp.indexOf("=", postion1 + parameterName.length) + 1;
        var endPosition = temp.indexOf("&", beginPosition);
        if (endPosition < 0)
        {
            endPosition = temp.length;
        }
        var paraValue = temp.substring(beginPosition, endPosition);
        return paraValue;
    }
    return "";
}

function openAdvertWindow(name, width, height, content) {
    var x = screen.width / 2 - width / 2;
    var y = screen.height / 2 - height / 2;
    var win = window.open("", name, 'width=' + width + ',height=' + height + ' ,left=' + x + ', top=' + y + ', scrollbars=yes, resizable=yes');
    win.document.write(content)
}
