



function captchaUpdate(id,type){
    var newCaptcha = APPURL + 'captcha/captcha_' + type + '.png?' + Math.random();
    alert(newCaptcha);
    $('#' + id).attr('src', newCaptcha);
}


function msgRedirect(url, wait) {
    if (!url || url == 'halt') {
        return false;
    } else {
        waitting = typeof wait == 'undefined' || wait === null ? 3000 : wait;
        switch(url) {
            case 'reload':
                setTimeout("self.location.reload();", wait);
                break;
            case 'back':
                setTimeout('history.go(-1)', wait);
                break;
            default:
                setTimeout("location.href='" + url + "'", wait);
                break;
        }
    }
}

(function(jQuery){
    $.fn.altEven = function(style){
        style = style ? style : 'row-even';
        this.removeClass(style).each(function(i){
            if(i%2) $(this).addClass(style);
        });
    }
})(jQuery);

function showBox(opts, element) {
    var $targetBox;
    if(element && $(element).length){
        $targetBox = $(element).removeAttr('class').addClass('modal '+ opts.style);
        $('h3', $targetBox).html(opts.title);
	
        $('.msg', $targetBox).html(opts.message);
        $targetBox.overlay({
//                            onClose: msgRedirect(opts.url, opts.wait)
            }).load();
    //                        setTimeout(function() {
    //                           $targetBox.overlay().close();
    //                            }, 3000);
    } else {
        $targetBox = $('<div></div>').attr('id','_msgBox').addClass('modal '+ opts.style)
        .append('<div><h3>'+opts.title+'</h3><div class="msg">'+opts.message+'</div></div>').appendTo('body').overlay({
            top: '20%',
            mask: {
                color: '#000',
                opacity: 0.5
            },
            load: true,
            onClose: msgRedirect(opts.url, opts.wait),
            onLoad:function(){
                setTimeout(function() {
                    $targetBox.overlay().close();
                }, 3000);
            }
        });   
    }
}



/*
 * ajaxIt 快捷AJAX请求(POST/GET)
 */
(function(jQuery){
    $.fn.ajaxIt = function(options){
        options = options ? options : {};
        var defaults = {
            before: null,           // 提交前执行的函数
            form: false,	    // 是否为表单
            target: '',             // 目标位置，显示AJAX内容的位置, 如为空则使用overlay
            callback: null,	    // 执行成功后的CALLBACK 函数
            overlay: '',            // 是否使用overlay显示信息，使用后target无用
            wait: '#ajaxwaiting',   // 加载时显示loading...的位置
            loading: 'Loading...',  // Loading内容，可使用图片和HTML
            dataType: 'xml',	    // 数据格式，默认为XML
            timeout: 3000,	    // 超时时间
            type: 'application/x-www-form-urlencoded'
        };
        var $ajaxObj = this;
        var params = $.extend({}, defaults, options || {});
        if(params.form) {
            $ajaxObj.submit(function(){
                return false;
            });
            params.method = $ajaxObj.attr('method').toUpperCase() == 'POST' ? 'POST' : 'GET';
            params.url = $ajaxObj.attr('action');
            params.type = $ajaxObj.attr('enctype');
            //	    if(params.type != 'application/x-www-form-urlencoded') {
            //		params.processData = false;
            //	    } else {
            //		params.processData = true;
            //	    }
            params.data = $ajaxObj.formToArray();
	    
        } else {
            params.url = options.url ? options.url : $ajaxObj.attr('href');
            params.method = 'GET';
 
        }
        $.doAjax(params);
	
    };

    $.doAjax = function(params) {
        $.ajax({
            url: params.url,
            type: params.method,
            contentType: params.type,
            data: params.data,
            dataType: params.dataType,
            timeout: params.timeout,
            //	    processData:params.processData,
            beforeSend: function(XMLHttpRequest){
                if(params.wait){
                    $(params.wait).html(params.loading).fadeIn('normal');
                }
                if(typeof params.before == 'function') {
                    params.before();
                }
            },
            complete: function(XMLHttpRequest, textStatus){
                if(params.wait){
                    $(params.wait).fadeOut('normal', function(){
                        $(this).html('')
                    });
                }
            },
            success: function(xml) {
                // alert($('root', xml).text());
                // $xml 为哈希数组形式
                

                var $xml = {
                    title: $('root', xml).attr('title'),
                    style: $('root', xml).attr('style'),
                    url: $('root', xml).attr('url'),
                    wait: $('root', xml).attr('wait'),
                    message: $('root', xml).text()
                };
     
                if(params.target) {
                    if(params.target == "#message") {
                        $(params.target).attr('style', $xml.style).html($xml.message).fadeIn('normal', function(){
                            setTimeout(function(){
                                $(params.target).fadeOut('normal');
                            }, 3000)
                        });
                    } else {
       
                        $(params.target).html($xml.message);
                        
                        if($(".kindeditor").length > 0) {
                            var keArea= $(".kindeditor").attr("id");
                            KE.init(getEditorParams(keArea));
                            KE.create(keArea);
                        }
                    }
                } else {
                    showBox($xml, params.overlay);
                }
                
                if(typeof params.callback == 'function') {
                    params.callback();
                }
            },
            error: function(request, status, error){
            //	$(params.target).html('<em class="ajaxmsg error">Error loading XML document! [CODE:'+status +']</em>');
            }
        });
    }
})(jQuery);




/**
 * COOKIE 操作, JQUERY扩展
 * 写入cookie:  $.cookie('variable', 'value');
 * 读取cookie:  $.cookie('variable');
 * 删除cookie:  $.cookie('variabl', null);
 */
//jQuery.extend({
//    cookie: function(name, val, opts) {
//        // objValue，用来将任何数据结构的数据序列化后保存在cookie里
//        var objValue = {
//            _serialize : function (obj){
//                if (!obj) return obj;
//                var tmp;
//                if ($.isArray(obj)) {
//                    tmp = [];
//                    $.each(obj, function(i, n) {
//                        tmp.push(objValue._serialize(n));
//                    });
//                    return '[' + tmp.join(',') + ']';
//                } else if (typeof obj == 'object') {
//                    tmp = [];
//                    $.each(obj, function(i, n) {
//                        tmp.push(i + ':' + objValue._serialize(n));
//                    });
//                    return '{' + tmp.join(',') + '}';
//                } else if (typeof obj == 'string') {
//                    return '"' + obj.replace('\\', '\\\\').replace('"', '\\"') + '"';
//                } else {
//                    return obj;
//                }
//            },
//            _unserialize : function (str){
//                return eval('(' + str + ')');
//            }
//        }
//        if (typeof val != 'undefined') {
//            opts = opts || {};
//            if (val === null) {
//                opts.expires = -1;
//            } else {
//                val = objValue._serialize(val);
//            }
//            var setCookie = {
//                _date : function( duration ) {
//                    var date = new Date();
//                    // 86400000 = 24 * 60 * 60 * 1000, or 1 day
//                    date.setTime( date.getTime() + ( duration * 86400000 ) );
//                    return date.toGMTString();
//                },
//                set : function() {
//                    var line = name + '=' + encodeURIComponent(val) +
//                    ( opts.domain ? '; domain=' + opts.domain : '') +
//                    ( opts.path ? '; path=' + opts.path : '' ) +
//                    ( opts.expires ? '; expires=' + setCookie._date(opts.expires) : '' ) +
//                    ( opts.secure ? '; secure' : '' );
//                    return document.cookie = line;
//                }
//            };
//            return setCookie.set();
//        } else {
//            var search = document.cookie.match('(?:^|;)\\s*' + name.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1') + '=([^;]*)');
//            if(search){
//                var ret = decodeURIComponent(search[1]);
//                if (ret || typeof ret == "boolean") {
//                    try {
//                        return objValue._unserialize(ret);
//                    } catch (e) {
//                        return ret;
//                    }
//                }
//            }
//            return null;
//        }
//    }
//});


(function(jQuery){
    $.fn.scrollTo = function(options){
        var defaults = {
            ieFreshFix: true,
            anchorSmooth: true,
            anchortag: "anchor",
            animateTime: 1000
        };
        var sets = $.extend({}, defaults, options || {});
        //修复IE下刷新锚点失效的问题
        if(sets.ieFreshFix){
            var url = window.location.toString();
            var id = url.split("#")[1];
            if(id){
                var t = $("#"+id).offset().top;
                $(window).scrollTop(t);
            }
        }
        //点击锚点跳转
        $(this).each(function(){
            $(this).click(function(){
                var aim = $(this).attr(sets.anchortag).replace(/#/g,"");	//跳转对象id
                var pos = $("#"+aim).offset().top;
                if(sets.anchorSmooth){
                    //平滑
                    $("html,body").animate({
                        scrollTop: pos
                    }, sets.animateTime);
                }else{
                    $(window).scrollTop(pos);
                }
                return false;
            });
        });
    };
})(jQuery);


;
(function(jQuery){
    /**
     * 将表单中所有的数据转为JQuery的$.ajax中data参数可用的格式
     */
    $.fn.clearForm = function() {
        return this.each(function() {
            $('input,select,textarea', this).clearFields();
        });
    };

    /**
     * Clears the selected form elements.
     */
    $.fn.clearFields = $.fn.clearInputs = function() {
        return this.each(function() {
            var t = this.type, tag = this.tagName.toLowerCase();
            if (t == 'text' || t == 'password' || tag == 'textarea')
                this.value = '';
            else if (t == 'checkbox' || t == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = 0;
        });
    };
    //    $.fn.fieldValue = function(successful) {
    //	for (var val=[], i=0, max=this.length; i < max; i++) {
    //	    var el = this[i];
    //	    var v = $.fieldValue(el, successful);
    //	    if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
    //		continue;
    //	    v.constructor == Array ? $.merge(val, v) : val.push(v);
    //	}
    //	return val;
    //    };

    /**
     * Returns the value of the field element.
     */
    $.fieldValue = function(el, successful) {
        var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
        if (typeof successful == 'undefined') successful = true;

        if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
            (t == 'checkbox' || t == 'radio') && !el.checked ||
            (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
            tag == 'select' && el.selectedIndex == -1))
            return null;

        if (tag == 'select') {
            var index = el.selectedIndex;
            if (index < 0) return null;
            var a = [], ops = el.options;
            var one = (t == 'select-one');
            var max = (one ? index+1 : ops.length);
            for(var i=(one ? index : 0); i < max; i++) {
                var op = ops[i];
                if (op.selected) {
                    var v = op.value;
                    if (!v) // extra pain for IE...
                        v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                    if (one) return v;
                    a.push(v);
                }
            }
            return a;
        }
        return el.value;
    };
    $.fn.formToArray = function() {
        var a = [];
        if (this.length == 0) return a;
        var form = this[0];
        var els = form.elements;
        if (!els) return a;
        for(var i=0, max=els.length; i < max; i++) {
            var el = els[i];
            var n = el.name;
            if (!n) continue;

            var v = $.fieldValue(el, true);
            if (v && v.constructor == Array) {
                for(var j=0, jmax=v.length; j < jmax; j++)
                    a.push({
                        name: n,
                        value: v[j]
                    });
            }
            else if (v !== null && typeof v != 'undefined')
                a.push({
                    name: n,
                    value: v
                });
        }

        return a;
    };
})(jQuery);

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

;
(function(jQuery){

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( fx.state == 0 ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
            }

            fx.elem.style[attr] = "rgb(" + [
            Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
            Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
            Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0]
    };

})(jQuery);






jQuery.extend({
    /** * @see 将javascript数据类型转换为json字符串 * @param 待转换对象,支持object,array,string,function,number,boolean,regexp * @return 返回json字符串 */
    toJSON: function (object) {
        var type = typeof object;
        if ('object' == type) {
            if (Array == object.constructor) type = 'array';
            else if (RegExp == object.constructor) type = 'regexp';
            else type = 'object';
        }
        switch (type) {
            case 'undefined':
            case 'unknown':
                return;
                break;
            case 'function':
            case 'boolean':
            case 'regexp':
                return object.toString();
                break;
            case 'number':
                return isFinite(object) ? object.toString() : 'null';
                break;
            case 'string':
                return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function () {
                    var a = arguments[0];
                    return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : ""
                }) + '"';
                break;
            case 'object':
                if (object === null) return 'null';
                var results = [];
                for (var property in object) {
                    var value = jQuery.toJSON(object[property]);
                    if (value !== undefined) results.push(jQuery.toJSON(property) + ':' + value);
                }
                return '{' + results.join(',') + '}';
                break;
            case 'array':
                var results = [];
                for (var i = 0; i < object.length; i++) {
                    var value = jQuery.toJSON(object[i]);
                    if (value !== undefined) results.push(value);
                }
                return '[' + results.join(',') + ']';
                break;
        }
    }

});











/**
     * 建立简单的show/hide 标签
     */
function initItabs(elm, panes){
    if(panes == undefined) {
        $elm = $(elm).children();
        $panes = $(elm + '_pane').children();
    } else {
        $elm = $(elm);
        $panes = $(panes);
    }
   
    $elm.each(function(i){
        $(this).bind('click',function(){
            if(!$panes.eq(i).hasClass('open')) {
                $panes.removeClass('open').fadeOut(400);
                setTimeout(function(){
                    $panes.eq(i).addClass('open').fadeIn("slow");
                }, 500);
            }
        });
    });
}




