ipod825 / AdCasemain

// ==UserScript==
// @name        AdCasemain
// @namespace   https://github.com/ipod825/userjs
// @include     http://adv.epb.taichung.gov.tw/Cases/CasesMain.aspx
// @version     1
// @grant       none
// ==/UserScript==

//$(".spanPageNum > select:nth-child(1) option:contains('50')").attr("selected",true)
$('.container')[1].innerHTML = '<div id="modifiedForm">\
<table>\
<tr>\
<th>舉發人:</th>\
<td id="witnessField"></td>\
<th>違規種類:</th>\
<td id="typeField"></td>\
<th>移送單位:</th>\
<td id="toPlaceField"></td>\
</tr>\
<tr>\
<th>序號:</th>\
<td class="mytd" id="seqField"></td>\
<th>登錄日期:</th>\
<td id="inDateField">~</td>\
<th>違規地點:</th>\
<td id="violatePlaceField"></td>\
</tr>\
<tr>\
<th>案件狀態:</th>\
<td id="statusField"></td>\
<th>違規日期:</th>\
<td id="violateDateField">~</td>\
<th>簽收人:</th>\
<td id="signerField"></td>\
</tr>\
<tr>\
<th>違規電話:</th>\
<td colspan="7"id="phoneField"></td>\
</tr>\
</tabe>\
</div>';

$('#seqField').append($('#BodyContent_txtSerial').css('width', '200px'));
$('#witnessField').append($('#BodyContent_ddlReporters').css('width', '200px'));
$('#typeField').append($('#BodyContent_ucViolationCode_ddlEipCode').css('width', '200px'));
$('#violatePlaceField').append($('#BodyContent_txtLocation').css('width', '200px'));
$('#statusField').append($('#BodyContent_ddl_CaseStatus').css('width', '200px'));
$('#inDateField').prepend($('#BodyContent_txtEntryDateF').css('width', '100px'));
$('#inDateField').append($('#BodyContent_txtEntryDateT').css('width', '100px'));
$('#violateDateField').prepend($('#BodyContent_txtHappenTimeF').css('width', '100px'));
$('#violateDateField').append($('#BodyContent_txtHappenTimeT').css('width', '100px'));
$('#signerField').append($('#BodyContent_txtReceiver').css('width', '200px'));
$('#phoneField').append($('#BodyContent_txtTel').css('width', '750px').dblclick(function(){this.select();}));
$('#toPlaceField').append($('#BodyContent_ucArea_ddlEipCode').css('width', '200px'));

$('#modifiedForm').append(
    $('<input/>').attr({
        type: 'button',
        id: 'field',
        class: 'btn btn-success',
        value: 'Open',
    }).click(function () {
        $('#BodyContent_gvDataList').parent().find('a').not('.aspNetDisabled').each(function () {window.open(this.href, '_blank');});
    })
).append(
    $('#BodyContent_btnSearch')
).append(
    $('<input/>').attr({
        type: 'button',
        id: 'field',
        class: 'btn btn-success',
        value: '連查',
    }).click(function () {
        $("#BodyContent_txtTel")[0].value.split(" ").map(function(phone){
            $.ajax({
                type: 'POST',
                url: 'http://adv.epb.taichung.gov.tw/Cases/CasesMain.aspx',
                data:	getFormContent({'ctl00$BodyContent$txtTel':phone},{"ctl00$BodyContent$gvDataList$ctl13$ctl00": "10"}),
                async: false,
                success: function (res) {
                    var doc=$(res);
                    $("input:hidden").not("#BodyContent_MainContent input").each(function(){
                        this.value=doc.find("#"+this.id)[0].value;
                    })
                    $('#BodyContent_MainContent .foldable:last').after(createFold(doc.find("#BodyContent_gvDataList"),$(res).find('input:hidden'),phone));
                }
            })
        });
    })
);

$("#BodyContent_divSearch").remove();
$("#BodyContent_MainContent").find(".row")[0].remove();
$("#BodyContent_gvDataList_gvDataList").remove();

$('#BodyContent_MainContent').append($('<div/>').attr({class: 'foldable'}));
var t=$("#BodyContent_gvDataList");
$('#BodyContent_MainContent').append(createFold(t,$("#BodyContent_ddl_CaseStatus option:selected")[0].text));
t.css({'display': 'table'});



function modifiTable(t){
    t.removeAttr("id")
    t.find("tr:last").remove();
    t.css({'display': 'none', 'margin':'0 0 0 0'});    
    t.find("a").filter(function() {return this.id.match(/BodyContent_gvDataList_hlSerial*/);}).each(function(){
        this.href= this.href.substr(0, this.href.lastIndexOf('&'));
        $(this).attr("target","_blank");
    });
    var arr=uniqueArr(t.find("td:nth-child(8)").map(function(){return $(this).html();}));
    var color="#FFFFCC";
    if(arr.length>1 || arr.length==0)
        color="red";
    var targetStr = arr[0];
    arr=uniqueArr(t.find("td:nth-child(3)").map(function(){return $(this).html();}));
    if(arr.length==1)
        targetStr=arr[0];
    t.find("th:nth-child(10),th:nth-child(11), td:nth-child(10),td:nth-child(11)").remove();
    return {'color':color,'targetStr':targetStr};
}

function createFoldHead(info,control){
    var c='#FFFFCC';
    if('color' in info)
        c=info.color;
    return $('<div/>').attr({class: "foldable"}).append(
        $('<div/>').attr({class: 'row'}).append(
            $('<div/>').attr({class: 'col-xs-1'}).append(
                $('<input/>').attr({ 
                    type: 'button',
                    value: '刪除查詢',
                }).click(function(){
                    $(this).parent().parent().next().remove();
                    $(this).parent().parent().parent().remove();
                })
            )
        ).append(
            $('<div/>').attr({class: 'col-xs-3'})
            .css({'background-color': c, 'border-style': 'outset'})
            .html(info.targetStr).click(function(){
                var n=$(this).parent().next();
                if(n.css("display")=='none')
                    n.css({display: 'table'});    
                else{
                    n.css({display: "none"});                            
                }
            })
        ).append(
            $('<div/>').attr({class: 'col-xs-8'}).append(control)
        )
    )
}

function pageDirection(ref,dir){
    //console.log(ref.parents(".foldable").find("table"));
    var t=ref.parents(".foldable").find("table");
    var pgIndSpan=ref.siblings(".pgInd");
    var pgInd=parseInt(pgIndSpan.html());
    var para=ref.parents(".foldable").find("input:last");
    var paraStr='';
    if(dir=='left'){
        if(pgInd==1)
            return false;
        else{
            pgInd-=1;
            paraStr=para.val()+'&__EVENTTARGET=ctl00%24BodyContent%24gvDataList%24ctl13%24ctl02';
        }
    }
    else{
        if(pgInd==parseInt(ref.siblings(".maxPgInd").html()))
            return false;
        else{
            pgInd+=1;
            paraStr=para.val()+'&__EVENTTARGET=ctl00%24BodyContent%24gvDataList%24ctl13%24ctl03';
        }
    }
    $.ajax({
        type: 'POST',
        url: 'http://adv.epb.taichung.gov.tw/Cases/CasesMain.aspx',
        data: paraStr,
        async: false,
        success: function (res) {
            var tnew=$(res).find("#BodyContent_gvDataList");
            modifiTable(tnew);
            tnew.css({'display':'table'});
            t.replaceWith(tnew);
            pgIndSpan.html(pgInd);
            para.val(getPagePara($(res)));
        }
    })
}
function createFold(t,targetStr){
    if(t.length==0)
        return createFoldHead({'targetStr':'查無資料: '+targetStr},null);
    
    t.find("tr:last-child input").remove();
    var str=t.find(".spanPageIndexs").html();
    
    var control=$("<div/>").append(
        $('<i/>').attr({class:'glyphicon glyphicon-circle-arrow-left'})
        .css({'font-size':'15px','width':'2em'})
        .click(function(){  pageDirection($(this),'left'); })
    )
    .append($("<span/>").html(str.slice(0,1)))
    .append($('<span/>').attr({class:'pgInd'}).html("1"))
    .append($("<span/>").html('/'))
    .append($("<span/>").attr({class:'maxPgInd'}).html((/\d+/g).exec(str)))
    .append($("<span/>").html('頁'))
    .append(
        $('<i/>').attr({class:'glyphicon glyphicon-circle-arrow-right'})
        .css({'font-size':'15px','width':'2em'})
        .click(function(){  pageDirection($(this),'right'); })
    )
    .append(t.find(".spanRecoderCount"));
    
    var info=modifiTable(t);
    return createFoldHead(info,control).append(t).append(
        $("<input/>").attr({type:"hidden",
                            value: getPagePara($(document))
                           })
        
    );
}

function getPagePara(doc){
    return getFormParStr(doc.find("input:hidden").not("#__EVENTTARGET").not("#BodyContent_MainContent input"),{})+
        "&"+getFormParStr(doc.find("#BodyContent_ddl_CaseStatus"),{})
}

function getFormContent(redifine,extra){
    var a=getFormParStr($("input,select").not("#BodyContent_MainContent input"),redifine)
    b='';
    for (var name in extra) 
        b+=name.replace(/\$/g,"%24")+"="+extra[name].replace(/\//g,"%2F").replace(/\+/g,"%2B").replace(/=/g,"%3D");
    return a+"&"+b;
}

function getFormParStr(inputs,redifine){
    return inputs.map(function(){
        var v=this.value;
        if (this.name in redifine)
            v=redifine[this.name];
        return this.name.replace(/\$/g,"%24")+"="+v.replace(/\$/g,"%24").replace(/\//g,"%2F").replace(/\+/g,"%2B").replace(/=/g,"%3D");
    }).get().join("&");
}
function uniqueArr(arr){
    return $.grep(arr, function(v, k){return $.inArray(v ,arr) === k;});
}