﻿/*
Script: Hg.Core.js
	一套基于jquery的实用工具
	Author  : Young.Jiang
    WebSite : http://www.holygrace.cn

 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 
 	
***************************************************************
jQuery默认方法  ============

inArray:  返回参数在数组中的索引,没找到是返回0。
          eg:  $.inArray("young", arr);
each:     遍历一个数组或对象属性
          eg:  $.each(obj,function(key,value){})
               当obj为数组时，key为索引值;当为对象时,key为对象属性值
extend:   用一个或多个对象扩展第一个对象
          eg:  $.extend( target, object1, [objectN] ) 
grep:     用过滤函数对数值进行过滤
          eg:  $.grep([5,6,9], function(n, i){})
          n,i分别对应值和相应位置索引
map:      对数值用相应函数重新转换
          eg:  $.map([5,6,9], function(n, i){})
          n,i分别对应值和相应位置索引
makeArray:将类似数值的对象转化为者真实的数组
          eg:  var arr = jQuery.makeArray($(".div"));
trim:     移除字符串两端的空格


***************************************************************
HG扩展方法  ============               
----------------------------------------------------------------------------------------
chk:      检查传入的对象或值是否存在。
          return true或false
---------------------------------------------------------------
defined:  检测传入的对象或值是否定义过
          return true或false
---------------------------------------------------------------
pick:     如果传入的参数被定义返回第一个对象,否则返回第二个.
          eg: $.pick(obj, {name:"Young.Jiang"});
---------------------------------------------------------------
random:   返回介于两个值之间的整数
---------------------------------------------------------------
toInt,toFloat:    将第一个参数转化为整数或浮点数,当无法转化，返回默认值,
          para: v-需转化的值; def，默认值，未定义是为0;
---------------------------------------------------------------
gmp:      get mouse positon的缩写,获取鼠标事件的位置
          return { x:x坐标值 , y:y坐标值 }
---------------------------------------------------------------
url:      url设置
          eg: var url="http://www.holygrace.cn/index.htm?fx=drag";
          var urlpara=$.url(url); alert(urlpara.fx)  //返回"drag"; urlpara为{pageName:"index.htm",fx:"drag"}
          urlpara=$url(url,"fx"); alert(urlpara)     //相当于"drag"
          var newurl=$.url(url,"fx","dialog"); //newurl为:"http://www.holygrace.cn/index.htm?fx=dialog";
          newurl=$.url(url,{pageName:"test.aspx",fx:"star",lg:"cn"}); //newurl为:"http://www.holygrace.cn/test.aspx?fx=dialog&lg=cn";
---------------------------------------------------------------
cookie:   cookie的设置和读取
          eg: $.cookie('name', 'value');
          $.cookie('name','value',{expires: 7, path:'/', domain:'www.holygrace.cn',secure: true});
          $.cookie('the_cookie', null); //删除

*/
var HG = {
	Version: '2.0',
	Author: 'Young.Jiang',
	Email:'holygrace.cn@gmail.com',
	WebSite:"http://www.holygrace.cn"
};

jQuery.extend({
    IsDate:function(v){ var r = v.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);if(r==null){return false;}var d = new Date(r[1], r[3]-1, r[4]);return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); },
    IsNoE:function(v){
        return v==null||v==""||typeof(v)=="undefined";
    },
    IsEmail:function(v){ var re=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;return re.test(v);},
    chk:function(obj){
        return !!(obj || obj === 0);
    },
    defined:function(obj){
        return (obj != undefined);
    },
    pick:function(){
        for (var i = 0, l = arguments.length; i < l; i++){
		    if ($.defined(arguments[i])) return arguments[i];
	    }
	    return null;
    },
    random:function(min, max){
        return Math.floor(Math.random() * (max - min + 1) + min);
    },
    parseNum:function(type,v,def){
        var r=(type=="float")?parseFloat(v):parseInt(v);
        return isNaN(r)?($.defined(def)?def:0):r;
    },
    toInt:function(v,def){
        return $.parseNum("int",v,def);
    },
    toFloat:function(v,def){
        return $.parseNum("float",v,def);
    },
    toBool:function(s){
        return s.toLowerCase()=="true"?true:false;
    },
    id:function(id){
        return document.getElementById(id);
    },
    gmp:function(e){
        var posx = 0;
		var posy = 0;
		if (!e){var e = window.event;}
		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) {
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
		};
		return { 'x': posx, 'y': posy };
    },
    url:function(url){
        url=url.split("#")[0];
        var urls=url.split("?");
        var paths=urls[0].split("/");
        var pageName= paths[paths.length-1];
        var querys=new Object();
        querys.pageName=pageName;
        var arg=arguments;
        if(url.indexOf("?")!=-1)
        {
            $.each(urls[1].split("&"),function(i,n){
                var v=n.split("=");
                querys[v[0]]=v[1];
            })
        }
        function urlToString(){
            url=urls[0]+"?";
            $.each(querys,function(i,n){
                url=i!="pageName"?url+i+"="+n+"&":url.replace(pageName,n);
            });
            return url.substr(0,url.length-1);
        }
        if(!$.defined(arg[1])){
            return querys;
        }
        if(typeof arg[1]=="object"){
            $.extend(querys, arg[1]);
            return urlToString();
        }
        if(typeof arg[1]=="string"){
            if($.defined(arg[2])){
                querys[arg[1]]=arg[2];
                return urlToString();
            }
            else{
                return querys[arg[1]]
            }
        }
    },
    cookie:function(name, value, options) { 
        if (typeof value != 'undefined') {
            options = options || {}; 
            if (value === null) { 
                value = ''; 
                options.expires = -1; 
            } 
            var expires = ''; 
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 
                var date; 
                if (typeof options.expires == 'number') { 
                    date = new Date(); 
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 
                } else { 
                    date = options.expires; 
                } 
                expires = '; expires=' + date.toUTCString(); 
            } 
            var path = options.path ? '; path=' + options.path : ''; 
            var domain = options.domain ? '; domain=' + options.domain : ''; 
            var secure = options.secure ? '; secure' : ''; 
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
        } else {
            var cookieValue = null; 
            if (document.cookie && document.cookie != '') { 
                var cookies = document.cookie.split(';'); 
                for (var i = 0; i < cookies.length; i++) { 
                    var cookie = jQuery.trim(cookies[i]); 
                    if (cookie.substring(0, name.length + 1) == (name + '=')) { 
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
                        break; 
                    } 
                } 
            } 
            return cookieValue; 
        } 
    },
    ctpy:function(str){
        function cnCharToPy(str){//str为一个汉字
             var result="";
             if (typeof(str)!="string") str=new String(str); 
             var tmp = 65536 + getAsc(str.substr(0,1));
             var uc=str.charCodeAt(0);
             if (uc<128){
                 if ((uc>=65&&uc<=90)||(uc>=97&&uc<=122)||(uc>=48&&uc<=57)){
                      return str.substr(0,1).toUpperCase();
                  }else{
                      return ""; 
                 }
             }
             if(tmp>=45217&&tmp<=45252) {
                  result= "A"}else if(tmp>=45253&&tmp<=45760) {
                  result= "B"}else if(tmp>=45761&&tmp<=46317) {
                  result= "C"}else if(tmp>=46318&&tmp<=46825) {
                  result= "D"}else if(tmp>=46826&&tmp<=47009) {
                  result= "E"}else if(tmp>=47010&&tmp<=47296) {
                  result= "F"}else if(tmp>=47297&&tmp<=47613) {
                  result= "G"}else if(tmp>=47614&&tmp<=48118) {
                  result= "H"}else if(tmp>=48119&&tmp<=49061) {
                  result= "J"}else if(tmp>=49062&&tmp<=49323) {
                  result= "K"}else if(tmp>=49324&&tmp<=49895) {
                  result= "L"}else if(tmp>=49896&&tmp<=50370) {
                  result= "M"}else if(tmp>=50371&&tmp<=50613) {
                  result= "N"}else if(tmp>=50614&&tmp<=50621) {
                  result= "O"}else if(tmp>=50622&&tmp<=50905) {
                  result= "P"}else if(tmp>=50906&&tmp<=51386) {
                  result= "Q"}else if(tmp>=51387&&tmp<=51445) {
                  result= "R"}else if(tmp>=51446&&tmp<=52217) {
                  result= "S"}else if(tmp>=52218&&tmp<=52697) {
                  result= "T"}else if(tmp>=52698&&tmp<=52979) {
                  result= "W"}else if(tmp>=52980&&tmp<=53640) {
                  result= "X"}else if(tmp>=53689&&tmp<=54480) {
                  result= "Y"}else if(tmp>=54481&&tmp<=62289) {
                  result= "Z"}else{  
                  result="";
            }
            return result;
        }
        var py="";
        for(var i=0;i<str.length;i++)
        {
            py=py+cnCharToPy(str.charAt(i));
        }
        return py;
    }
});

/// <summary>提示</summary>
/// <options name="areaid">提示区域id，比如一个div的id</options>
/// <options name="top">提示域距离鼠标顶部的距离</options>
/// <options name="left">提示域距离鼠标左侧的距离</options>
/// <options name="fn">tip触发后的事件,传入触发事件对象</options>
(function($) {
    $.fn.tip=function(options){
        options = $.extend({ 
            areaid:"",
            top:18,
            left:-5,
            fn:null
        },options);
        return this.each(function() {
            function Locate(e){
                var pos=$.gmp(e);
                $("#"+options.areaid).css({
                    top:pos.y+options.top,
                    left:pos.x+options.left
                });
            };
            var tip=$(this);
            tip.hover(function(e){
                $("#"+options.areaid).show();
                if(options.fn!=null){
                    options.fn(this)};
                Locate(e);
            },function(){
                $("#"+options.areaid).hide();
            }).mousemove(function(e){
                Locate(e);
            })
        })
    }
})(jQuery);

/// <summary>拖动</summary>
/// <param name="handle">拖动助手，一个jquery对象，该选项不是必须的</param>
(function($) {
    $.fn.drag=function(handle){
        var isMouseDown = false;
        var drag = null;
        var lastMouse=null;
	    var lastElem=null;	    
        function update(e) {
            var pos=$.gmp(e);
		    drag.css({
		        top:lastElem.top + pos.y - lastMouse.y,
		        left:lastElem.left + pos.x - lastMouse.x
		    });	   
        };
        $(document).mousemove(function(e){
		    if(isMouseDown){
			    update(e);
			    return false;
		    };
	    }).mouseup(function(e){
		    if(isMouseDown){
			    isMouseDown = false;
			    return false;
		    };
	    });
	    return this.each(function(){
	        drag=$(this);
            var dragHandle=($.defined(handle)?handle:drag).css("cursor","move");
            dragHandle.mousedown(function(e){
                drag.css("position","absolute");
                isMouseDown=true;
                lastMouse=$.gmp(e);
                lastElem=drag.offset();
                update(e);
            })
	    })
    }
})(jQuery);

Array.prototype.indexOf=function(v){
    if(arguments.length==1)
    {
        for(var i=0;i<this.length;i++){
            if(this[i]==v)
                return i;
        }
        return -1;
    }
    else
    {
        for(var i=0;i<this.length;i++){
            if(this[i][arguments[1]]==v)
                return i;
        }
        return -1;
    }
}
