var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
 }

var Fpi = {};

Fpi.Util = {
	isInt	:	function (str){
		if(!str){
			return false;
		}
	
		return /^[+-]?\d+$/.test(str);
	},
	
	isUInt	:	function (str){
		if(!str){
			return false;
		}
	
		return /^\d+$/.test(str);
	},
	
	isByte	:	function (str) {
		if (str && str.trim() != "") {
			var reg = /^(?:(?:0x[0-9a-fA-F]+)?[0-9]*)+$/;
			if (reg.test(str.trim())) {
				return parseInt(str) >= 0 && parseInt(str) <= 255;
			}
		}
		return false;
	},
	
	isBit	:	function (str) {
		if (str && str.trim() != "") {
			var reg = /^0|1$/;
			return reg.test(str.trim());	
		}
		return false;
	},

	isNumeric	:	function (str){
		if(!str){
			return false;
		}		   
		var reg = /^[+-]?\d+(?:\.?\d+)?$/;
		
		return reg.test(str);
	},
	isIdFormat		:	function(str){
		if(!str){
			return false;
		}
		
		return /^\w+$/.test(str);
	},
	
	decimal_digits : function(str){
		if(!this.isNumeric(str)){
			return -1
		}
		var i = str.indexOf(".");
		if(i == -1){
			return 0
		}else{
			return str.length - i - 1;
		}
	},
	isFloat : function(str){
		var reg = /^[+-]?\d+\.?\d*(?:E\d+)?$/i;
		
		return reg.test(str);
	},

	checkUserName	:	function(userName){
		if(!userName){
			return false;
		}
	
		return /^\w{3,20}$/.test(jQuery.trim(userName));
	},

	checkPassword	:	function(password){
		if(!password){
			return false;
		}
	
		password = jQuery.trim(password);
		if(password.length < 3 || password.length > 20){
			return false;
		}	
	
		return true;
	},

	checkURL	:	function(url){
		if(!url){
			return false;
		}
		var reg = /^http(?:s)?:\/\/([\w-]+\.)+[\w-]+(:\d+)?$/;
	
		return reg.test(url);
	},
	
	checkExcelFile	:	function(fileName){
		var reg = /^[a-zA-Z]:(\\|\/).+\.xls$/i
		return reg.test(fileName);
	},
	
	checkSpecialCharacter	:	function(str){
		var reg = /^[^'"<>\、=&]*$/i;
		return reg.test(str);
	},
	checkMaxLength	:	function(box, maxLength) {
		if ((box.value.length) >= maxLength) {
			box.value = box.value.substring(0, maxLength - 1);
		}
	},
	showError	:	function(msg, obj){
		this.showMessage(msg, 'error', obj);
	},

	showWarning	:	function(msg, obj){
		this.showMessage(msg, 'warning', obj);
	},

	showInfo	:	function(msg, obj){
		this.showMessage(msg, 'info', obj);
	},

	showMessage	:	function (msg, type, obj){
		var className = 'portlet-msg-success';
	
		switch(type){
			case 'info':className = 'portlet-msg-info';
				break;
			case 'succ':className = 'portlet-msg-success';
				break;
			case 'error':className = 'portlet-msg-error';
				break;
			case 'warning':className = 'portlet-msg-alert';
				break;
			default:className = 'portlet-msg-success';
				break;
		}
		var infoDiv = document.createElement('div');
		infoDiv.innerHTML = msg;
		infoDiv.className = className;
	
		if(obj && typeof(obj) == 'function'){
			obj(infoDiv);
		}else{
			var parent_ = (obj ? (typeof(obj) == 'object' ? obj : document.getElementById(obj)) : document.getElementById('messageInfo'));
			
			if(parent_){
				parent_.style.display = '';
				parent_.innerHTML = '';
				parent_.appendChild(infoDiv);
				this.scrollTo(infoDiv);
			}else{
				alert(msg);
			}
		}
	},	

    pageDatas:[] ,
	
	createTableList	:	function(table, datas, noDatasMessage, showCheckbox,createMenu){
		noDatasMessage = noDatasMessage || '\u627e\u4e0d\u5230\u8bb0\u5f55';
		this.pageDatas=[];
		if(!table){
			table = document.createElement('table');
			var tbody = document.createElement('tbody');
			table.appendChild(tbody);
		}
	
		//var tbody = (Liferay.Browser.is_ie ? table.getElementsByTagName('TBODY')[0] : table);
		var tbody = table.getElementsByTagName('TBODY')[0] || table;
	
		// clear rows
		while(tbody.childNodes.length > 0){
			tbody.removeChild(tbody.childNodes[0]);
		}
		
		// create header
		var headers = datas.headers;
		//modify by zyj 090416 自定义表头
		var selfHeaders = datas.selfHeaders;
		if(selfHeaders){
			jQuery(tbody).append(selfHeaders);
		}
		else if(headers && headers.length > 0){

			var headerRow = document.createElement('tr');
			
			// add header
			tbody.appendChild(headerRow);
			
			headerRow.className = 'portlet-section-header';
			
			// header checkbox
			if(showCheckbox){
				var checkTh = document.createElement('th');
				headerRow.appendChild(checkTh);
			
				var headerCheckbox = document.createElement('input');
				headerCheckbox.type = 'checkbox';
				checkTh.appendChild(headerCheckbox);
				
				// 绑定checkbox事件（全选或全不选）
				jQuery(headerCheckbox).bind('click', function(){
					var headerCheckbox = this;
					
					jQuery(table).find('tr').each(function(){
						jQuery(this).children(':first').children(':first').attr('checked', headerCheckbox.checked);
					});
				});
			}
			
			for(var i = 0; i < headers.length; i++){
				var th = document.createElement('th');
				
				// add column(th)
				headerRow.appendChild(th);
				
				/*
				 * header example
				 * {
				 * 		name : 第一列,
				 * 		field	:	'name',
				 * 		className : 'header-one',
				 *  	styles{
				 * 			background	:	'red',
				 * 			align		:	'center'
				 * 		},
				 * 		maxLength		: 40,
				 * 		
				 * }
				 */
				
				var head = headers[i];
				var headName = head.name || '';
				var headClassName = head.className;
				var styles = head.styles;
				
				if(headClassName){
					th.className = headClassName;
				}
				// set th style
				for(var style in styles){
					th.style[style] = styles[style];
				}
				
				var innerHeadDiv = document.createElement('div');
				
				th.appendChild(innerHeadDiv);
				
				getInnerHTMLWithStyle(innerHeadDiv, head, headName)
			}
		}
			
		// if no datas
		if(!datas || datas.length == 0){
			var tr = Fpi.Util.createRow(0);
			tbody.appendChild(tr);
			
			var td = Fpi.Util.createColumn();
			tr.appendChild(td);
			
			if(headers){
				td.colSpan = headers.length + (showCheckbox ? 1 : 0);
			}
			
			td.align = 'center';			jQuery(td).html(noDatasMessage);				
			return table;
		}
			
		// add datas
		for(var i = 0; i < datas.length; i++){
			var data = datas[i];
			data['recordId'] = i;
			
			this.pageDatas[data['recordId']]=data;
			var tr = Fpi.Util.createRow(i);
			
			tbody.appendChild(tr);
			
			if(headers && headers.length > 0){ // has headers
				
				// checkbox column
				if(showCheckbox){
					var checkTd = Fpi.Util.createColumn();
					tr.appendChild(checkTd);
				
					var ck = document.createElement('input');
					ck.type = 'checkbox';
					checkTd.appendChild(ck);
					
					jQuery(ck).click(changeCheck);
				}	
					
				for(var j = 0; j < headers.length; j++){
					
					var td = Fpi.Util.createColumn();
			
					tr.appendChild(td);
			
					var header = headers[j];
					var field = header.field; // 获取数据字段或显示方式
					//设置id
					if (data['id'] && header.id) {
						td.id = header.id + "_" +data['id'];
					}						
					if(typeof(field) == 'function'){
						//field(td, data);
						var returnData = field(td, data);
						
						// 如果有返回值，则表示需要格式化
						if(returnData && !returnData.tagName){
							var innerDiv = document.createElement('div');
						
							td.appendChild(innerDiv);
							getInnerHTMLWithStyle(innerDiv, header, returnData);
						}
					}else{
						var tdDatas = data[field];
						
						var innerDiv = document.createElement('div');
						
						td.appendChild(innerDiv);
						
						getInnerHTMLWithStyle(innerDiv, header, tdDatas);
					}
				}
			}else{
				for(var field in data){ // no headers, show all data field
					var td = Fpi.Util.createColumn();
					tr.appendChild(td);
					
					var innerDiv = document.createElement('div');
					td.appendChild(innerDiv);
					
					getInnerHTMLWithStyle(innerDiv, null, data[field])
				}
			}
		}
		
		if(createMenu){
			new Liferay.Menu(
				{
					trigger: '.lfr-trigger',
					context: table,
					button: '.lfr-actions'
				}
			);
		}
		
		return table;
		
		// 复选框选中状态更改
		function changeCheck(){
			var checkboxCount = jQuery(table).find('tr:gt(0)').length;
			
			var checkedCount = 0;
			
			jQuery(table).find('tr:gt(0)').each(function(){
				if(jQuery(this).find('td:first input:checkbox').eq(0).attr('checked')){
					checkedCount++;
				}
			});
			
			if(checkboxCount == checkedCount){
				jQuery(table).find('tr:first input:checkbox').eq(0).attr('checked', true);
			}else{
				jQuery(table).find('tr:first input:checkbox').eq(0).attr('checked', false);
			}
		}
		
		// 格式化文本
		function getInnerHTMLWithStyle(innerDiv, header, tdDatas){			
			
			innerDiv.style.whiteSpace = 'nowrap';
			innerDiv.style.textOverflow  = 'ellipsis';
			innerDiv.style.overflow = 'hidden';
			
			innerDiv.title = Fpi.Util.sub_str(Fpi.Util.decodeHTML(tdDatas), 800, 'left');
			
			if(!header){
				innerDiv.innerHTML = Fpi.Util.sub_str(tdDatas, 40, 'left');
				return;
			}
			
			if(header.width || (header.styles && header.styles.width)){ 
				innerDiv.style.width = header.width || header.styles.width;
			}
			
			if(header.maxLength){ // 最大长度限制
				innerDiv.innerHTML = Fpi.Util.sub_str(tdDatas, header.maxLength, 'left');
			}else if(!header.width){ // 没有最大宽度限制时，默认取 40 个字符（每个中文视为两个字符）
				jQuery(innerDiv).html(Fpi.Util.sub_str(tdDatas, 40, 'left')) ;
			} else{ // 有最大宽度限制时，默认取 400个字符（根据限制宽度，会自动取适合长度的字符串，限制取400个字符是当字符串长度太长时，浏览器长时间没有反应）
				innerDiv.innerHTML = Fpi.Util.sub_str(tdDatas, 400, 'left');
			}
		}
	},
	
	//获取每行对象
	getPageDatas:function(){
		return this.pageDatas;
	},
	createRow	:	function (i){
		var tr = document.createElement("tr");
			
		if(i % 2 ==0){
			//tr.setAttribute("className","portlet-section-body");
			//tr.onmouseleave  = function(){this.className = 'portlet-section-body';};
			tr.className = "portlet-section-body ";
			tr.onmouseout =  function(){this.className = 'portlet-section-body';};
			tr.onmouseover  =  function(){this.className = 'portlet-section-body-hover';} ;
		}else{
			//tr.setAttribute("className","portlet-section-alternate");
			//tr.onmouseleave  = function(){this.className = 'portlet-section-alternate';};
			tr.className = "portlet-section-alternate ";
			tr.onmouseout =  function(){this.className = 'portlet-section-alternate';};
			tr.onmouseover  =  function(){this.className = 'portlet-section-alternate-hover';} ;
		} 
		//tr.onmouseenter  =  function(){this.className = 'portlet-section-body-hover';} ;
		
		
		return tr;
	},
		
	createColumn	:	function(){
		var td = document.createElement("td");
		td.style.wordBreak  = 'keep-all';
		//td.width = '200px';
		td.style.textOverflow  = 'ellipsis';
		return td;
	},
	
	resizeIframe	:	function (){
		setTimeout(Fpi.Util.resize, 100);
	},
	
	resize			:	function (){
		
		//去除样式
	 	document.getElementsByTagName("body")[0].className="";
    	document.getElementsByTagName("body")[0].scroll="auto";
    	 
//		var popHeight = parseFloat(document.body.scrollHeight) > parseFloat(parent.Viewport.frame().y) ? (parent.Viewport.frame().y-60) : document.body.scrollHeight;
//		var popWidth = parseFloat(document.body.scrollWidth) > parseFloat(parent.Viewport.frame().x) ? (parent.Viewport.frame().y-60) : document.body.scrollWidth;
		var popHeight = window.screen.height * 0.7;	
		var popWidth =  window.screen.width * 0.8;
		popHeight = popHeight < 300 ? 300:popHeight;
		popWidth = popWidth < 800 ? 800:popWidth;
		parent.Liferay.Popup.resizeIframe(
			{
				height:popHeight,
				width:popWidth
			});
		
		parent.Liferay.Popup.center();
	},
	scrollTo	:	function(element){
		var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
	},
	escapeHTML	:	function (value)
    {
        function replaceChars(ch)
        {
            switch (ch)
            {
                case "<":
                    return "&lt;";
                case ">":
                    return "&gt;";
                case "&":
                    return "&amp;";
                case "'":
                    return "&#39;";
                case '"':
                    return "&quot;";
            }
            return "?";
        };
        return String(value).replace(/[<>&"']/g, replaceChars);
    },
    decodeHTML		:	function(value){
    	function replaceChars(ch){
    		switch(ch){
    			case '&lt;':
    				return '<';
    			case '&gt;':
    				return '>';
    			case '&amp;':
    				return '&';
    			case '&#39;':
    				return '\'';
    			case '&quot;':
    				return '"';
    		}
    		return '?';
    	}
    	
    	return String(value).replace(/(?:&lt;)|(?:&gt;)|(?:&amp;)|(?:&quot;)|(?:&#39;)/g, replaceChars);
    },
	sub_str		:	function(originalStr, len, place){
		originalStr = originalStr || '';
		
		originalStr = originalStr.toString();
		var str = originalStr;
		
		if(str.replace(/[^\x00-\xff]/gi,'xx').length <= len) 
			return str;
		if(place == 'left'){
			var temp_len = len;
			str = str.substr(0, len);
			while(str.replace(/[^\x00-\xff]/gi, 'xx').length > len){
				str = str.substr(0, --temp_len);
			}
		}
		
		if(place == 'right'){
			str = str.substr(str.length - len, len);
			while(str.replace(/[^\x00-\xff]/gi,'xx').length > len){
				str = str.substr(1, len);
			}
		}
		
		return originalStr.length > str.length ? str + '...' : str;
	},
	getCheckedValuesByName	:	function(name, form){
		form = form || document;
		
		var jQueryObj = jQuery('input[@type="checkbox"][@name="' + name + '"]:checkbox:checked', form);
		
		var valueArr = []
		
		jQueryObj.each(
			function(){
				valueArr.push(this.value);
			}
		);
		
		return valueArr;
	},
	createMenu		:	function(td, subMenus){
		if(!subMenus){
			return;
		}
		var jMenu =''
		//jMenu += '<ul class="lfr-actions">';
		jMenu += '<ul class="lfr-component lfr-actions right">';
		jMenu += '	<li class="lfr-trigger">';
		jMenu += '		<strong><span>actions</span></strong>';
		jMenu += '			<ul>'; 
					
		jMenu += '			</ul>';
		jMenu += '	</li>';
		jMenu += '</ul>'; 
					
		var j_q = jQuery(jMenu);
					
		j_q.find('li.lfr-trigger ul').append(jQuery(subMenus));
					
		j_q.appendTo(td);
					
		// 当行数增加时,速度太慢, context 由 tr 换成table, 该段代码由绑定数据后调用.
		/*new Liferay.Menu(
			{
				trigger: '.lfr-trigger',
				context: td.parentNode.parentNode,
				button: '.lfr-actions'
			}
		);*/
	},
	// 将有参数的函数封装为无参数的函数
	createFunction	:	function(obj, method){
		var args = new Array();
		
		obj = obj || window;
		
		for(var i = 2; i < arguments.length; i++){
			args.push(arguments[i]);
		}
		
		return function(){
			
			obj[method].apply(obj, args.concat($A(arguments)));
		}
	},
	getCheckedIndex	:	function(table, col){
		col = col || 0;
		
		var checkedIndexArr = [];
		
		jQuery(table).find('tr:gt(0)').each(function(index, tr){
			if(jQuery(this).find('td:eq(' + col + ') input:checkbox').eq(0).attr('checked')){
				checkedIndexArr.push(index);
			}
		});
		
		return checkedIndexArr;
	},
	getUncheckedIndex	:	function(table, col){
		col = col || 0;
		
		var uncheckedIndexArr = [];
		
		jQuery(table).find('tr:gt(0)').each(function(index, tr){
			//if(!jQuery(this).find('td:eq(' + col + ') input:checkbox').eq(0).attr('checked')){
			if(jQuery(this).find('td:eq(' + col + ') input:checkbox').eq(0).attr('checked') == false){
				uncheckedIndexArr.push(index);
			}
		});
		
		return uncheckedIndexArr;
	},
	setCheckedIndex	:	function(table, checkedIndexArr, col){
		col = col || 0;
		
		jQuery(checkedIndexArr).each(function(){
			jQuery(table).find('tr:eq(' + (this + 1) + ') td:eq(' + col + ') input:checkbox').attr('checked', true);
		});
	},
	// 封装Liferay提供的方法
	addParams		:	function(params, url) {
		return Liferay.Util.addParams(params, url);
	}
}

Fpi.Util.showWindow = function(url, params, title, onClose){
	if(params){
		url = Liferay.Util.addParams(params, url);
	}
	
	Fpi.Popup.iframe(url,
		{	
			title: title,
			onClose:onClose
		}
	);
}

Fpi.Popup = {
	iframe	:	function(url, options){
		
		var popHeight = window.screen.height * 0.7;	
		var popWidth =  window.screen.width * 0.8;
		if (options.width && options.height && options.width>0  && options.height>0) {
			popHeight = options.height;
			popWidth = options.width;		
		}
		else {
			popHeight = popHeight < 300 ? 300 : popHeight;
			popWidth = popWidth < 800 ? 800 : popWidth;
		}
		if (options.position) {
		   position = options.position;
		}
		else {
			position = ['center', 'middle'];
		}
		var defaultOptions = {
			modal: true,
			width: popWidth,
			height : popHeight,
			overflow: 'auto',
			position : position
		}
		
		jQuery.extend(options, defaultOptions);
		
		var iframe = document.createElement("iframe");

		iframe.src = url;
		iframe.frameBorder = 0;
		iframe.overflow = 'scroll';	
	
		iframe.width = options.width - 30;
		iframe.height = options.height - 30; 
		var wrap = document.createElement('div');
		//wrap.width = options.width;
		//wrap.height = options.height;
	
		wrap.appendChild(iframe);
		
		options.message = wrap;
	
		return Liferay.Popup(options);
	},
	close	:	function(el){
		Liferay.Popup.close(el);
	}
}
