function str_replace(){
	var args = arguments;
	return 	args[0].replace(/\{(\d+)\}/g, function(a, index){
		return args[index];
	});
}

function Alert(msg){
	Pur5.Record.append(msg);
	alert(msg);
}
function js_type(obj){
	return Object.prototype.toString.call(obj).match(/(\w+)/g)[1];
}

function toJson(key){
	var f = function(n) {
		return n < 10 ? '0' + n: n
	},
	keyType = js_type(key),
	hash = {
		'Date': function(){
			return isFinite(key.valueOf()) ? key.getFullYear() + '-' + f(key.getMonth() + 1) + '-' + f(key.getDate()) + ' ' + f(key.getHours()) + ':' + f(key.getMinutes()) + ':' + f(key.getSeconds()) : null;
		},
		'String': function(){
			return key.valueOf();
		},
		'Number': function(){
			return this['String']();
		},
		'Object': function(){
			return $.stringify(key);
		}
	};
	
	return hash[keyType]? hash[keyType]():'';
}


/** 
 *  
 * @param {String} 
 *            str 字符串 
 * @return {String} 将全角全部转换为半角的字符串 
 */  
function toDBC(str){  
    if (str) {  
        var result = "";  
        var code = 0;  
        for (var i = 0; i < str.length; i++) {  
            code = str.charCodeAt(i);  
            if (code == 12288) {  
                result += String.fromCharCode(32);  
            } else if (code > 65280 && code < 65375) {  
                result += String.fromCharCode(code - 65248);  
            } else {  
                result += str.charAt(i);  
            }  
        }  
        return result;  
    }  
    return str;  
} 

function gb2utf8(data){ 
    var glbEncode = []; 
    gb2utf8_data = data; 
    execScript("gb2utf8_data = MidB(gb2utf8_data, 1)", "VBScript"); 
    var t=escape(gb2utf8_data).replace(/%u/g,"").replace(/(.{2})(.{2})/g,"%$2%$1").replace(/%([A-Z].)%(.{2})/g,"@$1$2"); 
    t=t.split("@"); 
    var i=0,j=t.length,k; 
    while(++i<j) { 
       k=t[i].substring(0,4); 
       if(!glbEncode[k])  
       { 
          gb2utf8_char = eval("0x"+k); 
          execScript("gb2utf8_char = Chr(gb2utf8_char)", "VBScript"); 
          glbEncode[k]=escape(gb2utf8_char).substring(1,6); 
       } 
       t[i]=glbEncode[k]+t[i].substring(4); 
    } 
    gb2utf8_data = gb2utf8_char = null; 
    return unescape(t.join("%")); 
}

function getFields(fields, content, regexp){
	var result,
		regType,
		matched;
	
	if(js_type(regexp) == 'RegExp'){
		result = [];
		content.replace(regexp, function(){
			var arg = arguments,
				obj = {};
				
			$.each(fields, function(name, index){
				if(js_type(index) == 'Number'){
					obj[name] = arg[index];
				}else if(js_type(index) == 'Function'){
					obj[name] = index.call(obj, content);
				}else{
					obj[name] = index;
				}
			});
			result.push(obj);
		})
		if(!regexp.global) result = result[0];
	}else{
		result = {};
		$.each(fields, function(name, reg){
			regType = js_type(reg);
			if(regType === 'RegExp'){
				matched = content.match(reg);
				if(!matched){
					result[name] = false;
				}else if(matched.length === 1){
					result[name] = true;
				}else if(matched.length > 1){
					result[name] = matched[reg.global?0:1];
				}
			}else if(regType === 'Function'){
				result[name] = reg.call(fields, content);
			}else{
				result[name] = reg;
			}
		});
	}
	return result;
};

(function($){
	$.fn.extend({
		serializeObject: function(){
			var	form = this;
				tempObj = {},
				result = {};				
			if(form.length > 1) return false;
			$.each($.makeArray(form[0].elements), function(index, obj){
				if(obj.name)tempObj[obj.name] = obj.value
			});
			
			var elem,
				tagName,
				tagType,
				defaultValue;
				
			$.each(tempObj, function(key, val){
				elem = form.find('[name='+key+']');
				if(elem.length === 0) return;
				
				tagName = elem.prop('tagName').toLowerCase(),
				tagType = elem.prop('type'),
				defaultValue = elem.prop('default');
				
				if(tagName == 'input' && tagType == 'checkbox'){
					val = (function(){
						var value = [];
						elem.filter(':checked').each(function(){
							value.push($(this).val());
						});
						if(value.length === 1){
							value = value[0];
						}else if(value.length === 0){
							value = undefined;
						}
						return value;
					})();
					
				}
				if(val == '' && defaultValue){
					val = defaultValue;
				}
				
				result[key] = val;
			});
			
			return result;
		},
		keywordspath: function(){
			this.each(function(index, item){
				var self = $(item);
				self.val(Fso.read('controls/' +  self.attr('keywordspath')));
				self.blur(function(){
					this.value = (''+this.value).replace(/[,，\|\s]+/g,',').replace(/^,|,$/g,'');
					var path = 'controls/' +  self.attr('keywordspath');
					
					if(this.value == ''){
						Fso.del(path);
					}else{
						Fso.write(path, this.value);
					}
				});
			});
			return this;
		},
		datapath: function(){
			this.each(function(index, item){
				var self = $(item);
				self.val(Fso.read('controls/' +  self.attr('datapath')));
				self.blur(function(){
					this.value = (''+this.value);
					var path = 'controls/' +  self.attr('datapath');
					if(this.value == ''){
						Fso.del(path);
					}else{
						Fso.write(path, this.value);
					}
				});
			});
			return this;
		},
		tabs: function(){
			this.each(function(index, item){
				var self = $(item);
				self
				.bind('active', function(event, index){
					if(index === $(this).triggerHandler('getIndex')) return false;
					self.find('.nav').children().eq(index).addClass('actived').siblings().removeClass('actived');
					self.find('.content').children().eq(index).show().siblings().hide();
					self.trigger('actived', [index]);
				})
				.bind('getIndex', function(event){
					return self.find('.nav li.actived').index();
				})
				.find('.nav').children().click(function(){
					var This = $(this);
					self.trigger('active', [This.index()]);
				});
			});
			return this;	
		},
		gridview: function(){
			this.each(function(index, item){
				var gridview = $(item),
					selfHeight = gridview.outerHeight(),
					lastHeight = selfHeight,
					table = gridview.find('table')[0].outerHTML;
				gridview.empty();
				var	header = $('<div class="header hide"></div>').appendTo(gridview);
					bodier = $('<div class="bodier"></div>').appendTo(gridview);
					footer = $('<div class="footer hide">footer</div>').appendTo(gridview);
					
				bodier.append(table);
				header.append(table);
				header.find('tbody').remove();
				
				header.find('table th')
				.filter(':first').css({
					'border-left-color': header.find('table thead tr th').css('background-color')
				}).end()
				.filter(':last').css({
					'border-right-color': header.find('table thead tr th').css('background-color')
				});
				
				var	tbody = bodier.find('table tbody');
				if(gridview.attr('static') != 1){
					gridview.attr('template', tbody.html());
					tbody.empty();
				}				
				
				gridview
				.bind('selectstart', function(){
					return gridview.attr('actived') != 1;
				})
				.bind('refresh', function(event, Arg){
					var gridview = $(this),
						header = gridview.find('.header'),
						bodier = gridview.find('.bodier'),
						footer = gridview.find('.footer'),
						table = bodier.find('table'),
						template = gridview.attr('template') || '',
						contextMenu = gridview.find('.contextMenu').hide(),
						rowArr = [];
					header.find(':checkbox').attr('checked', false);
					
					var menus = ['反 选'];
					$.each(Arg.selected || [], function(text, action){
						menus.push(text);
					});
					
					if(!contextMenu.length){
						contextMenu = $('<ul class="contextMenu">' + joinWithTag(menus, '<li><a href="#">', '</a></li>') +  '</ul>').appendTo(gridview);
						contextMenu.css({
							width: contextMenu.width()
						});
						contextMenu.find('li>a').click(function(){
							gridview.trigger('hideContextMenu');
							if($(this).text() == '反 选'){
								table.find('tbody tr').toggleClass('actived');
								gridview.trigger('takeCheckbox');
								return false;
							}

							if(!Arg.selected[$(this).text()](gridview.triggerHandler('getSelectedRow', [Arg.getRow]), gridview)) return;
						});
					}
					
					if(gridview.attr('static') == 1){
						gridview.removeAttr('footer');
						var Arg = {
							list: [],
							filter: {}
						}
					}
					
					if(gridview.attr('header') == 1){
						header.show();
					}
					if(gridview.attr('footer') == 1){
						footer.show();
					}
					bodier.height(gridview.outerHeight() - (header.is(':visible')?header.outerHeight():0) - (footer.is(':visible')?footer.outerHeight():0));
					
					if(gridview.attr('static') != 1){
						table
						.find('tbody').empty()
						.html(parseData2Template(template, Arg.list, Arg.filter));
					}
					
					header.find(':checkbox').click(function(event){
						if(gridview.attr('actived') == 1){
							table.find('tbody tr').toggleClass('actived', $(this).is(':checked'));
							gridview.trigger('takeCheckbox');
						}
					});
					
					table
					.find('tbody tr')
					.mousedown(function(event){//TODO:拖动选择
						var Row = $(this);
						if(!event.shiftKey) gridview.attr('lastActivedRowIndex', Row.index());
					})
					.mousemove(function(){
						
					})
					.mouseup(function(){
						
					})
					.mouseover(function(){
						$(this).addClass('hover').siblings().removeClass('hover');
					})
					.bind('contextmenu', function(event){
						if(gridview.attr('actived') != 1) return;
						
						var Row = $(this);
						if(!Row.hasClass('actived')){
							Row.addClass('actived').siblings().removeClass('actived');
							gridview.trigger('takeCheckbox');
						}
						
						if(table.find('tbody tr.actived').length == 0) return false;
						contextMenu.css({
							left: event.pageX + gridview.position().left - gridview.offset().left + 5,
							top: event.pageY + gridview.position().top - gridview.offset().top							
						}).show();
						return false;
					})
					.click(function(event){
						var Row = $(this),
							rowIndex = Row.index(),
							lastActivedRowIndex = gridview.attr('lastActivedRowIndex');
						if(gridview.attr('actived') == 1){
							if(!event.shiftKey) gridview.attr('lastActivedRowIndex', Row.index());
							
							if(event.shiftKey){
								if(lastActivedRowIndex == undefined || rowIndex == lastActivedRowIndex) return false;
								var minIndex = Math.min(rowIndex,lastActivedRowIndex),
									maxIndex = Math.max(rowIndex,lastActivedRowIndex);
									
								table.find('tbody tr').each(function(index, tr){
									Row = $(this);
									if(index >= minIndex && index <= maxIndex){
										Row.addClass('actived');
									}else{
										Row.removeClass('actived');
									}
								});
							}else if(event.ctrlKey){
								Row.toggleClass('actived');
							}else{
								Row.addClass('actived').siblings().removeClass('actived');
							}
						}
						gridview.trigger('takeCheckbox');
					})
					.filter(':odd').addClass('odd').end()
					.find('td')
					.find(':checkbox').click(function(event){
						$(this).parent().parent().toggleClass('actived', $(this).is(':checked'));
						gridview.trigger('takeCheckbox');
						event.stopPropagation();
					})

					setTimeout(function(){
						header
						.find('table').width(table.outerWidth())
						.find('thead tr th').each(function(index, th){
							$(th).width(bodier.find('table tbody tr:eq(0) td:eq(' + index + ')').width());
						}).filter(':last').css({
						});
					}, 0);
					Arg.page && !function(){
						var Page = $.extend(Arg.page, {
							page_count: Arg.page.count < Arg.page.page_size?1:Math.ceil(Arg.page.count/Arg.page.page_size),
							page_no: parseInt(Arg.page.page_no)
						});
						
						footer.html('<table class="pagebar"><tr><td><ul>'+
							function(){
								var template = '<li class="$current" page="$page_no">$page_no_text</li>',
									start_page = Page.page_no - 3,
									end_page = Page.page_no + 3,
									start_page = start_page < 1?1:start_page,
									pages = (function(){
										var tempArr = [];
										for(var i=start_page; i<= end_page && i <= Page.page_count; i++){
											tempArr.push(
												template.replace(/\$page_no_text|\$page_no/g, i)
														.replace(/\$current/g, i==Page.page_no?'current':'')
											);
										}
										if(Page.page_count >= 5 && Page.page_no > 1){
											tempArr.unshift(
												template.replace(/\$page_no_text/g, '上页')
														.replace(/\$page_no/g, Page.page_no - 1)
											);
											tempArr.unshift(
												template.replace(/\$page_no_text/g, '首页')
														.replace(/\$page_no/g, 1)
											);
										}
										if(Page.page_count >= 5 && Page.page_no < Page.page_count){
											
											tempArr.push(
												template.replace(/\$page_no_text/g, '下页')
														.replace(/\$page_no/g, Page.page_no + 1)
											);
											tempArr.push(
												template.replace(/\$page_no_text/g, '尾页')
														.replace(/\$page_no/g, Page.page_count)
											);
										}
										return tempArr.join('');
									}());
								return pages;
							}()
						+'</ul></td>'
						+'</td></tr></table>')
						.find('table')
						.find('ul li').click(function(){
							Arg.pageAction($(this).attr('page'));
						});
					}();
				})
				.bind('hideContextMenu', function(){
					$(this).find('.contextMenu').hide();
				})
				.bind('click', function(){
					$(this).trigger('hideContextMenu');
				})
				.bind('takeCheckbox', function(){
					var gridview = $(this),
						header = gridview.find('.header'),
						bodier = gridview.find('.bodier'),
						footer = gridview.find('.footer'),
						table = bodier.find('table'),
						activedRows = table.find('tbody tr.actived');
						
					table.find('tbody tr').each(function(index, tr){
						$(this).find(':checkbox').attr('checked', $(this).hasClass('actived'));
					});
					
					header.find(':checkbox').attr('checked', table.find('tbody tr').length > 0 && table.find('tbody tr').length === activedRows.length);
					
					if(activedRows.length == 0) gridview.trigger('hideContextMenu');
				})
				.bind('getSelectedRow', function(event, get){
					var gridview = $(this),
						header = gridview.find('.header'),
						bodier = gridview.find('.bodier'),
						footer = gridview.find('.footer'),
						table = bodier.find('table'),
						row,
						rowArr = [];
					table.find('tbody tr.actived').each(function(index, tr){
						row = $(this);
						rowArr.push(get?get(row):row.index());
					});
					return rowArr;
				})
				.bind('getRow', function(event, get, hasSelected){
					var gridview = $(this),
						header = gridview.find('.header'),
						bodier = gridview.find('.bodier'),
						footer = gridview.find('.footer'),
						table = bodier.find('table'),
						row,
						rowArr = [];
					table.find('tbody tr' + (hasSelected?'.actived':'')).each(function(index, tr){
						row = $(this);
						rowArr.push(get?get(row):row.index());
					});
					
					if(gridview.attr('multible') == 0){
						rowArr = rowArr[0]|| {};
					}
					
					return rowArr;
				})
				.bind('active', function(event, indexs){
					var gridview = $(this);
					$.each(indexs||[], function(index, i){
						gridview.find('.bodier tbody tr:eq('+i+')').addClass('actived');
					});
					gridview.trigger('takeCheckbox');
				})
				.bind('empty', function(){
					$(this).find('.bodier table tbody').empty();
				});
			});
			return this;
		},
		dynamicSelect: function(){
			this.each(function(index, item){
				var Select = $(item),
					Default = (function(){
						var d = Select.find('.default'),
							r = d.length?d[0].outerHTML:'';
						d.remove();
						return r;
					}()),
					template = Select.html().replace(/selected/g, '');
					Select.html(Default);
					
				Select.bind('refresh', function(event, Arg){
					var Select = $(this);
					Select.empty();
					
					Select.html(
						Default + parseData2Template(template, Arg.list, Arg.filter)
					).val(Arg.defaultValue).width('auto');
				});
			});
			return this;	
		},
		button2: function(){
			this.each(function(index, item){
				var self = $(item);
				
				self
				.mouseover(function(){
					$(this).addClass('button2_hover');
				})
				.mousedown(function(){
					$(this).addClass('button2_down');
				})
				.mouseout(function(){
					$(this).removeClass('button2_down button2_hover');
				})
				.mouseup(function(){
					$(this).removeClass('button2_down');
				})
				.focus(function(){
					this.blur();
				})
				.bind('selectstart', function(){
					return false;
				});				
			});	
			return this;
		},
		button3: function(){
			this.each(function(index, item){
				var self = $(item);
				
				self
				.mouseover(function(){
					$(this).addClass('button3_hover');
				})
				.mousedown(function(){
					$(this).addClass('button3_down');
				})
				.mouseout(function(){
					$(this).removeClass('button3_down button3_hover');
				})
				.mouseup(function(){
					$(this).removeClass('button3_down');
				})
				.focus(function(){
					this.blur();
				})
				.bind('selectstart', function(){
					return false;
				});
			});	
			return this;		
		},
		pur5UI: function(){
			this.find('.button2').button2();	
			this.find('.button3').button3();			
			this.find('input[keywordspath]').keywordspath();
			this.find('input[datapath]').datapath();
			this.find('div.tabs').tabs();
			this.find('div.gridview').gridview();
			this.find('select.dynamicSelect').dynamicSelect();
			return this;
		}
	});
})(jQuery);

function joinWithTag(arr, tagStart, tagEnd){
	return tagStart + arr.join(tagEnd + tagStart) + tagEnd;
}

function parseData2Template(template, list, filter){
	var rowArr = [],
		rowValue,
		rowValueType,
		keyFilter,
		keyFilterType;
		
	if(js_type(list) != 'Array') list = [list];
	
	$.each(list, function(index, row){
		rowArr.push(
			template.replace(/\$(\w+)/g, function(all, key){
				if(filter && filter.hasOwnProperty(key)){
					keyFilter = filter[key];
					keyFilterType = js_type(keyFilter);
					if(keyFilterType == 'Function'){
						return keyFilter.call(row);
					}else{
						return keyFilter;
					}
				}
				
				rowValue = row[key];
				rowValueType = js_type(rowValue);
				
				if(/^String|Number|Boolean$/.test(rowValueType)){
					return rowValue;
				}else if(rowValue == 'Function'){
					return rowValue.call(row);
				}else{
					return ('$'+key);
				}
			})
		);
	});
	
	return rowArr.join('');
}

function isActionRunning(thisAction, interval){
	thisAction.interval = interval || 0;
	if(thisAction.ing || new Date().getTime() - (thisAction.lastTime||0) < thisAction.interval) return true;
	thisAction.lastTime  = new Date().getTime();
	thisAction.ing = true;
	return false;
}

function ajaxError(name, jqXhr, textStatus){
	return ([name, '错误：', (textStatus=='timeout'?'超时':jqXhr.responseText)].join('\n'));
}

function proxyFunc(func){
	setTimeout(func);
}

var superAjax = function(setting){
	setTimeout(function(){
		$.ajax(setting);
	}, 0);
};