//取字符串字节长度  中文2个，英文1个
var getByteLength = function (str)
{
	return str.replace(/[^\x00-\xff]/g,"00").length;
}


//包含一些特殊字符
function includeSpecialChar(s) {
     var temp=" `-=\~!@#$%^&*()+|/;'!！◎＃￥％……※×（）‘’“”》《\"";
	 for( j=0;j<s.length; j++ )
	 {
	     var ch=s.charAt(j);
		 if( temp.indexOf(ch) != -1)
		 {
		      return true;
		 }	 
	 }
     return false;
}


/*
 * 过滤HTML
 */
var filterHtml = function (str) {
	str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
	str.value = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
	str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
	return str;
}

/*
 * 替换
 */
String.prototype.replaceAll  = function(s1,s2){    
	return this.replace(new RegExp(s1,"gm"),s2);    
} 

/**
 * 打开对话框 Open DialogBox
 * @param {Object} divId
 */
function openMessageBox(divId,textId,mesId) {
	//if text have data , then clear it .
	$('#'+textId).val('');
	//if message have information, then clear it.
	$('#'+mesId).html('');
	
	jQuery.blockUI({  
        message: jQuery('#'+divId),
		css: {
			border:'0px solid #606060',
			width:'302px',
			height:'152px',
			cursor: 'auto'
    	},
		overlayCSS:  {  
	        backgroundColor:'#000000',  
	        opacity:'0.1',
			cursor: 'auto'
    	},
		fadeOut:100
    });
}

/**
 * 关闭对话框 Close DialogBox
 * @param {Object} divId
 */
function closeMessageBox(divId) {
	jQuery.unblockUI('#'+divId);
}

/**
 * 关闭对话框 close dialogbox
 * 并且焦点在text focus on text
 * @param {Object} divId
 * @param {Object} textId
 */
function closeMessageBoxAndFocusOnText(divId,textId) {
	jQuery.unblockUI('#'+divId);
	$('#'+textId).focus();
}

/**
 * 显示提示信息并且绑定确定按钮
 * show message and bind ok button
 * @param {Object} message
 * @param {Object} textId
 */
function showMessageAndBindMessageOkButton(message,textId) {
	
	$('#message_ok_button_id').unbind( "click");

	$('#message_ok_button_id').click(function() {
		closeMessageBoxAndFocusOnText('model_message_div_id',textId);
	});
	
	$('#message_info_id').html(message);
	openMessageBox(MESSAGE_DIALOG_DIV_ID);
	
}

/**
 * @param {Object} switchId
 * @param {Object} checkbox_name
 */
function checkAll(switchId,checkbox_name) {
	$("input[@type=checkbox][@name=" + checkbox_name + "]").attr("checked", $('#'+switchId).attr('checked'));
}

/**
 * forward
 * @param {Object} url
 */
function forward(url) {
	window.location.href = url;
}

/**
 * 验证是否是指定图片类型
 * @param p_imageNameId <input type="file" id="imageFile1">
 */
function judgePhotoType(p_imageNameId) {
	var imageNameId = 'imageFile';
	if(p_imageNameId!=null) {
		imageNameId = p_imageNameId;
	}
	
	var l_type = new Array("jpg","jpe","jpeg","gif","bmp","png");
	for (var i=1; i<=5; i++) {
		var photo = document.getElementById(imageNameId+i).value;
		if($.trim(photo)!='') {
			 var last = photo.lastIndexOf('.');
			 photo = photo.substring(last+1);
			 var isLegal = false;
			 for(var j=0;j<l_type.length;j++) {
			 	   if(photo.toLowerCase()==l_type[j]) {
			 	   	  isLegal = true;
			 	   	  break;
			 	   }	
			 }
			 if(!isLegal) {
			 		return false;
			 }
		}
	}
	return true;
}

/**
 * 获取checkbox的值
 * @param {Object} name 
 * for exmaple  name:aihao
 * <input type="checkbox" name="aihao" value="football"/>
 * @return 1|2|3 (以|分隔)
 */
function getCheckboxValue(name) {
	var object = $("input[@name="+name+"][@checked]");
	var checkedSize = object.length;
	var str = "";
	for(var i=0;i<checkedSize;i++) {
		str+=object.get(i).value;
		if(i!=(checkedSize-1)) {
			str+="|";
		}
	}
	return str;
}

/**
 * 是否是合法的Url
 */
function isRightUrl(url) {
	url = $.trim(url).toLowerCase();
	var patrn = /(^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$)|(^[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$)/;
	return execPatten(url,patrn);
}

/**
 * 是否是数字
 */
 function isNumber(s){ 
	var patrn = /^[0-9]*$/;
	return execPatten(s,patrn);
} 

/**
 * @param str 字符串
 * @param patten 表达式规则
 * 执行正则表达式(公用方法)
 */
function execPatten(str,patten) {
	if (!patten.exec(str)) 
	return false ;
	return true ;
}


/**
 * 设置标准模块名称
 * @param {Object} standId  标准模块ID
 * @param {Object} lang     CN or EN
 * @param {Object} isByLang true:根据语言来取
 */
function setStandardModuleAlias(standId,lang,isByLang) {
	var l_aliasCN = get_aliasByStandardId(standId,'CN');
	$("b").filter(".aliasCN").html(l_aliasCN);
	$("span").filter(".aliasCN").html(l_aliasCN);
	
	if (isByLang) {
		var l_aliasByLang = get_aliasByStandardId(standId,lang);
		$("b").filter(".aliasByLang").html(l_aliasByLang);
	}
}


/**
 * 主题图片按比例显示
 * @param {Object} ImgD
 * @param {Object} maxwidth
 * @param {Object} maxheight
 */
function DrawImage(imgId, maxwidth, maxheight){
    var ImgD = document.getElementById(imgId);
    var image = new Image();
    image.src = ImgD.src;
    if (image.width > 0 && image.height > 0) {
        if (image.width / image.height >= maxwidth / maxheight) {
            if (image.width > maxwidth) {
                ImgD.width = maxwidth;
                ImgD.height = (image.height * maxwidth) / image.width;
            }
            else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
        }
        else {
            if (image.height > maxheight) {
                ImgD.height = maxheight;
                ImgD.width = (image.width * maxheight) / image.height;
            }
            else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
        }
    }
}

var htmltool = {};
(function(){

  // not allowed tags
  var _aYesTag = [
    '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'
  ];

  // not allowed attribute
  var _aYesAttr = ['style', '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;
			}
		}
	};
	
	htmltool.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;
	}
})();



