var scripts = document.getElementsByTagName("script"),
	scripts_src = scripts[scripts.length-1].getAttribute("src"),
	jextpath = scripts_src.substring(0, scripts_src.lastIndexOf('/')) + '/',
	JextVersion = 'jext.js 开发版 2.0.0',
	JCode = '',
	JToken = '',
	JEXTFN = {},
	JEXTLANG = ['cn', 'en'],
	JEXTHTML = {},
	jLang = {},
	JsCssLink = {},
	McssData = {},
	language = $('[website-language]:eq(0)').attr('website-language') || 'cn',
	JsCssLoad = [0, 0, 0];
for (var i in JEXTLANG) {
	if (language.indexOf(JEXTLANG[i]) >= 0) {
		language = JEXTLANG[i];
		break;
	}
}

// 谁跨站调用谁就被坑！
var WP = window.parent || window;
var jQ = WP.$;
var jx = function(o,r,e) {
	r = r || '';
	r = o.replace(/[^a-zA-Z0-9]/g, '') + r;
	e = $(o).attr('exec') || ',';
	e = e.indexOf(',' + r + ',') >= 0 ? e : e + r + ',';
	return $(o).not('[exec*=",' + r + ',"]').attr({exec: e});
}
console.log(JextVersion);

// 颜色注册表
// 不能再改了，否则会出现一些效果冲突
var colorRegistry = {
	co: 'color',
	bo: 'border-color',
	border: 'border-color',
	ba: 'background-color',
	bg: 'background',
	opa: 'opacity',
	op: 'opacity'
}

// jq扩展
$.extend({

	// 修改链接但不跳转
	// 只适用于 H5
	href: function(url, json, fn, dataType) {
		if (typeof(window.history.replaceState) === 'function') {
			if (typeof(fn)=='function') $.get(url, json, function(data) {
				window.history.replaceState(null, '', url);
				fn(data);
			}, dataType);
		} else {
			location.href = url;
		}
	},

	// H5判断
	h5: function() {
		var el=document.createElement('canvas');
		return !!(el.getContext && el.getContext('2d'));
	},

	// ie判断
	ie: function() {
		var us = navigator.userAgent;
		return (us.indexOf('compatible') > -1 && us.indexOf("MSIE") > -1) || (us.indexOf('Trident') > -1 && us.indexOf("rv:11.0") > -1) || us.indexOf("Edge") > -1;
	},

	// json 转换
	json: function(str) {
		if (typeof(str) == 'string') {
			return $.parseJSON(str);
		} else {
			return JSON.stringify(str);
		}
	},
	
	// cookie 保存与读取
	// $.cookie('名称', '值', '时间')    这个是保存
	// $.cookie('名称')    这个是读取
	cookie: function(n, v, s, d, e) { 
	    if (v) {
	    	s=parseInt(s)||1;
		    e=new Date(); 
		    e.setTime(e.getTime() + s*1000); 
		    document.cookie = n + "="+ escape (v) + ";expires=" + e.toGMTString() + "; path=/";
	    } else {
		    var arr,reg=new RegExp("(^| )"+n+"=([^;]*)(;|$)");
		    if (arr=document.cookie.match(reg)) return unescape(arr[2]);
		    else return '';
	    }
	},

	cca: function(url, len) {
		url = encodeURIComponent(location.href).toUpperCase().replace(/[^A-Z]/g,'');
		len = url.length;
		return url.charCodeAt(len%5)^url.charCodeAt(len%3)^url.charCodeAt(len%8);
	},

	// css兼容处理
	wcss: function(t, c) {
		var a = ['-webkit-', '-ms-', '-moz-', '-o-'];
		var b = {};
		b[t] = c;
		for (var i in a) b[a[i]+t] = c;
		return b;
	},

	// 判断移动端
	mobile: function() {
	    var a = navigator.userAgent.toLowerCase(),
	    	b = a.match(/ipad/) == 'ipad',
	    	c = a.match(/iphone os/) == 'iphone os',
	    	d = a.match(/midp/) == 'midp',
	    	e = a.match(/rv:1.2.3.4/) == 'rv:1.2.3.4',
	    	f = a.match(/ucweb/) == 'ucweb',
	    	g = a.match(/android/) == 'android',
	    	h = a.match(/windows ce/) == 'windows ce',
	    	i = a.match(/windows mobile/) == 'windows mobile';
	    return b || c || d || e || f || g || h || i;
	},
	
	// 通过字符串执行函数
	eval: function(ss, a, b, c, d, e, f, g) {
		if (!ss) {
			return;
		}
		var aa = ss.split(/;|,|；|，/),
			rr,
			obj = a,
			ww = window;
		for(var kk in aa) {
			rr = aa[kk].match(/\((.*?)\)/);
			ss = aa[kk].replace(/\((.*?)\)/g, '').split('.');
			var i = 0;
			for(var ii in ss) {
				if (typeof(ww[ss[ii]]) == 'object') {
					ww = ww[ss[ii]];
					if (i == 0) {
						a = ww;
					}
					i++;
				} else if (typeof(ww[ss[ii]]) == 'function') {
					if (rr && rr[1]) {
						ww[ss[ii]].call(a ? a : window, rr[1] == 'this' ? obj : rr[1], b, c, d, e, f, g);
					} else {
						ww[ss[ii]].call(a ? a : window, b, c, d, e, f, g);
					}
				} else {
					break;
				}
			}
		}
	},

	// 剪切图片
	cropper: function(v) {
		if ($.isFunction($.fn.cropper)) {
			cropperDoIt(v);
		} else if (window.imageCropperInc != 1) {
			window.imageCropperInc=1;
			var lo = $.alert('loading');
			$.include(jextpath + 'web/cropper/cropper.min.css');
			$.include(jextpath + 'web/cropper/cropper.min.js');
			$.include(jextpath + 'web/cropper/do.it.js', function() {
				lo.remove(function() {
					cropperDoIt(v)
				});
			});
		}
	},

	// 定时执行所有效果函数
	all: function(t) {
		// 查看哪些链接加载错误
		// console.log(JsCssLink);
		if (JsCssLoad[0] == JsCssLoad[1]) {
			JsCssLoad[2] = 1;
		}
		for(var i in JEXTFN) {
			if (typeof(JEXTFN[i]) == 'function') {
				JEXTFN[i]();
			}
		}
		clearTimeout(window.alltimeout);
		window.alltimeout = setTimeout(function() {
			$.all(1)
		}, 600);
	},

	// 导入文件
	jxinclude: function(src, bools, callback) {
		var len = !($('[href^="' + src + '"]').size() || $('[src^="' + src + '"]').size());
		if (len && bools) {
			$.include(src, callback);
		}
	},
	include: function(src, callback) {
		if ($('[src^="' + src + '"]').size() || $('[href^="' + src + '"]').size()) {
			if (typeof(callback) == 'function') {
				callback();
			}
			return;
		}
		JsCssLoad[2] = 0;
		JsCssLoad[0]++;
        var css = src.indexOf('.css') > 0;
        var tags = css ? 'link' : 'script';
        var type = css ? 'text/css' : 'text/javascript';
        var link = css ? 'href' : 'src';
		if (typeof(callback) == 'function' || !callback) {
			var f, done = false;
	        f = document.createElement(tags);
	        if (css) {
	        	f.setAttribute('rel', 'stylesheet');
	        }
	        f.setAttribute('type', type);
	        f.setAttribute(link, src + '?t=' + Math.random());
	        document.getElementsByTagName('head')[0].appendChild(f);
	        JsCssLink[src] = 1;
			f.onload = f.onreadystatechange = function() {
				JsCssLoad[1]++;
				delete(JsCssLink[src]);
				if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
					done = true;
					$.all();
					if (typeof(callback) == 'function') {
						callback();
					}
				}
			}
		} else {
        	var attr = css ? 'rel="stylesheet"' : 'language="javascript"';
            var name = '<' + tags + ' type="' + type + '" ' + attr + link + '="' + src + '"' + '></' + tags + '>';
	    	$('head').append(name);
			JsCssLoad[1]++;
			$.all();
	    }
	}

});


$.fn.extend({
	// 鼠标右键展示菜单
	// $('.title').menu('type',function() {});
	menu: function(type, fn) {
		if ($('[src$="/web/contextmenu.js"]').size()==0) {
			$.include(jextpath + 'web/contextmenu.js');
		}
		this.mouseup(function(e) {
		    if (e.which==3) {
	        	if (typeof(jqcontextmenu)=='object') jqcontextmenu.a($(this), e, type, fn);
	        	e.stopPropagation();
		    }
		});
		return this;
	},

	// 鼠标移的距离
	// $('.title').move('.div',{});
	move: function(a, v) {
        var x, y, xx, yy, x0, y0, x1, y1, t0, w, h, l, t, start, end, left, top;
        var down = $.mobile() ? 'touchstart' : 'mousedown';
        var move = $.mobile() ? 'touchmove' : 'mousemove';
        var up = $.mobile() ? 'touchend' : 'mouseup';
        var v = $.extend({
        	not: 0
    	}, v);
        if (v.box) {
            var box = $(v.box);
            v.box = {
                left: 0,
                top: 0,
                width: box.width() - this.width(),
                height: box.height() - this.height()
            };
        }
        this.addClass('notcopy').on(down, function(e0) {
        	if (e0.which == 3) {
        		return;
        	}
        	e0.preventDefault();
            x = x0 = e0.pageX ? e0.pageX : e0.originalEvent.changedTouches[0].pageX;
            y = y0 = e0.pageY ? e0.pageY : e0.originalEvent.changedTouches[0].pageY;
			if ($.mobile() && e0.originalEvent.touches.length > 1) {
				t0 = 1;
				start = e0.originalEvent.touches;
			} else {
				t0 = 0;
			}
            w = $(window).width();
            h = $(window).height();
            l = parseInt($(a).css('left')) || 0;
            t = parseInt($(a).css('top')) || 0;
            // 当对象是定位的，并且有可能使用bottom,right撑开高度时，强行控制宽高
            if ($(a).css('bottom')) {
            	$(a).css({height: $(a).height()});
            }
            if ($(a).css('right')) {
            	$(a).css({width: $(a).width()});
            }
            $(a).css({margin: $(a).css('margin')});
            $('body').addClass('notcopy');
            if (typeof(v.down) == 'function') {
            	v.down({x: 0, y: 0, left: l, top: t});
            }
            $(window).on(move, function(e1) { //window 还需要继续优化
            	if ($(a).is(':hidden')) {
            		return;
				}
				if ($.mobile() && e1.originalEvent.touches.length > 1) {
					function distance(p1, p2) {
					    var x = p2.pageX - p1.pageX,
					    	y = p2.pageY - p1.pageY;
					    return Math.sqrt((x*x) + (y*y));
					}
					end = e1.originalEvent.touches;
					var hy0 = distance(start[0], start[1]), hy1 = distance(end[0], end[1]);
					var scale = hy0 > hy1 ? (hy1/hy0/100) : (hy0/hy1/100);
					scale = scale > 0.005 ? 0.005 : scale;
					if (typeof(v.scale) == 'function') {
						v.scale(hy0 > hy1 ? -scale : scale);
					}
				}
                if (t0 || v.not) {
                	return;
                }
                x1 = e1.pageX ? e1.pageX : e1.originalEvent.changedTouches[0].pageX;
                y1 = e1.pageY ? e1.pageY : e1.originalEvent.changedTouches[0].pageY;
                var xx0 = x > x1 ? -1 : (x == x1 ? 0 : 1);
                var yy0 = y > y1 ? -1 : (y == y1 ? 0 : 1);
                x = x1;
                y = y1;
                if (v.x && xx0 == 0) {
                	return;
                } else if (v.y && yy0 == 0) {
                	return;
                } else if (xx0 == 0 && yy0 == 0) {
                	return;
                }
                xx = xx0;
                yy = yy0;
                if (v.box) {
                    left = (l+x1-x0) < v.box.left ? v.box.left : (l+x1-x0);
                    left = left > v.box.width ? v.box.width : left;
                    top = (t+y1-y0) < v.box.top ? v.box.top : (t+y1-y0);
                    top = top > v.box.height ? v.box.height : top;
                } else {
                    left = l + x1 - x0;
                    top = t + y1 - y0;
                }
                if (v.x) {
                    $(a).css({left: left, right: 'auto'});
                } else if (v.y) {
                    $(a).css({top: top, bottom: 'auto'});
                } else {
                    $(a).css({left: left, top: top, right: 'auto', bottom: 'auto'});
                }
                if (typeof(v.move) == 'function') {
                	v.move({x: xx, y: yy, left: left, top: top});
                }
            }).off(up).on(up, function(e2) {
            	$(window).off(move);
            	if ($(a).is(':hidden')) {
            		return;
            	}
                t0 = 1;
                $('body').removeClass('notcopy');
                if (typeof(v.up) == 'function') {
                	v.up({x: xx, y: yy, left: left, top: top});
                }
            });
        });
    },

	// 获取图片对象
	file: function(fn) {
		var r = {}, f = {}, t;
		this.off('change').change(function(e) {
			t = $(this);
			f = $(this)[0].files;
			for (var i in f) {
				if (typeof(f[i]) != 'object') {
					continue;
				}
				fi(f[i], $(this));
			}
		});
		function fi(file,t,r) {
			r = new FileReader();
			r.readAsDataURL(file);
			r.onloadend = function(e) {
				fn.call(t, this.result, file, t);
			}
		}
		return this;
	},

	/*
	+-----------------------------------------------
	利用iframe实现普通表单提交，支持文件上传
	$('form').form({
		url:'/',
		end: function(data, f) {}
	});
	+-----------------------------------------------
	*/
	form: function(v) {
		var form = this;
		if ($.isFunction($.fn.formSubmit)) {
			form.formSubmit(v);
		} else {
			$.jxinclude(jextpath + 'web/form.js', 1);
			setTimeout(function() {
				form.form(v);
			}, 200);
		}
		return form;
	},

	/**************************************************
	div滚动到可视区域
	当标签属性 data-visible=0 时重置滚动响应 
	$('.div').visible({top:10, end: function(v) {}});
	**************************************************/
	visible: function(v,a,s) {
		v = v || {},
		v = $.extend({
			obj: this,
			end: function() {},
			top: 0
		}, v);
		s = {
			i: function() {
				s.s();
				$(window).on({
					mousewheel: function() {s.s()},
					touchmove: function() {s.s()},
				});
			},
			s: function() {
				var h = $(window).height(),
					w = $(window).width(),
					t = $(window).scrollTop() || $('html').scrollTop() || $('body').scrollTop();
				v.k = 0;
				v.obj.each(function() {
					var e = $(this),
						i = h + t,
						j = e.offset().top,
						k = e.attr('data-visible'),
						l = e[0].getBoundingClientRect().left,
						m = e[0].getBoundingClientRect().top;
					clearInterval(v.timeout);
					if (k != '1' && e.is(':visible')) {
						v.k++;
					}
					if (i >= j && k != '1' && e.is(':visible') && (w > l && l >= 0) && (h > m && m >= 0)) {
						e.attr({'data-visible': '1'});
						v.end(s, e);
					} else if (v.k > 0) {
						v.timeout=setInterval(s.s, 300);
					}
				});
			},
			reset: function(t) {
				$(t).removeAttr('data-visible');
			}
		}
		s.i();
		return this;
	}

});
$('html').append('<style alertstyle>.wow,[wow]{visibility:hidden}</style>');
$.include(jextpath + 'org/jquery.mousewheel.js', 1);
$.include(jextpath + 'org/md5.js', 1);
$.include(jextpath + 'lang/' + (language ? language : 'cn') + '.js', 1);
$.include(jextpath + 'css/animated.min.css');
$.include(jextpath + 'css/global.css');
$.include(jextpath + 'web/alert.js');

if (1 || location.href.indexOf('/manage') >= 0 && self == top) { 
	var JsCssLoadMask = $('<div></div>');
} else {
	var JsCssLoadMask = $('<div style="position:fixed;top:0;right:0;bottom:0;left:0;text-align:center;font-size:18px;color:#888;z-index:9999999999;background:#fff;line-height:' + $(window).height()/26 + ';font-family:Helvetica Neue,Helvetica,Hiragino Sans GB,Arial,sans-serif;">loading...</div>');
}
$('html').append(JsCssLoadMask);

// 记录
ISLOADING = 0;
IsReload = $.cookie('location-href') == location.href ? 1 : 0;
$.cookie('location-href', location.href, 20000);
// 节点加载完执行
$(window).ready(function() {
	JEXTHTML = $('html').html();
	$.jxinclude(jextpath + 'web/contextmenu.js', JEXTHTML.search(/ custom-contextmenu[ =\/>]/) > 0);
	$.include(jextpath + 'web/common.js');
	var ISLOADINGTIME = setInterval(function() {
		ISLOADING = 1;
		if (JsCssLoad[2]) {
			clearInterval(ISLOADINGTIME);
			JsCssLoadMask.fadeOut(500, function() {
				JsCssLoadMask.remove();
				$.all();
				$.jxinclude(jextpath + 'web/timing.js', typeof(TimingUrlData) == 'array');
			});
		}
	}, 300);
});

// 全部加载完执行
$(window).load(function() {
	// 
});