var contextPath = '/Regfoodexport';
//--------------------change_apply--------------------------------------
//保存div信息           
function saveDivString(divId){
    var url = contextPath+"/changeApply/saveDivString";
    var divStr = encodeURIComponent(document.getElementById(divId).innerHTML); 
    var paramStr = "applyId="+applyId+"&divId="+divId+"&divStr="+divStr+'&facId=' + facId+'&changeMethod=yes'+'&entId='+entId;
   // send_postRequest(url, paramStr, backSaveDivString);
    
   //添加aiid 参数
   if(aiid.length > 0)
   {
        paramStr += '&aiid='+aiid;
    }

    var saveChangeRecordUrl = divId+'.action';
    var formId = divId+"Form";
    stopSubmitFull();
    //alert(saveChangeRecordUrl);
    post_FormRequest(saveChangeRecordUrl,paramStr,formId,backSaveDivString);
}
//保存div页面后的回调方法
function backSaveDivString(){
    if (http_request.readyState == 4) { // 判断对象状态
        
        dialogmask.style.visibility = "hidden";
        itadu_messageDiv.style.visibility = "hidden";
        clearInterval(timer);

        if (http_request.status == 200) { // 信息已经成功返回，开始处理信息
             alert(http_request.responseText);
            setSaveStatus();
        } else { //页面不正常
            alert("保存页面出现异常!");
        }
        
        

    }
}
var dialogmask;
var itadu_messageDiv;
var timer;
var itadu_text;
function stopSubmitFull(){
     //主框架
     if(dialogmask == null)
    {
    dialogmask = document.createElement("<div style='position:absolute; top:0; left:0; min-height:100%; width:100%; background:#FFF; opacity:.75; filter:alpha(opacity=75); z-index:100'></div>");
    //消息框
    //POSITION: absolute;z-index:500;text-align:center;
    itadu_messageDiv=document.createElement("<div id='itadu_messageDiv' name='itadu_messageDiv' style='POSITION: absolute;z-index:500;width:250px;height:40px;BACKGROUND-COLOR: #9EDAFE;'></div>");
    //第一行文字说明
    itadu_text=document.createElement("<span id='itadu_text' name='itadu_text' style='width:100%'></span>");
    itadu_text.innerText="   程序处理中：请等待..........";
    itadu_messageDiv.appendChild(itadu_text);
    //第二行图片
    var itadu_loadimg=document.createElement("<img id='itadu_loadimg' width='100%' height='10' src='"+contextPath+"/resources/load.gif'/>");
    itadu_messageDiv.appendChild(itadu_loadimg);
    var list=document.getElementsByTagName("DIV");
    var bodyPanel=null;
    if(list!=null&&list.length>1)
        for(var i=0;i<list.length;i++)
            if(list[i].id.search("bodyPanel")!=-1){
                bodyPanel=list[i];break;
            }
    itadu_messageDiv.style.top="300px";
    itadu_messageDiv.style.left="300px";
    document.body.appendChild(dialogmask);
    document.body.appendChild(itadu_messageDiv);
    }
    itadu_messageDiv.style.top="300px";
    itadu_messageDiv.style.left="300px";
    dialogmask.style.minHeight="100%";
    dialogmask.style.width="100%";

var width = pageWidth();
  var height = pageHeight();
  var left = leftPosition();
  var top = topPosition();
  var dialogwidth = itadu_messageDiv.offsetWidth;
  var dialogheight = itadu_messageDiv.offsetHeight;
  var topposition = top + (height / 3) - (dialogheight / 2);
  var leftposition = left + (width / 2) - (dialogwidth / 2);
  itadu_messageDiv.style.top = topposition + "px";
  //itadu_messageDiv.style.left = leftposition + "px";

  dialogmask.style.height = document.body.offsetHeight + 'px';

    dialogmask.style.visibility = "visible";
    itadu_messageDiv.style.visibility = "visible";
    timer = setInterval(function(){itadu_text.innerText=itadu_text.innerText=='   程序处理中：请等待..........' ? '   程序处理中：请等待.....' 
    :'   程序处理中：请等待..........';},1000);  

}

// calculate the current window width //
function pageWidth() {
  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

// calculate the current window height //
function pageHeight() {
  return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

// calculate the current window vertical offset //
function topPosition() {
  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

// calculate the position starting at the left of the window //
function leftPosition() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}


//保存更改记录后的回调方法
function normalCallback(){
    if (http_request.readyState == 4) { // 判断对象状态
        if (http_request.status == 200) { // 信息已经成功返回，开始处理信息
            if(http_request.responseText != 'OK')
             alert(http_request.responseText);
        } else { //页面不正常
            alert("保存页面出现异常!");
        }
    }
}

//div保存成功后整改div样式(打开的div)
function setSaveStatus() {
	currentDiv.parentElement.style.backgroundColor="#9EDAFE";
}
//打开指定div
function openDiv(divId){
    var url = divId+'.action?facId=' + facId + '&divId=' + divId;
    if(applyId != ''){
        url += '&applyId=' + applyId;
    }
    var dis;
    for(var i=0; i < divs.length; i++){
        if(divs[i].id == divId){			
            currentDiv = divs[i];
            var str = divId+"Pic";
            if(divs[i].style.display=='none'){
                dis = 'block';
                document.getElementById(str).src="../resources/arrow_down.gif";
            }else{
                dis = 'none';
                document.getElementById(str).src="../resources/arrow_up.gif";
            }
        }else{		   
           var nonedivId = divs[i].id;
           var str = nonedivId+"Pic";
           document.getElementById(str).src="../resources/arrow_up.gif";
           dis ='none';

        }
        divs[i].style.display = dis;
    }
    if(currentDiv.status != 'finished'){//非'读取完成状态', 初始页面
        send_request(url, processRequest);
    }
}
//初始化、指定处理函数、发送请求的函数(get)
function send_request(url, invokeFunction) {
        http_request = false;
        //开始初始化XMLHttpRequest对象
        if(window.XMLHttpRequest) { //Mozilla 浏览器
                http_request = new XMLHttpRequest();
                if (http_request.overrideMimeType) {//设置MiME类别
                        http_request.overrideMimeType("text/xml");
                }
        }
        else if (window.ActiveXObject) { // IE浏览器
                try {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try {
                                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                }
        }
        if (!http_request) { // 异常，创建对象实例失败
                window.alert("不能创建XMLHttpRequest对象实例.");
                return false;
        }
        http_request.onreadystatechange = invokeFunction;
        // 确定发送请求的方式和URL以及是否同步执行下段代码
        http_request.open("GET", url, true);
        //清空缓存
        http_request.setRequestHeader("If-Modified-Since","0"); 
        http_request.send(null);
}
//初始化、指定处理函数、发送请求的函数(post)
function send_postRequest(url, parameterStr, invokeFunction) {
        http_request = false;
        //开始初始化XMLHttpRequest对象
        if(window.XMLHttpRequest) { //Mozilla 浏览器
                http_request = new XMLHttpRequest();
                if (http_request.overrideMimeType) {//设置MiME类别
                        http_request.overrideMimeType("text/xml");
                }
        }
        else if (window.ActiveXObject) { // IE浏览器
                try {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try {
                                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                }
        }
        if (!http_request) { // 异常，创建对象实例失败
                window.alert("不能创建XMLHttpRequest对象实例.");
                return false;
        }
        http_request.onreadystatechange = invokeFunction;
        // 确定发送请求的方式和URL以及是否同步执行下段代码
        http_request.open("POST", url, true);
        //清空缓存
        http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); 
        //传参

        http_request.send(parameterStr);

}

function post_FormRequest(url, paramStr,formId, invokeFunction) {
        http_request = false;
        //开始初始化XMLHttpRequest对象
        if(window.XMLHttpRequest) { //Mozilla 浏览器
                http_request = new XMLHttpRequest();
                if (http_request.overrideMimeType) {//设置MiME类别
                        http_request.overrideMimeType("text/xml");
                }
        }
        else if (window.ActiveXObject) { // IE浏览器
                try {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try {
                                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                }
        }
        if (!http_request) { // 异常，创建对象实例失败
                window.alert("不能创建XMLHttpRequest对象实例.");
                return false;
        }
        http_request.onreadystatechange = invokeFunction;
        // 确定发送请求的方式和URL以及是否同步执行下段代码
        http_request.open("POST", url, true);
        //清空缓存
        http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); 
        //传参
        if(formId == 'qualitySystemDivForm')
        {
            http_request.send(getDivFormQueryString('qualitySystemDiv')+'&'+paramStr);
        }
        else http_request.send(getFormQueryString(formId)+'&'+paramStr);

}

//得到一个表单里的全部信息
function getFormQueryString(frmID)
{ 
       var form = document.getElementById(frmID); 
       var i,queryString = "", and = "";
       var item; // for each form's object
       var itemValue;// store each form object's value

       for( i=0;i<form.length;i++ ) 
       {
              item = form.elements[i];// get form's each object
              if ( item.name!='' ) 
              {
                     if ( item.type == 'select-one' ) 
                     {
                            itemValue = item.options[item.selectedIndex].value;
                     }
                     else if ( item.type=='checkbox' || item.type=='radio') 
                     {
                            if ( item.checked == false )
                            {
                                   continue;    
                            }
                            itemValue = item.value;
                     }
                    else if ( item.type == 'button' || item.type == 'submit' || item.type == 'reset' || item.type == 'image' || item.type == 'form')

                     {// ignore this type
                            continue;
                     }
                     else 
                     {
                            itemValue = item.value;

                     }
                     itemValue = encodeURIComponent(itemValue);

                     queryString += and + item.name + '=' + itemValue;

                     and="&";
              }
       }   
       return queryString;
}

//得到一个DIV里的全部信息
function getDivFormQueryString(divId)
{ 
       var div = document.getElementById(divId); 
       var i,queryString = "", and = "";
       var item; // for each form's object
       var itemValue;// store each form object's value

       var items = div.all;
	for(var i=0; i < items.length; i++)
	{
                item = items[i];

                if ( item.type == 'select-one' ) 
                     {
                            itemValue = item.options[item.selectedIndex].value;
                     }
                     else if ( item.type=='checkbox' || item.type=='radio') 
                     {
                            if ( item.checked == false )
                            {
                                   continue;    
                            }
                            itemValue = item.value;
                     }
                     else if (items[i].type == "text" || items[i].type == "textarea" || items[i].type == "hidden")
                     {
                            itemValue = item.value;
                     }
                     else
                    {
                        continue;
                    }
                     itemValue = encodeURIComponent(itemValue);

                     queryString += and + item.name + '=' + itemValue;

                     and="&";
		
	}
       // alert(queryString);
       return queryString;
}

// 处理返回信息的函数
function processRequest() {
    if (http_request.readyState == 4) { // 判断对象状态
        if (http_request.status == 200) { // 信息已经成功返回，开始处理信息
             currentDiv.innerHTML=http_request.responseText;
             currentDiv.status='finished';//设置状态为读取完成状态

             initDiv(currentDiv);
        } else { //页面不正常
            alert("您所请求的页面有异常。");
        }
    }
}
 // 执行特定div的初始化方法
function initDiv(currentDiv){
    var fun;
    try{
        fun = eval("init_"+currentDiv.id);
        }catch(e){
            return;
        }
       eval("init_"+currentDiv.id+"()");
}
// select 给 input 赋值
function putAreaValueToInput( inputId ){
    // 把本组件值放到 input 中
    document.getElementById(inputId).value= event.srcElement.value;
}
//动态增加行
//tableId: 表id
//trSetId: 模板tr的Id
//firstDateRowIndex: 第一个数据行的位置
function addRow(tableId, trSetId, firstDateRowIndex){
    var table = document.getElementById(tableId);//表格
    var trSet = document.getElementById(trSetId);//模板tr
    var newTr = table.insertRow();//新增加的行
    var newTd;//新增加的列
    var tdSet;//模板td

    if(firstDateRowIndex == null){
        firstDateRowIndex = 1;//默认确定为数据项从第2行开始
    }
    if(table.maxRowIndex == null){
    		table.maxRowIndex = newTr.rowIndex - firstDateRowIndex;
    }
    var index = table.maxRowIndex++;
    //var index = newTr.rowIndex - firstDateRowIndex;//数据项list中 本行应保存在list集合中的位置
    for(var i=0; i<trSet.cells.length; i++){//遍历模板下的td
        tdSet = trSet.cells[i];
        newTd = newTr.insertCell();
        copyTd(tdSet, newTd, index);
    }
}
//sourceTd 模板td
//goalTd 目标td
//rowIndex 行号
function copyTd(sourceTd, goalTd, rowIndex){
    //1 复制td属性
    for(var i in sourceTd.attributes){
      try{
            if(sourceTd[i] != null && sourceTd[i] != ''  )
                    goalTd[i] = sourceTd[i];
      }catch(e){}                    
    }
    //2 复制td下控件
    var regex = /\+\+\*\+\+/g;
    var newHtml = sourceTd.innerHTML.replace(regex, rowIndex);
    goalTd.innerHTML = newHtml;
}
//删除行
function deleteRows(tableId, checkboxName){ 
    var boxs = document.getElementsByName(checkboxName);
    var dealType;
    for(var i=boxs.length-1; i>=0; i--){
        if(boxs[i].checked){
            var rowStatusInput = document.getElementById(boxs[i].rowStatusInputId);
            if(rowStatusInput.value == '1'){//后加入的项目
                dealType = 'deleteRow'
            }else{//原有项目
                dealType = 'addTag';
                boxs[i].checked=false;
            	rowStatusInput.value='3';//状态至为删除标记
            }
            var optTr = findParentTR(boxs[i]);
            var rowIndex = optTr.rowIndex;
            deleteRow(tableId, rowIndex , dealType);
            //删除行后 删除项的处理
            //setReadOnly(optTr);

/*
            var certNo = optTr.cells[2-1].childNodes(0);
            var rowIndex = optTr.rowIndex;
            if(checkDeleteProduct(tableId, rowIndex, certNo, rowStatusInput)) {
                deleteRow(tableId, rowIndex , dealType);
                //删除行后 删除项的处理
                //setReadOnly(optTr);
                boxs[i].checked=false;
                rowStatusInput.value='3';//状态至为删除标记
            } else {
                boxs[i].checked = false;
                alert("删除失败!该证书下最少保留一种产品!");
            }
*/
        }
    }
}
//删除单行 dealType:删除操作的方式
function deleteRow(tableId, rowIndex, dealType){
    var optTable = document.getElementById(tableId);
    if(dealType == 'deleteRow'){
    //1.直接删除
        optTable.deleteRow(rowIndex);
    }else{
        //2.加删除标记
        var deleteDiv = createDeleteLine();//document.getElementById('deleteDiv');
        var optTd = optTable.rows[rowIndex].cells[0];
        deleteDiv.firstChild.style.width=optTable.offsetWidth-optTd.offsetWidth;
        optTd.insertAdjacentElement('afterBegin', deleteDiv);
    }
}
//产品删除验证 add by LiYang on 2008-12-03 
function checkDeleteProduct(tableId, rowIndex, certNo) {
    var optTable = document.getElementById(tableId);
    var otherNo;
    
    for(var i = 2; i < optTable.rows.length; i++ ) {
        if(i != rowIndex ) {
            otherNo = optTable.rows(i).cells(2-1).childNodes(0);
            if(certNo.innerText == otherNo.innerText) 
                return true;
        }
    }
    return false;
}
//查找控件上级的tr控件
function findParentTR(obj){
    var newObj = obj.parentElement;
    if(newObj.tagName == 'TR'){
        return newObj;
    }else if(newObj.tagName == 'BODY'){
        return null;
    }else{
        return findParentTR(newObj);
    }
}
//删除线模板对象
function createDeleteLine(){
    var deleteDiv = document.createElement('DIV');
    deleteDiv.style.cssText = "position: relative; -rave-layout: grid; ";
    deleteDiv.innerHTML = "<table border='0'  style='position: absolute; heigth:10px;' cellpadding='0' cellspacing='0' >"
        +"<tr><td style='border:0px; background-color:transparent;' ><hr style='color:red' size='1' /></td></tr>"
        +"</table>";
    return deleteDiv;
}
//---------------------entAddress----------------------------
//联动下拉框相关方法
//加option
function addOpt(selectId,list){
    for(var i =0;i<list.length;i++){
            var temOption=new Option(list[i].name,list[i].value);
            var sel= document.getElementById(selectId);
            if (list[i].isSelected){
                    temOption.selected=true;
            }
            sel[sel.length]=temOption;	
    }
}
//初始化联动下拉框        
function district_init(initValue,selectId1,selectId2,selectId3){
        if(document.getElementById(selectId1).length == 0){
            dwr.util.removeAllOptions(selectId1);
            dwr.util.removeAllOptions(selectId2);
            dwr.util.removeAllOptions(selectId3);
             ProvinceFacade.getProvince(initValue,  function (list){
                 addOpt(selectId1,list);
                 district_province_change(initValue,selectId1,selectId2,selectId3);
            });
        }
}
//省下拉框变化	
function district_province_change(initValue,selectId1,selectId2,selectId3){

        dwr.util.removeAllOptions(selectId2);
        if(selectId3 != ''){
            dwr.util.removeAllOptions(selectId3);
        }
         var select1Value=dwr.util.getValue(selectId1); 

         ProvinceFacade.getCity(select1Value, initValue,function (list){
                addOpt(selectId2,list);
                if(selectId3 != ''){
                    district_city_change(initValue,selectId2,selectId3);
                }
        });   

}
//市下拉框变化	
function district_city_change(initValue,selectId2,selectId3){
        dwr.util.removeAllOptions(selectId3);
         var select2Value=dwr.util.getValue(selectId2);
         ProvinceFacade.getCounty(select2Value, initValue,function (list){
                addOpt(selectId3,list);
    });
}
//entAddressDiv 初始化方法 
function init_entAddressDiv(){
    //district_init(document.getElementById('entAddressDiv.oldEntAreaCode').value,'entAddressDiv.province','entAddressDiv.city','entAddressDiv.country');
     //district_init(document.getElementById('entAddressDiv.oldFacAreaCode').value,'entAddressDiv.provinceFac','entAddressDiv.cityFac','entAddressDiv.countryFac');
}
//--------------------productDiv-----------------------------
//此证书有没有其它相关的产品
function haveOtherProduct(obj){
    var licenceId = getCurrentLicenceId(obj);
    
    var boxs = document.getElementsByName(obj.name);

    for(var i=0; i<boxs.length; i++){
        if(boxs[i] != obj //不等于自身
            && boxs[i].rowStatusInputId.indexOf('++*++') < 0
            && getCurrentStatus(boxs[i]) != 3  //非删除的记录
            && !boxs[i].checked //没有被选中删除
            && getCurrentLicenceId(boxs[i]) == licenceId){//证书编号相同
            
            return true;
        }
    }
    return false;
}
//阻止删除证书所有的产品
function stopDelAllProduct(obj){
    if(obj.checked){//选中的情况下
        if(!haveOtherProduct(obj)){
            alert('不能删除最后一条，任何一个证书下必须保留一个产品，你可以对此产品进行变更操作!');
            obj.checked = false;
        }
    }
}

function getCurrentLicenceId(boxItem){
    return document.getElementById(boxItem.rowStatusInputId.substring(0, boxItem.rowStatusInputId.lastIndexOf('.')+1) + 'licenceId').value;
}
function getCurrentStatus(boxItem){
    return document.getElementById(boxItem.rowStatusInputId).value;
}

function selectType(labelId, valueId){   
    var sub = window.open(contextPath+"/faces/apply/select_productType.jsp?labelId="+labelId+'&valueId='+ valueId, "produceType", "top=20 left=20 height=270 width=585 location:0 menubar:0 resizable:0 scrollbars:0 status:0 toolbar:0 ");
    sub.focus();
}
function selectCountry(labelId, valueId){
    var sub = window.open(contextPath+"/faces/apply/select_country.jsp?labelId="+labelId+'&valueId='+ valueId, "country", "top=20 left=20 height=270 width=425 location:0 menubar:0 resizable:0 scrollbars:0 status:0 toolbar:0 ");
    sub.focus();
}
//-----------------------qualitySystemDiv-----------------------
function selectCertify(labelId, valueId){
    var sub = window.open(contextPath+"/faces/apply/select_certify.jsp?labelId="+labelId+'&valueId='+ valueId, "certify", "top=20 left=20 height=600 width=780 location=0 menubar=0 resizable=1 scrollbars=1 status=0 toolbar=0 ");
    sub.focus();
}
//上传文件的进度等待图片显示
function showmsg(){
    document.getElementById("msg").innerHTML='<img src=\'loading.gif\'>请稍等';
}
//---------------------------legalPersonDiv-------------------------------
function uploadFile(returnId, saveItem){
    var fileName = event.srcElement.form[saveItem].value;
    if(fileName == ''){
        alert('请选择上传文件!');
        return false;
    }else if(!/^.*\.jpg$|^.*\.JPG$/.test(fileName)){
        alert('上传文件必须是jpg格式!');
        return false;
    }
    document.getElementById('legalPersonDiv.saveItem').value=saveItem;
    document.getElementById('legalPersonDiv.returnId').value=returnId;
    return true;
}


