﻿//================================================
// CN WoW Community Site
// (c)2009 Blizzard Entertainment. Shanghai Easenet. All rights reserved.
//================================================

Browser.ie = Browser.Engine.trident;
Browser.ie6 = Browser.Engine.trident && (Browser.Engine.version == 4);

var ie6FootFix = function() {
	if(Browser.ie6) {
		$("main-bottom-dec").setStyle('display','none').setStyle('display','');
	}
};

var chkEmail = function(emailField) {
	return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test($(emailField).value);
};

var mainMenu = {
	start: function(currentNav) {
		$("nav-body").getElements("li").each(function(aMenu,i) {
			var hasSubmenu = aMenu.getElement("dd").get('class') != "seo" ? true : false;
			var isCurrentNav = false;
			if(currentNav == i) {
				aMenu.addClass("current");
				isCurrentNav = true;
			}
			aMenu.addEvent("mouseenter",this.onMouseEnter.bind(this,[aMenu,hasSubmenu]));
			aMenu.addEvent("mouseleave",this.onMouseLeave.bind(this,[aMenu,hasSubmenu,isCurrentNav]));
		}.bind(this));
	},
	onMouseEnter: function(thisMenu,toggleSubmenu) {
		thisMenu.addClass("current");
		if(toggleSubmenu) {
			thisMenu.getElement('dd').setStyle('display','block');
		}
	},
	onMouseLeave: function(thisMenu,toggleSubmenu,isCurrentNav) {
		if(!isCurrentNav) {
			thisMenu.removeClass("current");
		}
		if(toggleSubmenu) {
			thisMenu.getElement('dd').setStyle('display','none');
		}
	}
};

var LoadingTextIcons = new Class({
	Implements: Options,
	options: {
		rotateDuration: 150
	},
	initialize: function(container,charSet,options) {
		this.setOptions(options);
		this.charSet = charSet;
		this.length = this.charSet.length;
		this.container = $(container).set("html",charSet[0]);
		this.at = 0;
	},
	start: function() {
		this.rotation = this.rotate.periodical(this.options.rotateDuration,this);
		return this;
	},
	pause: function() {
		$clear(this.rotation);
		return this;
	},
	rotate: function() {
		this.at = this.at + 1 >= this.length ? 0 : this.at + 1;
		this.container.set("html",this.charSet[this.at]);
		return this;
	}
});

var AjaxReq = new Class({
	Implements: [Options,Events],
	options: {
		requestOptions: {
			method: 'get'
		},
		onError: function(message) {
			alert(message)
		},
		data: null,
		callType: 'json',
		callBack: $empty
	},
	error: function(r) {
		this.fireEvent('error', this.options.callType == 'html' ? [r.responseText] : [eval('(' + r.responseText + ')').errorMsg]);
		return this;
	},
	success: function(psedo1, psedo2, r, r2){
		if(this.options.callType == 'html') {
			this.options.callBack(r);
		} else {
			r = psedo1;
			this.options.callBack(r.data);
		}
		return this;
	},
	initialize: function(url,options){
		this.setOptions(options);
		this.options.requestOptions.onSuccess = this.success.bind(this);
		this.options.requestOptions.onFailure = this.error.bind(this);
		switch(this.options.callType) {
			case 'html':{
				new Request.HTML($extend(this.options.requestOptions,{url:url,onFailure:this.error.bind(this)})).send(this.options.data);
				break;
			}
			case 'json':{
				new Request.JSON($extend(this.options.requestOptions,{url:url,onFailure:this.error.bind(this)})).send(this.options.data);
				break;
			}
		}
		return this;
	}
});

var IEFocus = new Class({
	Implements: [Options],
	options: {
		focusClass: 'focus'
	},
	initialize: function(el,options) {
		this.setOptions(options);
		this.input = $(el).addEvents({
			focus: function() {
				this.input.addClass(this.options.focusClass);
			}.bind(this),
			blur: function() {
				this.input.removeClass(this.options.focusClass);
			}.bind(this)
		});
	}
});

var TextInput = new Class({
	Implements: [Options,Events],
	options: {
		onEnterPressed: $empty,
		hintColor: "#aaa"
	},
	initialize: function(input,defalutText,options) {
		this.setOptions(options);
		this.input = $(input).addEvents({
			keyup: function(e) {
				e.stop();
				if(e.keyCode == 13) {
					this.fireEvent('enterPressed');
				}
			}.bindWithEvent(this),
			focus: function() {
				if(this.getValue() == "") {
					this.input.value = "";
					this.input.setStyle("color",this.originalColor);
				}
			}.bind(this),
			blur: function() {
				if(this.getValue() == "") {
					this.setValue("");
				}
			}.bind(this)
		});
		this.originalColor = this.input.getStyle("color");
		this.defalutText = defalutText;
		if(this.getValue() == "") {
			this.setValue("");
		}
	},
	getValue: function() {
		return this.input.value == this.defalutText ? "" : this.input.value;
	},
	setValue: function(val) {
		if($chk(val) && val != this.defalutText) {
			this.input.value = val;
			this.input.setStyle("color",this.originalColor);
		} else {
			this.input.value = this.defalutText;
			this.input.setStyle("color",this.options.hintColor);
		}
		return this;
	},
	cleanUp: function() {
		if(this.getValue == "") {
			this.input.value = "";
		}
	}
});

var TextArea = new Class({
	Implements: [Options,Events],
	options: {
		statusHolderEl: 'div',
		statusText: '<span class="normalText">您还可以填写<strong></strong>字</span><span class="alert">输入文字过多，请适当删减</span>',
		getOkTextHandler: '.normalText',
		getErrorTextHandler: '.alert',
		getNumberHandler: 'strong'
	},
	initialize: function(input,limit,options) {
		this.setOptions(options);
		this.input = $(input).addEvent('keyup',this.checkNum.bind(this));
		this.limit = limit;
		this.statusHolder = new Element(this.options.statusHolderEl).set('html',this.options.statusText).inject(this.input,'after');
		this.okText = this.statusHolder.getElement(this.options.getOkTextHandler);
		this.errorText = this.statusHolder.getElement(this.options.getErrorTextHandler);
		this.availableNumberText = this.statusHolder.getElement(this.options.getNumberHandler);
		this.checkNum();
	},
	checkNum: function() {
		var length = this.input.value.length;
		if(length <= this.limit) {
			this.okText.setStyle('display','');
			this.errorText.setStyle('display','none');
			this.availableNumberText.set('text',this.limit - length);
			this.isValid = true;
		} else {
			this.okText.setStyle('display','none');
			this.errorText.setStyle('display','');
			this.isValid = false;
		}
		return this;
	},
	check: function() {
		this.checkNum();
		return this.isValid;
	}
});

var Captcha = new Class({
	Implements: [Options],
	options: {
		requestUrl: '/action/events/capture.aux',
		refreshText: '看不清，换一张',
		useCompactMode: false
	},
	initialize: function(capInput,imageHolder,refreshHolder,options) {
		this.setOptions(options);
		this.imageHolder = $(imageHolder);
		if(!this.options.useCompactMode) {
			this.refreshHolder = $(refreshHolder);
		}
		this.capInput = $(capInput).addEvent('focus',this.init.bind(this));
		this.isInit = false;
	},
	init: function() {
		if(!this.isInit) {
			this.imageRefresh = new Element('a').setProperties({
				href: '#',
				title: this.options.refreshText
			}).addEvent('click',this.loadCaptchaImage.bindWithEvent(this)).inject(this.imageHolder);
			if(!this.options.useCompactMode) {
				this.imageRefresh.empty().clone().cloneEvents(this.imageRefresh).set('text',this.options.refreshText).inject(this.refreshHolder);
			}
			this.loadCaptchaImage();
			this.isInit = true;
		}
		return this;
	},
	loadCaptchaImage: function(e) {
		if(e) {
			e.stop();
		}
		this.imageRefresh.empty().set('html','<img src="' + this.options.requestUrl + '?' + $time() + '" />');
		return this;
	}
});

var Criteria = new Class({
	initialize: function(criteriaInfo) {
		this.criteriaInfo = $merge({
			type: 'normal',
			check: [],
			errMessage: [],
			okMessage: '',
			defaultMessage: '',
			bang: false,
			infoHolder: false,
			onBlurCheck: false,
			onBlurCheckEl: false,
			bangClass: 'bang',
			textarea: false,
			limit: 0,
			breaksOnError: false,
			options: {}
		}, criteriaInfo);
		switch(this.criteriaInfo.type) {
			case 'normal':
				break;
			case 'text':
				this.text = new TextInput(this.criteriaInfo.textarea,this.criteriaInfo.defaultMessage,this.criteriaInfo.options);
				break;
			case 'textarea':
				this.textarea = new TextArea(this.criteriaInfo.textarea,this.criteriaInfo.limit,this.criteriaInfo.options);
				break;
			case 'abstract':
				break;
		}
		if(this.criteriaInfo.onBlurCheck) {
			this.criteriaInfo.onBlurCheckEl = $(this.criteriaInfo.onBlurCheckEl).addEvent('blur',this.check.bind(this));
		}
		if(this.criteriaInfo.bang) {
			this.criteriaInfo.bang = $(this.criteriaInfo.bang);
		}
		if(this.criteriaInfo.infoHolder) {
			this.criteriaInfo.infoHolder = $(this.criteriaInfo.infoHolder);
			if(this.criteriaInfo.okMessage != '') {
				this.criteriaInfo.infoHolder.set('text',this.criteriaInfo.okMessage);
			}
		}
	},
	check: function() {
		var checkItems = this.criteriaInfo.check;
		for(var i = 0; i < checkItems.length; i++) {
			if(!eval(checkItems[i])) {
				if(this.criteriaInfo.infoHolder) {
					this.criteriaInfo.infoHolder.set('html',this.criteriaInfo.errMessage[i]);
				}
				if(this.criteriaInfo.bang) {
					this.criteriaInfo.bang.addClass(this.criteriaInfo.bangClass);
				}
				return false;
			}
		}
		if(this.criteriaInfo.bang) {
			this.criteriaInfo.bang.removeClass(this.criteriaInfo.bangClass);
		}
		if(this.criteriaInfo.infoHolder) {
			this.criteriaInfo.infoHolder.set('html',this.criteriaInfo.okMessage);
		}
		return true;
	},
	get: function(item) {
		if( item == 'type' || item == 'okMessage' || item == 'bang' || item == 'onBlurCheck' || item == 'breaksOnError' ) {
			return this.criteriaInfo[item];
		} else {
			return null;
		}
	},
	cleanUp: function() {
		if(this.get("type") == "text") {
			this.text.cleanUp();
		}
	}
});

var CriteriaSet = new Class({
	Implements: [Options],
	options: {
		useScrollFx: true
	},
	initialize: function(criteria,options) {
		this.setOptions(options);
		this.criteria = {};
		for(var c in criteria) {
			this.criteria[c] = new Criteria(criteria[c]);
		}
		if(this.options.useScrollFx) {
			this.scrollFx = new Fx.Scroll($(document));
		}
	},
	checkAll: function() {
		var pass = true;
		var lastBang = false;
		for(var c in this.criteria) {
			if(!this.criteria[c].check()) {
				pass = false;
				lastBang = this.criteria[c].get('bang');
				if(this.criteria[c].get('breaksOnError')) {
					break;
				}
			}
		}
		if(lastBang) {
			this.toElement(lastBang);
		}
		return pass;
	},
	toElement: function(el) {
		if(this.options.useScrollFx) {
			this.scrollFx.toElement(el);
		} else {
			location.hash = el;
		}
	},
	cleanForSubmit: function() {
		for(var c in this.criteria) {
			this.criteria[c].cleanUp();
		}
	},
	getField: function(fieldName) {
		return this.criteria[fieldName];
	}
});

var FormRecorderItem = new Class({
	initialize: function(recordField,recordFieldName,setGuid) {
		this.recordField = $merge({
			type: "normal",
			field: false,
			options: {}
		}, recordField);
		this.recordFieldName = recordFieldName;
		this.setGuid = setGuid;
		switch(this.recordField.type) {
			case "text":
				this.recordField.field = this.recordField.field.text;
				break;
			case "normal":
			default:
				this.recordField.field = $(this.recordField.field);
		}
	},
	save: function() {
		var cookieVal = "";
		switch(this.recordField.type) {
			case "text":
				cookieVal = this.recordField.field.getValue();
				break;
			case "normal":
			default:
				cookieVal = this.recordField.field.value;
		}
		Cookie.write(this.setGuid + '_' + this.recordFieldName,cookieVal,this.recordField.options);
		return this;
	},
	load: function() {
		var cookieVal = Cookie.read(this.setGuid + '_' + this.recordFieldName);
		switch(this.recordField.type) {
			case "text":
				this.recordField.field.setValue($chk(cookieVal) ? cookieVal : "");
				break;
			case "normal":
			default:
				this.recordField.field.value = $chk(cookieVal) ? cookieVal : "";
		}
		return this;
	},
	clear: function() {
		Cookie.dispose(this.setGuid + '_' + this.recordFieldName,this.recordField.options);
		return this;
	}
});

var FormRecorder = new Class({
	Implements: [Options,Events],
	options: {},
	initialize: function(guid,recordFieldSet,options) {
		this.setOptions(options);
		this.guid = guid;
		this.recordFieldSet = {};
		for(var r in recordFieldSet) {
			this.recordFieldSet[r] = new FormRecorderItem(recordFieldSet[r],r,this.guid);
		}
	},
	load: function() {
		for(var r in this.recordFieldSet) {
			this.recordFieldSet[r].load();
		}
		return this;
	},
	clear: function() {
		for(var r in this.recordFieldSet) {
			this.recordFieldSet[r].clear();
		}
		return this;
	},
	save: function() {
		for(var r in this.recordFieldSet) {
			this.recordFieldSet[r].save();
		}
		return this;
	}
});

var Form = new Class({
	Implements: [Options,Events],
	options: {
		onBeforeSubmit: $empty,
		onBeforeCriteriaCheck: $empty,
		onCriteriaCheckFailed: $empty,
		ieFocus: 'focus'
	},
	status: {
		submitFired: false,
		isRecordingValue: false
	},
	initialize: function(formEl,criteria,options) {
		this.setOptions(options);
		this.formEl = $(formEl);
		this.criteria = new CriteriaSet(criteria);
		if(Browser.ie) {
			if(this.options.ieFocus) {
				this.formEl.getElements('input[type="text"]').each(function(input) {
					new IEFocus(input, {focusClass: this.options.ieFocus});
				}.bind(this));
				this.formEl.getElements('textarea').each(function(input) {
					new IEFocus(input, {focusClass: this.options.ieFocus});
				}.bind(this));
			}
		}
	},
	addSubmit: function(sumbitHandler,sumbitHandlerType) {
		switch(sumbitHandlerType) {
			case "psuedoButton":
				this.submitButton = $(sumbitHandler).addEvent('click', function(e) {
					e.stop();
					if(!this.status.submitFired) {
						this.fireEvent('beforeCriteriaCheck');
						if(this.criteria.checkAll()) {
							this.fireEvent('beforeSubmit');
							this.criteria.cleanForSubmit();
							if(this.status.isRecordingValue) {
								this.formValueRecorder.save();
							}
							this.status.submitFired = true;
							this.formEl.submit();
						} else {
							this.fireEvent('criteriaCheckFailed');
						}
					}
				}.bindWithEvent(this));
				break;
		}
		return this;
	},
	addFormValueRecorder: function(formValueRecorder,loadDataCriteria) {
		this.status.isRecordingValue = true;
		this.formValueRecorder = formValueRecorder;
		if(loadDataCriteria) {
			this.formValueRecorder.load();
		}
		this.formValueRecorder.clear();
		return this;
	},
	getField: function(fieldName) {
		return this.criteria.getField(fieldName);
	},
	toElement: function(el) {
		this.criteria.toElement(el);
		return this;
	}
});

var ItemView = new Class({
	Implements: [Options,Events],
	options: {
		zIndex: 9999
	},
	initialize: function(itemImageEl,itemDesc,options) {
		this.setOptions(options);
		this.itemImageEl = itemImageEl.addEvents({
			mouseenter: this.show.bind(this),
			mouseleave: this.hide.bind(this)
		});
		this.desc = itemDesc;
		this.isInited = false;
	},
	init: function() {
		var coods = this.itemImageEl.getCoordinates();
		this.descEl = new Element('div').set('html',this.desc).inject(document.body).setStyles({
			position: 'absolute',
			left: coods.right + 'px',
			top: coods.top + 'px',
			display: 'none',
			zIndex: this.options.zIndex
		});
		this.isInited = true;
	},
	show: function() {
		if(!this.isInited) {
			this.init();
		}
		this.descEl.setStyle('display','');
	},
	hide: function() {
		if(!this.isInited) {
			this.init();
		}
		this.descEl.setStyle('display','none');
	}
});

var ItemTable = new Class({
	Implements: [Options],
	options: {
		colSize: 2,
		wrapperPrev: '<div class="item-table"><div class="item-table-h"><div class="item-table-m">',
		wrapperAfter: '</div></div></div>'
	},
	initialize: function(holder,itemList,options) {
		this.setOptions(options);
		this.itemList = itemList;
		this.holder = $(holder);
		var rows = this.itemList.length % this.options.colSize == 0 ? this.itemList.length / this.options.colSize : parseInt(this.itemList.length / this.options.colSize) + 1;
		var html = [this.options.wrapperPrev + '<table><tbody>'];
		var i = 0;
		for(var j=0; j<rows; j++) {
			html.push('<tr>');
			for(var k=0; k<this.options.colSize; k++) {
				if(i < this.itemList.length) {
					html.push('<th><img src="' + this.itemList[i].url + '" /></th><td>' + this.itemList[i].name + '</td>')
				} else {
					html.push('<th>&nbsp;</th><td class="single">&nbsp;</td>');
				}
				i++;
			}
			html.push('</tr>');
		}
		html.push('<table><tbody>' + this.options.wrapperAfter);
		this.holder.set('html',html.join('\n'));
		ie6FootFix();
		this.init();
	},
	init: function() {
		this.images = this.holder.getElements('img');
		this.items = [];
		for(var i=0; i<this.itemList.length; i++) {
			this.items.push(new ItemView(this.images[i],this.itemList[i].desc));
		}
		return this;
	}
});

var siteOverall = {
	data: {
		currentNav: -1
	},
	start: function() {
		if($("nav-body")) {
			mainMenu.start(siteOverall.data.currentNav);
		}
	}
};

window.addEvent('domready',siteOverall.start);