﻿$(document).ready(function(){
	if($.browser.msie&&$.browser.version=='6.0')
	{
		document.execCommand('BackgroundImageCache', false, true);
	}
});
jQuery.extend({
    success: function (obj) {
        var o = {
            id: 'successdlgID',
            title: '系统提示',
            html: '',
            cover: true,
            width: 270,
            height: 160,
            icon: 'success',
            resize: false,
            rang: true,
            cusfn: function () {
                this.addBtn('cancel', '确定', this.cancel);
            }
        };
        if (typeof obj === 'string')
            o.html = '<p style="padding-left:15px">' + obj + '</p>';
        else
            o = $.extend(o, obj || {});
        new $.dialog(o).ShowDialog();
    },
    error: function (obj) {
        var o = {
            id: 'errordlgID',
            title: '系统提示',
            html: '',
            cover: true,
            width: 270,
            height: 160,
            icon: 'error',
            resize: false,
            rang: true,
            cusfn: function () {
                this.addBtn('cancel', '确定', this.cancel);
            }
        };
        if (typeof obj === 'string')
            o.html = '<p style="padding-left:15px">' + obj + '</p>';
        else
            o = $.extend(o, obj || {});
        new $.dialog(o).ShowDialog();
    },
    warning: function (obj) {
        var o = {
            id: 'warningdlgID',
            title: '系统提示',
            html: '',
            cover: true,
            width: 270,
            height: 160,
            icon: 'warning',
            resize: false,
            rang: true,
            cusfn: function () {
                this.addBtn('cancel', '确定', this.cancel);
            }
        };
        if (typeof obj === 'string')
            o.html = '<p style="padding-left:15px">' + obj + '</p>';
        else
            o = $.extend(o, obj || {});
        new $.dialog(o).ShowDialog();
    },
    info: function (obj) {
        var o = {
            id: 'infodlgID',
            title: '系统提示',
            html: '',
            cover: true,
            width: 270,
            height: 160,
            icon: 'info',
            resize: false,
            rang: true,
            cusfn: function () {
                this.addBtn('cancel', '确定', this.cancel);
            }
        };
        if (typeof obj === 'string')
            o.html = '<p style="padding-left:15px">' + obj + '</p>';
        else
            o = $.extend(o, obj || {});
        new $.dialog(o).ShowDialog();
    },
    confirm: function (obj, fn) {
        var o = {
            id: 'confirmdlgID',
            title: '系统提示',
            html: '',
            cover: true,
            width: 270,
            height: 160,
            icon: 'confirm',
            resize: false,
            rang: true,
            cusfn: function () {
                var dg = this;
                this.addBtn('ok', '确定', function () { fn.call(dg); });
                this.addBtn('cancel', '取消', this.cancel);
            }
        };
        if (typeof obj === 'string')
            o.html = '<p style="padding-left:15px">' + obj + '</p>';
        else
            o = $.extend(o, obj || {});
        new $.dialog(o).ShowDialog();
    },
    loadDialog: function (obj) {
        new $.dialog($.extend({
            id: 'loaddlgID',
            title: '',
            page: '',
            cover: true,
            width: '',
            height: '',
            resize: true,
            rang: true,
            btns: true
        }, obj || {})).ShowDialog();
    },
    fixDialog: function (obj) {
        new $.dialog($.extend(true, {
            id: 'fixdlgID',
            title: '随屏滚动',
            html: '',
            fixed: true,
            top: 'bottom',
            left: 'right',
            width: 200,
            height: 100,
            btns: false,
            rang: true
        }, obj || {})).ShowDialog();
    },
    showInfo: function (obj) {

        var showInfodlg = new $.dialog($.extend(true, {
            id: 'showInfodlgID',
            title: '',
            html: '',
            btns: false,
            rang: true,
            cover: true,
            myfn: function () { }
        }, obj || {}));
        showInfodlg.ShowDialog();
        if (obj.myfn) { obj.myfn.call(showInfodlg) }
    },
    loading: function loading(con) {
        var con = con || '正在加载数据，请稍后...';
        $.showInfo({
            title: "加载提示...",
            html: '<p style="line-height:50px;text-align:center">' + con + '</p>',
            width: 200,
            height: 100,
            myfn: function () {
                $('#lhgdig_xbtn', this.dg).unbind('click').click(function () {
                    alert("完成后将会自动关闭,请稍等...");
                    //this.cancel();
                });
            }
        });
    },
    url: function (paramName) {
        var url = unescape(window.location.href);
        var allargs = url.split("?")[1];
        if (allargs == undefined) return '';
        var args = allargs.split("&");
        var obj = {};
        for (var i = 0; i < args.length; i++) {
            var arg = args[i].split("=");
            if (arg[1].indexOf('#') != -1) {
                arg[1] = arg[1].substring(0, arg[1].indexOf('#'));
            }
            eval('obj.' + arg[0] + '="' + arg[1] + '";');
        }
        if (eval('obj.' + paramName) == undefined) {
            return '';
        }
        else {
            return eval('obj.' + paramName);
        }

    },
    url1: function (paramName) {
        var url = unescape(window.location.href);
        var allargs = url.split("?")[1];
        if (allargs == undefined) return '';
        var args = allargs.split("&");
        var obj = {};
        for (var i = 0; i < args.length; i++) {
            var arg = args[i].split("=");
            if (arg[1].indexOf('#') != -1) {
                arg[1] = arg[1].substring(0, arg[1].indexOf('#'));
            }
            if (arg.length > 1) {
                for (j = 0; j < arg.length; j++) {
                    arg[0] = arg[0] +"="+ arg[i + 1];
                }
            }
//            if (arg[2].length < 1) {
//                arg[1] = arg[1] + "=";
//                eval('obj.' + arg[0] + '="' + arg[1] + '";');
//                break;
//            }
            eval('obj.' + arg[0] + '="' + arg[1] + '";');
        }
        if (eval('obj.' + paramName) == undefined) {
            return '';
        }
        else {
            return eval('obj.' + paramName);
        }

    },
    loadData: function (obj) {
        $.ajax($.extend(true, {
            url: '',
            type: 'post',
            dataType: 'json',
            data: {},
            success: function () {
            },
            error: function () {
                alert('加载数据出错,请刷新后重试');
            }
        }, obj || {}));
    }
});
jQuery.fn.extend({
	grid: function(v) {
		var id = $(this).attr('id');
		var $nav=$(this).parent().prev('div.nav');
		$nav.prepend('<div class="searchBox"> <input type="text" class="keyword" /> <input type="submit" value="  " class="btn"></div>');
		var $keyword=$nav.find('input.keyword')
		.val('请输入关键字...')
		.focus(function() {
			if ($(this).val() == '请输入关键字...') {
				$(this).val('').css('color', '#1a1212');
			}
		}).blur(function() {
			if ($(this).val() == '') {
				$(this).val('请输入关键字...').css('color', '#b0acac');
			}
		});
		$('#' + id).data('nav',{'keyword':$keyword,'btn':$nav.find('input.btn')});
		$nav.find('input.btn').click(function() {
			var PostData=$('#'+id).jqGrid().getPostData();
			if(PostData._search==true){
				alert('搜索正处于高级模式,请先重置高级搜索');
				return false;
			}
			var Search_KeyWord = $(this).prev().eq(0);
			var Search_Value = Search_KeyWord.val() == '请输入关键字...' ? true : false;
			var Search_Color = Search_KeyWord.css('color') == '#b0acac' || 'rgb(176, 172, 172)' ? true : false;
			if (Search_Value && Search_Color) {
				$('#' + id).jqGrid('setGridParam', { postData: { keyword: ''} }).trigger("reloadGrid")
			} else {
				$('#' + id).jqGrid('setGridParam', { postData: { keyword: Search_KeyWord.val().replace(/\'/g,'')} }).trigger("reloadGrid")
			}
			Search_KeyWord.focus();
			return false;
		}).hover(function(){
			$(this).addClass('over');
		},function(){
			$(this).removeClass('over');
		});
		var height=$('#warp').height()-85;
		if($.browser.msie&&$.browser.version<='7.0'){
			height=height-12;
		}
		var p = $.extend(true, {
			url: '',
			datatype: "json",
			mtype: 'post',
			colNames: [],
			colModel: [],
			rowNum: 20,
			rowList: [10,15, 20, 30],
			pager: '',
			autowidth: true,
			viewrecords: true,
			height: height,
			multiselect: true,
			postData: {},
			jsonReader: {
				root: "data",//root的意思是，表格数据的名
				page: "currPage",
				total: "totalPages",
				records: "totalCount",
				repeatitems: false,//指定返回的数据的标签是否是可重复的，一般为false
				id: "0"//每行数据的唯一标识。可以设置为空字符串或者一个数字。一般设置为0
			}
		}, v);
		$(this).jqGrid(p);
		$(this).jqGrid('navGrid', p.pager, { edit: false, add: false, del: false, search: false });
	},
    gridnew: function (v, sdata) {
        var height = $('#warp').height() - 85;
        if ($.browser.msie && $.browser.version <= '7.0') {
            height = height - 12;
        }
        var p = $.extend(true, {
            url: '',
            datatype: "json",
            mtype: 'post',
            colNames: [],
            colModel: [],
            rowNum: 20,
            rowList: [10, 15, 20, 30],
            pager: '',
            autowidth: true,
            viewrecords: true,
            height: height,
            multiselect: true,
            postData: {},
            jsonReader: {
                root: "data", //root的意思是，表格数据的名
                page: "currPage",
                total: "totalPages",
                records: "totalCount",
                repeatitems: false, //指定返回的数据的标签是否是可重复的，一般为false
                id: "0"//每行数据的唯一标识。可以设置为空字符串或者一个数字。一般设置为0
            }
        }, v);
        $(this).jqGrid(p);
        $(this).jqGrid('navGrid', p.pager, { edit: false, add: false, del: false, search: false });
    },
	reloadGrid: function() {
		$(this).trigger('reloadGrid');
	},
	selectedRows: function() {
		return $(this).jqGrid('getGridParam', 'selarrrow');
	},
	validData:function(v){
		v=v||{};
		var validtype=v.validtype;
		if(!validtype||(validtype!='delete'&&validtype!='update')){
			alert('请检查validtype参数');
			return false;
		} 
		var msgtype=validtype=='delete'?'删除':'编辑';
		var p=$.extend(true,{
			validtype:'',
			multiselect:false,
			emptymsg:'请选择要'+msgtype+'的记录',
			multimsg:'只能选择一条记录'
		},v);
		var arr=$(this).selectedRows();
		if(arr.length==0){
			$.info(p.emptymsg);
			return false;
		}
		if(!p.multiselect&&arr.length>1){
			$.info(p.multimsg);
			return false;
		}else{
			return arr;
		} 
	},
	getSelectData: function(v) {
		var p = $.extend(true, {
			id: '',
			name: ''
		}, v)
		var id = $(this).jqGrid('getGridParam', 'selrow');
		if (p.id || id) {
			var ret = $(this).jqGrid('getRowData', p.id || id);
			return eval('ret.' + p.name);
		} else {
			return '';
		}
	},
	validt: function(v) {
	  return $(this).validate($.extend(true, {
			errorElement: "em",
			errorPlacement: function(error, element) {
				error.appendTo(element.closest("td").next("td"));
			},
			success: function(label) {
				label.removeAttr('original-title').addClass("success");
			}
		}, v));
	},
	editor: function(v) {
		$(this).xheditor($.extend(true, {
			skin: 'default',
			tools: 'full',
			upLinkUrl: "../AJaxHandler/Ajax_FileUpload.ashx?FileType=NoticeFile",
			upLinkExt: "zip,rar,txt,pdf,doc,docx,xls,xlsx",
			upImgUrl: "../AJaxHandler/Ajax_FileUpload.ashx?FileType=NoticeFile",
			upImgExt: "jpg,jpeg,gif,png",
			upFlashUrl: "../AJaxHandler/Ajax_FileUpload.ashx?FileType=NoticeFile",
			upFlashExt: "swf",
			upMediaUrl: "../AJaxHandler/Ajax_FileUpload.ashx?FileType=NoticeFile",
			upMediaExt: "wmv,avi,wma,mp3,mid"
		}, v));
	},
	loadData: function(v) {
		var o = $(this)[0];
		$.ajax($.extend(true, {
			url: '',
			type: 'post',
			dataType: 'json',
			data: {},
			beforeSend:function(){
				o.length = 0;
				o.options.add(new Option('正在读取数据...','正在读取数据...'));
			},
			success: function(data) {
				o.length = 0;
				if(data==undefined) return;
				for (var i = 0; i < data.length; i++) {
					o.options.add(new Option(data[i].text||data[i].TEXT, data[i].value||data[i].VALUE));
				}
				if(v.fn) v.fn();
			},
			error: function() {
				alert('下拉框加载数据出错');
			}
		}, v));
	},
	serializeData:function(v){
		var formData=$(this).serializeArray();
		var obj={};
		$.each(formData,function(index,field){
			eval('obj.'+field.name+'=\''+field.value.Replace()+'\'');
		});
		$.extend(true,obj,v||{});
		return obj;
	},
	addTab:function(v){
		var tabHtml=[];
		var id=$(this).attr('id');
		var p=$.extend(true,{
			title:'tab标题',
			contentDiv:'',
			selectIndex:0,
			items:[]
		},v);
		p.selectTab=function(index){
			$('#'+id+' a').removeClass("on").eq(index).addClass("on").click();
			$('#'+p.contentDiv+'>div:eq('+index+')').show().siblings().hide();
		};
		if(!p.contentDiv){
			alert('没有内容元素');
			return;
		}
		if(p.items.length!=$('#'+p.contentDiv+'>div').length){
			alert('tab标题与内容数目不等');
			return;
		}
		tabHtml.push('<ul>');
		$.each(p.items,function(i,o){
			var cls=p.selectIndex==i?'on':'';
			var title=o.title?o.title:p.title;
			tabHtml.push('<li><a class="'+cls+'"  href="javascript:void(0)" onclick="this.blur()">'+title+'</a></li>');
		});
		tabHtml.push('</ul>');
		$(this).html(tabHtml.join('')).addClass('tag_new');
		
		$('#'+p.contentDiv+'>div:not(:eq('+p.selectIndex+'))').hide();
		 $('#'+id+' a').click(function () {
			var index = $('#'+id+' a').index(this);
			$(this).addClass("on").parent().siblings().children().removeClass("on");
			$('#'+p.contentDiv+'>div:eq('+index+')').show().siblings().hide();
			return false;
		});
		$('#'+id+' a').one('click',function(){
			var index = $('#'+id+' a').index(this);
			if(p.items[index].fn) p.items[index].fn();
			return false;
		});
		return p;
	}
});
String.prototype.Trim = function() { 
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
} 
String.prototype.LTrim = function() { 
	return this.replace(/(^\s*)/g, ""); 
} 
String.prototype.RTrim = function() { 
	return this.replace(/(\s*$)/g, ""); 
}
String.prototype.Replace=function(){
	var str=this.replace(/(^\s*)|(\s*$)/g, ""); 
	str=str.replace(/\n|\r|\t/g,"");
	str=str.replace(/'/g,'\\\'');
	return str;
}
String.prototype.formatCurrency=function(){
	num = this.toString().replace(/\￥|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '￥' + num + '.' + cents);
}
