﻿///--------------------------------------------
///MyAuth & FormAuth

var FormAuth = Class.create();
var loginPanelHtml = "<h4>请登录</h4><div style='text-align:center'><p>用户名：<input type='text' id='__auth__username__' /></p><p>密　码：<input type='password' id='__auth__password__' /></p><p><span id='__auth__result__' style='color:#f00;'></span></p><p><button id='__auth__go__'>登录</button></p><br /><a href='/usercenter/register.aspx' target='_blank'>新用户点这里注册</a></div>";
MyAuth = Class.create();
MyAuth.prototype = {
	initialize: function(options) {
		this.afterLogined = options.afterLogined;
		this.pop = null;
	},
	checkLogin: function(evt) {
		this._event = evt;
		new Ajax.Request('/usercenter/auth.ashx?t=q', {
			method: 'get',
			onSuccess: function(result) {
				if (result.responseText == '1') { //already signed in                       
					this.loginOk();
				}
				else {
					this.pop = new Popup();
					this.pop.showMessageBox("登录/注册", loginPanelHtml, this._event, 300);
					Event.observe($('__auth__go__'), 'click', this.tryLogin.bind(this), false);
				}
			} .bind(this)
		});
	},
	tryLogin: function() {
		new Ajax.Request('/usercenter/auth.ashx', {
			method: 'post',
			parameters: 't=s&user=' + $('__auth__username__').value + '&password=' + $('__auth__password__').value,
			onSuccess: function(result) {
				if (result.responseText == '1') {//signed in successfully
					this.loginOk();
				}
				else {
					this.loginFail();
				}
			} .bind(this)
		});
	},
	loginFail: function() {
		$('__auth__result__').innerHTML = '用户名/密码不正确';
	},
	loginOk: function() {
		if (this.pop) {
			var m = $('__auth__result__');
			if(m) m.innerHTML = '';
			this.pop.closeWindow();
		}
		if (this.afterLogined)
			setTimeout(this.afterLogined.bind(this), 10);
	}
}

FormAuth.prototype = {
	initialize: function(form) {
		this.form = $(form);
		this.submitBinding = this.onSubmit.bind(this);
		this._event = null;
		this.pop = new Popup();
		Event.observe(this.form, 'submit', this.submitBinding, false);
	},
	onSubmit: function(ev) {
		Event.stop(ev);
		this.pop.setPosition(ev);
		this.checkLogin();
	},
	checkLogin: function(evt) {
		this._event = evt;		
		new Ajax.Request('/usercenter/auth.ashx?t=q', {
			method: 'get',
			onSuccess: function(result) {
				if (result.responseText == '1') {
					//already signed in
					this.loginOk();
				}
				else {
					this.pop.showMessageBox("登录/注册", loginPanelHtml, this._event !=null ? this._event : event, 300);
					Event.observe($('__auth__go__'), 'click', this.tryLogin.bind(this), false);
				}
			} .bind(this)
		});
	},
	tryLogin: function() {
		new Ajax.Request('/usercenter/auth.ashx', {
			method: 'post',
			parameters: 't=s&user=' + $('__auth__username__').value + '&password=' + $('__auth__password__').value,
			onSuccess: function(result) {
				if (result.responseText == '1') {//signed in successfully                    
					this.loginOk();
				}
				else {
					this.loginFail();
				}
			} .bind(this)
		});
	},
	loginFail: function() {
		$('__auth__result__').innerHTML = '用户名/密码不正确';
	},
	loginOk: function() {
		Event.stopObserving(this.form, 'submit', this.submitBinding, false);
		$('__auth__result__').innerHTML = '';
		this.form.submit();
	},
	cancel: function() {
		if (this.pop) this.pop.closeWindow();
	}
}


///golbal

Popup = Class.create();
//
Popup.prototype = {
	initialize: function() {
		this.isIe = (document.all) ? true : false;
		this.position = { x: 0, y: 0 };
	},
	//设置select的可见状态
	setSelectState: function(state) {
		var objl = document.getElementsByTagName('select');
		for (var i = 0; i < objl.length; i++) {
			objl[i].style.visibility = state;
		}
	},
	setPosition: function(ev) {
		this.position = this.mousePosition(ev);
	},
	mousePosition: function(ev) {
		try {
			ev = ev || window.event;
			if (ev.pageX || ev.pageY) {
				return { x: ev.pageX, y: ev.pageY };
			}
			return {
				x: ev.clientX + document.body.scrollLeft
					- document.body.clientLeft + ev.offsetX,
				y: ev.clientY + document.body.scrollTop
					- document.body.clientTop + ev.offsetY
			};
		} catch (e) {
			window.moveTo(0, 0);
			return { x: 300, y: 100 };
		}
	},
	//弹出方法
	showMessageBox: function(wTitle, content, evt, wWidth) {
		this.closeWindow();
		var pos = this.mousePosition(evt);
		if (pos.x + pos.y == 0) {
			pos = this.getXY(0, 0);
		}
		var bWidth = parseInt(document.documentElement.scrollWidth);
		var bHeight = parseInt(document.documentElement.scrollHeight);
		if (this.isIe) {
			this.setSelectState('hidden');
		}
		var back = document.createElement("div");
		back.id = "back";
		var styleStr = "top:0px;left:0px;position:absolute;background:#666;width:" + bWidth + "px;height:" + bHeight + "px;";
		styleStr += (this.isIe) ? "filter:alpha(opacity=40);" : "opacity:0.40;";
		back.style.cssText = styleStr;
		document.body.appendChild(back);
		var mesW = document.createElement("div");
		mesW.id = "mesWindow";
		mesW.className = "mesWindow";
		mesW.innerHTML = "<div class='mesWindowTop'><table width='100%' height='100%'><tr><td>" + wTitle + "</td><td style='width:1px;'><input type='button' id='__popup_close__'  title='关闭窗口' class='close' value='关闭' /></td></tr></table></div><div class='mesWindowContent' id='mesWindowContent'>" + content + "</div><div class='mesWindowBottom'></div>";
		styleStr = "left:" + (((pos.x - wWidth) > 0) ? (pos.x - wWidth) : pos.x) + "px;top:" + (pos.y) + "px;position:absolute;width:" + wWidth + "px;";
		mesW.style.cssText = styleStr;
		document.body.appendChild(mesW);
		Event.observe($('__popup_close__'), 'click', this.closeWindow.bind(this), false);

	},
	showBackground: function(obj, endInt) {
		obj.filters.alpha.opacity += 1;
		if (obj.filters.alpha.opacity < endInt) {
			setTimeout(function() { this.showBackground(obj, endInt) } .bind(this), 8);
		}
	},
	//关闭窗口
	closeWindow: function() {
		if ($('back') != null) {
			$('back').parentNode.removeChild($('back'));
		}
		if ($('mesWindow') != null) {
			$('mesWindow').parentNode.removeChild($('mesWindow'));
		}
		if (this.isIe) {
			this.setSelectState('');
		}
	},
	getInnerXY: function() {
		var myWidth = 0, myHeight = 0;
		if (typeof (window.innerWidth) == 'number') {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		return { x: myWidth, y: myHeight };
	},

	getScrollXY: function() {
		var scrOfX = 0, scrOfY = 0;
		if (typeof (window.pageYOffset) == 'number') {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return { x: scrOfX, y: scrOfY };
	},
	getXY: function(width, height) {
		var innerxy = this.getInnerXY();
		var offxy = this.getScrollXY();
		if (this.isIe) { // ie
			return { x: ((innerxy.x - width) / 2 + offxy.x), y: ((innerxy.y - height) / 2 + offxy.y - 150) };
		} else {
			return { x: ((innerxy.x - width) / 2), y: ((innerxy.y - height) / 2) };
		}
	}
}



///-----------------------------------------------------------------------------------------------------
///product: user want discount
///
UserWantDiscount = Class.create();
//
UserWantDiscount.prototype = {
	initialize: function(productId, options) {
		this.productId = productId;
		this.myAuth = new MyAuth({ afterLogined: function() { this.showPanel() } .bind(this) })
		this.productId = productId;
		this.cookieName = "UserWantDiscountCookie";
		this.currentCount = 0;
		this.maxCount = 3;
		this.panelHtml = "<div style='padding:20px;'>您想降低折扣点：<select id='wantedDiscount'><option value=''>-请选择-</option><option value='1'>1%</option><option value='2'>2%</option><option value='3'>3%</option><option value='4'>4%</option><option value='5'>5%</option><option value='6'>6%</option><option value='7'>7%</option><option value='8'>8%</option><option value='9'>9%</option><option value='10'>10%</option></select> <br /> 降价通知我：<input id='noticeMe' type='checkbox' checked='checked' /><br> <input type='button' value=' 确定 ' id='__discount_ok__' /></div>";
		this.pop = null;
		this._event = null;
	},
	clickDiscount: function() {
		this._event = event;
		this.myAuth.checkLogin(this._event);
	},
	showPanel: function() {
		if (this.currentCount == 0) {
			var list = GetCookie(this.cookieName);
			var got = false;
			if (typeof (list) != "undefined" && list != "" && list != "undefined") {
				var arr = list.split(",");
				for (var index = 0; index < arr.length; index++) {
					var arr2 = arr[index].split(":");
					if (this.productId == arr2[0]) {
						this.currentCount = parseInt(arr2[1]);
						this.maxCount = parseInt(arr2[2]);
						got = true;
						break;
					}
				}
			}
			if (!got) {
				var vNum
				vNum = Math.random()
				vNum = 3 + Math.round(vNum * 6)
				this.maxCount = vNum;
			}
		}

		if (this.currentCount <= this.maxCount) {
			this.showPanelHelper();
		}
		else {
			alert("我们已经收到了您的要求了，感谢您的支持。");
		}
	},
	showPanelHelper: function() {
		this.pop = new Popup();
		this.pop.showMessageBox("点降台", this.panelHtml, this._event, 300);

		Event.observe($('__discount_ok__'), 'click', this.saveUserWantDiscount.bind(this), false);
	},
	saveUserWantDiscount: function() {
		var wantedDiscount = $F('wantedDiscount');
		if (wantedDiscount == '') {
			alert("请选择折扣点");
			return;
		}
		var noticeMe = $('noticeMe').checked ? 1 : 0;
		//
		this.currentCount++;
		var list = GetCookie(this.cookieName);
		var p = this.productId + ":" + this.currentCount + ":" + this.maxCount;
		if (typeof (list) != "undefined" && list != "" && list != "undefined") {
			var arr = list.split(",");
			list = p;
			for (var index = 0; index < arr.length; index++) {
				var arr2 = arr[index].split(":");
				if (this.productId != arr2[0]) {
					list += "," + arr[index];
				}
			}
		} else {
			list = p;
		}

		var expdate = new Date();
		expdate.setTime(expdate.getTime() + (1 * 24 * 60 * 60 * 1000));
		SetCookie(this.cookieName, list, expdate);

		var pars = 'id=' + this.productId + '&discount=' + wantedDiscount + '&noticeMe=' + noticeMe;
		var myAjax = new Ajax.Request('/service/http/WantDisountForProduct.aspx?t=1', {
			method: 'get',
			parameters: pars,
			onComplete: function(result) {
				if (result.responseText != '') {
					var f = $("wantDiscountIndex").innerText;
					$("wantDiscountIndex").innerHTML = parseInt(f) + 1;
					alert(result.responseText);
				}
				this.pop.closeWindow();
			} .bind(this)
		});
	}

}
