/**
 * Autonavi jQuery Plugins
 */

(function(jQuery) {
    var DEBUG = true;
    var MSG_LEVEL_ERROR = 3;
    var MSG_LEVEL_WARN = 2;
    var MSG_LEVEL_INFO = 1;
    var MSG_LEVEL_DEBUG = 0;

    var reURL = new RegExp([
        "^((https|http|ftp|rtsp|mms)?://)",
        // ftp的user@
        "?(([0-9a-z_!~*'().&amp;=+$%-]+: )?[0-9a-z_!~*'().&amp;=+$%-]+@)?",
        // IP形式的URL- 192.168.0.1
        "(([0-9]{1,3}\.){3}[0-9]{1,3}",
        // 允许IP和DOMAIN（域名）
        "|",
        // 域名- www.
        "([0-9a-z_!~*'()-]+\.)*",
        // 二级域名
        "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.",
        // first level domain- .com or .museum
        "[a-z]{2,6})",
        // 端口- :80
        "(:[0-9]{1,4})?",
        // a slash isn't required if there is no file name
        "((/?)|",
        "(/[0-9a-z_!~*'().;?:@&amp;=+$,%#-]+)+/?)$"].join(''));
    
    jQuery.isURL = function(url) {
        return reURL.test(url);
    };
    
    jQuery.namespace = function() {
        var o, d;
        jQuery.each(arguments, function(i, v) {
            d = v.split(".");
            o = window[d[0]] = window[d[0]] || {};
            jQuery.each(d.slice(1), function(i, v2) {
                o = o[v2] = o[v2] || {};
            });
        });
        return o;
    };
    jQuery.ns = jQuery.namespace;
    
    jQuery.mapChecker = function(h) {
        var handler = h || {mapId: 'mapper'};
        $('#loading-msg').html('正在初始化地图组件...');
        var counter = 0;
        function checker() {
            if (!window.MMap || !window.MMapOptions) {
                counter++;
                if (counter > 20) {
                    var msger = $('#loading-msg');
                    msger.html('地图组件初始化失败,请检查网络!');
                    msger.css('color','red');
                    return;
                }
                window.setTimeout(checker, 500);
            } else {
                jQuery.mapIniter(handler);
            } // End IF
        } // End checker function
        checker();
    };
    
    jQuery.mapIniter = function(h) {
        var mapoption = new MMapOptions();
        mapoption.zoom = h.zoom || 10;
        mapoption.center = new MLngLat(h.lng || 121.47311159362, h.lat || 31.233375874191);
        mapoption.toolbar = h.toolbar || DEFAULT;
        mapoption.toolbarPos = h.toolbarPos || {x:0, y:0};
        mapoption.overviewMap = h.overviewMap || DEFAULT;
        mapoption.returnCoordType = h.returnCoordType || COORD_TYPE_OFFSET;
        mapoption.isCongruence = true;
        mapoption.hasDefaultMenu = true;
        h[Config.MAPPER] = new MMap(h.mapId, mapoption);
        $('#loading-msg').html('地图初始化完毕,正在加载事件!');
    };
    jQuery.showRedHighlight = function(id) {
        $('#' + id).parent().append($('#' + id));
        // var offset = $('#' + id).find('img').offset();
        // var highlight = $('#redHighlight');
        // highlight.css('left', offset.left);
        // highlight.css('top', offset.top);
        // highlight.show();
    };
    jQuery.hideRedHighlight = function(id) {
        $('#redHighlight').hide();
    };
    jQuery.showBlueHighlight = function(id) {
        $('#' + id).parent().append($('#' + id));
        // var offset = $('#' + id).find('img').offset();
        // var highlight = $('#blueHighlight');
        // highlight.css('left', offset.left);
        // highlight.css('top', offset.top);
        // highlight.show();
    };
    jQuery.hideBlueHighlight = function(id) {
        $('#blueHighlight').hide();
    };
    jQuery.mapCenter = function(mapper, x, y) {
        mapper.setCenter(new MLngLat(x, y));
    };
    jQuery.mapZoomCenter = function(mapper, x, y, level) {
        mapper.setZoomAndCenter(level, new MLngLat(x, y));
    };
    jQuery.mapZoomin = function(mapper, lnglat) {
        mapper.zoomIn(lnglat);
    };
    jQuery.mapZoomout = function(mapper, lnglat) {
        mapper.zoomOut(lnglat);
    };
    jQuery.mapClear = function(mapper) {
        mapper.removeAllOverlays();
        mapper.setCurrentMouseTool(PAN_WHEELZOOM);
    };
    jQuery.mapPan = function(mapper) {
        mapper.setCurrentMouseTool(PAN_WHEELZOOM);
    };
    jQuery.mapZoom = function(mapper, level) {
        mapper.setZoomLevel(level);
    };
    jQuery.mapRuler = function(mapper) {
        mapper.setCurrentMouseTool(RULER, {hasCircle: true, hasPrompt: false});
    };
    jQuery.mapPoiHighlight = function(cssSelector) {
        $(cssSelector).mouseenter(function() {
            var poi = $(this);
            var id = 'poi_' + poi.attr('id').split('_')[1];
            $.showRedHighlight(id);
            poi.addClass('focus');
        }).mouseleave(function() {
            var poi = $(this);
            var id = 'poi_' + poi.attr('id').split('_')[1];
            $.hideRedHighlight(id);
            poi.removeClass('focus');
        }).click(function() {
            var id = 'poi_' + $(this).attr('id').split('_')[1];
            var marker = Config.getMapper().getOverlayById(id);
            if (marker) {
                $.mapCenter(Config.getMapper(), marker.lnglat.lngX, marker.lnglat.latY);
            }
        });
    };
    
    jQuery.getParent = function() {
        if (parent == window) return null;
        return parent;
    };
    
    jQuery.time = Date.now || function(){
        return +new Date;
    };
    
    jQuery.sort = function(ary, k) {
        ary.sort(function(a, b) {
            return a[k] - b[k];
        });
    };
    
    jQuery.formatUrl = function(url) {
        var result = [url];
        if ( url.indexOf('?') !== -1 ) {
            result.push('&');
        } else {
            result.push('?');
        }
        result.push('timesnap=');
        result.push(jQuery.time());
        result.push('&resType=json');
        return result.join('');
    };
    
    jQuery.debug = function(msg) {
        if (DEBUG && window.console) {
            console.debug(msg);
        }
    };
    jQuery.showMessage = function(type, msg, title) {
        alert(msg, title || '系统提示');
    };
    jQuery.showError = function(msg, title) {
        jQuery.showMessage(MSG_LEVEL_ERROR, msg, title);
    };
    
    
    /**
     * 获取对象的所有属性值
     * var obj = {firstName: 'Greco', lastName: 'Shi'};
     * $.getMapValues(obj); // "Greco,Shi"
     */
    jQuery.getMapValues = function(map) {
        var result = [];
        for (var v in map) {
            if ( map.hasOwnProperty(v) ) {
                result.push(map[v]);
            }
        }
        return result.join();
    };
    /**
     * 获取对象的所有属性名
     * var obj = {firstName: 'Greco', lastName: 'Shi'};
     * $.getMapValues(obj); // "firstName,lastName"
     */
    jQuery.getMapKeys = function(map) {
        var result = [];
        for (var v in map) {
            if ( map.hasOwnProperty(v) ) {
                result.push(v);
            }
        }
        return result.join();
    };
    
    jQuery.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure': '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    
	/*空值判断*/
	jQuery.isNull = function(elementId){
		//参数非空判断
		if (elementId==null||elementId==""){
			alert("isNull(elementId)的参数不能为空");
			return;
		}
		//对象有无判断	
		if (document.getElementById(elementId)== null){
			alert("缺少对象:"+elementId);
			return;
		}
			
		var element=document.getElementById(elementId);	
		if (element.value ==null||element.value ==""){
			element.focus();
			return true;
		}
		return false;
	}
    
	/*字符串去空格*/
	jQuery.Trim = function(s) {
		s = s.replace(/(^\s+)|(\s+$)/ig,"");
		s = s.replace(/\u3000+/g, " ");
		s = s.replace(/\s+/g," ");
		return s;
	}
    var waitings = [];
    jQuery.showWaiting = function(el, id) {
        var waiter;
        for(var i=0, w; w = waitings[i++];) {
            if ( !w.elid ) {
                waiter = w;
            }
        }
        if (!waiter) {
            waiter = $('<div class="waiting_panel"></div>');
            waitings.push(waiter);
            $('body').append(waiter);
        }
        var offset = el.offset();
        waiter.width(el.width());
        waiter.height(el.height());
        waiter.css('left', offset.left);
        waiter.css('top', offset.top);
        waiter.elid = id;
        waiter.show();
    };
    jQuery.hideWaiting = function(id) {
        for(var i=0, w; w = waitings[i++];) {
            if ( id === w.elid ) {
                w.hide();
                w.elid = null;
                return;
            }
        }
    };
    
    jQuery.request = function(o) {
        if (!o || !o.url) {
            jQuery.showError('Connection URL undefined, please contact administrator!', 'Error');
            return;
        }
        var scope = o.scope || this;
        jQuery.ajax({
            complete: function(request, status) {
                if ( status === 'error' || status === 'parsererror' ) {
                    jQuery.showError('结果返回错误，请联系管理员!');
                } else if ( status === 'timeout') {
                    jQuery.showError('连接超时,请检查网络!', '连接失败');
                }
                if (o.after) {
                    o.after.apply(scope);
                }
            },
            success: function(data, status, request) {
                if (o.success) {
                    o.success.apply(scope, [data]);
                }
                //if (o.failure) {
                //    o.failure.apply(scope);
                //}
            },
            url: jQuery.formatUrl(o.url),   // [*]request
            type: o.method || 'POST',
            data: o.params,
            dataType: o.dataType || 'json'
        });
    };
    
    jQuery._uuid_default_prefix = '';
    jQuery._uuidlet = function() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    /*
        Generates random uuid
      */
    jQuery.uuid = function(p) {
        if (typeof(p) == 'object' && typeof(p.prefix) == 'string') {
            jQuery._uuid_default_prefix = p.prefix;
        } else {
            p = p || jQuery._uuid_default_prefix || '';
            return (p + jQuery._uuidlet() + jQuery._uuidlet() + "-" + jQuery._uuidlet() + "-" + jQuery._uuidlet() + "-" + jQuery._uuidlet() + "-" + jQuery._uuidlet() + jQuery._uuidlet() + jQuery._uuidlet());
        };
    };
    
    String.format = function() {
      var s = arguments[0];
      for (var i = 0; i < arguments.length - 1; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");             
        s = s.replace(reg, arguments[i + 1]);
      }

      return s;
    }

})(jQuery);


