﻿// a method to replace document.getElementById
function _$(){
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string'){
            element = document.getElementById(element);
        }
        if (arguments.length == 1){ 
            return element; 
        }
        elements.push(element); 
    }
    return elements;
}

//function prototype of Araay.concat.unique
Array.prototype.unique   =   function()   
{   
    var a =  {};
    for(var  i=0; i<this.length; i++)   
    {   
        if(typeof a[this[i]]  ==  "undefined")   
            a[this[i]]  =  1;   
    }   
    this.length   =   0;   
    for(var  i  in  a){   
        this[this.length]  =  i;
    }
    return this;   
}

//function prototype of Araay.del
Array.prototype.del = function(n)
{
//prototype为对象原型，注意这里为对象增加自定义方法的方法。
    if(n<0)  //如果n<0，则不进行任何操作。
        return this;
    else
        return this.slice(0,n).concat(this.slice(n+1,this.length));
    /*
      concat方法：返回一个新数组，这个新数组是由两个或更多数组组合而成的。
      　　　　　　这里就是返回this.slice(0,n)/this.slice(n+1,this.length)
     　　　　　　组成的新数组，这中间，刚好少了第n项。
      slice方法： 返回一个数组的一段，两个参数，分别指定开始和结束的位置。
    */
}

//erase head space
function Trim(str){
    if(str.charAt(0) == " "){
        str = str.slice(1);
        str = Trim(str); 
    }
    return str;
}

//validate unsign integer
function isNumber(num){
    strRef = "1234567890";
    strobj = new String(num);
    len = strobj.length;
    if(len == 0){
        return false;
    }
    for (i=0; i<len; i++){
        tempChar= strobj.substring(i, i+1);
        if (strRef.indexOf(tempChar, 0) == -1){
            return false; 
        }
    }
    return true;
}

//validate date format with YYYY-MM-DD
function isDate(date){
    var date = new String(date);
    date_list = date.split('-');
	
    if (date_list.length != 3){
        return false;
    }
	
    if (date_list[1].length != 2 || date_list[2].length != 2 || date_list[0].length != 4) {
        return false;
    }
	
    var i_year = new Number(date_list[0]);
    var i_month = new Number(date_list[1]);
    var i_day = new Number(date_list[2]);

    if (!isNumber(i_year) || !isNumber(i_month) || !isNumber(i_day)){
        return false;
    }

    if (i_year < 1900 || i_month < 1 || i_day < 1 || i_month > 12) {
        return false;
    }
	
	var maxday = new Number(30);
	
	if (i_month == 1 || i_month == 3 || i_month == 5 ||
		i_month == 7 || i_month == 8 || i_month == 10 || i_month == 12 ) {

		maxday = 31;
	}
	
	if (i_month == 2) {
		if ((i_year % 4) == 0 && (i_year % 100) != 0) {
			maxday = 29;
		} else if ((i_year % 400) == 0) {
			maxday = 29;
		} else {
			maxday = 28;
		}
	}
	
	if (i_day > maxday) {
		return false;
	}

	return true;
}
