/* 
 * common.js
 * author sin .
 * 
 */

DWIN={};
DWIN.confirm = false;
DWIN.zIndex = 1000;
DAJAX=[];
BROWSER = {}
BROWSER.ie= navigator.userAgent.toLowerCase().indexOf('msie')!='-1' ;
BROWSER.is_ie6 = $.browser.msie && ($.browser.version == "6.0") && !$.support.style ; 
BROWSER.opera = navigator.userAgent.toLowerCase().indexOf('presto')!='-1' ;
function $Id(id){
    return document.getElementById(id);
}

function sethtml(id,html){
    $Id(id).innerHTML = html;
    return $Id(id);
}

function isset(variable) {
	return typeof variable == 'undefined' ? false : true;
}

function in_array(needle, haystack) {
	if(typeof needle == 'string' || typeof needle == 'number') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}

function empty(variable){
        return typeof variable == 'undefined' || variable==null || variable=='' || !variable ? true : false;
}

function trim(str) {
	return (str + '').replace(/(^[\s　]+)|([\s　]+$)/g, '') ;
}

function strlen(str) {
	return (Browser.Engine.trident && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}

function mb_strlen(str,charset) {
	var len = 0;
        if(typeof charset=='undefined') charset = 'UTF-8';
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'UTF-8' ? 3 : 2) : 1;
	}
	return len;
}

function mb_cutstr(str, maxlen, dot, charset) {
	var len = 0;
	var rst = '';
        if(typeof charset=='undefined') charset = 'UTF-8';
	dot = typeof dot=='undefined' || !dot ? '...' : '';
	maxlen = maxlen - dot.length;
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'UTF-8' ? 3 : 2) : 1;
		if(len > maxlen) {
			rst += dot;
			break;
		}
		rst += str.substr(i, 1);
	}
	return rst;
}

function createCookie(name,value,days) {
        var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function doane(event) {
	e = event ? event : window.event;
	if(!e) e = getEvent();
	if(BROWSER.ie) {
		e.returnValue = false;
		e.cancelBubble = true;
	} else if(e) {
		e.stopPropagation();
		e.preventDefault();
	}
}

function stop_pop(event){
        e = event ? event : window.event;
        if(!e) e = getEvent();
        if(BROWSER.ie) {
            e.cancelBubble = true;
        } else if(e) {
            e.stopPropagation();
        }
}

function attach_event(obj, evt, func, eventobj) {
	eventobj = !eventobj ? obj : eventobj;
	if(obj.addEventListener) {
		obj.addEventListener(evt, func, false);
	} else if(eventobj.attachEvent) {
		obj.attachEvent('on' + evt, func);
	}
}

function detach_event(obj, evt, func, eventobj) {
	eventobj = !eventobj ? obj : eventobj;
	if(obj.removeEventListener) {
		obj.removeEventListener(evt, func, false);
	} else if(eventobj.detachEvent) {
		obj.detachEvent('on' + evt, func);
	}
}

function getEvent() {
    if(document.all) return window.event;
	func = getEvent.caller;
	while(func != null) {
		var arg0 = func.arguments[0];
		if (arg0) {
			if((arg0.constructor  == Event || arg0.constructor == MouseEvent) || (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
				return arg0;
			}
		}
		func=func.caller;
	}
	return null;
}


function remove_dom(domEl, callback){
        callback = callback || function(){} ;
        $(domEl).animate({
            opacity:0, height:0
        }, {duration:700, queue:true, complete:function(){$(domEl).remove();callback();}}) ;
}

function remove_doms(arr, i, callback){
    callback = callback || function(){} ;
    if(i<arr.length){
         $(arr[i]).animate({
            opacity:0, height:0
        }, {duration:700, queue:true, complete:function(){
                $(arr[i]).remove();
                if( i<arr.length-1 ) {
                    remove_doms(arr, i+1, callback);
                }else{
                    callback();
                }
            }}) ;
    }
}

function show_dom(domEl, callback){
        callback = callback || function(){};
        $(domEl).css('opacity', 0);
        $(domEl).slideDown(800, function(){
            $(domEl).animate({
                opacity:1
            }, {duration:600, queue:true, complete:function(){$(domEl).show();callback();}}) ;
        });
}

function show_doms(arr, everycall, callback){
    everycall = everycall || function(){};
    callback = callback || function(){} ;
    var length = arr.length ;
    var _show = function(len){
        if(len>=0){
            arr.eq(len).css('opacity', 0);
            arr.eq(len).slideDown(800, function(){
                arr.eq(len).animate({
                    opacity:1
                }, {
                    duration:600,
                    queue:true,
                    complete:function(){
                        everycall();
                        arr.eq(len).show();
                        if(len>0) {
                            _show(len-1);
                        }else{
                            callback();
                        }
                    }
                }) ;
            });
        }
    };
    _show(length-1);

}

function tmpl(id, data){
    var str = $Id(id).innerHTML;
    return str.replace(/\$\[(\w+)\]/g,  function(m,i){
        return isset(data[i]) ? data[i] : '';
    });
}

function utf8_decode ( str_data ) {
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    
    return tmp_arr.join('');
}

function base64_decode (data) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }
    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);

    return dec;
}

function base64_encode (data) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = this.utf8_encode(data+'');

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}


function refresh(t){
    setTimeout(function(){
        location.reload();
    }, t*1000);
}


function show_win(opts){
    var options = {};
    var defaults = {
        mode : 'url',
        cache : true,
        closeIcon : true,
        title: '',
        showTitle: false,
        drag: false,
        pos: null,
        closeall: false,
        blank:false,
        remove:true,
        modal: false,
        loading: '<div class="ajax-get">\u6B63\u5728\u52A0\u8F7D...</div>',
        foot: false
    };
    $.extend(options ,defaults, opts);
    var winid = 'dwin_'+options.id ;
    var contid = winid+'_content' ;
    var dtitid = winid+ '_title';
    var dwin = $('#'+winid) ;
    var iframeid = 'ifame_'+options.id ;
    var fetch = false;
    var dcont = null ;
    var is_ie6 = BROWSER.is_ie6  ;
    if(options.closeall){
        $('.dwin').css('display','none');
    }
    if(options.modal){
        $('.dwin').hide();
    }
    var foot =options.foot ?  '<div class="dmsg_ft"><span onclick="hide_win(\''+options.id+'\');">Close</span></div>' : '' ;
    if( !$Id(winid) ) {
        var wrap =!options.blank ? ['<table class="dtable" cellspacing="0" cellpadding="0">' ,
        '<tr><td class="dt_l"></td><td class="dt_c"></td><td class="dt_r"></td></tr>',
        '<tr><td class="dm_l"></td><td class="dm_c"><div class="dwin_inner"><h3 class="dwin_title"><em id="'+dtitid+'"></em><span>',
        (options.closeIcon ? '<a title="Close" onclick="hide_win(\''+options.id+'\')" class="dclose" href="javascript:;">X</a>' : '') + '</span></h3>',
        '<div class="dwin_content" id="'+contid+'"></div>'+foot+'</div></td><td class="dm_r"></td></tr>',
        '<tr><td class="db_l"></td><td class="db_c"></td><td class="db_r"></td></tr></table>'].join('') :
        [options.showTitle ? '<h3 class="dwin-title"><em id="'+dtitid+'"></em><span>'+(options.closeIcon ? '<a title="Close" onclick="hide_win(\''+options.id+'\')" class="dclose" href="javascript:;">X</a>' : '')+'</span></h3>' : '',
        '<div class="dw-in" id="'+contid+'">'+'</div>'].join('');
        dwin = $('<div id="'+winid+'" class="dwin'+(options.style ? ' '+options.style : '')+(options.blank ? ' dwinb' : '')+'">' +wrap+(is_ie6 ? '<iframe id="'+iframeid+'" style="position:absolute;left:0; top:0;z-index:-1;width:100%;height:100%;filter:alpha(opacity=0);"></iframe>' : '')+'</div>').appendTo('#append_parent');
        fetch = true;
    } else {
        dwin.css('display', 'block');
        if(!options.cache){
            fetch = true;
        }
    }
    var dtit = $('#'+dtitid);
    dwin.css('z-index',DWIN.zIndex);
    DWIN.zIndex++;
    if(options.drag){
        dwin.css('cursor', 'move');
    //dwin.makeDraggable();
    }
    dcont = $('#'+contid);
    if(options.modal){
        var mid = 'dwin-modal' ;
        if(!$Id(mid)){
            $('<div class="dmask" id="'+mid+'"></div>').css({width:$(document).width(), height:$(document).height()}).appendTo('#append_parent');
        }
        $('#'+mid).css('opacity',0.5).height($(document).height()).show();
    }
    var set_position = function(pos){
        if(is_ie6){
            dwin.css({
                'position' : 'absolute'
            });
            $Id(iframeid).style.width = dwin.width() +'px';
            $Id(iframeid).style.height = dwin.height() + 'px';
        }else{
            dwin.css({
                'position' : 'fixed'
            });
        }
        if(pos!=null){
            dwin.css({
                'position':'absolute',
                'left':pos.x,
                'top': pos.y
                });
        }else{
            var boxLeft = Math.floor($(window).width()  - dwin.width() ) /2 ;
            var boxTop = Math.floor($(window).height()  - dwin.height() ) /2 ;
            if(isset(dwin.css('position')) && dwin.css('position').toLowerCase() =='absolute'){
                boxLeft += $(window).scrollLeft() ;
                boxTop += $(window).scrollTop();
            }
            dwin.css({
                left:boxLeft,
                top:boxTop
            });
        }
    };
    var fetch_content = function(){
        if(options.mode=='html') {
            dtit.html( options.title);
            dcont.html(options.url) ;
        }else if(options.mode=='inner'){
            dtit.html(options.title);
            var html = $('#'+options.url).html();
            if(options.remove){
                $('#'+options.url).html('');
            }
            dcont.html(html) ;
        }else if(options.mode=='url') {
            if(!options.blank){
                dtit.html('<b class="dloading">Loading....</b>');
                dcont.html('');
            }else{
                dcont.html(options.loading);
            }
            $.ajax({
                url:options.url,
                cache:false,
                type:'get',
                dataType:'html',
                success: function(rs){
                    if($(rs).filter('script.err-script').length>0){
                        hide_win(options.id);
                        $('#append_parent').append(rs);
                    }else{
                        dtit.html(options.title);
                        dcont.html(rs);
                        set_position(options.pos);
                    }
                },
                error:function(){
                    dtit.html('Error');
                    dcont.html('<div class="dmsg"><div class="dmsg_in d_error">Load Error, Please Refresh !</div></div>');
                }
            });
        }
    };

    if(fetch) {
        fetch_content();
    }
    set_position(options.pos);
}

function is_win(id){
    return $Id('dwin_'+id) ? true : false  ;
}

function set_win_title(id, title){
    $Id('dwin_'+id+'_title').innerHTML = title;
}

function hide_win(id, unload){
    if(!isset(unload)) unload = false;
    var w = null;
    if(isset(id)){
        w = $('#dwin_' + id);
    }else {
        w = $('.dwin');
    }
    if(w && w.length>0){
        w.css('display', 'none');
        if(unload){
            w.remove() ;
        }
    }
    if($Id('dwin-modal')){
        $('#dwin-modal').hide();
    }
}


function show_msg(opts){
    var options = {} ;
    var defaults = {
        id : 'default_msg',
        title : _G.LANG=='zh' ? '\u63D0\u793A\u4FE1\u606F' : 'Notice',
        pos: null ,
        type : 'info',  // ['info', 'right', 'error','loading']
        cache: false,
        time : 0
    };
    $.extend(options , defaults, typeof  opts=='string' ? {
        msg:opts
    } : opts);
    var html = '<div class="dmsg"><table><tr><td class="dmsg_in d_'+options.type+'">' +options.msg.replace(/\n/g, '<br />')+ '</td></tr></table></div>'+
    '<div class="dmsg_ft"><span onclick="hide_win(\''+options.id+'\');">'+(_G.LANG=='zh' ? '\u5173 \u95ED':'Close')+'</span></div>' ;
    show_win({
        id:options.id,
        title: options.title,
        style: 'dmsg_win',
        url: html,
        mode: 'html',
        cache: options.cache,
        drag:false,
        pos: options.pos
    });
    if(options.time>0)
    {
        setTimeout(function(){
            hide_win(options.id);
        }, options.time);
    }
}


function hide_msg(id){
    if(!isset(id)){
        id = 'default_msg';
    }
    hide_win(id);
}

function pop_point(msg){
    var top = 120;
    var top_show = '+=80px';
    var top_hide = '-=80px';
    var is_ie6 = $.browser.msie && ($.browser.version == "6.0") && !$.support.style  ;
    var p_win = $('#kc_pop_tip');
    if( p_win.length<=0 ){
        var html = ['<div class="pop_tip" id="kc_pop_tip">',
        '<table cellpadding="0" cellspacing="0"><tbody>',
        '<tr><td class="pp_l">&nbsp;</td><td class="pp_c">',
        '<div id="kc_pop_tip_inner" class="pp_inner"></div></td>',
        '<td class="pp_r">&nbsp;</td></tr></tbody></table>',
        '</div>'].join('');
        p_win = $(html).appendTo('#append_parent');
        p_win.find('#kc_pop_tip_inner').html(msg);
        if(is_ie6){
            p_win.css({
                'position' : 'absolute'
            });
        }else{
            p_win.css({
                'position' : 'fixed'
            });
        }
        var boxLeft = Math.floor($(window).width()  - p_win.width() ) /2 ;
        var boxTop = top ;
        if(typeof p_win.css('position') !='undefined' && p_win.css('position').toLowerCase() =='absolute'){
            boxLeft += $(window).scrollLeft() ;
            boxTop += $(window).scrollTop();
        }
        p_win.css({
            left : boxLeft,
            top : boxTop  - 80,
            opacity : 0
        });
        
    }else if(p_win.css('opacity')==1){
        return ;
    }else{
        p_win.find('#kc_pop_tip_inner').html(msg);
    }
    p_win.animate({
        top:top_show,
        opacity:1
    }, 200, function(){
        setTimeout(function(){
            p_win.animate({
                top: top_hide,
                opacity:0
            }, 200,'linear') ;
        },3000);
    }) ;
}



function ajaxpost(opt){
    var form_action = $Id(opt.formid).action;
    if(!form_action || form_action=='') form_action = location.href;
    var btn = isset(opt.submitobj) ? $(opt.submitobj) : ( isset(opt.submitid) ? $('#'+opt.submitid) : null );
    var msgbox = isset(opt.msgid) && $Id(opt.msgid) ? $Id(opt.msgid) : null;
    var msg = ['正在请求...', '正在跳转...' , '<b class="err">错误，请重试...</b>'];
    var data = isset(opt.data) ? opt.data : $('#'+opt.formid).serialize() ;
    var disabledClass = isset(opt.disabledClass) ? opt.disabledClass : 'disabled-btn';
    if(isset(opt.callbefore) && opt.callbefore){
        if(typeof callbefore == 'function') {
            opt.callbefore();
        } else {
            eval(opt.callbefore);
        }
    }
    if(msgbox){
        msgbox.className='d_i_loading';
        msgbox.innerHTML = msg[0];
    }else{
        tip_loading();
    }
    if(btn && btn.length>0){
        disable_button(btn, true, disabledClass);
    }
    $.ajax({
        url:form_action,
        cache:false,
        data: data,
        type:'POST',
        dataType: 'json',
        success:function(rs){
            tip_loading('hide');
            var json =  rs ;
            if (isset(opt.callback)) {
                    if (typeof opt.callback == 'function') {
                                opt.callback(json);
                     } else {
                                eval(opt.callback);
                     }
            }
            if(msgbox){
                msgbox.className='';
                msgbox.innerHTML = '';
            }
            if(json.m!=''){
                var jm = isset(opt.time) ? msg[1] : '';
                if(json.s==1){
                        if(msgbox){
                            msgbox.innerHTML =json.m +' '+ jm;
                            msgbox.className = 'd_i_right';
                        }else{
                            if(isset(opt.time)){
                                show_msg({
                                    msg:json.m+'<br />'+jm,
                                    type:'done',
                                    time: opt.time
                                    });
                            }else{
                                show_msg({
                                    msg:json.m+'<br />'+jm,
                                    type:'done'
                                });
                            }
                        }
                        if(isset(opt.time)){
                            setTimeout(function(){
                                if(isset(json.url)){
                                    location.href=json.url;
                                } else if($Id('redirect_url') && $Id('redirect_url').innerHTML!=''){
                                    location.href=$Id('redirect_url').innerHTML ;
                                }else{
                                    location.reload();
                                }
                            },opt.time);
                        }

                    }else{
                        if(msgbox){
                            msgbox.innerHTML =json.m;
                            msgbox.className = json.s==2 ? 'd_i_warn' :  'd_i_error';
                        }else{
                            if(json.s==2){ // contain warning
                                show_msg({msg:'<b class="wrn">'+json.m+'</b>', type:'warn'});
                            }else{
                                show_msg({msg:'<b class="err">'+json.m+'</b>', type:'error'});
                            }
                        }
                    }
            }
          if(btn && btn.length>0){
             disable_button(btn, false, disabledClass); // enable buttons 
          }
        },
        error:function(){
            tip_loading('hide');
            if(msgbox){
                msgbox.innerHTML =msg[2];
                msgbox.className = 'd_i_error';
            }else{
                if(isset(opt.time)){show_msg({msg:msg[2], time: opt.time, type:'error'});}
                else{show_msg({msg:msg[2], type:'error'});}
            }
            
            if(btn && btn.length>0){
                disable_button(btn, false, disabledClass);
            }
        }
    });
    return false;
}


function ajaxget(id, url, data, callback){
    $(id).html('<div class="ajax-get">正在加载...</div>');
    $.get(_CONFIG.base_url+url, data || {}, function(rsp){
       $(id).html(rsp);
       if(typeof callback=='function'){
           callback(rsp);
       }
    }, 'html') ;
}

function get_file_name(path){
    var pos1 = path.lastIndexOf('/');
    var pos2 = path.lastIndexOf('\\');
    var pos  = Math.max(pos1, pos2)
    if( pos<0 )
        return path;
    else
        return path.substring(pos+1);
}


function upload_attach(uploadid, formid, btnid, form_ac, callback){
        $Id(uploadid).style.display='';
        var form = $Id(formid);
        var form_action = form.action;
        var form_target  = form.target ;
        var form_enctype = form.enctype ;
        var form_encoding = form.encoding ;
        var form_action_m = form_ac!='' ? form_ac : form_action;
        var iframeid = 'iframe_'+formid ;
        var iframe = $Id(iframeid);
        var n = navigator.userAgent.toLowerCase() ;
        var is_ie = n.indexOf('msie')!='-1' ;

        var handleResult = function() {

            var rsp = '';
            try {
                rsp = $Id(iframeid).contentWindow.document.body.innerHTML;
            } catch(e) {
                rsp = '内部错误！';
            }
            var json = eval('('+rsp+')');
            if(form){
                form.target = form_target;
                form.action = form_action ;
                form.enctype = form_enctype ;
                form.encoding = form_encoding ;
            }
            
            if(typeof callback == 'function') {
                callback(json);
            } else {
                eval(callback);
            }
            iframe.loading = 0;
            detach_event(iframe, 'load', handleResult, iframe);
            $Id(uploadid).style.display = 'none';
            $Id(btnid).disabled = false;
            $Id(btnid).value = '';
            if(BROWSER.ie || BROWSER.opera){
                $Id(btnid).outerHTML += '' ;
            }
            //$Id('append_parent').removeChild(iframe); // don't need to unload
        };
        if(!iframe) {
            if ( is_ie ) {
                iframe = document.createElement('<iframe name="' + iframeid + '" id="' + iframeid + '"></iframe>');
            } else {
                iframe = document.createElement('iframe');
                iframe.name = iframeid;
                iframe.id = iframeid;
            }
            iframe.style.display = 'none';
            iframe.loading = 1;
            $Id('append_parent').appendChild(iframe);
        } else if(iframe.loading) {
            return false;
        }
        if(form_action_m.indexOf('?')!=-1){
            form_action_m +='&is_frame=1&file='+btnid;
        }else{
            form_action_m +='?is_frame=1&file='+btnid;
        }
        form.action = form_action_m ;
        form.target = iframeid ;
        form.enctype = 'multipart/form-data' ;
        form.encoding = 'multipart/form-data' ;
        form.submit();
        $Id(btnid).disabled = true;
        attach_event(iframe, 'load', handleResult);
        doane();
        return false;
}


function menu_drop(menuId, display)
{
    $Id(menuId).style.display=display;
}


function ajaxdo(opt){
    if(!isset(opt.theadId)) opt.threadId = opt.msgid;
    if(isset(DAJAX[opt.threadId]) && DAJAX[opt.threadId]==true){
        return ;
    }
    DAJAX[opt.threadId] = true;
    if(!isset(opt.disableClass)) opt.disableClass='lbtn-dis';
    if(isset(opt.btnids)){
        $(opt.btnids).addClass(opt.disableClass) ;
    }
    if(!isset(opt.msgid)){
        tip_loading('show');
    }else{
        $(opt.msgid).addClass('loading').html('正在请求').show();
    }
    if(!isset(opt.url)) opt.url= location.href;
    $.ajax({
        url:opt.url,
        cache:false,
        data: isset(opt.data) ? opt.data : {},
        type:'POST',
        dataType: 'json',
        success:function(rs){
            if(!isset(opt.msgid)){
                tip_loading('hide');
            }else{
                $(opt.msgid).html('') ;
                $(opt.msgid).removeClass('loading');
                if(isset(rs.s) && rs.s==0 && isset(rs.m) && rs.m!=''){
                    $(opt.msgid).html(rs.m) ;
                }
            }
            if (isset(opt.callback)) {
                    if (typeof opt.callback == 'function') {
                                opt.callback(rs);
                     } else {
                                eval(opt.callback);
                     }
            }
        },
        complete:function(){
            DAJAX[opt.threadId] = false;
            if(isset(opt.btnids)){
                $(opt.btnids).removeClass(opt.disableClass) ;
            }
        },
        error:function(){
            if(isset(opt.msgid)){
                 $(opt.msgid).removeClass('loading').html('请求错误，请重试').show();
            }else{
                tip_loading('hide');
                show_msg('请求错误，请重试');
            }
        }
    });
}


function tip_loading(type){
    if(!isset(type)) type = 'show';
    var tip = $('#kc_tip_loading') ;
    if(!tip || tip.length<=0){
        tip = $('<div id="kc_tip_loading" class="tip_loading">正在请求，请稍后...</div>').appendTo('#append_parent');
       // tip.css('opacity', 0);
    }else if(type=='show' && tip.css('opacity')==1){
        return ;
    }
    if(type!='show'){
        tip.css('opactiy', 0);
        tip.hide();
    }else{
        tip.show();
    }
    var top = 50 ;
    var top_show = '+=50px';
    var top_hide = '-=50px';
    var is_ie6 = $.browser.msie && ($.browser.version == "6.0") && !$.support.style ;
    
    if(is_ie6){
        tip.css({
            position:'absolute',
            left: ($(window).width() + $(window).scrollLeft() - tip.width())/2,
            top: $(window).scrollTop() + top
        });
    }else{
        tip.css({
            position : 'fixed',
            left: ($(window).width() - tip.width())/2,
            top : top
        });
    }
    if(type=='show'){
        tip.animate({
            opacity:1
        }, {duration:200, queue:true}) ;
    }else{
        tip.animate({
            opacity:0
        }, {duration:200, queue:true, complete:function(){tip.hide();}}) ;
    }
}


/**
 * toggle user nav bar
 *
 **/
function toggle_folder(o){
    if($(o).hasClass('opened')){
        $(o).removeClass('opened').addClass('closed');
        $(o).find('b').removeClass('close').addClass('open') ;
    }else{
        $(o).removeClass('closed').addClass('opened');
        $(o).find('b').removeClass('open').addClass('close') ;
    }
    $(o).siblings('ul').slideToggle(600);
}


// implement JSON.stringify serialization
function json_stringify(obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"'+obj+'"';
		return String(obj);
	}
	else {
		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n];t = typeof(v);
			if (t == "string") v = '"'+v+'"';
			else if (t == "object" && v !== null) v = json_stringify(v);
			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
}

function toggle_check_all(o){
    $('input:checkbox[name="check_ids[]"]').attr('checked',o.checked ? true : false);
    reset_button('.xdobtn');
}

function if_check_all(){
    if($('input:checkbox[name="check_ids[]"]').length==$('input:checkbox[name="check_ids[]"][checked]').length){
        $('.chkall').attr('checked',true);
    }else{
        $('.chkall').attr('checked',false);
    }
    reset_button('.xdobtn');
}

function reset_button(cls){
    if($('input:checkbox[name="check_ids[]"][checked]').length>0){
        disable_button($(cls), false, 'lbtn-dis') ;
    }else{
        disable_button($(cls), true, 'lbtn-dis') ;
    }
}

function disable_button(jq, status, cls){
    if( true==status ){
        jq.attr('disabled', true).addClass(cls);
    }else{
        jq.attr('disabled', false).removeClass(cls);
    }
}

function set_xdo(x){
    $('#xdo').val(x);
    if($('input:checkbox[name="check_ids[]"][checked]').length<=0){
        alert('至少选择一条记录');
        return false;
    }else{
        return true;
    }
}

function post_do(obj, data){
    ajaxpost({
        formid:'post_frm',
        submitobj:obj,
        data:data,
        time:1000,
        disabledClass: 'lbtn-dis'
    });
}

function post_xdo(xdo, callback){
    if(set_xdo(xdo)){
        var ex = true;
        if(xdo=='delete'){
            if(!confirm("确认删除？一旦删除不可恢复！")) ex = false;
        }
        if(ex){
            if(!isset(callback)) callback = function(){};
            ajaxpost({
                formid:'post_frm',
                submitobj:'.xdobtn',
                time:1000,
                disabledClass: 'lbtn-dis',
                callback:function(rsp){callback(rsp);}
            });
        }
    }
}

function ajaxpage(id, url, page, data, callback){
    tip_loading();
    if(!isset(data)) data = {};
    data.page= page;
    data.ajaxpage =1 ;
    $.post(url, data, function(rsp){
        tip_loading('hide');
        $(id).html(rsp);
        if(isset(callback)){
            setTimeout(function(){
                callback(rsp);
            },20);
        }
    }, 'html') ;
}

function flush_code(obj, url){
    obj.src = url + '?_r=' + Math.random();
}

function msg_frm(ms, frm){
    var jElm = $(ms);
    var jEfrm = $(frm) ;
    if(jElm.hasClass('claps')){
        jElm.removeClass('claps');
        jEfrm.hide();
    }else{
        jElm.addClass('claps');
        jEfrm.show();
    }
}


