var SELECTOR="td[style*='padding-left']";$(function(){function f(t,i){for(var r=0;r<n.length;r++)if(n[r].key===t)return;n.push({key:t,rows:i})}function r(t){for(var i=0;i<n.length;i++)if(n[i].key===t)return n[i].rows;return null}function t(n){var t=n.find(SELECTOR).css("padding-left");return t?parseInt(t,10):0}function i(n){return $.trim(n.find(SELECTOR).text())}function u(n,i){for(var u=[n],r=n.next();r.length;){if(t(r)<=i)break;u.push(r);r=r.next()}return u}function e(n){n.find("input,textarea,select").each(function(){var n=$(this);n.is(":checkbox, :radio")?n.prop("checked",!1):n.is("input,textarea")?n.val(""):n.is("select")&&n.prop("selectedIndex",0)})}function o(n,r){for(var s=i(n),f=n.next(),e,u,o;f.length;){if(e=t(f),e<r)break;if(e===r&&i(f)===s)return!0;f=f.next()}for(u=n.prev();u.length;){if(o=t(u),o<r)break;if(o===r&&i(u)===s)return!0;u=u.prev()}return!1}function s(n,i){var s,c,o,l,a,h;if(r(n[0])||f(n[0],u(n,i)),s=r(n[0]),s&&s.length){for(c=n,o=n.next();o.length&&t(o)>i;)c=o,o=o.next();for(l=0;l<s.length;l++)a=s[l],h=$(a.clone()),e(h),h.addClass("new-block"),c.after(h),c=h}}function h(n,t){var r,i;if(!o(n,t)){alert("Cannot delete the last block.");return}for(r=u(n,t),i=0;i<r.length;i++)r[i].remove()}var n=[];$("table").on("click","button.b-add, button.b-del",function(){var n=$(this),i=n.closest("tr"),r=t(i);n.hasClass("b-add")?s(i,r):n.hasClass("b-del")&&h(i,r)})})