// This make sure that every console.log call executes even w/o firebug or ie8
	
if (typeof console === 'undefined') {
    var console =  {log: function(){}};
}
var iOkun = {
	isNumber: function (val) {
		return (isNaN(parseFloat(val))) ? false : true;
	},
	
    json2options : function(data) {
      var options = '';
      $.each(data, function(k, v) {
        options += '<option value="'+k+'">'+v;
      });
      return options
    },
	// Gets position of an element
	// @param HtmlElement el
	// return Object {int x, int y}
	getElementPos: function(el) {
		var offset = $(el).offset();

		var parent = el;
		var x = offset.left;
		var y = offset.top;
		while (parent && typeof parent.style !=='undefined') {
			var tmpX = parseInt(parent.style.left);
			if (!isNaN(tmpX))
				x -= tmpX;
			
			var tmpY = parseInt(parent.style.top);
			if (!isNaN(tmpY))
				y -= tmpY;
			
			parent = parent.parentNode;
		}
		
		return {x:x, y:y};
	},

    createCookie: function (name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    },

    readCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    },

    eraseCookie: function(name) {
        iOkun.createCookie(name,"",-1);
    },


	initializeMaxLengthValidation : function() {
		
		var items = $('textarea');
		items.each( function() {
		
			var obj = $(this);
			var toValidate = obj.attr('className').match(/maxLength_([0-9]*)/i);
			if (toValidate !== null) {
				var maxLength = toValidate[1];
				
			}
			
		});
		
	},
	strtotime: function (str, now) {
	    // Convert string representation of date and time to a timestamp  
	    // 
	    // version: 1103.1210
	    // discuss at: http://phpjs.org/functions/strtotime    // +   original by: Caio Ariede (http://caioariede.com)
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +      input by: David
	    // +   improved by: Caio Ariede (http://caioariede.com)
	    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Wagner B. Soares
	    // +   bugfixed by: Artur Tchernychev
	    // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)
	    // *     example 1: strtotime('+1 day', 1129633200);
	    // *     returns 1: 1129719600    // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);
	    // *     returns 2: 1130425202
	    // *     example 3: strtotime('last month', 1129633200);
	    // *     returns 3: 1127041200
	    // *     example 4: strtotime('2009-05-04 08:30:00');    // *     returns 4: 1241418600
	    
		var i, match, s, strTmp = '',
	        parse = '';
	 
	    var strTmp = str;  
	   
	    	
	    strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces
	    strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars
	   
	    if (strTmp == 'now') {
	        return (new Date()).getTime() / 1000; // Return seconds, not milli-seconds
	    } else if (!isNaN(parse = Date.parse(strTmp))) {return (parse / 1000);
	    } else if (now) {
	        now = new Date(now * 1000); // Accept PHP-style seconds
	    } else {
	        now = new Date();}
	   
	    strTmp = strTmp.toLowerCase();
	 
	    var __is = {day: {
	            'sun': 0,
	            'mon': 1,
	            'tue': 2,
	            'wed': 3,            'thu': 4,
	            'fri': 5,
	            'sat': 6
	        },
	        mon: {'jan': 0,
	            'feb': 1,
	            'mar': 2,
	            'apr': 3,
	            'may': 4,            'jun': 5,
	            'jul': 6,
	            'aug': 7,
	            'sep': 8,
	            'oct': 9,            'nov': 10,
	            'dec': 11
	        }
	    };
	     var process = function (m) {
	        var ago = (m[2] && m[2] == 'ago');
	        var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);
	 
	        switch (m[0]) {case 'last':
	        case 'next':
	            switch (m[1].substring(0, 3)) {
	            case 'yea':
	                now.setFullYear(now.getFullYear() + num);break;
	            case 'mon':
	                now.setMonth(now.getMonth() + num);
	                break;
	            case 'wee':now.setDate(now.getDate() + (num * 7));
	                break;
	            case 'day':
	                now.setDate(now.getDate() + num);
	                break;case 'hou':
	                now.setHours(now.getHours() + num);
	                break;
	            case 'min':
	                now.setMinutes(now.getMinutes() + num);break;
	            case 'sec':
	                now.setSeconds(now.getSeconds() + num);
	                break;
	            default:var day;
	                if (typeof(day = __is.day[m[1].substring(0, 3)]) != 'undefined') {
	                    var diff = day - now.getDay();
	                    if (diff == 0) {
	                        diff = 7 * num;} else if (diff > 0) {
	                        if (m[0] == 'last') {
	                            diff -= 7;
	                        }
	                    } else {if (m[0] == 'next') {
	                            diff += 7;
	                        }
	                    }
	                    now.setDate(now.getDate() + diff);}
	            }
	            break;
	 
	        default:if (/\d+/.test(m[0])) {
	                num *= parseInt(m[0], 10);
	 
	                switch (m[1].substring(0, 3)) {
	                case 'yea':now.setFullYear(now.getFullYear() + num);
	                    break;
	                case 'mon':
	                    now.setMonth(now.getMonth() + num);
	                    break;case 'wee':
	                    now.setDate(now.getDate() + (num * 7));
	                    break;
	                case 'day':
	                    now.setDate(now.getDate() + num);break;
	                case 'hou':
	                    now.setHours(now.getHours() + num);
	                    break;
	                case 'min':now.setMinutes(now.getMinutes() + num);
	                    break;
	                case 'sec':
	                    now.setSeconds(now.getSeconds() + num);
	                    break;}
	            } else {
	                return false;
	            }
	            break;}
	        return true;
	    };
	 
	    match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);if (match != null) {
	        if (!match[2]) {
	            match[2] = '00:00:00';
	        } else if (!match[3]) {
	            match[2] += ':00';}
	 
	        s = match[1].split(/-/g);
	 
	        for (i in __is.mon) {if (__is.mon[i] == s[1] - 1) {
	                s[1] = i;
	            }
	        }
	        s[0] = parseInt(s[0], 10); 
	        s[0] = (s[0] >= 0 && s[0] <= 69) ? '20' + (s[0] < 10 ? '0' + s[0] : s[0] + '') : (s[0] >= 70 && s[0] <= 99) ? '19' + s[0] : s[0] + '';
	        return parseInt(this.strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]) + (match[4] ? match[4] / 1000 : ''), 10);
	    }
	     var regex = '([+-]?\\d+\\s' + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' + '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday' + '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)' + '|(last|next)\\s' + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' + '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday' + '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))' + '(\\sago)?';
	 
	    match = strTmp.match(new RegExp(regex, 'gi')); // Brett: seems should be case insensitive per docs, so added 'i'
	    if (match == null) {
	        return false;}
	 
	    for (i = 0; i < match.length; i++) {
	        if (!process(match[i].split(' '))) {
	            return false;}
	    }
	 
	    return (now.getTime() / 1000);
	},
	
	fetchPartsFromTimestampString: function(timestamp){
		var args = timestamp.split(' ');//args[0] -> year-month-day, arg[1] = hours:minutes:seconds
		
		return new Object({'year'   : args[0].split('-')[0],
						   'month'  : args[0].split('-')[1],
						   'day'    : args[0].split('-')[2],
						   'hour'   : args[1].split(':')[0],
						   'minute' : args[1].split(':')[1],
						   'second': args[1].split(':')[2]
		});
	},
	
	/**
	 * returns unix time in ms 
	 */
	getCurrentTime: function(){
		var d = new Date();
		return General.dateTime.getTime() - AppData.timeZoneOffset;
	},
	
	convertUnixTime: function(time){
	    	var time = (time - General.serverOffset);
			var d = new Date(time + AppData.timeZoneOffset);
			
			var year  = d.getFullYear();
			var month = d.getMonth() + 1;
			var date   = d.getDate();
			
			var hours   =  d.getHours();
			var minutes = d.getMinutes();
			var seconds = d.getSeconds();
			
			if ( hours < 10) hours     = '0' + hours;
	        if ( minutes < 10) minutes = '0' + minutes;
	        if ( seconds < 10) seconds = '0' + seconds;
	        
	        if ( date < 10) date = '0' + date;
	        if ( month < 10) month = '0' + month;
	        
	        return  new Object({'year'   : year, 
	        					'month'  : month, 
	        					'day'    : date, 
	        					'hour'   : hours, 
	        					'minute' : minutes, 
	        					'second': seconds});

	    }
}


jQuery.create = function(tagName, elementName) {
	if (typeof elementName !== 'undefined')
		if ($.browser.msie)
			return $(document.createElement('<'+tagName+' name="'+elementName+'">'));
		else
			return $(document.createElement(tagName)).attr('name', elementName);
	else
		return $(document.createElement(tagName));
}

jQuery.createTextNode = function(text) {
	return $(document.createTextNode(text));	
}

String.prototype.addCommas = function() {
	nStr = this;
	nStr += '';
	x = nStr.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;
}

Number.prototype.addCommas = function() {
	nStr = this + '';
	return nStr.addCommas();
}


