var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event;
YAHOO.namespace('mabole');

/**
 * animation
 */
(function(){
	var els = Dom.getElementsByClassName('message', 'div');
	for (var i=0,n=els.length; i<n; i++) {
		var el = els[i];
		var attributes = {
			color: { to: Dom.getStyle(el, 'color') },
			backgroundColor: { to: Dom.getStyle(el, 'backgroundColor') }
		};
		var backgroundColor;
		if (Dom.hasClass(el, 'error')) {
			backgroundColor = '#F00';
		}
		if (Dom.hasClass(el, 'warning')) {
			backgroundColor = '#FF0';
		}
		if (Dom.hasClass(el, 'success')) {
			backgroundColor = '#0F0';
		}
		Dom.setStyle(el, 'color', '#FFF');
		Dom.setStyle(el, 'backgroundColor', backgroundColor);
		
		var anim = new YAHOO.util.ColorAnim(el, attributes);
		anim.animate(); 
	}
})();

/**
 * HTML Parser as YUI extension
 * @author stauren (stauren.net)
 * based on HTML Parser By John Resig (ejohn.org)
 *
 * usage : 
 * YAHOO.maoble.HTMLtoXML(htmlString);
 *
 */
(function(){

  var _aYesTag = ['a', 'div','span','p','h1','br','img','td','th','li','tr','table','ul','ol','strong','em','i','b','h2','dt','dd','dl','hr','h3','sub','sup'];

  var _aYesAttr = ['style', 'href', 'src','title', 'align','border','cellpadding', 'cellspacing','colspan','rowspan'];

	// Regular Expressions for parsing tags and attributes
	var startTag = /^<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
		endTag = /^<\/(\w+)[^>]*>/,
		attr = /(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
		
	// Empty Elements - HTML 4.01
	var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");

	// Block Elements - HTML 4.01
	var block = makeMap("address,applet,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");

	// Inline Elements - HTML 4.01
	var inline = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");

	// Elements that you can, intentionally, leave open
	// (and which close themselves)
	var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");

	// Attributes that have their values filled in disabled="disabled"
	var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");

	// Special Elements (can contain anything)
	var special = makeMap("script,style");

	var HTMLParser = function( html, handler ) {
		var index, chars, match, stack = [], last = html;
		stack.last = function(){
			return this[ this.length - 1 ];
		};

		while ( html ) {
			chars = true;

			// Make sure we're not in a script or style element
			if ( !stack.last() || !special[ stack.last() ] ) {

				// Comment
				if ( html.indexOf("<!--") == 0 ) {
					index = html.indexOf("-->");
	
					if ( index >= 0 ) {
						if ( handler.comment )
							handler.comment( html.substring( 4, index ) );
						html = html.substring( index + 3 );
						chars = false;
					}
	
				// end tag
				} else if ( html.indexOf("</") == 0 ) {
					match = html.match( endTag );
	
					if ( match ) {
						html = html.substring( match[0].length );
						match[0].replace( endTag, parseEndTag );
						chars = false;
					}
	
				// start tag
				} else if ( html.indexOf("<") == 0 ) {
					match = html.match( startTag );
	
					if ( match ) {
						html = html.substring( match[0].length );
						match[0].replace( startTag, parseStartTag );
						chars = false;
					}
				}

				if ( chars ) {
					index = html.indexOf("<");
					
					var text = index < 0 ? html : html.substring( 0, index );
					html = index < 0 ? "" : html.substring( index );
					
					if ( handler.chars )
						handler.chars( text );
				}

			} else {
				html = html.replace(new RegExp("(.*)<\/" + stack.last() + "[^>]*>"), function(all, text){
					text = text.replace(/<!--(.*?)-->/g, "$1")
						.replace(/<!\[CDATA\[(.*?)]]>/g, "$1");

					if ( handler.chars )
						handler.chars( text );

					return "";
				});

				parseEndTag( "", stack.last() );
			}

			if ( html == last )
				throw "Parse Error: " + html;
			last = html;
		}
		
		// Clean up any remaining tags
		parseEndTag();

		function parseStartTag( tag, tagName, rest, unary ) {
			if ( block[ tagName ] ) {
				while ( stack.last() && inline[ stack.last() ] ) {
					parseEndTag( "", stack.last() );
				}
			}

			if ( closeSelf[ tagName ] && stack.last() == tagName ) {
				parseEndTag( "", tagName );
			}

			unary = empty[ tagName ] || !!unary;

			if ( !unary )
				stack.push( tagName );
			
			if ( handler.start ) {
				var attrs = [];
	
				rest.replace(attr, function(match, name) {
					var value = arguments[2] ? arguments[2] :
						arguments[3] ? arguments[3] :
						arguments[4] ? arguments[4] :
						fillAttrs[name] ? name : "";
					
					attrs.push({
						name: name,
						value: value,
						escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
					});
				});
	
				if ( handler.start )
					handler.start( tagName, attrs, unary );
			}
		}

		function parseEndTag( tag, tagName ) {
			// If no tag name is provided, clean shop
			if ( !tagName )
				var pos = 0;
				
			// Find the closest opened tag of the same type
			else
				for ( var pos = stack.length - 1; pos >= 0; pos-- )
					if ( stack[ pos ] == tagName )
						break;
			
			if ( pos >= 0 ) {
				// Close all the open elements, up the stack
				for ( var i = stack.length - 1; i >= pos; i-- )
					if ( handler.end )
						handler.end( stack[ i ] );
				
				// Remove the open elements from the stack
				stack.length = pos;
			}
		}
	};
	
	YAHOO.mabole.HTMLtoXML = function( html ) {
		var results = "",
      _each = function(aAry, fn) {
        var i,j;
        if (aAry.length) {
          for(i=0,j=aAry.length;i<j;i++) {
            fn(aAry[i], i);
          }
        } else {
          for(i in aAry) {
            fn(aAry[i], i)
          }
        }
      },
      _inArray = function(obj, ary, strict) {
        var i, j;
        for (var i=0,j=ary.length;i<j;i++) {
          if(ary[i]===obj || (!strict && ary[i]==obj)) {
            return true;
            break;
          }
        }
        return false;
      };
		
		HTMLParser(html, {
			start: function( tag, attrs, unary ) {
        if (_inArray(tag.toLowerCase(), _aYesTag)) {
          results += "<" + tag;
      
          for ( var i = 0; i < attrs.length; i++ ) {
            if (_inArray(attrs[i].name.toLowerCase(), _aYesAttr)) {
              results += " " + attrs[i].name + '="' + attrs[i].escaped + '"';
            }
          }
      

          results += (unary ? "/" : "") + ">";
        }
			},
			end: function( tag ) {
        if (_inArray(tag.toLowerCase(), _aYesTag)) {
          results += "</" + tag + ">";
        }
			},
			chars: function( text ) {
				results += text;
			},
			comment: function( text ) {
				results += "<!--" + text + "-->";
			}
		});
		
		return results;
	};
	
	function makeMap(str){
		var obj = {}, items = str.split(",");
		for ( var i = 0; i < items.length; i++ )
			obj[ items[i] ] = true;
		return obj;
	}
})();

/**
 * create Rich text editor
 * @param {String} textareaId
 * @param {Object} config
 */
YAHOO.mabole.createRTE = function(textareaId, config) {
	var _config = config || {};
	_config.width = _config.width || '550px';
	_config.height = _config.height || '300px';
	_config.useAnchor = _config.useAnchor || false;
	_config.useImage = _config.useImage || false;
	_config.useEmotion = _config.useEmotion || false;
	var loader = new YAHOO.util.YUILoader({
		require : ['menu', 'button', 'simpleeditor'],
		onSuccess : function() {
			YAHOO.util.Event.onAvailable(textareaId, function() {
				var myEditor = _createRTE(textareaId);
				var form = textarea = Dom.get(textareaId);
				textarea.rte = myEditor;
				while(Dom.isAncestor(document.body, form)) {
					if (form.tagName.toLowerCase() == 'form') {
						Event.on(form, 'submit', function() {
							myEditor.saveHTML();
							textarea.value = YAHOO.mabole.HTMLtoXML(textarea.value);
						});
						break;
					}
					form = form.parentNode;
				}
			});
		},
		onFailure : function(o) {
			alert("error: " + YAHOO.lang.dump(o)); 
		}
	});
	loader.insert();
	var _createRTE = function(textareaId) {
		(function() {
			var Dom = YAHOO.util.Dom,
				Event = YAHOO.util.Event;
				
			YAHOO.mabole.glacier = function() {
				return {
					status: false,
					glacier: null,
					des: ['微笑','害羞','吐舌头','偷笑','爱慕','大笑','跳舞','飞吻','安慰','抱抱','加油','胜利','强','亲亲','花痴','露齿笑','查找','呼叫','算账','财迷','好主意','鬼脸','天使','再见','流口水','享受','色情狂','呆若木鸡','思考','迷惑','疑问','没钱了','无聊','怀疑','嘘','委屈','摇头','感冒','尴尬','傻笑','不会吧','无奈','流汗','凄凉','困了','晕','忧伤','委屈','悲泣','大哭','痛哭','I服了U','对不起','再见','皱眉','好累','生病','吐','背','惊讶','惊愕','闭嘴','欠扁','鄙视你','大怒','生气','财神','学习雷锋','恭喜发财','小二','老大','邪恶','单挑','CS','忍者','炸弹','惊声尖叫','漂亮MM','帅哥','招财猫','OK','鼓掌','握手','KISS','玫瑰','残花','爱心','心碎'],
					createGlacier: function() {
						this.glacier = new YAHOO.widget.Overlay('glacier1', {
							height: '245px',
							width: '335px',
							position: 'absolute',
							visible: false
						});
						this.glacier.hideEvent.subscribe(function() {
							myEditor.toolbar.deselectButton('emotion');
						}, this, true);
						this.glacier.showEvent.subscribe(function() {
						    myEditor.toolbar.selectButton('emotion');
							this.glacier.cfg.setProperty('context', [myEditor.toolbar.getButtonByValue('emotion').get('element'), 'tl', 'bl']);
						}, this, true);
						var warn = '';
						if (myEditor.browser.webkit || myEditor.browser.opera) {
						    warn = myEditor.STR_IMAGE_COPY;
						}
						var table = '<table id="glacier_emotion_list" style="background:url(http://static.mabole.com/images/emotion/emotions.png) no-repeat;margin:2px 3px 3px 2px">';
						var rows = 8,cols = 11,size=30;
						for (var i=0; i<rows; i++) {
							var rowHtml = '<tr>';
							for (var j=0; j<cols; j++) {
								var code = i*11 + j;
								var des = this.des;
								var title  = (des[code]) ? des[code] : '';
								rowHtml += '<td width="'+size+'" height="'+size+'" code="'+code+'" title="'+title+'"><div style="width:'+(size-1)+'px;height:'+(size-1)+'px"></div></td>';
							}
							rowHtml += '</tr>';
							table += rowHtml;
						}
						table += '</table>';
						this.glacier.setBody(table + warn);
						this.glacier.render(document.body);
						Dom.setStyle('glacier1', 'backgroundColor', 'white');
						Dom.setStyle('glacier1', 'opacity', '0.9');
		            },
		            open: function() {
		                this.glacier.show();
						this.status = true;
		            },
		            close: function() {
		                this.glacier.hide();
		                this.status = false;
		            },
		            toggle: function() {
		                if (this.status) {
		                    this.close();
		                } else {
		                    this.open();
		                }
		            }
		        }
		    }
		    
		})();
		var glacier = null;
		var anchorButton = { type: 'push', label: '插入链接', value: 'createlink', disabled: true };
		var imageButton = { type: 'push', label: '插入外链图片', value: 'insertimage' };
		var myConfig = {
			blankimage: 'http://static.mabole.com/images/blankimage.png',
			height: _config.height,
	        width: _config.width,
			handleSubmit:false,
			toolbar: {
				buttons: [
					{ group: 'insertitem', label: '',
						buttons: []
					}
				]
			}	
		}
		var buttonArray = myConfig.toolbar.buttons[0].buttons;
		if (_config.useAnchor) {
			buttonArray.push(anchorButton);
		}
		if (_config.useImage) {
			buttonArray.push(imageButton);
		}
		var myEditor = new YAHOO.widget.SimpleEditor(textareaId, myConfig);
		myEditor.STR_LINK_URL = '请填入链接地址';
		myEditor.STR_IMAGE_HERE = '图片地址';
		myEditor.on('toolbarLoaded', function() {
			if (_config.useEmotion) {
				glacier = new YAHOO.mabole.glacier();
				var emotionConfig = {
					type: 'push',
					label: '插入表情',
					value: 'emotion'
				}
				myEditor.toolbar.addButtonToGroup(emotionConfig, 'insertitem');
				myEditor.toolbar.on('emotionClick', function(ev) {
					if (ev && ev.code) {
						var src = 'http://static.mabole.com/images/emotion/' + ev.code + '.gif';
						var html = '<img src="' + src + '" title="' + ev.title + '" alt="' + ev.title + '">';
						this.execCommand('inserthtml', html);
					}
					glacier.toggle();
				}, myEditor, true);
				glacier.createGlacier();
			}
		});
		myEditor._defaultToolbar.buttonType = 'advanced'; 
		myEditor.render();
		
		YAHOO.util.Event.on('glacier_emotion_list', 'mousedown', function(ev) {
			var tar = YAHOO.util.Event.getTarget(ev);
			if (tar.tagName.toLowerCase() == 'div' && tar.parentNode.tagName.toLowerCase() == 'td') {
				var td = tar.parentNode;
				var code = td.getAttribute('code');
				var title = td.getAttribute('title');
				this.toolbar.fireEvent('emotionClick', {
					type: 'emotionClick',
					code: code,
					title: title
				});
			}
			YAHOO.util.Event.stopEvent(ev);
		}, myEditor, true);
		
		YAHOO.util.Event.on('glacier_emotion_list', 'mouseover', function(ev) {
			var tar = YAHOO.util.Event.getTarget(ev);
			if (tar.tagName.toLowerCase() == 'div' && tar.parentNode.tagName.toLowerCase() == 'td') {
				tar.style.borderStyle = 'outset';
				tar.style.borderWidth = '1px';
			}
		});
		
		YAHOO.util.Event.on('glacier_emotion_list', 'mouseout', function(ev) {
			var tar = YAHOO.util.Event.getTarget(ev);
			if (tar.tagName.toLowerCase() == 'div' && tar.parentNode.tagName.toLowerCase() == 'td') {
				tar.style.borderStyle = 'none';
				tar.style.borderWidth = '0px';
			}
		});
		return myEditor;
	};
}

YAHOO.mabole.Slide = function(containerId, oConfigs) {
	var AUTOPLAYTIMEOUT = 5000, TOGGLEDELAY = 100;
	if (oConfigs != undefined) {
		var autoPlayTimeout = oConfigs['autoPlayTimeout'];
		if (autoPlayTimeout != undefined) AUTOPLAYTIMEOUT = parseInt(autoPlayTimeout, 10) * 1000;
	}
	
	var container = Dom.get(containerId);
	var previewUl = Dom.getElementsByClassName('slide-preview', 'ul', container)[0];
	var previewLis = previewUl.getElementsByTagName('li');
	var titleUl = Dom.getElementsByClassName('slide-title', 'ul', container)[0];
	var titleLis = titleUl.getElementsByTagName('li');
	var currentIndex = 0;
	var total = titleLis.length;
	var autoInterval, toggleTimeout;
	
	for (var i=0,l=previewLis.length; i<l; i++) {
		if (i != 0) {
			previewLis[i].style.display = 'none';
		}
	}
	for (var i=0,l=titleLis.length; i<l; i++) {
		titleLis[i].setAttribute("yn-slide-index", i + '');
	}

	function showSlide(index) {
		if (currentIndex == index) return;
		previewLis[currentIndex].style.display = 'none';
		previewLis[index].style.display = 'block';
		Dom.removeClass(titleLis[currentIndex], 'current');
		Dom.addClass(titleLis[index], 'current');
		currentIndex = index;
	}
	
	function autoPlay() {
		var index = currentIndex + 1;
		if (index >= total) {
			index = 0;
		}
		showSlide(index);
	}
	
	function togglePlay(index) {
		showSlide(index);
	}
	
	//closure for setTimeout with parameters
	function callLater(index) {
		return (function() {
			togglePlay(index);
		});
	}
	
	autoInterval = window.setInterval(autoPlay, AUTOPLAYTIMEOUT);
	
	Event.on(previewUl, 'mouseover', function() {
		window.clearInterval(autoInterval);
	});
	Event.on(previewUl, 'mouseout', function() {
		autoInterval = window.setInterval(autoPlay, AUTOPLAYTIMEOUT);
	});
	
	Event.on(titleUl, 'mouseover', function(ev) {
		window.clearInterval(autoInterval);
		var container = this;
		var li = Event.getTarget(ev);
		while (li.tagName != 'LI' && Dom.isAncestor(container,li)) {
			li = li.parentNode;
		}
		if (li.tagName != 'LI') {
			return;
		}
		var index = parseInt(li.getAttribute('yn-slide-index'), 10);
		var laterToggelPlay = callLater(index);
		toggleTimeout = window.setTimeout(laterToggelPlay, TOGGLEDELAY);
	});
	Event.on(titleUl, 'mouseout', function(ev) {
		autoInterval = window.setInterval(autoPlay, AUTOPLAYTIMEOUT);
		window.clearTimeout(toggleTimeout);
	});
}