﻿
/**
* @author basil
* 
*/
jQuery.create = function() {
    if (arguments.length == 0) return [];
    var first_arg = arguments[0];
    var elt = null;
    var elts = null;
    var siblings = null;

    // in case someone passes in a null object, assume that they want an empty string.
    if (first_arg == null) first_arg = "";
    if (first_arg.constructor == String) {
        if (arguments.length > 1) {
            var second_arg = arguments[1];
            if (second_arg.constructor == String) {
                elt = document.createTextNode(first_arg);
                elts = [];
                elts.push(elt);
                var siblings = jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
                elts = elts.concat(siblings);
                return elts;

            } else {
                elt = document.createElement(first_arg);

                // set element attributes.
                var attributes = arguments[1];
                for (var attr in attributes) jQuery(elt).attr(attr, attributes[attr]);

                // add children of this element.
                var children = arguments[2];
                children = jQuery.create.apply(null, children);
                jQuery(elt).append(children);

                // if there are more siblings, render those too.
                if (arguments.length > 3) {
                    siblings = jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
                    return [elt].concat(siblings);
                }
                return elt;
            }
        } else return document.createTextNode(first_arg);
    } else {
        elts = [];
        elts.push(first_arg);
        siblings = jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
        elts = elts.concat(siblings);
        return elts;
    }
};

jQuery.extend({
    num: function(v) {
        var n = parseInt(v);
        return n == null || isNaN(n) ? 0 : n;
    },

    toUniqArr: function(arr) {
        var r = [], d = {};
        for (var i = 0, l = arr.length; i < l; i++) {
            var id = arr[i];
            if (!done[id]) {
                done[id] = true;
                r.push(arr[i]);
            }
        }
        return r;
    },

    isArray: function(v) {
        return typeof (v) == 'object' && v != null && typeof (v.length) == 'number';
    },

    isNullOrEmpty: function(o) {
        if (o == null
			    && o == '') return true;
        return false
    },

    isNull: function(o) { if (o == null && o == undefined) { return true; } return false },

    addCommas: function(num) {
        num += '';
        x = num.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        return x1 + x2;
    },

    getUrlParam: function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var res = (new RegExp("[\\?&]" + name + "=([^&#]*)")).exec(window.location.href);
        return res ? decodeURIComponent(res[1]) : '';
    },
    
    toQueryString: function (toadd , qs){
        if(!toadd || toadd=="") return qs;
        if(!qs || qs =="") return "?" +toadd;
        if(/\?/.test(qs)) return  qs+"&"+toadd;
        
        return "?" + qs + "&" + toadd;
    }
});

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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(); // use expires attribute, max-age is not supported by IE
        }
        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 { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery.timer = function (interval, callback) {
    /**
    *
    * timer() provides a cleaner way to handle intervals  
    *
    *@usage
    * $.timer(interval, callback);
    *
    *
    * @example
    * $.timer(1000, function (timer) {
    * 	alert("hello");
    * 	timer.stop();
    * });
    * @desc Show an alert box after 1 second and stop
    * 
    * @example
    * var second = false;
    *	$.timer(1000, function (timer) {
    *		if (!second) {
    *			alert('First time!');
    *			second = true;
    *			timer.reset(3000);
    *		}
    *		else {
    *			alert('Second time');
    *			timer.stop();
    *		}
    *	});
    * @desc show an alert box after 1 second and show another after 3 seconds
    *
    * 
    */
	var interval = interval || 100;
	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
    };
    
	return new _timer(interval, callback);
};

