var isIE = (document.all) ? true : false;

var Bind = function(object, fun) {
	return function() {
		return fun.apply(object, arguments);
	}
}

var BindAsEventListener = function(object, fun) {
	return function(event) {
		return fun.call(object, (event || window.event));
	}
}

var CurrentStyle = function(element) {
	return element.currentStyle
			|| document.defaultView.getComputedStyle(element, null);
}

function addEventHandler(oTarget, sEventType, fnHandler) {
	if (oTarget.addEventListener) {
		oTarget.addEventListener(sEventType, fnHandler, false);
	} else if (oTarget.attachEvent) {
		oTarget.attachEvent("on" + sEventType, fnHandler);
	} else {
		oTarget["on" + sEventType] = fnHandler;
	}
};

function removeEventHandler(oTarget, sEventType, fnHandler) {
	if (oTarget.removeEventListener) {
		oTarget.removeEventListener(sEventType, fnHandler, false);
	} else if (oTarget.detachEvent) {
		oTarget.detachEvent("on" + sEventType, fnHandler);
	} else {
		oTarget["on" + sEventType] = null;
	}
};
// 拖放程序
var Drag = Class.create();
Drag.prototype = {
	// 拖放对象
	initialize : function(drag, options) {
		this.Drag = $(drag);// 拖放对象
		this._x = this._y = 0;// 记录鼠标相对拖放对象的位置
		this._marginLeft = this._marginTop = 0;// 记录margin
		// 事件对象(用于绑定移除事件)
		this._fM = BindAsEventListener(this, this.Move);
		this._fS = Bind(this, this.Stop);
		// 设置右键菜单消失
		this._hi = BindAsEventListener(this, this.RightShow);

		this.SetOptions(options);

		this.Limit = !!this.options.Limit;
		this.mxLeft = parseInt(this.options.mxLeft);
		this.mxRight = parseInt(this.options.mxRight);
		this.mxTop = parseInt(this.options.mxTop);
		this.mxBottom = parseInt(this.options.mxBottom);

		this.LockX = !!this.options.LockX;
		this.LockY = !!this.options.LockY;
		this.Lock = !!this.options.Lock;

		this.onStart = this.options.onStart;
		this.onMove = this.options.onMove;
		this.onStop = this.options.onStop;

		this._Handle = $(this.options.Handle) || this.Drag;
		this._mxContainer = $(this.options.mxContainer) || null;
		// 右键支持
		this._rightBtn = this.options.rightBtn;

		this.Drag.style.position = "absolute";
		//处理png
		// 透明
		if (isIE && !!this.options.Transparent) {
			// 填充拖放对象
			with (this._Handle.appendChild(document.createElement("div")).style) {
				width = height = "100%";
				backgroundColor = "#fff";
				filter = "alpha(opacity:0)";
				fontSize = 0;
			}
		}
		// 修正范围
		this.Repair();
		addEventHandler(this._Handle, "mousedown", BindAsEventListener(this,
						this.Start));
	},
	// 设置默认属性
	SetOptions : function(options) {
		this.options = {// 默认值
			Handle : "",// 设置触发对象（不设置则使用拖放对象）
			Limit : false,// 是否设置范围限制(为true时下面参数有用,可以是负数)
			mxLeft : 0,// 左边限制
			mxRight : 9999,// 右边限制
			mxTop : 0,// 上边限制
			mxBottom : 9999,// 下边限制
			mxContainer : "",// 指定限制在容器内
			LockX : false,// 是否锁定水平方向拖放
			LockY : false,// 是否锁定垂直方向拖放
			Lock : false,// 是否锁定
			Transparent : false,// 是否透明
			onStart : function() {
			},// 开始移动时执行
			onMove : function() {
			},// 移动时执行
			onStop : function() {
			},// 结束移动时执行
			Right : function() {
			}// 右键支持
		};
		Object.extend(this.options, options || {});
	},
	// 准备拖动
	Start : function(oEvent) {
		if (this.Lock) {
			return;
		}
		this.Repair();
		// 记录鼠标相对拖放对象的位置
		this._x = oEvent.clientX - this.Drag.offsetLeft;
		this._y = oEvent.clientY - this.Drag.offsetTop;
		// 记录margin
		this._marginLeft = parseInt(CurrentStyle(this.Drag).marginLeft) || 0;
		this._marginTop = parseInt(CurrentStyle(this.Drag).marginTop) || 0;
		// mousemove时移动 mouseup时停止
		addEventHandler(document, "mousemove", this._fM);
		addEventHandler(document, "mouseup", this._fS);
		if (isIE) {
			// 焦点丢失
			addEventHandler(this._Handle, "losecapture", this._fS);
			// 设置鼠标捕获
			this._Handle.setCapture();
		} else {
			// 焦点丢失
			addEventHandler(window, "blur", this._fS);
			// 阻止默认动作
			oEvent.preventDefault();
		};
		// 附加程序
		this.onStart();
	},
	// 修正范围
	Repair : function() {
		if (this.Limit) {
			// 修正错误范围参数
			this.mxRight = Math.max(this.mxRight, this.mxLeft
							+ this.Drag.offsetWidth + 100);
			this.mxBottom = Math.max(this.mxBottom, this.mxTop
							+ this.Drag.offsetHeight + 100);
			// 如果有容器必须设置position为relative或absolute来相对或绝对定位，并在获取offset之前设置
			!this._mxContainer
					|| CurrentStyle(this._mxContainer).position == "relative"
					|| CurrentStyle(this._mxContainer).position == "absolute"
					|| (this._mxContainer.style.position = "relative");
		}
	},
	// 拖动
	Move : function(oEvent) {
		// 判断是否锁定
		if (this.Lock) {
			this.Stop();
			return;
		};
		// 清除选择
		window.getSelection
				? window.getSelection().removeAllRanges()
				: document.selection.empty();
		// 设置移动参数
		var iLeft = oEvent.clientX - this._x, iTop = oEvent.clientY - this._y;
		// 设置范围限制
		if (this.Limit) {
			// 设置范围参数
			var mxLeft = this.mxLeft, mxRight = this.mxRight, mxTop = this.mxTop, mxBottom = this.mxBottom;
			// 如果设置了容器，再修正范围参数
			if (!!this._mxContainer) {
				mxLeft = Math.max(mxLeft, 0)-100;
				mxTop = Math.max(mxTop, 0)-100;
				mxRight = Math.min(mxRight, this._mxContainer.clientWidth)+250;
				mxBottom = Math.min(mxBottom, this._mxContainer.clientHeight)+250;
			};
			// 修正移动参数
			iLeft = Math.max(Math.min(iLeft, mxRight - this.Drag.offsetWidth),
					mxLeft);
			iTop = Math.max(Math.min(iTop, mxBottom - this.Drag.offsetHeight),
					mxTop);
		}
		// 设置位置，并修正margin
		if (!this.LockX) {
			this.Drag.style.left = iLeft - this._marginLeft + "px";
		}
		if (!this.LockY) {
			this.Drag.style.top = iTop - this._marginTop + "px";
		}
		// 附加程序
		this.onMove();
	},
	// 停止拖动
	Stop : function() {
		// 移除事件
		removeEventHandler(document, "mousemove", this._fM);
		removeEventHandler(document, "mouseup", this._fS);
		if (isIE) {
			removeEventHandler(this._Handle, "losecapture", this._fS);
			this._Handle.releaseCapture();
		} else {
			removeEventHandler(window, "blur", this._fS);
		};
		// 附加程序
		this.onStop();
	},
	// 右键支持
	RightShow : function() {
		// 获得鼠标点击的对象
		addEventHandler(document, "contextmenu", this._hi);
		// 添加事件监听
	}
};
// 通用方法 创建DIV
createEl = function(t, a, y, x)// 编写建立一个新对象的通用方法
{
	var e = document.createElement(t);
	document.body.appendChild(e); // 漏了这一句，否则行不通
	if (a) {
		for (var k in a) {
			if (k == 'class')
				e.className = a[k];
			else if (k == 'id')
				e.id = a[k];
			else if( k == "src")
				e.src = a[k];
				else 
					e.setAttribute(k,a[k]);
		}
	}
	if (y) {
		for (var k in y)
			e.style[k] = y[k];
	}
	if (x) {
		//e.appendChild(document.createTextNode(x));
		e.appendChild(x);
	}
	return e;
}

// 动态创建可拖动div
/*
 * @
 */
DragDiv = function(bigimg_url,img_id,middleimg) {
	img_id = img_id+parseInt(Math.random()*100000);
	 /*var newDiv = createEl("img", {
	 	id:img_id,
		src:bigimg_url
	 }, {
	 cursor : "move",
	 position : "absolute",
	 
	 });*/
	 var newDiv = createEl("div", {
	 	id:img_id
	 }, {
	 cursor : "move",
	 position : "absolute",
	 height:"500px",
	 width:"500px",
	 background:"none",
	 filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+getRelativePath(bigimg_url)+bigimg_url+")"
	 });
	newDiv.oncontextmenu = function() {
		// 操作3个对象
		var dynamicRight = "";
		removeIt();
		PopMenu(this, event.clientX+document.body.scrollLeft - document.body.clientLeft, event.clientY+document.body.scrollTop  - document.body.clientTop); //传入参数图片ID
		return false;
	};
	var mdimg = middleimg.substring(3,middleimg.length);
	var show = new Drag(newDiv, {
				mxContainer : "idContainer", Handle: "idHandle", Limit: true,
				onStart: function(){},
				onMove: function(){
					
				},
	onStop: function(){
			if(this.Drag.getWidth()/2+ this.Drag.offsetLeft< 150){
							//原型
							this.Drag.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+getRelativePath(bigimg_url)+bigimg_url+")";
						}else{
								//变形
								if(600-this.Drag.offsetLeft-this.Drag.getWidth()/2 < 150){
										this.Drag.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+getRelativePath(bigimg_url)+bigimg_url+") fliph";
									}else{
											this.Drag.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+mdimg+")";
										
										}
							}
		}
			});
	$('idContainer').appendChild(newDiv);// 添加至div
}
// 移除右键
removeIt = function() {
	var obj = $('showRight');
	if (obj) {
		obj.remove();
	}
}

//初始化右键属性
function PopMenu(doc, x, y) {
	var rightcon2 = createEl("a",{
							onclick: function(){
									doc.style.display= 'none';
								}
							},{width : "100px",
				height : "30px",
				cursor: "pointer"
				});
	var rightcon1 = createEl("a",{
							onclick: function(){
								var c = doc.style.filter;
								if(c.indexOf("fliph")>0){
										doc.style.filter = c.substring("fliph", doc.style.filter.length-5);
										doc.style.zindex = 2;
								}else{
										doc.style.filter =c+ " fliph";
										doc.style.zindex = 2;
									}
								}
							},{width : "100px",
				height : "60px",
				cursor: "pointer"
				},rightcon2);
	
	var craeteRigth = createEl("div", {
				id : "showRight",
				onclick: function(){
						//doc.style.filter=doc.style.filter=="fliph"?"":"fliph";
						craeteRigth.style.display = 'none';
					}
			}, {
				width : "100px",
				height : "60px",
				backgroundColor : "red",
				backgroundImage :"url('images/bak.png')",
				position : "absolute",
				left : x,
				top : y
			},rightcon1);
}

	//改变背景图片
function getRelativePath(url)
{
	var url = url.substring(0,url.indexOf('images'));
	return url;
}


