﻿//jquery plugin include http://plugins.jquery.com/project/includedemand
(function($){$.extend({ImportBasePath:'',__WaitingTasks:new Object(),__loadedSuccessfully:function(taskId){if(taskId in $.__WaitingTasks){if(($.__WaitingTasks[taskId].loading-=1)<1){var callback=$.__WaitingTasks[taskId].task;if(typeof callback=='function'){callback()}delete $.__WaitingTasks[taskId]}}},fileinfo:function(data){data=data.replace(/^\s|\s$/g,"");var m;if(/\.\w+$/.test(data)){m=data.match(/([^\/\\]+)\.(\w+)$/);if(m){if(m[2]=='js'){return{filename:m[1],ext:m[2],tag:'script'}}else if(m[2]=='css'){return{filename:m[1],ext:m[2],tag:'link'}}else{return{filename:m[1],ext:m[2],tag:null}}}else{return{filename:null,ext:null}}}else{m=data.match(/([^\/\\]+)$/);if(m){return{filename:m[1],ext:null,tag:null}}else{return{filename:null,ext:null,tag:null}}}},fileExist:function(filename,filetype,attrCheck){var elementsArray=document.getElementsByTagName(filetype);for(var i=0;i<elementsArray.length;i++){if(elementsArray[i].getAttribute(attrCheck)==$.ImportBasePath+filename){return true}}return false},createElement:function(filename,filetype){switch(filetype){case'script':if(!$.fileExist(filename,filetype,'src')){var scriptTag=document.createElement(filetype);scriptTag.setAttribute('language','javascript');scriptTag.setAttribute('type','text/javascript');scriptTag.setAttribute('src',$.ImportBasePath+filename);return scriptTag}else{return false}break;case'link':if(!$.fileExist(filename,filetype,'href')){var styleTag=document.createElement(filetype);styleTag.setAttribute('type','text/css');styleTag.setAttribute('rel','stylesheet');styleTag.setAttribute('href',$.ImportBasePath+filename);return styleTag}else{return false}break;default:return false;break}},cssReady:function(index,taskId){function check(){if(document.styleSheets[index]){window.clearInterval(checkInterval);$.__loadedSuccessfully(taskId)}}var checkInterval=window.setInterval(check,200)},include:function(file,callback){var headerTag=document.getElementsByTagName('head')[0];var fileArray=[];typeof file=='string'?fileArray[0]=file:fileArray=file;var taskId=new Date().getTime().toString();$.__WaitingTasks[taskId]={'loading':fileArray.length,'task':callback};for(var i=0;i<fileArray.length;i++){var elementTag=$.fileinfo(fileArray[i]).tag;var el=[];if(elementTag!==null){el[i]=$.createElement(fileArray[i],elementTag);if(el[i]){headerTag.appendChild(el[i]);if($.browser.msie){el[i].onreadystatechange=function(){if(this.readyState==='loaded'||this.readyState==='complete'){$.__loadedSuccessfully(taskId)}}}else{if(elementTag=='link'){$.cssReady(i,taskId)}else{if(/WebKit/i.test(navigator.userAgent)){var _timer=setInterval(function(){if(/loaded|complete/.test(document.readyState)){$.__loadedSuccessfully(taskId)}},100)}el[i].onload=function(){$.__loadedSuccessfully(taskId)}}}}else{$.__loadedSuccessfully(taskId)}}else{return false}}}})})(jQuery);
function CommonSearch(Url,type,divId,divBgId,divParId,inputPrefix,parAppend,pageIndex,pageSize,sortBy,isAsc,dType,jsFun)
{
    var params="";
    params=getParams(divParId,inputPrefix);
    if(IsEmpty(params))params="";
    if(!IsEmpty(pageIndex)){params+="&page="+pageIndex;}
    if(!IsEmpty(pageSize)){params+="&size="+pageSize;}
    if(!IsEmpty(sortBy)){params+="&sort="+sortBy;}
    if(!IsEmpty(isAsc)){params+="&asc="+(isAsc?"Y":"N");}
    if(!IsEmpty(parAppend)){params+=parAppend;}
    params="type="+type+"&parms="+params;
    CallAjaxForGetList(SerUrl+Url,params,divId,divBgId,dType,jsFun);
}

function CommonCall(Url,type,divId,divBgId,divParId,inputPrefix,parAppend,dType,jsFun)
{
    var params="";
    params=getParams(divParId,inputPrefix);
    if(IsEmpty(params))params="";
    if(!IsEmpty(parAppend)){params+=parAppend;}
    params="type="+type+"&parms="+params;
    CallAjaxForGetList(SerUrl+Url,params,divId,divBgId,dType,jsFun);
}

function CallAjaxForGetList(url, params, divId, divBgId, dType, jsFun) {
    if (dType == null) dType = "text";
    $.ajax({
        url: url,
        type: 'post',
        random: Math.random(),
        cache: false,
        dataType: dType,
        data: params,
        beforeSend: function() {
            if (!IsEmpty(divBgId)) sld(divBgId);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (IsTimeout(XMLHttpRequest.responseText)) { RedirectLogin(); return;}
            if (!IsEmpty(divBgId)) CloseMsgBox();
            $("#" + divId).html('occur error!');
        },
        success: function(data, textStatus) {
	   	    if (IsTimeout(data)) { RedirectLogin(); return;}	
            if (dType == 'text') {
                if (!IsEmpty(divBgId)) CloseMsgBox();
                if (!IsEmpty(divId)) $("#" + divId).html(data);
                if (jsFun != null)
                {
                    if($.isFunction(jsFun))
                        jsFun(data,textStatus);
                    else    
                        eval(jsFun);
                }
            }
            else if (dType == 'json') {
                if (data.success) {
                    if (jsFun != null)
                    {
                        if($.isFunction(jsFun))
                            jsFun(data,textStatus);
                        else    
                            eval(jsFun);
                    }
                }
                else {
                    if (!IsEmpty(divBgId)) CM();MsgBox(data.message, 'System Information', true, divBgId);
                }
            }
        }
    });
}
//CallAjaxForDelSel('Callback/Sys/RightRef.aspx',3,'RC','keys','dv_rightRef_list','content','','','','json','SearchRightRefList();')
function CallAjaxForDelSel(Url,type,chkPrefix,callBackParaName,divId,divBgId,divParId,inputPrefix,parAppend,dType,jsFunc,isChecked)
{
    var params="";
    if(IsEmpty(dType)) dType='json';
    if(!IsEmpty(callBackParaName)) params="&"+callBackParaName+'='+GetSelect(divId,chkPrefix,isChecked);
    if(!IsEmpty(params))parAppend=parAppend+params;
    CommonCall(Url,type,divId,divBgId,divParId,inputPrefix,parAppend,dType,jsFunc);
}
function ConfirmAndDelSel(Url, type, chkPrefix, callBackParaName, divId, divBgId, divParId, inputPrefix, parAppend, dType, jsFunc, isChecked, confirmMsg, atLeastMsg)
{
   if (atLeastMsg == null)
        atLeastMsg = 'You must select at least one item.';
   if (confirmMsg == null)
       confirmMsg = 'Are you sure to delete the select items?'
   if (GetSelect(divId, chkPrefix, isChecked) == '') { MsgBox(atLeastMsg, 'Information', true, divBgId); return; } 
   Confirm(confirmMsg,'Information',true,divBgId,'CallAjaxForDelSel(\''+Url+'\','+type+',\''+chkPrefix+'\',\''+callBackParaName+'\',\''+divId+'\',\''+divBgId+'\',\''+divParId+'\',\''+inputPrefix+'\',\''+parAppend+'\',\''+dType+'\',\''+jsFunc+'\','+isChecked+')');
}
function ConfirmAndDelSelCss(content,title,Url,type,chkPrefix,callBackParaName,divId,divBgId,divParId,inputPrefix,parAppend,dType,jsFunc,isChecked)
{
   if(GetSelect(divId,chkPrefix,isChecked)==''){ MsgBox('You must select at least one item!','Information',true,divId);return;} 
   Confirm(content,title,true,divBgId,'CallAjaxForDelSel(\''+Url+'\','+type+',\''+chkPrefix+'\',\''+callBackParaName+'\',\''+divId+'\',\''+divBgId+'\',\''+divParId+'\',\''+inputPrefix+'\',\''+parAppend+'\',\''+dType+'\',\''+jsFunc+'\','+isChecked+')','btn7','btn4');
}
function ValidateTxt(dvForm)
{
    var success=true;
    $('input:text',"#"+dvForm).each(function (i){
        this.className="txt";
        if(isRequired(this) && this.style.display!='none')
        {
            if(this.value.replace(/(^\s*)|(\s*$)/g, "")==""){this.className="txtrq";success=false;}
        }});
    return success;
}
function ValidateTxtAndSel(dvForm)
{
    var success=true;
    success=ValidateTxt(dvForm)&&ValidateSel(dvForm);    
    return success;
}
function ValidateSel(dvForm)
{
   var success=true;
    $('select',"#"+dvForm).each(function (i){
        this.className="sel";
        if(isRequired(this))
        {
            if(this.value==""){this.className="select_rq";success=false;}
        }});
    return success;
}
function ValidateTextareaLenghth(dvForm,maxlength)
{
    var success=true;
    maxlength=maxlength=null?500:maxlength;
    $('textarea',"#"+dvForm).each(function (i){
        this.className='txt';
        if(this.value.length>maxlength)
        {
            success=false;
            this.className="txtrq";
        }
    });
    return success;
}
function ValidateTxtAndAreaAndSel(dvForm){
    var success=true;
    success=ValidateTxt(dvForm)&&ValidateTxtArea(dvForm)&&ValidateSel(dvForm);    
    return success;    
}
function ValidateTxtArea(dvForm){
    var success=true;
    $('textArea',"#"+dvForm).each(function (i){
        this.className="txt";
        if(isRequired(this) && this.style.display!='none')
        {
            if(this.value==""){this.className="txtrq";success=false;}
        }});
    return success;    
}
function SelectAll(chkObj,chkPrefix,divID)
{
    var chks;
    if(IsEmpty(divID))
       chks=$('input:checkbox');
    else
       chks=$('input:checkbox','#'+divID)           
    chks.each(function(i){
    if(IsEmpty(chkPrefix)||this.id.indexOf(chkPrefix,0)>-1)
        {
            this.checked=chkObj.checked;
        }
    });     
}

function GetSelect(divId,chkPrefix,isChecked,separator)
{
    var sel="";
    if(IsEmpty(isChecked)) isChecked=true;
    var chks;
    if(IsEmpty(divId))
       chks=$('input:checkbox');
    else
       chks=$('input:checkbox','#'+divId)          
    chks.each(function(i){
        if(this.checked==isChecked) {
           if(IsEmpty(chkPrefix)||(!IsEmpty(chkPrefix)&&this.id.indexOf(chkPrefix,0)>-1))
           {
              sel+=this.value+(separator==null? ",":separator);
           }
        }
    });
    var l = separator == null ? sel.length - 1 : sel.length - separator.length;
    sel=sel.substr(0,l);
    return encodeURIComponent(sel);
}

function AjaxMsg(title,width,height,serUrl,page,sId,func)
{
    var f=func;
    if(f==null)f=EndRequestAndValidate;
    MsgAjax(title,width,height,serUrl,page,sId,f);
}

function GetTextAreaPara(dvId,prefix)
{
    var params='';
    $('textarea[id^="'+prefix+'"]','#'+dvId).each(function (){
        params += "&" + this.id + "=" + encodeURIComponent(this.value);
    });
    return params;
}

/*usage:
<input id="txtDep" class="txt" style="width: 80px;" value='' type="text" maxlength="12" months='2' maxdate='10/12/2010' mindate='+1m'/>
<span id="cal-dep" class="imgCal">&nbsp;</span>
new RegDateControl('txtRet', "cal-ret", AirSchDate, true, 2, '+0d','err-tip',true);
remark:
if DateControljQuery numberOfMonths,minDate,maxDate not equal null,the parameter priority will higer than the control attribute
*/
function DateControljQuery(sId, butId, onchange, allowEmpty, left, top, error_lb, isAddErrCss,minDate, maxDate,numberOfMonths) {
    var lang=(typeof(LangType)=='undefined')? "en-us":LangType;
    RegJs(SerUrl+"js/jquery/jquery.ui.datepicker-"+lang+".js");
    var lid=null;
    var oj = o(sId);
    if (oj == null) { alert('Miss the "' + sId + '"'); return; }
    var errMsg = "Invalid date format";
    if (oj.attributes["errmsg"] != null) { errMsg = oj.attributes["errmsg"].value; }
    if (oj.attributes["lid"] != null) { lid = oj.attributes["lid"].value; }
    
    if (IsEmpty(numberOfMonths)) {
        if (!IsEmpty($(oj).attr("months")))
            numberOfMonths = $(oj).attr("months");
        else
            numberOfMonths = 1;
    }
    if (IsEmpty(maxDate)) {
        if (!IsEmpty($(oj).attr("maxdate")))
            maxDate = $(oj).attr("maxdate");
        else
            maxDate = null;
    }
    else
    {
        if(!TestType(maxDate,'date'))
        {
            if(ValidateDate(maxDate)){
                maxDate=ConvertDate(maxDate);
            }
        }    
    }
    if (IsEmpty(minDate)) {
        if (!IsEmpty($(oj).attr("mindate")))
            minDate = $(oj).attr("mindate");
        else
            minDate = null;
    }
    else
    {
        if(!TestType(minDate,'date'))
        {
            if(ValidateDate(minDate)){
                minDate=ConvertDate(minDate);
            }
        }    
    }
    var showAnim=null;
    var animDuration;
    if($.browser.msie)
    {
        if($.browser.version=='6.0')
        {
            showAnim=null;
            animDuration=100;
        }
        else
        {
            showAnim=null;
            animDuration=0;
        }
    }
    else
    {
        showAnim=null;
        animDuration=300;
    }
    
    //if (oj.attributes["errmsg"] != null) { errMsg = $(oj).attr("errmsg").value; }
    $(oj).datepicker({
        buttonId: butId,
        showOn: 'button',
        buttonImageOnly: true,
        buttonText: 'Date',
        dateFormat: 'dd/mm/yy',
        showButtonPanel: false,
        showAnim: showAnim,
        duration: animDuration,
        changeYear: true,
        changeMonth: true,
        numberOfMonths: numberOfMonths,
        maxDate: maxDate,
        minDate: minDate,
        yearRange: 'c-5:c+5',
        showButtonPanel:false
    });
    var lv = oj.value;
    oj.onfocus = "";
    oj.onblur = "";
    oj.onchange = function() { if (formatDate(oj, allowEmpty)) { if (isAddErrCss && error_lb!=null) { oj.className = 'txt'; o(error_lb).innerHTML = ''; } if (onchange != null && oj.value != "") { onchange(sId); } } else { if (isAddErrCss) { oj.className = 'txtrq'; } inputErr(); } };

    function inputErr() {
        if (error_lb == null)
            Error(errMsg,lid);
        else
            o(error_lb).innerHTML = errMsg;
        oj.value = lv;
    }
    return $(oj);
}
$.aws = function(url, dm, fs) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: url,
        data: typeof dm=='string'?dm:o2s(dm),
        dataType: "json",
        success: fs
    });
}
function FixReportViewer()
{
    $('table').each(function(){if(this.id.indexOf('ReportViewer')>0){if(this.title=='Refresh'){$(this).parent().css({"display":"none"});}}});
}