if (typeof (pl) == 'undefined') {
	var pl = {};
}
if (typeof (pl.mediovski) == 'undefined') {
	pl.mediovski = {};
}
if (typeof (pl.mediovski.technology) == 'undefined') {
	pl.mediovski.technology = {};
}

pl.mediovski.technology.log = function(){
	if(typeof console != 'undefined'){
		console.log.apply(console,arguments);
	}
};
pl.mediovski.technology.error = function(){
	if(typeof console != 'undefined'){
		console.error.apply(console,arguments);
	}
};
pl.mediovski.technology.cookie = {
	set:function(key,value,opts){
		value = encodeURIComponent(value || '');
		if(opts){
		if (opts.domain) value += '; domain=' + opts.domain;
		if (opts.path) value += '; path=' + opts.path;
		if (opts.expires) {
			var expires = '';
			if(typeof opts.expires == 'number'){
				var date = new Date();
				date.setTime(date.getTime()+(opts.expires*24*60*60*1000)); //days
				expires = date.toUTCString();
			}else if (typeof opts.expires == 'object' && opts.expires.toUTCString){
				expires = opts.expires.toUTCString();
			}else{
				expires = opts.expires;
			}
			if(expires){
				value += '; expires='+ expires;
			}
		}
		if (opts.secure) value += '; secure';
		}
		document.cookie = key +'='+ value;
	},
	get:function(key){
		var cookies = {};
		if (document.cookie && document.cookie != '') {
			var vals = document.cookie.split(/; ?/);
			for (var i = 0, l = vals.length; i < l; i++) {
				var tmp = vals[i].split('=');
				try{
					cookies[tmp[0]] = decodeURIComponent(tmp[1]);
				}catch(e){
				}
			}
		}
		if(key){
			return (key in cookies) ? cookies[key] : null;
		}
		return cookies;
	},
	remove:function(key){
		this.set(key,'',{expires:-1});
	}
};
pl.mediovski.technology.Connector = function(id, apiUri, template, directives,
		handlerFunction, initFunction) {
	var _data = {
		selector : '#' + id,
		apiUri : apiUri,
		template : template,
		directives : directives,
		handlerFunction : handlerFunction,
		initFunction : initFunction
	};
	
	var _private = {
		parseUri: function(uri) {
			var address = uri.split('#');
			var fragment = '';
			if (address.length > 1) {
				fragment = address[1];
			}
			address = address[0].split('?');
			var params = {};
			if (address.length > 1) {
				var _params = address[1].split('&');
				for (var i=0; i<_params.length; i++) {
					var pair = _params[i].split('=');
					params[pair[0]] = pair[1];
				}
			}
			address = address[0];
			return {
				address: address,
				params: params,
				fragment: fragment
			};
		},
		buildUri: function(obj) {
			var address = obj.address;
			var params = [];
			for (key in obj.params) {
				params.push(key + '=' + obj.params[key]);
			}
			if (params.length > 0) {
				address += '?';
				address += params.join('&');
			}
			if (obj.fragment != '') {
				address += '#' + obj.fragment;
			}
			return address;
		},
		setParam: function(key, value) {
			var parsedUri = _private.parseUri(_data.apiUri);
			parsedUri.params[key] = value;
			_data.apiUri = _private.buildUri(parsedUri);
		}
	};

	this.handle = function() {
		if (_data.initFunction != null) {
			if (_data.initFunction(_data, _private) == false) {
				return;
			}
		}
		var manager = pl.mediovski.technology.ConnectorRequestManager.getInstance();
		var hash = manager.get(_data.apiUri, function(data) {
			var jsonData = data;
			var template = jQuery(jQuery.base64Decode(_data.template));
			jQuery(document).append(template).remove();

			try {
				if (_data.handlerFunction != null) {
					_data.handlerFunction(_data.selector, jsonData, template, _private);
				} else {
					jQuery(_data.selector).empty().append(
							template.render(data, _data.directives).html());
				}
			} catch(e) {
				return false;
			}
			return true;
		}, 'json');
	};
};

/**
 * Request manager for connector JS mechanism
 * 
 */
pl.mediovski.technology.ConnectorRequestManager = (function(){
	var STATUS_COMPETED = 'completed';
	var STATUS_ERROR = 'error';
	var STATUS_PENDING = 'pending';
	
	var TYPE_JSON = 'json';
	var TYPE_STRING = 'string';
	
	var Constructor = function() {
			var self = {
				data: {},
				createHash: function(api) {
					var init = 31243;
					var hash = 0;
					for(var i=0; i<api.length; i++) {
						if (hash == 0) {
							hash = init;
						}
						var charCode = api.charCodeAt(i);
						hash = (hash * charCode) % 65536;
					}
					var timestamp = Math.round(new Date().getTime() / 1000);
					return hash + 'x' + timestamp;
				}
			};
		
			this.hash = Math.round(Math.random() * 9999999);
			
			this.registerData = function(key, data) {
				
				var instanceList = self.data[key];
				var parsed = data;
				if (typeof(data) == 'string' && inst.type == TYPE_JSON) {
				        parsed = jQuery.parseJSON(data);
				}
				for (i = 0; i < instanceList.length; i++) {
					var inst = instanceList[i];
					inst.data = parsed;
				    try {
				    	if (inst.status != STATUS_PENDING) {
				    		continue;
				    	}
				        if (inst.handler(parsed)) {
					        inst.status = STATUS_COMPETED;
					    } else {
							inst.status = STATUS_ERROR;
						}
					} catch(e) {
					        inst.status = STATUS_ERROR;
					}
				}
			};
			
			this.get = function(api, handler, type) {
				var hash = self.createHash(api);
				if (typeof(type) != 'undefined') {
					type = TYPE_JSON;
				}
                if (typeof(self.data[hash]) == 'undefined') {
                    self.data[hash] = [];
                }
                self.data[hash].push({
					api: api,
					handler: handler,
					status: STATUS_PENDING,
					type: type,
					errors: [],
					data: null
				});
                if (self.data[hash].length > 1) {
                	var instanceList = self.data[hash];
                	for (i = 0; i < instanceList.length; i++) {
                		var inst = instanceList[i];
                		if (inst.data != null) {
                			this.registerData(hash, inst.data);
                		}
                	}
                    return hash;
                }
				
				var scriptTag = jQuery('<script />');
				var protocol = document.location.protocol;
				var delimiter = '?';
				if (api.indexOf('?') != -1) {
					delimiter = '&'; 
				}
				var href = protocol + '//' + api + delimiter + '__jskey=' + hash;
				scriptTag.attr({
					type: 'text/javascript',
					src: href
				});
				jQuery('head').append(scriptTag);
				return hash;
			};
	};

	return {
		getInstance: function (){
			return this.instance || (this.instance = new Constructor);
		}
	};
})();

/**
 * UniFeeder
 */
pl.mediovski.technology.feeder = (function() {
    var sid = 'pl-mediovski-technology-unifeeder';
    var NAMESPACE_UNI = 'UniFeeder';
    var NAMESPACE_CANDLE = 'CandleSticks';
    var TYPE_UNI = 1;
    var TYPE_CANDLE = 2;
    var listeners = [];
    var isInit = false;
    var types = {
        ERROR : 'onError',
        RESPONSE : 'onResponse',
        CLOSE : 'onClose',
        CONNECT : 'onConnect'
    };
    var root = '';
    function findRoot() {
        $('script').each(function(i, e) {
            var src = $(e).attr('src');
            if (src) {
                var pos = src.indexOf('script/scripts.js');
                if (pos != -1) {
                    root = src.substr(0, pos);
                }
            }
        });
    }
    
        function initSWF() {
            findRoot();
            var flashvars = {};
            var params = {
                menu : "false",
                scale : "noScale",
                allowFullscreen : "true",
                allowScriptAccess : "always",
                bgcolor : "#FFFFFF"
            };
            var attributes = {
                id : sid
            };
            $(document.body).append('<div id="'+sid+'" />');
			if (thisSite != undefined) {
				swfobject.embedSWF(root + thisSite +"/swf/UniFeeder.swf",sid, "1", "1", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
			} else {
				swfobject.embedSWF(root + "swf/UniFeeder.swf",sid, "1", "1", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
			}
			
        }
            function init() {
                if (!isInit) {
                    isInit = true;
                    initSWF();
                    var i = 0;
                    var timer = setInterval(function(){
                        try {
                            $('#' + sid).get(0).start();
                            clearTimeout(timer);
                            pl.mediovski.technology.log('UniFeeder.init');
                        } catch (e) {
                        	if(i++ == 100){
                        		// pl.mediovski.technology.error(e);
                        		clearTimeout(timer);
                        	}
                        }
                    },100);
                }
            }
                // init();
                
                    function response(type, data) {
                    	pl.mediovski.technology.log(type,data);
                        try {
                            data = $.parseJSON(data);
                            var space;
                            if (data) {
                                space = data.namespace;
                                // :/ why? because uni get string :/
                                data = typeof data.data == 'string' ? $.parseJSON(data.data)
                                : data.data;
                            }
                                        if (types[type]) {
                                            var fn = types[type];
                                            for ( var i = 0; i < listeners.length; i++) {
                                                try {
                                                    var obj = listeners[i];
                                                    if (fn != types.RESPONSE
                                                        || !obj.namespace
                                                                                        || ((obj.namespace == TYPE_UNI && space == NAMESPACE_UNI) || (obj.namespace == TYPE_CANDLE && space == NAMESPACE_CANDLE))) {
                                                        obj[fn](data);
                                                                                        }
                                                } catch (e) {
                                                	pl.mediovski.technology.error(e);
                                                }
                                            }
                                        }
                        } catch (e) {
                        	pl.mediovski.technology.error(e);
                        }
                    }
                    
                        return {
                            TYPE_UNI : TYPE_UNI,
                            TYPE_CANDLE : TYPE_CANDLE,
                            addListener : function(obj, namespace) {
                            	pl.mediovski.technology.log('UniFeeder.addListener',obj,namespace);
                                init();
                                if (obj) {
                                    listeners.push({
                                        onConnect : obj.onConnect || function() {
                                        },
                                        onError : obj.onError || function() {
                                        },
                                        onResponse : obj.onResponse || function() {
                                        },
                                        namespace : namespace
                                    });
                                }
                            },
                            removeListener : function() {
                            },
                            response : function(type, data) {
                            	response(type, data);
                            }
                        };
})();

