/**
 * @author Sulaeman, sulaeman.nowhere@gmail.com
 */

(function(){
	if ( window.FeelInc ) var FeelInc = window.FeelInc;
	
	var FeelInc = window.FeelInc = function() {return new FeelInc.init();};
	
	FeelInc.apply = function(o, c, defaults){
	    if(defaults){FeelInc.apply(o, defaults);}
	    if(o && c && typeof c == 'object'){for(var p in c){o[p] = c[p];}}
	    return o;
	};
	
	FeelInc.CheckData = function(strSearch, data) {
		if (data != null) {
			for(var i=0; i<data.length; ++i) {
				if (data[i].toLowerCase() == strSearch.toLowerCase()) return true;
			}
		}
		return false;
	};
	
	FeelInc.apply(FeelInc, {
		
		boxid: 0,
		version: '1.0.0',
		
		init: function() {return this.version;},
		
		emailCheck: function (str) {
			var at="@"
			var dot="."
			var lat=str.indexOf(at)
			var lstr=str.length
			var ldot=str.indexOf(dot)
			if (str.indexOf(at)==-1) return false;
			if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
			if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
			if (str.indexOf(at,(lat+1))!=-1) return false;
			if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
			if (str.indexOf(dot,(lat+2))==-1) return false;
			if (str.indexOf(" ")!=-1) return false;
			return true					
		},
		
		loading: function(el) {
			var el = (typeof el == 'string') ? $('#'+el) : el;
			var _parentWidth = el.width();
			var _parentHeight = el.height();
			var _boxLoading = $('<div id="loading-'+(++this.boxid)+'"/>').css({position: 'absolute', top: el.offset().top, left: el.offset().left, width: _parentWidth, height: _parentHeight});
			var _innerLoading = $('<div id="loading-'+(++this.boxid)+'"/>').css({position: 'relative', margin: 'auto', top: (_parentHeight / 2), width: 200, height: 50, backgroundColor: '#fff', border: '#000 1px dotted'});
			var _boxImgLoding = $('<div id="loading-'+(++this.boxid)+'"/>').css({float: 'left', width: 20, height: 50});
			var _boxTextLoading = $('<div id="loading-'+(++this.boxid)+'"/>').css({float: 'left', height: 50, padding: '17px 0 0 0'});
			_boxLoading.append(_innerLoading.append(_boxImgLoding).append(_boxTextLoading)).appendTo(document.body);
			_boxImgLoding[0].className = 'loading';
			_boxTextLoading[0].innerHTML = 'Sedang mengambil data ......';
			return _boxLoading;
		},
		
		clearTime: function(timer){
			clearTimeout(timer);
			clearInterval(timer);
			return null;
		},
		
		setBoxID: function() {
			var _d = new Date();
			return _d.getTime();
		}
			
	});
	
	FeelInc.ui = FeelInc.ui || {};
	FeelInc.util = FeelInc.util || {};
})();

FeelInc.util.JSON = new (function(){
    var useHasOwn = {}.hasOwnProperty ? true : false;
    
    var pad = function(n) {
        return n < 10 ? "0" + n : n;
    };
    
    var m = {
        "\b": '\\b',
        "\t": '\\t',
        "\n": '\\n',
        "\f": '\\f',
        "\r": '\\r',
        '"' : '\\"',
        "\\": '\\\\'
    };

    var encodeString = function(s){
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if(c){
                    return c;
                }
                c = b.charCodeAt();
                return "\\u00" +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };
    
    var encodeArray = function(o){
        var a = ["["], b, i, l = o.length, v;
            for (i = 0; i < l; i += 1) {
                v = o[i];
                switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if (b) {
                            a.push(',');
                        }
                        a.push(v === null ? "null" : FeelInc.util.JSON.encode(v));
                        b = true;
                }
            }
            a.push("]");
            return a.join("");
    };
    
    var encodeDate = function(o){
        return '"' + o.getFullYear() + "-" +
                pad(o.getMonth() + 1) + "-" +
                pad(o.getDate()) + "T" +
                pad(o.getHours()) + ":" +
                pad(o.getMinutes()) + ":" +
                pad(o.getSeconds()) + '"';
    };
    
    this.encode = function(o){
        if(typeof o == "undefined" || o === null){
            return "null";
        }else if(o instanceof Array){
            return encodeArray(o);
        }else if(o instanceof Date){
            return encodeDate(o);
        }else if(typeof o == "string"){
            return encodeString(o);
        }else if(typeof o == "number"){
            return isFinite(o) ? String(o) : "null";
        }else if(typeof o == "boolean"){
            return String(o);
        }else {
            var a = ["{"], b, i, v;
            for (i in o) {
                if(!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if(b){
                            a.push(',');
                        }
                        a.push(this.encode(i), ":",
                                v === null ? "null" : this.encode(v));
                        b = true;
                    }
                }
            }
            a.push("}");
            return a.join("");
        }
    };
    
    this.decode = function(json){
        return eval("(" + json + ')');
    };
})();

FeelInc.encode = FeelInc.util.JSON.encode;
FeelInc.decode = FeelInc.util.JSON.decode;

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
};

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
};

FeelInc.ui.Tips = function() {
	
	return {
		
		options: {
			maxTitleChars: 30,
			showDelay: 100,
			hideDelay: 100,
			className: 'tool',
			offsets: {'x': 16, 'y': 16},
			fixed: false
		},
		
	init: function(elements, options){
		$.extend(FeelInc.ui.Tips.options, options)
		FeelInc.ui.Tips.toolTip = $('<div class="'+FeelInc.ui.Tips.options.className+'-tip" style="position:absolute;top:0;left:0;display:none;"/>').appendTo(document.body);
		FeelInc.ui.Tips.wrapper = $('<div/>').appendTo(FeelInc.ui.Tips.toolTip);
		var _build = FeelInc.ui.Tips.build.bind(FeelInc.ui.Tips);
		elements.each(function(){_build(this)});
		if (FeelInc.ui.Tips.options.initialize) FeelInc.ui.Tips.options.initialize.call(this);
	},

	build: function(el){
		$.extend(el, {tmp: {myTitle: ((el.href && $(el).children('a')[0]) ? el.href.replace('http://', '') : (el.rel || false))}})
		if (el.title){
			var dual = el.title.split('::');
			if (dual.length > 1){
				$.extend(el, {tmp: {myTitle: $.trim(dual[0])}});
				$.extend(el.tmp, {myText: $.trim(dual[1])});
			} else {
				$.extend(el, {tmp: {myText: el.title}});
			}
			$(el).removeAttr('title');
		} else {
			$.extend(el, {tmp: {myText: false}});
		}
		if (el.tmp.myTitle && el.tmp.myTitle.length > this.options.maxTitleChars) {
			el.tmp.myTitle = el.tmp.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
		}
		$(el).bind('mouseenter', function(event){
			this.start(el);
			if (!this.options.fixed) this.locate(event);
			else this.position(el);
		}.bind(this));
		if (!this.options.fixed) $(el).bind('mousemove', this.locate.bind(this));
		var end = this.end.bind(this);
		$(el).bind('mouseleave', end);
		$(el).bind('trash', end);
	},

	start: function(el){
		this.wrapper.empty();
		if (el.tmp.myTitle){
			this.title = $('<span/>').appendTo($('<div class="'+this.options.className+'-title"/>').appendTo(this.wrapper)).html(el.tmp.myTitle);
		}
		if (el.tmp.myText){
			this.text = $('<span/>').appendTo($('<div class="'+this.options.className+'-text"/>').appendTo(this.wrapper)).html(el.tmp.myText);
		}
		this.show();
	},

	end: function(event){
		this.hide();
	},

	position: function(element){
		var pos = element.getPosition();
		this.toolTip.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y
		});
	},

	locate: function(event){
		var win = {'x': $(window).width(), 'y': $(window).height()};
		var scroll = {'x': $(window).scrollLeft(), 'y': $(window).scrollTop()};
		var tip = {'x': this.toolTip.width(), 'y': this.toolTip.height()};
		
		var pos = event.pageX + this.options.offsets['x'];
		if ((pos + tip['x'] - scroll['x']) > win['x']) pos = event.pageX - this.options.offsets['x'] - tip['x'];
		this.toolTip.css('left', pos);
		
		var pos = event.pageY + this.options.offsets['y'];
		if ((pos + tip['y'] - scroll['y']) > win['y']) pos = event.pageY - this.options.offsets['y'] - tip['y'];
		this.toolTip.css('top', pos);
	},

	show: function(){
		this.toolTip.fadeIn('fast');
	},

	hide: function(){
		this.toolTip.fadeOut('fast');
	}
		
	};
	
}();