/*! Data Events - v0.1.0 - 2016-01-18
* https://github.com/ssauermann/data-events
* Copyright (c) 2016 S. Sauermann; Licensed MIT */
!function($){"use strict";function getDataId(a){return a.data("id@")}function getAttributes(a){var b=a.data();return $.each(b,function(a){0!==a.indexOf("@")&&delete b[a]}),b}function getChildAttributes(a){var b=[];return a.find("*").each(function(){b.push([$(this),getAttributes($(this))])}),b}function resolveReference(a){return $.each(a,function(b,c){if(c.length<2)throw"Missing data: [dom, attribute]";var d=c[1];$.each(d,function(b,c){if("object"!=typeof c)throw console.error(d),"Format has to be: data-@name={event, handler}or {id, attribute} for a reference'";var e=[c],f=function(b){debug&&(console.log("Resolving reference for: "),console.log(b));var c,d=$.grep(a,function(a){var c=getDataId(a[0]);return c===b.id});if(0===d.length)throw"Reference id not found: "+b.id;if(d.length>1)throw"Reference id is ambigous: "+b.id;if(c=d[0][0].data(b.attribute),"undefined"!=typeof c.event)return debug&&(console.log("Resolved to: "),console.log(c)),c;if(debug&&console.log(c),$.inArray(c,e))throw"References are cyclic";f(c)};"undefined"==typeof c.event&&(d[b]=f(c))})}),a}function handleEvent(dom,attributename,event,handler,value){debug&&(console.log("Handling event:"),console.log(dom),console.log(attributename),console.log(handler),console.log(value));var resultValue;if(resultValue="object"==typeof handler?handler[value]:"undefined"==typeof handler?value:eval("("+handler+")")(event,value),"undefined"==typeof resultValue)throw"Handler is invalid: "+handler;dom.attr(attributename.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),resultValue)}function executeEvent(a,b,c){return debug&&(console.log("Executing event:"),console.log(b),console.log(c)),$.each(a,function(a,d){$.each(d[1],function(a,e){"object"==typeof e.event?$.each(e.event,function(f,g){g===b&&handleEvent(d[0],a.substring(1),e.event,e.handler,c)}):e.event===b&&handleEvent(d[0],a.substring(1),e.event,e.handler,c)})}),$.grep(a,function(a){return $.isEmptyObject(a)})}var debug=!1;$.fn.dataevent=function(a,b){return this.find("[data-at]").each(function(){var c=$(this);executeEvent(resolveReference(getChildAttributes(c)),a,b)}),this}}(jQuery);