/**
 * <p>Title:       pas.js</p>
 * <p>Description: 扩展js</p>
 * <p>Createtime:  2011-8-3 上午10:42:56</p>
 * @author:        Nycas
 * @version:       1.0     
 */

if(typeof PAS == 'undefined') {
	var PAS = {};
};
PAS.page = {};
$.extend(PAS.page, {
    load: function(url){
	    var target = $("#main");
        this.loadPage(target, url);
    },
    get:function(obj, total){
    	if (obj) {
    		var page = $(obj).parent().find('.gotoPage').val();
    		if (!page) {
    			return;
    		}
    		page = parseInt(page);
    		if (!page) {
    			page = 1;
    		}
    		else {
    			if (page > total) {
    				page = total;
    			}
    		}
    		return page;
    	}
    	return 1;
    },
    /**
     * 去某个页
     * @param obj:this
     */
    gotoPage:function(obj, total){
    		this.go(this.get(obj, total));
    },
    toPage:function(obj, total, func){
    	(func)(this.get(obj, total));
    },
    /**
     * 加载页面
     * target :对象
     * url:链接
     */
    loadPage:function(target, url){
    	$.get(url, {}, function (data) {
    		target.html(data);
        });	
    },
    /**
     * 跳转到哪一页
     */
    go: function(page, url){
    	if(!url) {
    		url = location.href;
    	}
    	var pos = url.indexOf('#');
    	if(pos > 0) {
    		url = url.substring(0, pos);
    	}
    	if (url.indexOf('?') > -1) {
    		if (url.indexOf('page=') > -1) {
    			url = PAS.url.changeParam(url, 'page', page);
    		}else {
    			url += "&page=" + page;
    		}
    	}
    	else {
    		url += "?page=" + page;
    	}
    	location.href = url;
    }
});
/**
 * url
 */
PAS.url = {
	changeParam: function(url, param, val){
	    if (url.indexOf('?') < 1) {
		    return url;
		}
		var regexp = new RegExp(param + '=([^&])*', 'i');
		url = url.replace(regexp, param + '=' + val)
		return url;
	},
	back:function(){
		//history.back(-1);
		location.href = document.referrer;
	},
	/**
	 * 取url参数值
	 * @param: 参数值
	 */
    getValue: function(param) {
    	var reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)", "i");
    	var r = window.location.search.substr(1).match(reg);
    	if (r != null) return unescape(r[2]); return null;
    }
};
PAS.doc = {
    title:{
		tit:null,
		titSubfix1:'【新消息】－',
		titSubfix2:'【　　　】－',
		hit: false,
		vInterval:null,
		auto:function(){
	        if (this.vInterval != null) {
	        	return;
	        }
		    if(this.tit == null) {
		    	this.tit = document.title;
		    }
		    this.vInterval = setInterval(function(){
		    	PAS.doc.title.show();
		    }, 1000);
	    },
	    show:function(){
	    	if (this.hit){
	    		document.title = this.titSubfix1 + this.tit;
	    	}
	    	else {
	    		document.title = this.titSubfix2 + this.tit;
	    	}
	    	this.hit = !this.hit;
	    },
	    clear:function(){
	    	if (this.vInterval != null) {
	    		clearInterval(this.vInterval);
	    		this.vInterval = null;
	    		document.title = this.tit;
	    	}
	    }
    },
    v:function(o){
	   return $.trim($(o).val());
    },
	top:function(value){
	   if (value) {
		   $(document).scrollTop(value);
	   }
	   else {
		   $(document).scrollTop(0);
	   }
	},
   components:{
	   error:function(o){
	     if (o) {
	    	 o.addClass('error');
	     }
       },
       input:{
		   init:function(){
		   	    $('.input').hover(function(){
			    	$(this).removeClass('error');
			        $(this).addClass('focus');
			    },function(){
			        $(this).removeClass('focus');
			    });	 
	       }
       }
   },
   
	/**
	 * 滚动条的位置
	 */
	scroller:{
		/**
		 * 当前位置
		 */
		top:0,
		/**
		 * 长度
		 */
		height:0,
		init:function(callback){
		   $(document).scroll(function(){
			   var height = $(this).height();
			   var top = $(this).scrollTop();
			   if (top > height * 0.6) {
				   (callback)();
			   }
		   });
		},
		isDown:function(top){
			if (top > this.top) {
				this.top = top;
				return true;
			}
			this.top = top;
			return false;
		}
	},
	/**
	 * 加入 收藏夹
	 */
	addFavorite: function(sURL, sTitle){
	    try{
	        window.external.addFavorite(sURL, sTitle);
	    }
	    catch (e){
	        try{
	            window.sidebar.addPanel(sTitle, sURL, "");
	        }
	        catch (e){
	            alert("加入收藏失败，请使用Ctrl+D进行添加");
	        }
	    }
	},
	/**
	 * 设为首页
	 */
	setHomePage: function(obj,vrl){
        try{
           obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
        }
        catch(e){
           if(window.netscape) {
                try {
                   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                }
                catch (e) {
                   alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将 [signed.applets.codebase_principal_support]的值设置为'true',双击即可。");
                }
                var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                prefs.setCharPref('browser.startup.homepage',vrl);
           }
       }
	}
}
/**
 * 表情
 * 
 * 
 */
PAS.emote = {
		isRuning:false,
		init:function(){},
		hide:function(){
			$('.fer_face').hide();
		},
		 /**
		  * 表情
		  */
		 EMOTE_TITLES : ["微笑","撇嘴","色","发呆", "得意", "流泪" ,"害羞", "闭嘴", "睡", "大哭","尴尬","发怒","调皮","呲牙","惊讶","难过","酷","冷汗","抓狂","吐"],
		 
		 /**
		 *创建表情框
		 **/
		 createEmotesPanel: function (id){
			    var html = [];
			    html.push('<div class="fer_face" id="facePanel' + id +'">');	      	                    		     
				    html.push('<div class="faceTit"><a class="close" title="关闭" href="javascript:void(0);" onclick="PAS.emote.close(this, \'' + id +'\')"></a></div>');
					html.push('<div class="faceBox" id="faceBox' + id +'">');
					for (var i = 0; i < this.EMOTE_TITLES.length; i ++) {
						html.push('<a class="f' +(i + 1) +'" title="' + this.EMOTE_TITLES[i] +  '" href="javascript:void(0);"></a>');
					}									
					html.push('</div>');
			    html.push('</div>');

		     return html.join('');
		},
		/**
		 * @pram target: this
		 * @param id:textarea id
		 */
		tip: function(target, id){
			this.hide();
			var o = $('#facePanel'+id);
			if(o.length > 0) {
				o.show();
				return;
			}
			
			$(target).parent().find('.facePos').html(this.createEmotesPanel(id));
	         $('#faceBox'+id + ' > a').each(function(){
		          $(this).click(function(){
		        	  PAS.component.insertTextIntoTextarea(id, '/' + $(this).attr('title'));
		          });
		     });
		},
		close:function(obj, id){
			//$(obj).parent().parent().remove();
			$(obj).parent().parent().hide();
		},
		/**
		 * 表情转换
		 */
		parse:function(input){
			if (!input) {
				return '';
			}
			var img = '<img src=\"./services/theme/face/';
			for (var i = 0; i < this.EMOTE_TITLES.length; i ++) {
				var emote = '/' + this.EMOTE_TITLES[i];
				if (input.indexOf(emote) > -1){
					var reg = new RegExp(emote,'gi' );
					input = input.replace(reg, img + (i + 1) + ".gif\"/>");
				}
			}
			return input;
		}
}
PAS.component = {
	 /**
	  **插入数据
	  **/
	  insertTextIntoTextarea: function(obj, tag){
	    var txtarea = document.getElementById(obj);
	   //IE
	    if(document.selection) {
	    var theSelection = document.selection.createRange().text;
		  if(!theSelection) { theSelection=tag}
		  txtarea.focus();
		  if(theSelection.charAt(theSelection.length - 1) == " "){
		   theSelection = theSelection.substring(0, theSelection.length - 1);
		   document.selection.createRange().text = theSelection+ " ";
		  } else {
		   document.selection.createRange().text = theSelection;
		  }
		  // Mozilla
		 }else if(txtarea.selectionStart || txtarea.selectionStart == '0'){
		    var startPos = txtarea.selectionStart;
		  var endPos = txtarea.selectionEnd;
		  var myText = (txtarea.value).substring(startPos, endPos);
		  if(!myText) { myText=tag;}
		  if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
		   subst = myText.substring(0, (myText.length - 1))+ " "; 
		  } else {
		   subst = myText; 
		  }
		  txtarea.value = txtarea.value.substring(0, startPos) + subst + txtarea.value.substring(endPos, txtarea.value.length);
		  txtarea.focus();
		  var cPos=startPos+(myText.length);
		  txtarea.selectionStart=cPos;
		  txtarea.selectionEnd=cPos;
		  // All others
		 }else{
		    txtarea.value+=tag;
		    txtarea.focus();
		 }
		 if (txtarea.createTextRange) txtarea.caretPos = document.selection.createRange().duplicate();
	 },
	 button: {
		 disable: function(id) {
		    $('#' + id).attr('disabled', true);
	     },
	     enable: function(id) {
		    $('#' + id).attr('disabled', false);
	     }
	 },
	 textarea: {
		 limit: function(event, o, len){
		    event = (event) ? event : ((window.event) ? window.event : ""); 
		    var key = event.keyCode?event.keyCode:event.which; 
		    if (key ==8  ||key == 37 || key == 39 || key == 9) {
		    	return true;
		    }
		 	var val = $(o).val();
		 	if (val.length >= len) {
		 		Window.showError('只能输入' + len + "个字符！")
		 		return false;
		 	}
		 	return true;
	     }
	 },
	 select: {
		 /**
		  * id:select id
		  * array:[]
		  */
		 append: function(id, array, target){
	   	    if(array && array.length > 0) {
	   	    	var o = $('#' + id);
		    	for(var i = 0; i < array.length; i ++){
	    	    	var v = array[i];
	    	    	if (!target || i != target) {
	    	    		o.append('<option value="' + i + '">' + v + '</option>');
	    	    	}
	    	    	else {
	    	    		o.append('<option selected="selected" value="' + i + '">' + v + '</option>');
	    	    	}
		    	};
		    }
	     }
	 }
}
/**
 * 文件
 */
PAS.file = {
   /**
    * 取文件名称 
    */
   getName:function(path){
	 return path.substring(path.lastIndexOf('\\')+1);
   },
   /**
    * 文件名称 检查
    */
   checkFileName: function(filename){
	    var EXT_FILE_TYPES = ['gif','jpg','jpeg','png','bmp'];
		var ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
		var past = false;
		for (var i = 0; i < EXT_FILE_TYPES.length; i++) {
		   if (ext == EXT_FILE_TYPES[i]) {
				 past = true;
				 break;
		   }
		}
		return past;
	},
	/**
	 * 清空
	 */
    clearFile:function(name){
        var obj = document.getElementById(name);
        if (!window.addEventListener) {      
            //obj.select();  
         	obj.outerHTML+='';
            // obj.blur();  
         } else {  
            //非IE  
             obj.value = "";  
        }  
	}
}
PAS.css = {
	focus:function(id) {
	    $('#' + id).addClass('selected');
    },
    blur:function(id){
    	$('#' + id).removeClass('selected');
    }
}
/**
 * 客户端 
 */
PAS.client = {
	/**
	 * 默认post请求
	 */
	request: function (url , data , handler, type){
	   if (!type) {
		   this.post(url, data, handler);
	   }   
    },
    /**
     * post
     * @param url :http://
     * @param data:{a:"b"}
     * @param hander:function 
     * 
     */
    post:function (url, data, handler) {
       if(!url) {
    	   return;
       }
 	   $.ajax({
          	url: url,
          	type:'POST',
          	data: data,
          	async: true,             	
          	success: function(msg){	 
 		        if(handler){
 		        	(handler)(msg);
 		        }
          	}
       });
    },
    /**
     * @param url:url
     * @param data:{}json 
     * @param func:function
     */
    done:function(url, data, func){
   	   this.post(url,
    			data,
    			function(rs){
                  var o = JsonUtil.toJson(rs);
                   if (func) {
                 	  (func)(o);
                   }
           	});
    }
}

