
//----------------------------------------------------原型扩展
//去除左右空格
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, ""); }

//----------------------------------------------------jquery扩展
if(typeof(jQuery) != 'undefined')
{    
    /*
    **************图片加载插件******************
    scaling     是否等比例自动缩放
    width       图片最大高
    height      图片最大宽
    loadpic     加载中的图片路径
    proxy                 代理文件路径
    needProxyWeb    需要代理的网站域名数组
    attachLink          是否自动添加超链接
    complete_callback 加载完成时执行的方法
    */
    jQuery.fn.preloadImage=function(scaling,width,height,loadpic,proxy,needProxyWeb,attachLink, complete_callback){

	    return this.each(function(){
		    var t=$(this);
		    var src=$(this).attr("src");
		    t.attr('oSrc', src);             //保存原始url
		    var img=new Image();

            //添加代理
            var needProxyWebReg = null;            
            if(needProxyWeb != null && needProxyWeb.length > 0)
            {            
                needProxyWebReg = new RegExp(("(" + needProxyWeb.join(")|(") + ")").replace(/\./ig,"\\."), "ig");
                
                if(needProxyWebReg.test(src))
                    src = proxy + '?url=' + encodeURI(src); 
            }    
           
		    img.src=src;
		    
		    //自动缩放图片
		    var autoScaling=function(){
			    if(scaling){    			
				    if(img.width>0 && img.height>0){ 
				    
			            //自动添加超链接			    
                        if(attachLink && $(img).parent().attr("tagName") != "A")
                        {                         
                            if( img.width >= width || img.height >= height )
                            {
                                t.css("cursor","pointer");  
                                t.click(function()
                                {
                                    window.open(t.attr('oSrc'));
                                });
                            }
                        }
				    
			            if(img.width/img.height>=width/height){ 
			                if(img.width>width){ 
			                    t.width(width); 
			                    t.height((img.height*width)/img.width); 
			                }else{ 
			                    t.width(img.width); 
			                    t.height(img.height); 
			                } 
			            } 
			            else{ 
			                if(img.height>height){ 
			                    t.height(height); 
			                    t.width((img.width*height)/img.height); 
			                }else{ 
			                    t.width(img.width); 
			                    t.height(img.height); 
			                } 
			            } 
			        } 
			    }	
		    }
		    
		    //处理ff下会自动读取缓存图片
		    if(img.complete){
			    autoScaling();
			    if(complete_callback != null)
			    {
			        complete_callback(this);
			    }
			    
		        return;
		    }
		    $(this).attr("src","");		    
		    
		    var loading = null;		    
		    if(loadpic != '' && loadpic != null)
		        loading = $("<img alt=\"加载中...\" title=\"图片加载中...\" src=\""+loadpic+"\" />");
		    else
		        loading = $("<span>图片加载中...</span>");
    		
		    t.hide();
		    t.after(loading);
		    $(img).load(function(){
			    autoScaling();
			    loading.remove();
			    t.attr("src",this.src);
			    t.show();
		
			    if(complete_callback != null)
			    {
			        complete_callback(t);
			    }
		    });    		
	    });
    }
    
    //自动添加图像代理
    jQuery.fn.setImageProxy = function(proxyUrl, domainArray) 
    {
        $("img", this).each(function() 
        { 
            var domainArrayReg = null;
            
            if(domainArray != null && domainArray.length > 0)
            {            
                domainArrayReg = new RegExp(("(" + domainArray.join(")|(") + ")").replace(/\./ig,"\\."), "ig");
            }
        
           var image = $(this);           
     
           if(domainArrayReg != null && domainArrayReg.test(image.attr("src"))) 
           {     
                image.attr('src', proxyUrl + '?url=' + escape(image.attr("src"))); 
           }
        });
    }
    
    //禁止输入框的回车自动提交
    jQuery.fn.disableEnterPost = function() 
    {
        $("input[type='text']", this).each(function() 
        {             
            this.onkeypress = function()
            {
                return !(window.event && window.event.keyCode == 13); 
            }
        });
    }    
}


//----------------------------------------------------乐道工具
var $ledao = 
{
    form : new FormUtil(),
    text : new TextUtil(),
    browser : new BrowserUtil(),
    image : new ImageUtil()
}

//----------------------------------------------------表单工具
function FormUtil()
{
    //保存选择状态的对象
    var bv_selected = {};

    //全选和反选所有checkbox
    this.selectCheckBox = function(groupName)
    {
        if(!bv_selected[groupName])
        { 
            $("input[@group=" + groupName + "]").each(function() { 
                    $(this).attr("checked", true); 
            }); 
            bv_selected[groupName] = true;
        }
        else
        { 
            $("input[@group=" + groupName + "]").each(function() { 
                    $(this).attr("checked", false); 
            }); 
            bv_selected[groupName] = false;
        }  
    }

    //显示批量确认对话框
    this.confirmCheckBox = function(confirmText, groupName)
    {
        //判断是否有选中值
        var result = false; 
        $('input[@group=' + groupName + ']').each(function() { 
                if($(this).attr("checked") == true)
                { 
                    result = true; 
                    return; 
                }
        });
        
       if(!result)
       {
            alert('请选择要操作的值');
            return false;
       }
       else if(confirmText == '' || confirmText == null)
       {
            return true;
       }
       else
       {
            return confirm(confirmText);
       }
    }
    
    //禁止输入回车提交
    this.disableInputEnter = function(input)
    {
        input.onkeypress = function(){ return !(window.event && window.event.keyCode == 13); }
    }
}

//----------------------------------------------------文本处理工具
function TextUtil()
{    
    //过滤HTML代码
    this.filterHTML = function(html)
    {            
        //过滤危险代码
        
        //过滤基本元素 html,body,head,form,input,script,style,iframe,frame
        html = html.replace(/<[\s]*?html[^>]*?>/ig, '');
        html = html.replace(/<[\s]*?\/[\s]*?html[\s]*?>/ig, '');
        html = html.replace(/<[\s]*?body[^>]*?>/ig, '');
        html = html.replace(/<[\s]*?\/[\s]*?body[\s]*?>/ig, '');         
        html = html.replace(/<[\s]*?head[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?head[\s]*?>/ig, '');  
        
        html = html.replace(/<[\s]*?form[^>]*?>/ig, '');
        html = html.replace(/<[\s]*?\/[\s]*?form[\s]*?>/ig, ''); 
        html = html.replace(/<[\s]*?input[^>]*?\/[\s]*?>/ig, '');     
        html = html.replace(/<[\s]*?select[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?select[\s]*?>/ig, '');  
        html = html.replace(/<[\s]*?textarea[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?textarea[\s]*?>/ig, '');  
        
        html = html.replace(/<[\s]*?script[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?script[\s]*?>/ig, '');
        html = html.replace(/<[\s]*?style[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?style[\s]*?>/ig, '');       
        
        html = html.replace(/<[\s]*?iframe[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?iframe[\s]*?>/ig, '');  
        html = html.replace(/<[\s]*?frame[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?frame[\s]*?>/ig, '');       
        html = html.replace(/<[\s]*?frameset[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?frameset[\s]*?>/ig, '');       

        //过滤属性中的所有javascript:
        html = html.replace(/javascript\:/ig, 'return false;');

        //过滤所有事件属性 on        
        html = html.replace( /<(\w[^>]*) onabort="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onchange="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onerror="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onkeydown="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onkeypress="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onkeyup="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onmousemove="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) onmousedown="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) onmouseup="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) onclick="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) ondblclick="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	    html = html.replace( /<(\w[^>]*) onblur="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onfocus="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onload="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onunload="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onerror="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onresize="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onscroll="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onreset="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onselect="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onsubmit="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) onmousewheel="([^\"]*)"([^>]*)/gi, "<$1$3") ;
        
        //过滤所有样式属性 class
	    html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
	    
        return html;
    }
}


//----------------------------------------------------图像处理工具
function ImageUtil()
{  
    //等比缩放图片
    //iwidth : 最大宽度
    //iheight : 最大高度
    this.resizeImage = function(img, iwidth,iheight) 
    {
       var _img = new Image();
       _img.src = img.src;

       if(_img.width > _img.height)
       {      
          img.width = (_img.width > iwidth) ? iwidth : _img.width;
          img.height = (_img.height / _img.width) * img.width;
          img.style.width = (_img.width > iwidth) ? iwidth : _img.width;
          img.style.height = (_img.height / _img.width) * img.width;
       }
       else if(_img.width < _img.height)
       {
          img.height = (_img.height > iheight) ? iheight : _img.height;
          img.width = (_img.width / _img.height) * img.height ;
          img.style.height = (_img.height > iheight) ? iheight : _img.height;
          img.style.width = (_img.width / _img.height) * img.height ;
       }
       else
       {
          img.height = (_img.height > iheight) ? iheight : _img.height;
          img.width = (_img.width > iwidth) ? iwidth : _img.width;
          img.style.height = (_img.height > iheight) ? iheight : _img.height;
          img.style.width = (_img.width > iwidth) ? iwidth : _img.width;
       }    
    }
    
    //----------------------------------------------------------------------图片本地化
    //proxyPath = "/Proxy.aspx?url={0}"
    //imgs img元素节点数组
    //filterUrls 需要过滤的url数组
    //completed_callback 完成后要执行的回调
    this.locaingImg = function(proxyPath, imgs, filterUrls, completed_callback)
    {
        if(imgs.length > 0)
        {
            //过滤url            
            for(var img_count = imgs.length-1; img_count >= 0; img_count--)
            {
                for(var fu_count = 0; fu_count < filterUrls.length; fu_count++)
                {
                    if(imgs[img_count].src.indexOf(filterUrls[fu_count]) > -1)
                    {
                        //移除地址
                        imgs.splice(img_count, 1);
                    }
                }
            }
        
            locaingImgWithXmlhttp(proxyPath, imgs, 0, receive); 
        } 
        
        //接收方法
        function receive(xmlhttp, proxyPath, imgs, locaingCount)
        {  
            if(xmlhttp.readyState == 4)
            {
                if(xmlhttp.status==200 && xmlhttp.responseText != "")   
                { 
                    if(xmlhttp.responseText != "localized")
                    {
                        //alert('本地化成功:' + xmlhttp.responseText + "|" + imgs[locaingCount].src);
                        imgs[locaingCount].src = xmlhttp.responseText;                        
                    }
                    else
                    {
                        //alert('已本地化:' +  imgs[locaingCount].src);
                    }
                }   
                else
                {
                    alert(imgs[locaingCount].src + " : 本地化出错");
                }
          
                //继续下一个
                locaingCount++;
                if(locaingCount < imgs.length)
                {
                    locaingImgWithXmlhttp(proxyPath, imgs, locaingCount, receive); 
                }
                else
                {
                    locaingCount = 0;
                    completed_callback();
                    alert("本地化完成");
                } 
            }
        }
       
        function locaingImgWithXmlhttp(proxyPath, imgs, locaingCount, callback) 
        { 
            var url = proxyPath.replace("{0}", imgs[locaingCount].src) + "&rnd=" + Math.round(Math.random() * 10000);
        
            var xmlhttp = null; 
            if(window.ActiveXObject)
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            else if(window.XMLHttpRequest)
            {
                xmlhttp=new XMLHttpRequest();
            }
            
            try 
            {   
                 xmlhttp.open('GET', url, true); 
                 xmlhttp.onreadystatechange = function(){callback(xmlhttp, proxyPath, imgs, locaingCount);};
                 xmlhttp.send();
            } 
            catch(e) 
            { 
                 alert(url + " : " + e.message); 
            } 
        }          
    }
    
    //给图片添加分页按钮
    //imgs        图片数组
    //maximgs   最大图片数，超过这个数值将不附加分页按钮
    //preurl      上一页的地址
    //nexturl    下一页的地址
    //pageindex  当前页索引
    //pagecount 页总数
    this.attachPageBtn = function(imgs, maximgs, preurl, nexturl, pageindex, pagecount)
    {
        if(imgs.length > maximgs)
        {
            //如果同一页的图片数超过指定数，则不添加快捷按钮，必须让用户向下滚动，完整浏览内容
            return;
        }
        
        var temp = null;
        var point = null;
        for(var i = 0; i < imgs.length; i++)
        {
            temp = [];            

            point = $ledao.browser.getAbsPoint($(imgs[i]).get()[0]);
            
            imgs[i].btnid =  (new Date() * 1) + '';//随机生成btnid;
            
            $(imgs[i]).mouseover(function()
            {
                $("#" + this.btnid).show();
            });

            temp.push('<i id="' + imgs[i].btnid + '" class="imgnav" style=" left:' + point.left + ';top:' + point.top + ';width:' + $(imgs[i]).attr('width') + 'px;height:' + $(imgs[i]).attr('height') + 'px;display:none;"><i><b>');
            if(pageindex > 1 )
            {
                temp.push('<a class="prevpic" href="' + preurl + '" title="上一张"></a>');
            }
            else
            {
                temp.push('<a class="prevpic" href="javascript:alert(\'当前已经为第一页\');" title="当前已经为第一页"></a>');
            }            
       
            temp.push('<a class="zoomin" href="' + $(imgs[i]).attr('src') + '" title="查看原图" target="_blank"></a>');
            
            if(pageindex < pagecount)
            {
                temp.push('<a class="nextpic" href="' + nexturl + '" title="下一张"></a>');
            }
            else
            {
                temp.push('<a class="nextpic" href="javascript:alert(\'当前已经为最后一页\');" title="当前已经为最后一页"></a>');
            }      
            
            temp.push('</b></i></i>');
            
            //插入节点
            $(imgs[i]).after(temp.join(''));
        }
    }
}




    
//----------------------------------------------------浏览器工具
function BrowserUtil()
{
    this.addBookmark = function(title,url) {
        if (window.sidebar) { 
            window.sidebar.addPanel(title, url,""); 
        } else if( document.all ) {
            window.external.AddFavorite( url, title);
        } else if( window.opera && window.print ) {
            return true;
        }
    }

    this.setHomePage = function(obj, url)
    {
	    if (obj.all)
	    {
		    obj.body.style.behavior='url(#default#homepage)';
		    obj.body.setHomePage(url);	
	    }
	    else if (window.sidebar)
	    {
    		
		    if(window.netscape)
		    {
			    try
			    {  
				    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
			    }  
			    catch (e)  
			    {  
				    alert( "该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项signed.applets.codebase_principal_support 值该为true" );  
			    }
		    } 
		    var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
		    prefs.setCharPref('browser.startup.homepage',url);
	    }
    }

    //复制当前url到剪贴板
    this.copyUrlToClipBoard = function(title, url)
    {
        var clipBoardContent = (title || document.title) + "-" + (url || window.location); 
        
        if(this.copyTxtToClipboard(clipBoardContent))
            alert("复制成功，请粘贴到你的QQ/MSN上推荐给你的好友"); 
    } 

    //复制到剪贴板
    this.copyTxtToClipboard = function(txt)
    { 
          if(window.clipboardData) 
          {    
                 window.clipboardData.clearData();    
                 window.clipboardData.setData("Text", txt);    
                 return true;
          } 
          else if(navigator.userAgent.indexOf("Opera") != -1) 
          {    
                  window.location = txt;    
                  return true;
          } 
          else if (window.netscape) 
          {    
              try 
              {    
                       netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");    
              } 
              catch (e) 
              {    
                       alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");   
                       return false; 
              }   
               
              var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);    
              if (!clip) return false 
              
              var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);    
              if (!trans)  return false;    
              
              trans.addDataFlavor('text/unicode');    
              var str = new Object();    
              var len = new Object();    
              var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);    
              var copytext = txt;    
              str.data = copytext;    
              trans.setTransferData("text/unicode",str,copytext.length*2);    
              var clipid = Components.interfaces.nsIClipboard;    
              if (!clip) return false;    
              
              clip.setData(trans,null,clipid.kGlobalClipboard);    
              return true;
         }  
         
         return false; 
    } 

    //获取url参数
    this.queryString = function(key)
    {
        var strHref = window.document.location.href; 
        var strRight = strHref.split("?"); 
        
        if(strRight.length != 2)
            return '';

        var keyValueArray = strRight[1].split("&");
        var arrTemp = null;
        for(var i = 0, len= keyValueArray.length; i < len; i++) 
        { 
            arrTemp = keyValueArray[i].split("="); 
            
             if(arrTemp.length != 2)
                continue;
            
            //过滤最后的?sddsf=sd#xxx
            if(i == (len -1) && arrTemp[1].indexOf("#") > -1)
            {  
                arrTemp[1] = arrTemp[1].split("#")[0];
            }
            
            if(arrTemp[0].toUpperCase() == key.toUpperCase()) 
                return arrTemp[1]; 
        } 
        
        return ""; 
    }
    
    //获取对象的绝对位置
    this.getAbsPoint = function(obj)   
    {   
        var point = null;
    
        switch(this.getOS())
        {
            case 'msie':
                var e = obj;
                var x = e.offsetLeft;
                var y = e.offsetTop;
                
                while(e=e.offsetParent) 
                { 
                   x   +=   e.offsetLeft;   
                   y   +=   e.offsetTop;
                } 
        
                point = {top : y, left : x};
                break;	
            default:       
               var oElement = obj;
               var x = 0;
               var y = 0;
               
               if( oElement )
               {
                    x = oElement.offsetLeft;
                    y = oElement.offsetTop;
                    var x2 = 0, y2 = 0;
                    while( oElement.offsetParent )
                    {
                        //累加从该元素起至父元素的offsetLeft和offsetTop
                        x2 += oElement.offsetParent.offsetLeft;
                        y2 += oElement.offsetParent.offsetTop;
                        //遇到table标签则表明累计的量都应该累加到该元素的offsetLeft和offsetTop(Table中按IE方式计算)
                        if( oElement.offsetParent.tagName.toLowerCase() == "table" )
                        {
                             x += x2;
                             y += y2;
                             x2 = 0;
                             y2 = 0;
                        }
                        oElement = oElement.offsetParent;
                    }
                }

                point = {top : y + 'px', left : x + 'px'};
                break;
        }

        return point;
    }
    
    //获取当前浏览器类型标识
    this.getOS = function() 
    { 
       var OsObject = ""; 
       if(navigator.userAgent.indexOf("MSIE")>0) { 
            return "msie"; 
       } 
       if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ 
            return "firefox"; 
       } 
       if(isSafari=navigator.userAgent.indexOf("Safari")>0) { 
            return "safari"; 
       }  
       if(isCamino=navigator.userAgent.indexOf("Camino")>0){ 
            return "camino"; 
       } 
       if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){ 
            return "gecko"; 
       }
       
       alert('未知的浏览器类型');       
    } 
}